Chapter 7 AD/DA Converter
108
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
d e f
analogRead
(
chn
):
#read ADC value,chn:0,1,2,3
value
=
bus
.
read_byte_data
(
address
,
cmd
+
chn
)
r e turn
value
d e f
analogWrite
(
value
):
#write DAC value
bus
.
write_byte_data
(
address
,
cmd
,
value
)
d e f
loop
( ):
w h ile
T r ue
:
value
=
analogRead
(
0
)
#read the ADC value of channel 0
analogWrite
(
value
)
#write the DAC value
voltage
=
value
/
255.0
*
3.3
#calculate the voltage value
p r int
(
'ADC Value : %d, Voltage : %.2f'
% (
value
,
voltage
))
time
.
sleep
(
0.01
)
d e f
destroy
():
bus
.
close
()
i f
__name__
= =
'__main__'
:
p r int
(
'Program is starting ... '
)
t r y
:
loop
( )
e x cept
KeyboardInterrupt
:
destroy
()
First, define the I2C address and control byte of PCF8591, and then instantiate object bus of SMBus, which
can be used to operate ADC and DAC of PCF8591.
address
=
0x48
# default address of PCF8591
bus
=
smbus
.
SMBus
(
1
)
cmd
=
0x40
# command
This subfunction is used to read the ADC. Its parameter “chn” represents the input channel number: 0, 1, 2, 3.
Its return value is the read ADC value.
d e f
analogRead
(
chn
):
# read ADC value
,
chn:0,1,2,3
value
=
bus
.
read_byte_data
(
address
,
cmd
+
chn
)
r e turn
value
This subfunction is used to write DAC. Its parameter “value” represents the digital quality to be written,
between 0-255.
d e f
analogWrite
(
value
):
# write DAC value
bus
.
write_byte_data
(
address
,
cmd
,
value
)
In the “while” cycle, first read the ADC value of channel 0, and then write the value as the DAC digital quality
and output corresponding voltage in the out pin of PCF8591. Then calculate the corresponding voltage value
and print it out.
d e f
loop
( ):
w h ile
T r ue
:
Summary of Contents for Ultimate Starter Kit
Page 1: ...Free your innovation Freenove is an open source electronics platform www freenove com ...
Page 117: ...117 Chapter 9 Potentiometer RGBLED www freenove com support freenove com Hardware connection ...
Page 155: ...155 Chapter 14 Relay Motor www freenove com support freenove com Hardware connection OFF 3 3V ...
Page 173: ...173 Chapter 16 Stepping Motor www freenove com support freenove com Hardware connection ...
Page 239: ...239 Chapter 22 Matrix Keypad www freenove com support freenove com Circuit Schematic diagram ...
Page 240: ...Chapter 22 Matrix Keypad 240 www freenove com support freenove com Hardware connection ...