I got my first arduino on Monday and have been learning ever since. I bought the MAKE "Getting Started With Arduino" book and have completed most of the exercises.
I have written a sketch which fades a single LED in and out, simple enough and it works. I have since combined this with a switch and can get it to switch on fine. However I cannot understand the correct logic to successfully see if the switch has been turned off. My sketch code is as follows:
#define LED 9
#define BUTTON 7
int i = 0;
int state = 0;
int val = 0;
int old_val = 0;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop()
{
val = digitalRead(BUTTON);
if ((val == HIGH) && (old_val == LOW))
{
state = 1 - state;
delay(10);
}
if (state == 1)
{
for (i = 0; i < 255; i++)
{
analogWrite(LED, i);
delay(10);
}
for (i = 255; i > 0; i--)
{
analogWrite(LED, i);
delay(10);
}
}
}
Any help on the correct code would be most appreciated as I really am stuck.
I have this working now. I just got confused about the state of a button when it is pressed and not pressed. Needed to include a function during the fading to check whether the button had been pressed.
Here is my code as it is now working:
#define LED 9
#define BUTTON 7
int i = 0;
int state = 0;
int val = 0;
//A function to see if the button has been pressed, returns an int
int CheckButton()
{
return(digitalRead(BUTTON) == HIGH);
}
void setup()
{
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop()
{
//Check to see if the button has been pressed.
if(digitalRead(BUTTON) == HIGH)
{
//While the digital read statement is true (high) continue the loop
while(digitalRead(BUTTON) == HIGH)
continue;
//state is true as state is 0 and if we do !state then it is 1
state = !state;
}
//If state is 1 which it will be as we wont make it 0. If we dont use state then we have to keep pressing the button
if(state)
{
for (i = 0; i < 255; i++)
{
//If checkbutton is true it means the button has been pressed
if(CheckButton())
{
//Turn off the LED and break the loop
analogWrite(LED, 0);
break;
}
//Continue fading
analogWrite(LED, i);
delay(10);
}
for (i = 255; i > 0; i--)
{
//If the checkbutton is true it means the button has been pressed
if(CheckButton())
{
//Turn off the LED and break the loop
analogWrite(LED, 0);
break;
}
//Continue fading
analogWrite(LED, i);
delay(10);
}
}
}