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.
Hardware Connection
• 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:
1 from machine import ADC, Pin
2 from time import sleep
3
4 LED = Pin(16, Pin. OUT)
5 ROTARY_ANGLE_SENSOR = ADC(1)
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.
1 from machine import ADC, Pin
2 from time import sleep
3
4 LED - Pin(16, Pin.OUT)
5 ROTARY_ANGLE_SENSOR = ADC (1)
6 while True:
7 print(ROTARY_ANGLE_SENSOR.read_u16() )
8 if ROTARY_ANGLE_SENSOR.read_u16) > 30000:
9 LED.value(1)
10 sleep(1)
11 else:
12 LED.value (0) 13 sleep(1)
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:
1 from machine import ADC, Pin
2 from time import sleep
3
4 LED = Pin(16, Pin. OUT)
5 ROTARY_ANGLE_SENSOR = ADC(1)
6 while True:
7 print(ROTARY_ANGLE_SENSOR.read_u16 )
8 if ROTARY_ANGLE_SENSOR.read_u16) > 20000 and ROTARY_ANGLE_SENSOR.read_u16) < 40000:
9 LED.value(1)
10 sleep(1)
11 else:
12 LED.value () 13 sleep(1)