control servo using android

时光总嘲笑我的痴心妄想 提交于 2019-12-13 09:36:12

问题


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);}} 

回答1:


  1. Read the data as string using: string input = bluetooth.readString();
  2. Then convert string to int using: int servopos = int(input);
  3. Then write the position to the servo:servo.write(servopos);

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);

Your corrected code:

#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);
  }
}



回答2:


What you are reading from the bluetooth is coming in as individual bytes of ascii code. The ascii codes for digits run from 48 to 57. So if you send for example "10" then it sends a 49 and then a 48. You are just reading the values directly. Instead you need to accumulate the characters you read into a buffer until you have them all and then use atoi to convert to a real number you can use.



来源:https://stackoverflow.com/questions/44381882/control-servo-using-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!