My code does not work i'm working on making the piezo buzz and led to light up, whenever my servo turns

#include<Servo.h>

Servo servo;
const int BUZZER_PIN = 3; // Arduino pin connected to Buzzer's pin
int led = 0;
int Servomotor = 9;

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

void loop() {

int servoState = digitalRead(Servomotor); // read new state

servo.detach();
delay(1000);
servo.attach(9);
servo.write(60);
delay(2000);

if (servoState == LOW) {
Serial.println("The button is being pressed");
digitalWrite(BUZZER_PIN, HIGH); // turn on
digitalWrite(led, HIGH); // turn on led
}
else
if (servoState == HIGH) {
Serial.println("The button is unpressed");
digitalWrite(BUZZER_PIN, LOW); // turn off
digitalWrite(led, LOW); // turn off led
}

}

This one has the LED lighting up when the servo moves. ( As long as it's not going wide open. Must be tiny bit slower so that it's regulating the servo's speed. ) You can figure out how to make the Tone go.

-jim lee

Hello jrom1

Welcome to the worldbest forum.

My recommendation is to run a servo and button tutorial to get started.

Have a nice day and enjoy coding in C++.

not clear what you're trying to do.

  • servoMotor is presumably the pin the servo is attached to. yet you read it, int servoState = digitalRead(Servomotor); and report it as a button being pressed. i don't see any button pin defined

  • not clear what the purpose if for driving the servo to the same value each iteration of loop, servo.write(60);

  • seems you expect that reading the servo pin will indicate if the servo is moving. there's no feedback from the servo. see Servo Control to see that a servo is controlled by the width of a pulse

  • seems that maybe you want to use a button to alternate between 2 servo positions and perhaps briefly turn on a buzzer and LED when the button state changes

Hi, @jrom1
Welcome to the forum.

Can you tell us in point/step form what you want your code to do?

What you have connected to your controller?

What model Arduino do you have?

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

This is not a valid way to determine if the servo is turning.

There is no way to determine if a servo is turning without opening the servo and wiring to the internal control electronics. That is beyond the scope of a beginner project.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.