4. case 01 Light Controller#

4.1. Our Goal#

Use basic kit to control light.

4.2. Material#

1 x basic kit

4.3. Background Knowledge#

4.4. Hardware Connection#

Connect the crash sensor to P1 port on basic:bit, connect an LED module to P2 and connect a potentiometer module to P0, just like the picture showed below.

../../_images/27lfueI.jpg

../../_images/Fmowi1n.jpg

Note: The switch on basic:bit must be shifted to P0 end, or the buzzer onboard will be connected to P0 port.

4.5. Software#

Microsoft Makecode

4.6. Programming#

Step 1#

When start, set a pull-up to P1 port to initialize the crash sensor.

../../_images/pixzSbA.png

Step 2#

Read the return value of P1 port in digital way, and assign it to variable button to obtain the status of crash sensor. Judge if button equals to 1. If button is equal to 1, it means the crash sensor is pressed down and we have to delay time and debounce. Judge the variable light. If the value of light is 0, it means the light is turned off, and we set light to 1. Or else, we set it to 0.

../../_images/TbOZTKM.png

Step 3#

Judge the variable light. If light is equal to 1, it means the light is turned on. Then read the value of P0 port(i.e. the return value of the potentiometer) in analog way, while writing it to P2 port with the same method. Now, this value becomes the parameter of LED module. If light isn’t equal to 1, it means the light is turned off. Then analog write P2 to 0 and turn off LED.

../../_images/0ivAACf.png

Program#

The link of the whole program: https://makecode.microbit.org/_DL87DfRpaL7z

You can also check the program from the page below.

4.7. Result#

Press the crash sensor for once, the LED module is turned on; press again, then it is turned off. When the LED is turned on, we can adjust the brightness of LED by rotating the knob on the potentiometer.

4.8. Think#

Why we need to delay time and debounce ?

4.9. FAQ#

4.10. Relative Readings#