This is what I believe to be the easiest way of making an idiot-proof toggle switch with a push button. Take a look!
byte ledPin = 2;
byte buttonPin = 3;
bool buttonState;
bool lastButtonState = false;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin,INPUT);
}
void loop() {
byte buttonPinRead = digitalRead(buttonPin);
if((buttonPinRead == HIGH) && (lastButtonState == false)){
buttonState = !buttonState;
lastButtonState = true;
}
if(buttonPinRead == LOW){
lastButtonState = false;
}
if(buttonState == true){
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(ledPin, LOW);
}
}
Do you have a question? If not, why post this here?
Why do you think it is "the easiest way"?
Why do you think it is "idiot-proof"?
Do you know what de-bouncing is?
Do you know what a pullup resistor is for?
When is your assignment due?
Pete
Too wordy for me
Try this
const byte ledPin = 2;
const byte buttonPin = 3;
byte currentButtonState;
byte previousButtonState;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop()
{
previousButtonState = currentButtonState;
currentButtonState = digitalRead(buttonPin);
if (currentButtonState != previousButtonState && currentButtonState == LOW)
{
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
I don't claim that it is easy or idiot proof but at least it uses consistent data type
Of course, it really needs debouncing too