使用Android控制伺服器



问问题主,如何在Arduino中编码使用Androet通过蓝牙控制伺服器?下面的代码不起作用,伺服器仅在48-56之间运行。

#include <SoftwareSerial.h> #include <SoftwareSerial.h> #include <Servo.h> Servo servo; int bluetoothTx = 10; int bluetoothRx = 11; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); void setup() {   servo.attach(9);
 Serial.begin(9600); bluetooth.begin(9600);} void loop() {
//read from bluetooth and wrtite to usb serial
if(bluetooth.available()> 0 ){    int servopos = bluetooth.read();
Serial.println(servopos);
servo.write(servopos);}} 

您正在从蓝牙中读取的内容作为ASCII代码的单个字节出现。ASCII的数字代码为48至57。因此,如果您发送" 10",则它将发送49,然后发送48。您只是直接读取值。取而代之的是,您需要将阅读的字符累积到缓冲区中,直到拥有全部,然后使用ATOI转换为可以使用的实际号码。

  1. 将数据读为字符串:string input = bluetooth.readString();
  2. 然后将字符串转换为int使用:int servopos = int(input);
  3. 然后将位置写入伺服器:servo.write(servopos);

现在,根据您从Android发送的数据,您可能需要:
修剪:input = input.trim();
或限制它:servopos = constrain(servopos,0,180);

您的校正代码:

#include <SoftwareSerial.h>
#include <Servo.h>
Servo servo;
int bluetoothTx = 10;
int bluetoothRx = 11;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup() {
  servo.attach(9);
  Serial.begin(9600);
  bluetooth.begin(9600);
} 
void loop() {
  //read from bluetooth and wrtite to usb serial
  if (bluetooth.available() > 0 ) {
    String s = bluetooth.readString();
    s.trim();
    float servopos = s.toFloat();
    servopos = constrain(servopos, 0, 180);
    Serial.println("Angle: "+String(servopos));
    servo.write(servopos);
  }
}

最新更新