使用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:
int servepos = int(input);
- 然后将位置写入舵机:
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屋!
查看全文