使用android控制伺服 [英] control servo using android
本文介绍了使用android控制伺服的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问问题大师,如何在arduino中编码以通过蓝牙使用android控制伺服器?以下代码无效,伺服系统只能在48-56之间运行.
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);}}
推荐答案
- 使用以下命令以字符串形式读取数据:
string input = bluetooth.readString();
- 然后使用
int servopos = int(input);
将字符串转换为int
- 然后将位置写入伺服器:
servo.write(servopos);
- Read the data as string using:
string input = bluetooth.readString();
- Then convert string to int using:
int servopos = int(input);
- Then write the position to the servo:
servo.write(servopos);
现在,根据您从android发送的数据,您可能需要:
修剪:input = input.trim();
或限制它:servopos = constrain(servopos,0,180);
Now depending on the data you send from android, you could need to :
Trim it: input = input.trim();
Or constrain it : 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);
}
}
这篇关于使用android控制伺服的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文