0% found this document useful (0 votes)
9 views48 pages

Measuring Temperature Using A Digital Sensor

The document provides detailed specifications and usage instructions for the DS18B20 digital temperature sensor and the HC-SR04 ultrasonic rangefinder. It includes programming examples for measuring temperature and distance using these sensors with a Raspberry Pi, along with explanations of the underlying principles. Additionally, it discusses the setup and connection requirements for both sensors, as well as how to log data to a USB flash drive.

Uploaded by

outoftime1001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views48 pages

Measuring Temperature Using A Digital Sensor

The document provides detailed specifications and usage instructions for the DS18B20 digital temperature sensor and the HC-SR04 ultrasonic rangefinder. It includes programming examples for measuring temperature and distance using these sensors with a Raspberry Pi, along with explanations of the underlying principles. Additionally, it discusses the setup and connection requirements for both sensors, as well as how to log data to a USB flash drive.

Uploaded by

outoftime1001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 4

Measuring Temperature Using a Digital Sensor


DS18B20 Sensor Specifications
• Programmable Digital Temperature Sensor
• Communicates using 1-Wire method
• Operating voltage: 3V to 5V
• Temperature Range: -55°C to +125°C
• Accuracy: ±0.5°C
• Output Resolution: 9-bit to 12-bit (programmable)
• Unique 64-bit address enables multiplexing
• Conversion time: 750ms at 12-bit
• Programmable alarm options
• Available as To-92, SOP and even as a waterproof sensor
• [Link]
• One of the biggest advantages of DS18B20 is that multiple DS18B20s can coexist on the same 1-Wire bus. As each DS18B20 has a
unique 64-bit serial code burned in at the factory, it’s easier to differentiate them from one another.
• This feature can be a huge advantage when you want to control many DS18B20s distributed over a large area
SENSOR CONNECTION
Measure temperature using an accurate digital
sensor
• Use the DS18B20 digital temperature sensor. This
device is more accurate than the TMP36 and uses a
one-wire digital interface, so it doesn’t require an
ADC chip.
• Although called one-wire, this just refers to the data
pin. You do need at least one other wire to connect
to a one-wire device.
Component required:
• Breadboard and jumper wires
• DS18B20 temperature sensor
• 4.7kΩ resistor
PROGRAM When the program is run, it will report the temperature once a second in both degrees
Celsius and Fahrenheit:
$ python temp_DS18B20.py
import os, glob, time temp C=25.187000 temp F=77.336600
temp C=25.125000 temp F=77.225000
[Link]('modprobe w1-gpio') temp C=25.062000 temp F=77.111600
temp C=26.312000 temp F=79.361600
[Link]('modprobe w1-therm') temp C=27.875000 temp F=82.175000
temp C=28.875000 temp F=83.975000
base_dir = '/sys/bus/w1/devices/'
device_folder = [Link](base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
• At first sight, the program looks a little odd. The interface to the DS18B20 uses
def read_temp_raw(): a file like interface.
f = open(device_file, 'r') • The file interface for the device will always be in the folder
lines = [Link]() /sys/bus/w1/devices/ and the name of the file path will start with 28, but the rest
[Link]()
return lines of the file path will be different for each sensor.
def read_temp(): • The code assumes that there will only be one sensor and finds the first folder
lines = read_temp_raw() starting with 28. Within that folder will be a file called w1_slave, which is
while lines[0].strip()[-3:] != 'YES':
[Link](0.2)
opened and read to find the temperature.
lines = read_temp_raw() • The sensor actually returns strings of text like this:
equals_pos = lines[1].find('t=') • 81 01 4b 46 7f ff 0f 10 71 : crc=71 YES
if equals_pos != -1: • 81 01 4b 46 7f ff 0f 10 71 t=24062
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0 • The remainder of the code extracts the temperature part of this message. This
temp_f = temp_c * 9.0 / 5.0 + 32.0 appears after t= and is the temperature in one-thousandths of a degree Celsius.
return temp_c, temp_f • The read_temp function calculates the temperature in degrees Fahrenheit and
while True:
returns both.
print("temp C=%f\ttemp F=%f" % read_temp())
[Link](1) • Besides the basic chip version of the DS18B20, you can also buy a version
encapsulated in a rugged and waterproof probe.
import os, glob, time
os → used to run system commands

glob → used to find files matching a pattern

time → used for delays (sleep())


[Link]('modprobe w1-gpio')
[Link]('modprobe w1-therm')
These commands load kernel modules that enable the Raspberry Pi to communicate using the 1-Wire protocol.

w1-gpio – allows using GPIO pins for 1-Wire communication

w1-therm – handles temperature sensors like DS18B20


base_dir = '/sys/bus/w1/devices/'
device_folder = [Link](base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
The DS18B20 sensor is automatically detected and listed in the directory /sys/bus/w1/devices/.

Each sensor has a unique address starting with “28”.

The code finds the first sensor folder (28*) and then opens the data file w1_slave, which contains the temperature
readings.
Opens the def read_temp_raw():
f = open(device_file, 'r')
lines = [Link]()
[Link]()
return lines
file containing the raw data from the sensor.
Example content of /w1_slave:
r

9e 01 4b 46 7f ff 0c 10 5e : crc=5e YES
9e 01 4b 46 7f ff 0c 10 5e t=25625
The first line ends with “YES” if the reading is valid.

The second line has t=25625, which means 25.625°C.


def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
[Link](0.2)
lines = read_temp_raw()
Keeps reading until a valid temperature line is received (ending with “YES”).
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f
Extracts the numeric value after “t=”.

Divides by 1000 to convert from millidegrees to °C.

Converts °C to °F.
while True:
print("temp C=%f\ttemp F=%f" % read_temp())
[Link](1)
Continuously prints the temperature every 1 second.

Example output:

temp C=25.625000 temp F=78.125000


[Link]
DS18B20 WITH RASPBERRY PI
1 WIRE SUPPORT
• The Raspbian distribution includes support for the DS18B20 1-wire
temperature sensor. These sensors come in a small three pin package
like a transistor and are accurate digital devices.
SR-04 rangefinder
• Ultrasonic range finders are fun little sensors that can measure
distance.
• You can use them to find the distance to an object, or to detect when
something is near the sensor like a motion detector.
• They’re ideal for projects involving navigation, object avoidance, and
home security.
• they use sound to measure distance
• can measure distances from 2 cm up to 400 cm with an accuracy of ±3
mm.
WORKING PRINCIPLE
• Ultrasonic range finders measure distance by emitting a pulse of
ultrasonic sound that travels through the air until it hits an object.
When that pulse of sound hits an object, it’s reflected off the object
and travels back to the ultrasonic range finder. The ultrasonic range
finder measures how long it takes the sound pulse to travel in its round
trip journey from the sensor and back. It then sends a signal to the
MICROCONTROLLER with information about how long it took for
the sonic pulse to [Link] the time it takes the ultrasonic pulse
to travel back and forth to the object, and also knowing the speed of
sound, the MICROCONTROLLER can calculate the distance to the
object. The formula relating the speed of sound, distance, and time
traveled is:
ABOUT SENSOR
• an IC behind the transmitting transducer labelled
MAX3232. This is the IC that controls the
transmitting transducer. Behind the receiving
transducer is an IC labelled LM324. This is a quad
Op-Amp that amplifies the signal generated by the
receiving transducer
The HC-SR04 ultrasonic range finder has four pins:
• Vcc – supplies the power to generate the ultrasonic
pulses
• GND – connected to ground
• Trig – where the microcontroller sends the signal
to start the ultrasonic pulse
• Echo – where the ultrasonic range finder sends the
information about the duration of the trip taken by
the ultrasonic pulse to the microcontroller
Working with sensor
• To initiate a distance measurement, we need to send a 5V high signal to the Trig
pin for at least 10 µs.
• When the module receives this signal, it will emit 8 pulses of ultrasonic sound at a
frequency of 40 KHz from the transmitting transducer.
• Then it waits and listens at the receiving transducer for the reflected signal. If an
object is within range, the 8 pulses will be reflected back to the sensor. When the
pulse hits the receiving transducer, the Echo pin outputs a high voltage signal.
• The length of this high voltage signal is equal to the total time the 8 pulses take to
travel from the transmitting transducer and back to the receiving transducer.
However, we only want to measure the distance to the object, and not the distance
of the path the sound pulse took. Therefore, we divide that time in half to get the
time variable in the d = s x t equation above. Since we already know the the speed
of sound (s), we can solve the equation for distance.
Measuring Distance
• measure distance using an ultrasonic rangefinder.
• Use a low cost SR-04 rangefinder. These devices
need two GPIO pins, one to trigger the
• pulse of ultrasound and the other to monitor how
long it takes for the echo to return.
• To make this recipe, you will need:
• Breadboard and jumper wires
• SR-04 rangefinder
• 470Ω resistor
• 270Ω resistor
• The resistors are necessary to reduce the echo
output of the rangefinder from 5V to 3.3V
Program
• import [Link] as GPIO
• import time • def get_distance():
• trigger_pin = 18 • send_trigger_pulse()
• echo_pin = 23 • wait_for_echo(True, 10000)
• [Link]([Link]) • start = [Link]()
• [Link](trigger_pin, [Link]) • wait_for_echo(False, 10000)
• [Link](echo_pin, [Link]) • finish = [Link]()
• def send_trigger_pulse(): • pulse_len = finish - start
• [Link](trigger_pin, True) • distance_cm = pulse_len / 0.000058
• [Link](0.0001) • distance_in = distance_cm / 2.5
• [Link](trigger_pin, False) • return (distance_cm, distance_in)
• def wait_for_echo(value, timeout): • while True:
• count = timeout • print("cm=%f\tinches=%f" % get_distance())
• while [Link](echo_pin) != value and • [Link](1)
count > 0:
• count = count - 1
•trigger_pin sends a short pulse to start the ultrasonic measurement.
•echo_pin listens for the returning sound wave.
•send_trigger_pulse() sends a 10 µs pulse to initiate measurement.
•wait_for_echo() waits until the echo pin changes state (either HIGH or LOW)
or until the timeout expires.
• def get_distance():
• Defines a function to measure and return the • distance_cm = pulse_len / 0.000058
distance in centimeters (cm) and inches (in). • Converts the pulse duration to centimeters.
• Sound speed ≈ 343 m/s = 0.0343 cm/µs
• send_trigger_pulse() • The signal travels to the object and back, so
• Sends a short 10 µs pulse to the trigger pin to start divide by 2 → ≈ 0.01715 cm/µs
the ultrasonic burst.
• wait_for_echo(True, 10000)
• 1/0.000058≈17,241, which fits the scaling
• start = [Link]() factor for cm.
• Waits until the echo pin goes HIGH (sound pulse
sent and traveling).
• When it goes HIGH, it records the start time. • distance_in = distance_cm / 2.5
• wait_for_echo(False, 10000) • Converts centimeters to inches (since 1 inch ≈
2.54 cm).
• finish = [Link]()
• Waits until the echo pin goes LOW (sound pulse
returned).
• When it goes LOW, it records the finish time.
• pulse_len = finish - start
• Calculates the duration that the echo pin was HIGH
— i.e., how long it took for the ultrasonic pulse to
go to the object and come back.
code
Program explanation
• We can then calculate the distance using the time
taken for the echo pulse and the speed of sound.
• the trig (trigger) input to the rangefinder is
connected to a GPIO output, and the echo output of • The wait_for_echo function waits until the echo pin
the rangefinder is connected to a GPIO input on the either goes high or low, depending on its first
Raspberry Pi after having its voltage range lowered argument. Its second argument is used to provide a
from 5V to a safe 3.3V. timeout so that if for any reason, the echo pin does
not change to the state being waited for, the loop
• Figure 12-18 shows an oscilloscope trace of the won’t hang indefinitely.
sensor in action. The top (red) trace is connected to
trig and the bottom (yellow) trace is connected to
echo. You can see that first the trig pin is taken high
for a short pulse. There is then a short delay before
the echo pin goes high. This then stays high for a
period that is proportional to the distance from the
sensor.
• The code for this sensor first generates a trigger
pulse (using the function send_trig ger_pulse). It
must wait until the echo pin goes high and then
times how long the echo pin stays high.
Program output
• When the program is run, it will report the distance in both centimeters and inches, once
per second.
• Use your hand or some other obstacle to change the reading.
• sudo python [Link]
• cm=154.741879 inches=61.896752
• cm=155.670889 inches=62.268356
• cm=154.865199 inches=61.946080
• cm=12.948595 inches=5.179438
• cm=14.087249 inches=5.634900
• cm=13.741954 inches=5.496781
• cm=20.775302 inches=8.310121
• cm=20.224473 inches=8.089789
• [Link]
• Sr-04 with raspberry pi
• [Link]
range-sensor-on-the-raspberry-pi
• Reference for sr04
Logging to a USB Flash Drive
• You want to log data measured with a sensor onto a USB flash drive.
• Write a Python program that writes the data to a file on a USB flash
drive. By writing the file in CSV (comma-separated values), you can
import directly into a spreadsheet, including Gnumeric on the
Raspberry
• The example program will log temperature readings recorded from a
DS18B20.
Program
• def read_temp():
• import os, glob, time, datetime
• lines = read_temp_raw()
• log_period = 600 # seconds
• while lines[0].strip()[-3:] != 'YES':
• logging_folder = [Link]('/media/*')[0]
• [Link](0.2)
• dt = [Link]()
• lines = read_temp_raw()
• file_name = "temp_log_{:%Y_%m_%d}.csv".format(dt)
• equals_pos = lines[1].find('t=')
• logging_file = logging_folder + '/' + file_name
• if equals_pos != -1:
• [Link]('modprobe w1-gpio')
• temp_string = lines[1][equals_pos+2:]
• [Link]('modprobe w1-therm')
• temp_c = float(temp_string) / 1000.0
• base_dir = '/sys/bus/w1/devices/’
• temp_f = temp_c * 9.0 / 5.0 + 32.0
• device_folder = [Link](base_dir + '28*')[0]
• return temp_c, temp_f
• device_file = device_folder + '/w1_slave'
• def log_temp():
• def read_temp_raw():
• temp_c, temp_f = read_temp()
• f = open(device_file, 'r')
• dt = [Link]()
• lines = [Link]()
• f = open(logging_file, 'a')
• [Link]()
• [Link]('\n"{:%H:%M:%S}",'.format(dt))
• return lines
• [Link](str(temp_c))
• [Link]()
• import os, glob, time, datetime
• os → used to run system commands and
interact with the filesystem • 4. Create a Log File Name
• glob → used to search for files or directories • dt = [Link]()
that match a pattern (like • file_name =
/sys/bus/w1/devices/28*) "temp_log_{:%Y_%m_%d}.csv".format(dt)
• time → used for delays or time intervals • logging_file = logging_folder + '/' + file_name
• datetime → used to timestamp and name log • Gets the current date and time.
files
• Creates a file named like:
2. Set Logging Interval
• temp_log_2025_10_07.csv
• log_period = 600 # seconds
• Full path example:
• The program logs data every 600 seconds = 10
minutes. • /media/pi/temp_log_2025_10_07.csv

3. Set the Logging Folder 5. Load 1-Wire Kernel Modules


• logging_folder = [Link]('/media/*')[0] • [Link]('modprobe w1-gpio')
• Finds the first mounted media device (like a • [Link]('modprobe w1-therm')
USB drive). • These commands enable the Raspberry Pi’s 1-
• /media/* typically contains mounted external Wire interface.
storage. • w1-gpio: enables GPIO for 1-Wire
• [0] selects the first found folder. communication.
• w1-therm: enables temperature sensor support.
• 7. Function to Read Raw Temperature Data
• def read_temp_raw():
• f = open(device_file, 'r')
• 6. Locate the Sensor’s Device File
• base_dir = '/sys/bus/w1/devices/' • lines = [Link]()
• device_folder = [Link](base_dir + '28*')[0] • [Link]()
• device_file = device_folder + '/w1_slave' • return lines
• /sys/bus/w1/devices/ → system folder where • Opens the sensor’s data file.
1-Wire devices appear after being detected.
• Each DS18B20 sensor has a unique serial • Reads all lines into a list.
number starting with 28-. • Closes the file.
• Example path:
• Returns the lines for further processing.
• /sys/bus/w1/devices/28-
01193a5b9bff/w1_slave • Example content of /w1_slave:
• The file w1_slave contains raw sensor data • 7f 01 4b 46 7f ff 0c 10 ae : crc=ae YES
(two lines of text with the temperature
reading). • 7f 01 4b 46 7f ff 0c 10 ae t=23750
• °C. • The first line ends with YES (meaning the
reading is valid).
• The second line ends with t=23750, meaning
temperature = 23.75
Program Explanation
• print("Logging to: " + logging_file) • When you plug a USB flash drive in to a
Raspberry Pi, it automatically installs it
• while True: under/media.
• log_temp() • If there is more than one drive, then the
• [Link](log_period) program uses the first folder it finds inside
/media. The name of the logging file is
• The program is set to log the temperature constructed from the current date.
every 10 minutes (600 seconds). You can alter
this by changing the value of log_period • If you open the file in a spreadsheet like Open
Office, you will be able to edit it directly.
• Your spreadsheet may ask you to specify the
separator for the data, which will be a comma.
• Figure shows a set of data captured using this
recipe, and the resulting file has been opened
with the Gnumeric spreadsheet running on the
Raspberry Pi.
• print("Logging to: " + logging_file) • log_period = 600 → logs every 10 minutes
• Displays the name (path) of the file where • You can change it to:
temperature readings will be saved.
• 60 → every 1 minute
• 300 → every 5 minutes, etc.
• while True:
• log_temp()
• Output Example (Spreadsheet)
• Creates an infinite loop, so the program
continuously logs temperature until it’s • The lower part of the image shows:
stopped manually. • A CSV file (opened in Excel or OpenOffice
• Calls a function (log_temp()) that reads the Calc)
current temperature from a connected sensor • Two columns:
(like a DS18B20) and writes it to the log file
with a timestamp. • Timestamp (e.g., [Link])
• [Link](log_period) • Temperature values (e.g., 24.812°C)
• Pauses the program for the duration of
log_period seconds before logging the next
reading. • A line graph plotted from the logged data
showing temperature variation over time.
• Logging Interval
• “The program is set to log the temperature
every 10 minutes (600 seconds). You can alter • This visualization helps monitor temperature
this by changing the value of log_period.” trends.
• [Link]
?v=iqImMHMXRSw&t=526s
• How To Create Raspberry Pi
DataLogger using python |
DS18B20 |
Using a Four-Digit LED Display
• You want to display a four-digit number in an old-fashioned,
seven-segment LED display
• Use an I2C LED module, such as the model shown in Figure 13-1
attached via a breadboard
• to a Raspberry Pi.
• To make this recipe, you need:
• • Breadboard and jumper wires (see “Prototyping Equipment”
on page 380)
• • Adafruit 4 × 7-segment LED with I2C backpack (see “Modules”
on page 381)
• Figure 13-2 shows the arrangement of components on the
breadboard.
• For this recipe to work, you will also need to set up your
Raspberry Pi for I2C, so follow
• Recipe 8.4 first.
• The display has an accompanying Python library written by Adafruit. It isn’t installed
• as a proper library, so to use it, you first need to download the folder structure. If you
• do not have Git installed, install it now with the following command (see Recipe 3.19).
• $ sudo apt-get install git
• Now, you can download the folder structure from GitHub:
• $ git clone [Link]
• Change directory into the Adafruit code using:
• $ cd Adafruit-Raspberry-Pi-Python-Code
• $ cd Adafruit_LEDBackpack
• In this folder, you will find a test program that will display the time. Run it using the
• command:
• $ sudo python ex_7segment_clock.py
[Link]
4 digit LED display with Raspberry pi
• import time [Link](3, int(minute / 10)) # Tens
• import datetime [Link](4, minute % 10) # Ones
• from Adafruit_7Segment import
SevenSegment # Toggle colon
• # Clock Example [Link](second % 2) # Toggle colon at 1Hz
• segment = SevenSegment(address=0x70)
# Wait one second
• print("Press CTRL+Z to exit") [Link](1)
• # Continually update the time on a 4-char, 7-
segment display
• while True:
• now = [Link]()
• hour = [Link]
• minute = [Link]
• second = [Link]
• # Set hours
• [Link](0, int(hour / 10)) #
Tens
• [Link](1, hour % 10) #
Ones
• # Set m inute s
• If you open the example file ex_7segment_clock.py in nano, you’ll see that the key
commands are:
• from Adafruit_7Segment import SevenSegment

• which import the library code into your program. You then need to create a instance of
• SevenSegment using the next line of code. The address supplied as an argument is the
• I2C address (see Recipe 8.4).
• Every I2C slave device has an address number. The LED board has three pairs of solder
• pads on the back that can be bridged with solder if you want to change the address. This
• is essential if you need to operate more than one of the displays from a single Raspberry
Pi.
• segment = SevenSegment(address=0x70)

• To actually set the contents of a particular digit, use a line like this one:
• [Link](0, int(hour / 10))

• The first argument (0) is the digit position. Note that these positions are 0, 1, 3, and 4.
• Position 2 is reserved for the two dots in the center of the display.
• The second argument is the number to display.
• You can find out more about the Adafruit li brary at [Link] y/HQBE6W.
Displaying Messages on an I2C LED matrix
You want to control the pixels of a
multicolor LED matrix display
• Use an I2C LED module, such as the model shown
in Figure 13-3 attached via a breadboard
• to a Raspberry Pi. Note that the LED in the
breadboard layout looks a little different
• to the one in the wiring diagram, but their pinouts
are the same.
• To make this recipe, you need:
• • Breadboard and jumper wires
• Adafruit bicolor LED square-pixel matrix with I2C
backpack
• Figure 13-4 shows the arrangement of components on the breadboard. In fact, if you
• do not have any buttons or extra components to add, you could just use female-tofemale
• jumper wires and connect the module directly to the Raspberry Pi. For this recipe to work, you will
also need to set up your Raspberry Pi for I2C, so follow
• Recipe 8.4 first.
• The display has an accompanying Python library written by Adafruit. It’s not installed
• as a proper library, so to use it, you first need to download the folder structure. If you
• don’t have Git installed, install it now with the following command (see Recipe 3.19):
• $ sudo apt-get install git
• Now, you can download the folder structure from GitHub:
• $ git clone [Link]
• Change directory into the Adafruit code using:
• $ cd Adafruit-Raspberry-Pi-Python-Code
• $ cd Adafruit_LEDBackpack
• In this folder, you will find a test program that displays the time as scrolling digits. Run
• it using the command:
• $ sudo python ex_8x8_color_pixels.py
• 13.2
• The program cycles through all the colors for each pixel in turn. The code is • Every I2C slave device has an address number. The LED board has three pairs of solder
listed here, • pads on the back that can be bridged with solder if you want to change the address. This
• with some of the comments and an unnecessary import removed: • is essential if you need to operate more than one of the displays from a single Raspberry
• import time • Pi.
• from Adafruit_8x8 import ColorEightByEight • The variable iter gets 1 added to it each time through the loop. The command
• grid = ColorEightByEight(address=0x70) • [Link] takes x and y coordinates as its first two parameters. The final parameter
• iter = 0 • is the color to which the pixel will be set. This is a number between 0 and 3 (0 is off, 1
• # Continually update the 8x8 display one pixel at a time • is green, 2 is red, and 3 is orange).
• while(True): • The variable iter is used to generate the number between 0 and 3 using the % operator,
• iter += 1 • which is the modulo remainder (i.e., what is left over when you divide iter by 4).
• for x in range(0, 8): • You can find out more about this product at [Link] [Link]/ pro ducts/902.

• for y in range(0, 8):


• [Link](x, y, iter % 4 )

• [Link](0.02)

• After the import, an instance of ColorEightByEight is created.


• The address supplied as an argument to the next line is the I2C address (see
Recipe 8.4):
• grid = ColorEightByEight(address=0x70)
Displaying Messages on an Alphanumeric LCD

• You want to display text on an alphanumeric LCD display.

• Solution
• Use an HD44780-compatible LCD module and wire it to the GPIO
connector.
• You will find many low-cost LCD modules, such as the one shown
connected to a
• Raspberry Pi in Figure 13-6. These have 16 pins, although fortunately,
not all of them
• have to be connected to a GPIO pin.
• These modules are available in a number of sizes and are specified by the number of
• columns and rows of letters they can display. So, for example, the module used in this

• recipe is described as 16×2, as it can display two rows each of 16 characters. Other
• common sizes are 8×1, 16×1, 16×2, 20×2, and 20×4.
• To make this recipe, you will need:

• • Breadboard and jumper wires (see “Prototyping Equipment” on page 380)


• • 16×2 HD44780-compatible LCD module (see “Modules” on page 381)

• • Row of 16 header pins (see “Miscellaneous” on page 382)


• 10kΩ trimpot (see “Resistors and Capacitors” on page 380)
• Figure 13-7 shows the breadboard layout for connecting the display.
The LCD modules
• are not normally supplied with header pins, so you will need to solder
these in place.
• The trimpot is used to control the contrast of the display. Note that if it
looks like the
• project has not worked, try moving the knob of the trimpot over its
entire range. It may
• well be that the contrast is so off that the display characters are not
visible at all.
• The Adafruit Raspberry Pi example code, available from GitHub, includes a library for
• controlling LCD displays that use the HD44780 driver. Before installing it, follow
• Recipe 8.3 to install the [Link] library.
• The Adafruit library is not installed as a proper library, so to use it, you first need to
• download the folder structure. If you don’t have Git installed, install it now with this
• command (see Recipe 3.19):
• $ sudo apt-get install git
• Now, you can download the folder structure from GitHub:
• $ git clone [Link]
• Change directory into the Adafruit code using:
• $ cd Adafruit-Raspberry-Pi-Python-Code
• $ cd Adafruit_CharLCD
• There is a test program here that displays the time and IP address of the Raspberry Pi.
• But first, if you are using a newer Raspberry Pi model B, revision 2, you will need to
• edit the file Adafruit_CharLCD.py:
• $ nano Adafruit_CharLCD.py
• Search for the line:
• def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 21, 22], GPIO = None):
• Replace the number 21 with 27 so that the line looks as follows, and then save and exit
• the file:
• def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO = None):
• You can now run the example program with the command:
• $ sudo python Adafruit_CharLCD_IPclock_example.py
• These displays can operate either
with a four- or eight-bit data bus
and also require three
• control pins. The pins are
connected as per Table 13-1.
• The Adafruit library file
Adafruit_CharLCD.py is responsible
for setting the values on
• the data pins and then sending
them to the display module. It
provides the following
• The following minimal example program shows how easy it is to display a
simple message
• functions, which you can use in your programs:
• by using the library:
• from Adafruit_CharLCD import Adafruit_CharLCD
• home()
• from time import sleep
• Move to top left.
• clear() • lcd = Adafruit_CharLCD()
• Clear all text off the display. • [Link](16,2)
• setCursor(column, row) • i=0
• Set the cursor position from where text will be written. • while Tue:
• cursor()
• [Link]()
• Turn on cursor display.
• [Link]('Counting: ' + str(i))
• noCursor()
• sleep(1)
• Turn off cursor display (default).
• message(text) • i=i+1
• Write the text at the current cursor position. • These modules are available in many sizes and are specified by the number of
columns
• and rows of letters they can display. So, for example, the module used in this
recipe is
• described as 16×2, as it can display two rows each of 16 characters. Other
common sizes are 8×1, 16×1, 16×2, 20×2, and 20×4.
[Link] • This recipe is bas ed on the Adafruit tutorial at the Adafruit learning webs ite. htt ps: // le [Link] .com/ dri ve-a-16x2-l cd-direc tl y-wit h-a-raspberry-pi/ overvie w

• Adafruit also sells a plug-in shield with an LCD display attached that is compatible with this recipe.

You might also like