Raspberry Display Rotary Angle Sensor Reading with LCD
In addition to displaying the characters we have written, the LCD can also display the values returned by other sensors.
Hardware Connection
In this project, the electronic hardware we need to use is as follows:
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - 16 x 2 LCD
• Grove - Rotary Angle Sensor
Plug the Pico and the Shield, use a Grove data cable to connect the LCD to I2C1, and connect the Rotary Angle Sensor to A0.
Write a Program
In Lesson 6, we learned how to use ADC to read the Rotary Angle Sensor value. Can we use “d.print()" to display the reading directly? Let's try the following program first:
1 from lcd160
2 import LCD1602 2 from machine import I2C, Pin, ADC
3 from utime import sleep
4
5 ROTARY_ANGLE_SENSOR = ADC(O)
6 i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000)
7 d = LCD1602(i2c, 2, 16)
8 d.display()
9
10 while True:
11
12 sleep (1)
13 d.clear()
14 d.setCursor(0, 0)
15 d.print(ROTARY_ANGLE_SENSOR.read_u16())
16 sleep(1)
Running the program, Thonny tells us that there is an error in the program, and the error is on line 14. The error message is:
TypeError: ‘int' object isn't iterable
This means that the parameter we pass into the print() function is not of the type it can execute.
·Note·
Data Type
In programming, due to the different storage capacities of various data, different types of data need to be matched with the different memory spaces that they are stored in. Therefore, it is important to know about different data types. Every time we create a variable in Python, we are requesting a storage location from memory and storing a certain piece of data in that memory space. In Python, we divide all kinds of data into six basic types:
• Number
• String
• List
• Tuple
• Set
• Dictionary
In “print()", we specify in the lcd1602 function library that it can only input parameters whose data type is String, while ROTARY_ANGLE_SENSOR.read_u16() returns integer “int" of Number. If we want to use the print() function to output the value of the Rotary Angle Sensor, we need to convert Number data into String data. There is such a function in Python built-in functions: str(), which can convert other data types into String. Then we can use print() to output the value of the Rotary Angle Sensor.
The revised program is as follows:
1 from lcd1602 import LCD1602
2 from machine import I2C, Pin, ADC, PWM
3 from utime import sleep
4
5 ROTARY_ANGLE_SENSOR = ADC(0)
6 i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000)
7 d = LCD1602(i2c, 2, 16)
8 d.display ( )
9
10 while True:
11 sleep (1)
12 d.clear()
13 d.setCursor(0, 0)
14 d.print(str(ROTARY_ANGLE_SENSOR.read_u16()))
15 sleep(1)
Use a USB cable to connect Pico to the computer, click the “run" button to save the program to any location, rotate the Rotary Angle Sensor, you can see the actual running effect of the program.