首页 文章

使用Software Serial一次接收多个字符

提问于
浏览
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());  
  }
}

我甚至尝试改变波特率,但没有帮助

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

2 回答

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

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

  • 1

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

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

相关问题