-1

I'm newbie to coding and for the last few days, I've been trying to make a servo rotate 180 degrees by typing 1 on an app on my phone connected to an HC 05 Bluetooth module. When I type one the servo rotates 180 degrees when I type 0 the servo rotates 180 degrees the other way. This is what I've done so far by combining bits of different codes. Can you please help resolve what's wrong? (I really don't get it) Here's the code :

 #include <Servo.h>
 char data = 0; 
 int pos = 0;      
 Servo servo;

 void setup() 
 {
 servo.attach(9);
 }

 void loop(){
 data = Serial.read();      
 Serial.print(data);     
 Serial.print("\n");         
 if(data == '1')            
 digitalWrite(pos = 0; pos <= 180; pos += 1) {
 servo.write(pos);              
 delay(15); 

else if(data == '0')
digitalWrite(pos = 180; pos >= 0; pos -= 1) { 
servo.write(pos);              
delay(15);
}
}

Thank you for your time!

PS: please forgive the spelling mistakes

  • Vote to close. If you need help, you're supposed to US what's wrong. This looks like the same code you posted before. – TomServo Mar 23 '20 at 23:38

1 Answers1

0

You probably want something like this:

#include <Servo.h>

int data = 0;
int pos = 0;

int degrees = 30;
//int degrees = 180;

Servo servo;

void setup()
{
    Serial.begin(9600);
    servo.attach(9);
}

void loop(){

    if (Serial.available() > 0) {

        data = Serial.read();
        Serial.println(data);

        if(data == '1') {
            for (pos = 0; pos <= degrees; pos++) {
                servo.write(pos);
                delay(15);
            }
        }
        else if(data == '0') {
            for (pos = degrees; pos >= 0; pos--) {
                servo.write(pos);
                delay(15);
            }
        }
    }
}

Try with 30 degrees first, since not all servos support 180 degrees.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46