8_8 Tilt LED Bulb Control

Tilt LED Bulb Control

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 Sensor Trio 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 Sensor Trio Add-On yet, visit Chapter 0 to watch a video showing you how to do that.


/* Tilt LED Bulb Control: Tilt Code Lab Mini + Sensor Trio Add-On to determine which LED is lit up. Tilt right for higher pin number LEDs, left for lower pin number LEDs */ int LED = 7; //variable named LED starting just below the pin number of the LEDs void setup() { //All of Code Lab Mini's LEDs pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,OUTPUT); pinMode(12,OUTPUT); pinMode(A4,INPUT_PULLUP);//Left Tilt Sensor pinMode(A5,INPUT_PULLUP);//Right Tilt Sensor } void loop() { //Turn off all of the LEDs 1st so you're starting with a blank Code Lab Mini digitalWrite(8,LOW); digitalWrite(9,LOW); digitalWrite(10,LOW); digitalWrite(11,LOW); digitalWrite(12,LOW); digitalWrite(LED,HIGH);//Use the variable to decide which LED is turned on if(digitalRead(A5)==LOW){ //If Code Lab Mini is tilted right... LED++; //increase the value of LED by 1 delay(200); //Pause for 200 milliseconds so the tilt doesn't count as multiple changes if(LED >= 12){ //if LED reaches or goes higher than the maximum pin number of 12 LED = 12; //keep the LED at 12 } } else if(digitalRead(A4)==LOW){ //If Code Lab Mini is tilted left... LED--; //decrease the variable by 1 delay(200); //Pause for 200 milliseconds so the tilt doesn't count as multiple changes if(LED <= 8){ //if LED variable goes below the lowest pin number that has an LED on it LED = 8; //keep the LED at 8 } } } // (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!