How to do it...

In the next section, we shall write a script to allow us to gather data that we will then use later on in this chapter.

Create the following script, data_adc.py, as follows:

  1. First, import the modules and create the variables we will use, as follows:
#!/usr/bin/env python3 
#data_adc.py 
import wiringpi2 
import time 
 
DEBUG=False 
LIGHT=0;TEMP=1;EXT=2;POT=3 
ADC_CH=[LIGHT,TEMP,EXT,POT] 
ADC_ADR=0x48 
ADC_CYCLE=0x04 
BUS_GAP=0.25 
DATANAME=["0:Light","1:Temperature", 
          "2:External","3:Potentiometer"] 
  1. Create the device class with a constructor to initialize it, as follows:
class device: 
  # Constructor: 
  def __init__(self,addr=ADC_ADR): 
    self.NAME = DATANAME 
    self.i2c = wiringpi2.I2C() 
    self.devADC=self.i2c.setup(addr) 
    pwrup = self.i2c.read(self.devADC) #flush powerup value 
    if DEBUG==True and pwrup!=-1: 
      print("ADC Ready") 
    self.i2c.read(self.devADC) #flush first value 
    time.sleep(BUS_GAP) 
    self.i2c.write(self.devADC,ADC_CYCLE) 
    time.sleep(BUS_GAP) 
    self.i2c.read(self.devADC) #flush first value 
  1. Within the class, define a function to provide a list of channel names, as follows:
def getName(self): 
  return self.NAME
  1. Define another function (still as part of the class) to return a new set of samples from the ADC channels, as follows:
def getNew(self): 
  data=[] 
  for ch in ADC_CH: 
    time.sleep(BUS_GAP) 
    data.append(self.i2c.read(self.devADC)) 
  return data 
  1. Finally, after the device class, create a test function to exercise our new device class, as follows. This is only to be run when the script is executed directly:
def main(): 
  ADC = device(ADC_ADR) 
  print (str(ADC.getName())) 
  for i in range(10): 
    dataValues = ADC.getNew() 
    print (str(dataValues)) 
    time.sleep(1) 
 
if __name__=='__main__': 
  main() 
#End 

You can run the test function of this module using the following command:

sudo python3 data_adc.py  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251