freenove_car/Code/Server/ADC.py

84 lines
2.7 KiB
Python
Raw Permalink Normal View History

2019-09-24 21:09:34 -04:00
import smbus
import time
class Adc:
def __init__(self):
2020-02-26 21:58:39 -05:00
# Get I2C bus
self.bus = smbus.SMBus(1)
2020-03-03 04:39:01 -05:00
2020-02-26 21:58:39 -05:00
# I2C address of the device
self.ADDRESS = 0x48
2020-03-03 04:39:01 -05:00
2020-02-26 21:58:39 -05:00
# PCF8591 Command
self.PCF8591_CMD =0x40 #Command
2020-03-03 04:39:01 -05:00
# ADS7830 Command
self.ADS7830_CMD = 0x84 # Single-Ended Inputs
2020-02-26 21:58:39 -05:00
for i in range(3):
aa=self.bus.read_byte_data(self.ADDRESS,0xf4)
if aa < 150:
self.Index="PCF8591"
else:
self.Index="ADS7830"
def analogReadPCF8591(self,chn):#PCF8591 read ADC value,chn:0,1,2,3
2019-09-24 21:09:34 -04:00
value=[0,0,0,0,0,0,0,0,0]
for i in range(9):
2020-02-26 21:58:39 -05:00
value[i] = self.bus.read_byte_data(self.ADDRESS,self.PCF8591_CMD+chn)
2019-09-24 21:09:34 -04:00
value=sorted(value)
2020-02-26 21:58:39 -05:00
return value[4]
def analogWritePCF8591(self,value):#PCF8591 write DAC value
self.bus.write_byte_data(self.ADDRESS,cmd,value)
def recvPCF8591(self,channel):#PCF8591 write DAC value
while(1):
value1 = self.analogReadPCF8591(channel) #read the ADC value of channel 0,1,2,
value2 = self.analogReadPCF8591(channel)
if value1==value2:
break;
voltage = value1 / 256.0 * 3.3 #calculate the voltage value
voltage = round(voltage,2)
return voltage
def recvADS7830(self,channel):
"""Select the Command data from the given provided value above"""
2020-03-03 04:39:01 -05:00
COMMAND_SET = self.ADS7830_CMD | ((((channel<<2)|(channel>>1))&0x07)<<4)
self.bus.write_byte(self.ADDRESS,COMMAND_SET)
2019-09-24 21:09:34 -04:00
while(1):
2020-02-26 21:58:39 -05:00
value1 = self.bus.read_byte(self.ADDRESS)
value2 = self.bus.read_byte(self.ADDRESS)
if value1==value2:
2019-09-24 21:09:34 -04:00
break;
2020-03-03 04:39:01 -05:00
voltage = value1 / 255.0 * 3.3 #calculate the voltage value
2020-02-26 21:58:39 -05:00
voltage = round(voltage,2)
return voltage
def recvADC(self,channel):
if self.Index=="PCF8591":
data=self.recvPCF8591(channel)
elif self.Index=="ADS7830":
data=self.recvADS7830(channel)
return data
def i2cClose(self):
2019-09-24 21:09:34 -04:00
self.bus.close()
def loop():
2020-02-26 21:58:39 -05:00
adc=Adc()
2019-09-24 21:09:34 -04:00
while True:
Left_IDR=adc.recvADC(0)
print (Left_IDR)
Right_IDR=adc.recvADC(1)
print (Right_IDR)
Power=adc.recvADC(2)*3
print (Power)
time.sleep(1)
2020-02-26 21:58:39 -05:00
print ('----')
2019-09-24 21:09:34 -04:00
def destroy():
pass
# Main program logic follows:
if __name__ == '__main__':
print ('Program is starting ... ')
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
2020-02-26 21:58:39 -05:00
destroy()