如何从Unity C# Android 应用程序通过蓝牙将字符串发送到Arduino?

5
当我尝试发送字符串并且在Arduino上进行验证时,它无法通过任何if语句。device.send()是我从名为Android&Microcontrollers / Bluetooth的资产包中使用的方法,由Tech Tweaking提供。我如何将来自Unity C# Android应用程序的字符串发送到我的Arduino并通过if语句?

Unity C# 代码

device.send(System.Text.Encoding.ASCII.GetBytes("0,0"));

Arduino 代码

#include <Wire.h>
#include <Adafruit_MotorShield.h>
Adafruit_MotorShield AFMS = Adafruit_MotorShield(); 
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

#include <SoftwareSerial.h>
SoftwareSerial Bluetooth(10, 9); // RX, TX
//int LED = 13; // the on-board LED


String Data; // the data received

int LED = 12; // LED on bread board

int height;
void setup() {
  Bluetooth.begin(38400);
  Serial.begin(38400);
  Serial.println("Waiting for command...");
  Bluetooth.println("Send 1 to turn on the LED. Send 0 to turn Off");
  pinMode(LED,OUTPUT);

  AFMS.begin();  // create with the default frequency 1.6KHz


  myMotor->setSpeed(100);  // 10 rpm   

  }

void loop() {
  if (Bluetooth.available()){ //wait for data received
  Data=Bluetooth.read();
if(Data == "0,1"){  
  digitalWrite(LED,1);
  Serial.println("LED On!");
  Bluetooth.println("LED On!");
  Serial.println("Single coil steps");
   myMotor->step(500, FORWARD, SINGLE); 

   }
else if(Data == "0,0"){
   digitalWrite(LED,0);
   Serial.println("LED Off!");
   Bluetooth.println("LED Off!");
   myMotor->step(500, BACKWARD, SINGLE); 
   }
else{;}


delay(100);
}

由于蓝牙传输,您的字符串可能包含不可打印字符,例如零终止符“\0”。在检查字符串之前尝试修剪字符串或使用类似Data.Contains(“0,1”)的内容。 - Markus Deibel
当我检查Serial.print(Data)中的数据时,我只看到一堆问号,而且它们会无限制地继续产生。因此,我认为Data.Contains("0,1")不起作用。 - Christian Velez
我需要了解发送字符串的方式是否正确,或者是否需要字节数组或其他东西,然后才能继续进行Arduino部分。 - Christian Velez
根据这个答案,你可能需要发送单独的char。字符数组也可能起作用。 - Markus Deibel
1个回答

2
我已经解决了它。请注意,我正在使用一个名为Android & Microcontrollers / Bluetooth的Unity资产,这是device.send()方法的来源。
C#代码
device.send(System.Text.Encoding.ASCII.GetBytes ("0,1" + '\n'));

Arduino代码

#include <SoftwareSerial.h>
SoftwareSerial Bluetooth(10, 9); // RX, TX
String data = "";
int LED = 12; 


void setup() {
  //Bluetooth module baud rate which I set using AT commands
  Bluetooth.begin(38400);
  //Serial baud rate which I use to communicate with the Serial Monitor in the Arduino IDE
  Serial.begin(9600);
  Serial.println("Waiting for command...");

  pinMode(LED,OUTPUT);
}

void loop() {

 if(Bluetooth.available() > 0) {
     data = Bluetooth.readStringUntil('\n');

     if (data == "0,1") {
         digitalWrite(LED,1);
         Serial.println("LED ON!"); 
 }
}

你是通过试错还是找到了参考/链接来解决这个问题的? - Markus Deibel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接