Raspberry Turn an LED On and Off with a Rotary Angle Sensor
First, let's try to write a simple program to turn on the LED when the Rotary Angle Sensor rotates through the center point.
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - LED Pack
• Grove - Rotary Angle Sensor
Plug the Pico and the Shield, use a Grove data cable to connect the LED to D16, and connect the Rotary Angle Sensor to A1.
Write a Program
Similarly, at the beginning of the program, import the functions that need to be used in the machine library, and define pins:
Then use the “if" statement to judge the condition. When the return value of the Rotary Angle Sensor is greater than 30000, the LED turns on; otherwise, the LED turns off.
In the "if" statement, we use the comparison operator ">" to compare the relationship between the analog value read from the Rotary Angle Sensor and the 30000 threshold.
You can test the effect of the program by changing the comparison operator used in the "if" statement. Note that if we use "==" to write expressions in the program, it is difficult to achieve the effect we want. This is because the value range of analog value is wide. When we rotate the knob, it is difficult to turn it to a specific value to fulfill the condition of the expression.
In addition to using the comparison operator to complete a single expression statement, we can also use the logical operator to concatenate two independent statements to control the LED to light only within a specific value range: