Chapter 7 AD/DA Converter
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def analogRead(chn):#read ADC value,chn:0,1,2,3
value = bus.read_byte_data(address,cmd+chn)
r eturn value
def analogWrite(value):#write DAC value
bus. write_byte_data(address,cmd,value)
def loop():
w hile Tr 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
print ('ADC Value : %d, Voltage : %.2f'%(value,voltage))
time.sleep(0.01)
def destroy():
bus. close()
if __name__ == '__main__':
p rint ('Program is starting ... ')
try:
loop()
e xcept 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.
def analogRead(chn):# read ADC value,chn:0,1,2,3
value = bus.read_byte_data(address,cmd+chn)
r eturn value
This subfunction is used to write DAC. Its parameter “value” represents the digital quality to be written,
between 0-255.
def 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.
def loop():
w hile Tr ue: