In this lesson, we will use a touch switch and an RGB LED module to make a touch color light.
Create a new project, then click on the Simulation icon on the left side of the page to enter the Simulation page.
Connect the touch switch to D0; RGB LED to P0, P1 and P2 respectively. When you use the touch switch, the state of the touch switch will be opposite to the previous state. If the state is 0 at this time, after the touch, the state will change to 1.
Click the Create variable button in the Variables category.
Input the variable name: lastState.
Create another variable, currentState, in the same way.
Drag a set currentState to block from the Variables category into the Start block, and select lastState from the drop-down menu.
Then, put the Touch switch block under the Sensor Kit category to the area behind the set lastState to block to assign the value of Touch switch to the variable lastState.
The variable currentState is used to record the real-time read value of the touch switch.
Click on Logic category and drag an if do block to below the set currentState to block.
Connect a Comparison Operator ( = ) block after the if and change the equal sign to the inequality sign.
When we use the touch switch, the state of the touch switch will be opposite to the previous state. So use the if do block to set a condition that whether lastState is equal to currentState. The lastState and currentState blocks are from the Variables category.
Add the RGB module block under the Sensor Kit category into the do block, and add a random colour block under the Colour category to the area after the set colour to block so as to make the RGB LED module display the random colour.
Assign the value of currentState to lastState so that the next time when the touch switch is used, the condition judgment can be triggered.
Go to the Simulation page and click on the Run button, then click on the Touch switch. If the RGB light changes colors with touching, it means that there is no problem with the code. Now click Flash to compile and download the code.