使用 android 控制伺服
control servo using android
请教题主,如何在arduino中编码,通过蓝牙使用android控制舵机?下面的代码不起作用,伺服只在 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 码形式传入的。数字 运行 从 48 到 57 的 ascii 代码。因此,如果您发送例如“10”,那么它会发送 49,然后发送 48。您只是直接读取值。相反,您需要将读取的字符累积到缓冲区中,直到拥有所有字符,然后使用 atoi 转换为可以使用的实数。
- 使用以下方法将数据读取为字符串:
string input = bluetooth.readString();
- 然后使用以下方法将字符串转换为整数:
int servopos = int(input);
- 然后将位置写入舵机:
servo.write(servopos);
现在,根据您从 android 发送的数据,您可能需要:
Trim它: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);
}
}
请教题主,如何在arduino中编码,通过蓝牙使用android控制舵机?下面的代码不起作用,伺服只在 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 码形式传入的。数字 运行 从 48 到 57 的 ascii 代码。因此,如果您发送例如“10”,那么它会发送 49,然后发送 48。您只是直接读取值。相反,您需要将读取的字符累积到缓冲区中,直到拥有所有字符,然后使用 atoi 转换为可以使用的实数。
- 使用以下方法将数据读取为字符串:
string input = bluetooth.readString();
- 然后使用以下方法将字符串转换为整数:
int servopos = int(input);
- 然后将位置写入舵机:
servo.write(servopos);
现在,根据您从 android 发送的数据,您可能需要:
Trim它: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);
}
}