Raspberry Check Return Value of Rotary Angle Sensor
First, let's learn how to use the PWM signal to output analog signal, and use the return value of the Rotary Angle Sensor to control the brightness of the LED.
Hardware Connection
In this project, the electronic hardware we need to use is as follows:
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - Rotary Angle Sensor
Plug the Pico and the Shield, use a Grove data cable to connect the LED to D18, and connect the Rotary Angle Sensor to A0
Write a Program
Just like the Pin function, the function of setting pins to PWM mode is also available in the machine library:
1 from machine import Pin, ADC, PWM
We need to use PWM to set related pins. Although each pin of Pico can be set as a PWM pin, some pins cannot be simultaneously set to PWM mode. This is because the pulse width modulator on Pico is divided into eight parts, where each part has two outputs — A and B. Pico has 26 pins, which causes some pins on Pico to share the same pulse width modulator. Therefore, when you need to set multiple PWM pins, you need to be careful to avoid conflicting pin settings.
Fortunately, we don't need to account for this problem in this program. All we have to do is set a single PWM pin:
1 ROTARY_ANGLE_SENSOR = ADC(O)
2 LED_PWM = PWM(Pin(18))
After setting the pin, use the “freq()" function to set the frequency of the PWM signal to 500:
1 LED_PWM. freq(500)
It is very important to choose the right frequency. If the frequency is very low, the flash of the LED during power on and off will be visible to the naked eye and occur intermittently. If the frequency is very high, it will cause the LED switch to fail to open and close normally, affecting the stability.
In this program, we use “read_u16()" to read the return value of the Rotary Angle Sensor, and use “duty_u16()" to output analog value to the LED. As the range of the two values is the same: 0–65535, we can directly use the return value of the Rotary Angle Sensor to control the brightness of the LED.
In the cycle, we first save the input analog value of the Rotary Angle Sensor to the variable “val", and then set the duty cycle of the PWM signal of the LED to “val". The complete program is as follows:
1 from machine import Pin, ADC, PWM
2
3 ROTARY_ANGLE_SENSOR = ADC(O)
4 LED_PWM = PWM(Pin(18))
5
6 LED_PWM. freq(500)
7
8 while True:
9 val = ROTARY_ANGLE_SENSOR.read_u16()
10 LED_PWM. duty_u16(val)
Use a USB cable to connect Pico to the computer, click the “run" button to save the program to any location, you can see the actual running effect of the program.