I need help writing a code for an arduino and servo motor. I need the servo moto
ID: 3813115 • Letter: I
Question
I need help writing a code for an arduino and servo motor. I need the servo motor to rotate 180* after pressing a button on my laptop and then I need the servo motor to go back to 0* after pressing a button on my laptop again. I found this code but it doesn't work and I don't think it goes from 180* to 0* on command.
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Explanation / Answer
#include <Servo.h>
Servo myservo;
int pos = 0;
int pushButton = 2;
int LED = 13;
int state = HIGH;
int readibg;
int previous = LOW;
long time = 0;
long debounce =200;
void setup()
{
{
pinMode(pushButton, INPUT);
pinMode(LED, OUTPUT);
}
{
myservo.attach(9);
}{
Serial.begin(9600);
pinMode(pushButton,INPUT);
}
}
void loop()
{
{
reading = digitalRead(pushButton);
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
if (state == HIGH)
state = LOW;
else
state = HIGH;
time = millis();
}
digitalWrite(outPin, state);
previous = reading;
}
{
int buttonState = digitalRead (pushButton);
Serial.println(buttonState);
}
for(pos = 0; pos < 180; pos +=1)
{
myservo.write(pos);
}
for(pos = 180; pos >= 1; pos -=1)
{
myservo.write(pos); }
}
}