(deleted)
buttonState = digitalRead(But);
if (buttonState == HIGH)
{
if (on == true)
{
on = false;
}
else
{
on = true;
}
digitalWrite(LED, on);
}
But you should look a State Change Detection
.
The state change example is good for showing how to detect the state change, but it uses an active HIGH switch which requires an external pulldown resistor. It is more accepted to use an active LOW switch which allows the use of the internal (built into the processor chip) pullup resistors. The internal pullup is enabled with the pinMode(pin, INPUT_PULLUP) statement.
Switch wiriting:
Modified state change detection code for active LOW switch to toggle built in LED:
const byte buttonPin = 4;
const byte led = 13;
boolean lastState = HIGH;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(led, OUTPUT);
}
void loop()
{
boolean state = digitalRead(buttonPin);
if(state != lastState) // state changed
{
if(state == LOW) //button pushed
{
digitalWrite(led, !digitalRead(led));
}
lastState = state; // remember state for next time
}
}
This statement:
if (on == true)
makes a professional programmer cringe. Here's why.
on == true is true if on is true.
on == true is false if on is false.
So, if(on) {} does exactly the same thing, but looks neater, and we prefer neater code. Plus, it's less typing.
The heart of your problem, though, is that you have not posted ALL of your code or a schematic. What is the mode of the pin named But? Why are you using buttons instead of switches? Do you have pullup or pulldown resistors?
(deleted)