Go Down

Topic: How do I do this. Push a button and make light turn on and LCD display status? (Read 368 times) previous topic - next topic

apples

How do I code the arduino so that if I have a light, LED, motor etc connected when I turn it on, it displays a text message on the LCD like " motor on"  "motor off" or "LED on"  " LED off " etc.

Like in this video here: http://www.youtube.com/watch?v=Ha5BfCLX7Jg

UKHeliBob

What code have you got already ?

Can you read the state of a button and turn an LED on and off ?
Can you write to the LCD ?

If not, get them working first, then the ideas can be combined.
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

apples

I can write text to the LCD.
I can turn LED on/off using a push button, but do not know code to press once and leave LED on, then press again to turn off.

This sounds like the "read state of a button" thing.



tobyb121

There are two ways that I might go about this, the first is to monitor the state of the button, and compare it to the state the last time you checked, something along the lines of:
Code: [Select]

int lastState; //set this in setup() to digitalRead(PIN)

void loop()
{
    int currentState=digitalRead(PIN)
    if(lastState!=currentState){
        //button has changed state, pressed/released, do something
    }
    lastState=currentState
}

You can also do different combinations of logic in the if statement, such as (lastState<currentState) to detect it switching to ON only.

The other way is to use interrupts, this is a bit more advanced and limits which pins you can use, but overall is a better way of writing this kind of program for an microcontroller. Interrupts monitor the state of the pin for you in the background, and when the state of the line changes it calls a function you've specified. As you can now remove all the code from your loop, interrupts allow you to do other things at the same time, they also guarantee that you will not miss the button press (this wouldn't be a problem in your case, but imagine in your loop you have some other code that takes a long time to complete, you could miss the state change). To find out how to use interrupts have a look at http://arduino.cc/en/Reference/AttachInterrupt

Go Up