使用软件串行一次接收多个字符 [英] Receiving multiple chars at once with Software Serial

查看:19
本文介绍了使用软件串行一次接收多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Arduino Uno R3 和一个蓝牙伴侣.将 Mate 连接到 Arduino 硬件串行(引脚 0,1)时,我可以从连接的设备一次发送多个字符,但是当我尝试使用软件串行(例如,使用引脚 4,2)做同样的事情时,我只能得到第一个字符和其余的字符都搞砸了.

I have a Arduino Uno R3 and a Bluetooth Mate. When linking the Mate to the Arduino Hardware Serial (pin 0,1) I can send multiple characters at once from my connected device but when I try to make the same thing with Software Serial (using pin 4,2 for example) I only get the first character and the rest of the chars are messed up.

我的代码:

#include <SoftwareSerial.h>  

int bluetoothTx = 4;  
int bluetoothRx = 2;  

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup() 
{
  Serial.begin(115200);  
  bluetooth.begin(115200);  
}

void loop()
{
  if(bluetooth.available())
  {
    Serial.print((char)bluetooth.read());  
  }
}

例如,如果我从我的 android 设备发送这个字符:abcd,我会在串行监视器中得到它:a±,ö

For example if I send this chars: abcd from my android device I get this in the serial monitor: a±,ö

这段使用硬件串行(我将蓝牙连接到引脚 0 和 1)的代码运行良好:

This code that uses Hardware Serial (I link my bluetooth to pins 0 and 1) works just fine:

void setup()
{
  Serial.begin(115200);  
}

void loop()
{
  if(Serial.available())
  {
    Serial.print((char)Serial.read());  
  }
}

我什至尝试过更改波特率,但没有帮助

I even tried changing the baud rate but it didn't helped

如果我一个一个地发送字符,它工作正常,但我希望能够将它们作为字符串发送.

If I send the chars one by one it works fine but I would like to be able to send them as a string.

推荐答案

正如@hyperflexed 在评论中指出的那样,这是一个与波特率相关的问题.我不得不将波特率降至 9600 才能使其正常工作.

As pointed out by @hyperflexed in the comments this is a baudrate related issue. I had to take the baudrate as low as 9600 to make it work.

这是有效的代码:

#include "SoftwareSerial.h";
int bluetoothTx = 4;
int bluetoothRx = 2;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  Serial.begin(9600);
  delay(500);
  bluetooth.begin(115200);
  delay(500);
  bluetooth.print("$$$");
  delay(500);
  bluetooth.println("U,9600,N");
  delay(500);
  bluetooth.begin(9600);
}

void loop()
{
  if(bluetooth.available()) {
    char toSend = (char)bluetooth.read();
    Serial.print(toSend);
  }

  if(Serial.available()) {
    char toSend = (char)Serial.read();
    bluetooth.print(toSend);
  }
}

为了改变波特率,我不得不进行一些大的延迟以确保命令被执行,否则它将无法工作.

For changing the baudrate I had to put some big delays to make sure the commands are executed otherwise it won't work.

这篇关于使用软件串行一次接收多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆