Servo 180 deg and Bluetooth (MIT App Inventor)

The "stop function" did not work out well.. Nevertheless, I managed to achieve what I want by modifying the Block function in MIT App Inventor (thanks to someone posting the solution in MIT App Inventor forum). Basically, as long as I push the button, the app will continuously send command string to Arduino with the help of clock timer (example : every 100 ms sending the same command to Arduino via Bluetooth), causing the servo to rotate every 100 ms as a result.

I thought I might share both of my Arduino code and my MIT App Inventor Block function here for those who might need it in the future for references.

#include <Servo.h>

Servo servo;

int angle = 90; //set servo to middle position

char command;

void setup() {
servo.attach(A0); // servo pin
Serial.begin(9600);
}

void loop() {
if(Serial.available()) {
command = Serial.read();

if(command == 'a'){
constrain(angle, 0, 180);
angle = angle + 3; //rotate to one direction
Serial.print(angle);
}

if(command == 'b'){
constrain(angle, 0, 180);
angle = angle - 3; //rotate to opposing direction
Serial.print(angle);
}

if(command == 'c'){
angle = 90; //set to middle position
Serial.print(angle);
}

servo.write(angle);
delay(100);
}
}

1 Like