Hi,
I've written a simple sketch with and an If statement and two conditions based on whether a button is pressed. The problem is, nothing happens when I press the button - if the button is pressed when I start the sketch, it stays in this state no matter if I release the button, and similarly if the button is open, it will continue registering it as open even if I press the button. I've been on this for two days and feel I must be missing something very simple as I can't for the life of me work out why it's not looping correctly. Feels like some stupid syntax error, but I just can't see what it is. Any suggestions gratefully received - I feel like I've tried everything google has to offer! Code below - realise it's a but ugly, but I'm pretty new to all this. Thanks, Paul
#include "pitches.h"
#include <Servo.h>
int melody[] = {
NOTE_C5,NOTE_C5,NOTE_C5 };
int duration = 400; // 400 miliseconds
Servo myservo; // create servo object to control a servo
int pos = 0;
int wait = (3);
int servPosition = 10;
int servDelay = 1;
int ledPin = 2 ;
int pushButton = 13;
int buttonState = digitalRead(pushButton);
void setup() {
myservo.attach(10); // attaches the servo on pin 10 to the servo object
pinMode (1,OUTPUT);
pinMode (2,OUTPUT);
pinMode (3,OUTPUT);
pinMode (4,OUTPUT);
pinMode (5,OUTPUT);
pinMode (pushButton,INPUT);
Serial.begin(9600);
}
void loop () {
if (buttonState == HIGH)
{
myservo.write(servPosition);
for (int thisNote = 0; thisNote < 3; thisNote++) {
tone(8, melody[thisNote], duration);
digitalWrite (ledPin,HIGH);
delay(800);
ledPin++;}
tone (8,NOTE_C6, 800);
myservo.write(300);
digitalWrite (2,LOW);
digitalWrite (3,LOW);
digitalWrite (4,LOW);
digitalWrite (5,HIGH);
delay(5000);
digitalWrite (2,LOW);
digitalWrite (3,LOW);
digitalWrite (4,LOW);
digitalWrite (5,LOW);
ledPin=2;
}
else {digitalWrite (5,HIGH);
delay(2000);
}
}