0

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

我的代码:

#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±,ö

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

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

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

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

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

4

2 回答 2

0

您可以尝试在打印之前缓冲字符串。

看下面的答案:Convert serial.read() into a useable string using Arduino?

于 2014-10-08T07:00:56.140 回答
0

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

这是有效的代码:

#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);
  }
}

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

于 2014-10-09T07:21:32.113 回答