Hello. I´m new here. I´m from Spain and I don´t speak english very well, please, excuse me if I make mistakes.
I have started learning arduino and I see this code to use a switch as a toogle switch. The idea is to use pull-up resistor to get in pin 7 a HIGH value all the time and when I push the button get LOW and a moment later HIGH again. I have tried it and it works.
int LEDs=0;
int new;
int old=1;
int led=4;
void setup() {
pinMode(7,INPUT_PULLUP);
pinMode(4,OUTPUT);
}
void loop() {
new=digitalRead(7);
delay(100);
if (old==0 && new==1) {
if (LEDs==0)
{ digitalWrite(4,HIGH);
LEDs=1;}
else
{digitalWrite(4,LOW);
LEDs=0;}
}
old=new;
}
What I am missing is how the code know I pushed the button, I mean, the condition is that it has to read a LOW or 0 value in pin 7, but I don´t see where it do it. I think it something related to "old" but I can´t figure out.
I really appreciate any help or advice. For sure there will be easier wways to make this, but I really like to understand whats going on, at least, this is my way to learn, being sure that I understand everything.
You read the input pin and if it returns zero then the button is pushed. If it reads HIGH the the button is not being pressed.
What you code is doing is comparing the current state of the switch with what is was the last time you read it. If it is now HIGH (variable new) and last time it was read it was LOW (variable old) then the action of lighting the LEDS is undertaken.
BUT this results in changing the LEDs when the push button switch is released not when it is pressed.
Thank you all for your answers! The trees didn´t let me the forest.
By the way, could you recommend me a free course of arduino? I was following a guy in youtube, but he doesn´t really explain the things, it only write the code and explain the surface...