6_4 Toggle Motor Power and Screen Message

Toggle Motor Power and Screen Message

Code

The code in the editor below is ready to run! Plug Code Lab Mini in to your computer's USB port, make sure that your Code Lab Mini Screen Add-On (sold separately) is attached, and hit 'Upload Your Code!' to see what it does. Change something in the code, like a delay or pin number. Try to add something new to the program - it's yours to tinker with! You can always press the 'Restore' button to return the code to the working example.

If you haven't set up your Code Lab Mini Screen Add-On yet, visit Chapter 0 to watch a video showing you how to do that.


/* Create an on button that switches on the motor pressed, then turns it off when the button is pressed again. Show the status of the motor on the screen. */ #include "CLMiniScreen.h" //A code library enables new functions to be used with the screen CLMiniScreen lcd; //the library name is followed by the 'name' you give the LCD screen. Here it is 'lcd' int pressCount = 0; //An integer (whole number) variable to keep track of how many times the button is pressed void setup(){ pinMode(3,OUTPUT); //motor pinMode(4,INPUT_PULLUP); //button lcd.begin(); //.begin() 'sets up' the screen } void loop(){ if(digitalRead(4)==LOW){ //if button 4 is pressed pressCount++; //add one to a variable. Now pressCount = its former value + 1 lcd.clear(); //clear off any message on the screen when the pressCount variable changes delay(250); //delay to release your finger from the button without counting multiple presses } if(pressCount == 1){ //if pressCount equals 1.. lcd.print("Motor On"); //Show the "on" message lcd.setCursor(0,0); //Set the cursor to the top-left corner so the message overwrites in the same location digitalWrite(3,HIGH); //turn on the motor } else{ //if pressCount is anything other than 1... lcd.print("Motor Off"); //Show the "off" lcd.setCursor(0,0); //Set the cursor to the top-left corner so the message overwrites in the same location digitalWrite(3,LOW); //turn off the motor pressCount = 0; //reset the count to 0 before the loop starts again } } // (c) 2023 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Walkthrough Video

Watch the video for a line-by-line explanation of how the example program works. Then you'll be ready to make some changes of your own!

Challenges

Coming Soon!