-2

Asked question master, how to coding in arduino for controlling servo using android via bluetooth? Code below does not work, servo only runs between 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);}} 
4

2 回答 2

1

您从蓝牙读取的内容是作为单个字节的 ascii 代码输入的。数字的 ascii 代码从 48 到 57。因此,如果您发送例如“10”,那么它会发送一个 49,然后是一个 48。您只是直接读取这些值。相反,您需要将读入的字符累积到缓冲区中,直到拥有所有字符,然后使用 atoi 转换为您可以使用的实数。

于 2017-06-06T20:20:34.047 回答
0
  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);
  }
}
于 2017-06-07T01:46:17.863 回答