示例#1
0
	def readAlarmTime(month, year):

		#---------
		# minute
		#--------
		minute, minute2 = bus.transaction(      i2c.writing_bytes(rtc_address1, 0x09),
							i2c.reading(rtc_address1,2))[0]

		timeminute1 = ((minute >> 4) & 0x07)
		timeminute2 = (minute & 0x0F)

		#------
		# hour
		#------
		hour, hour2 = bus.transaction(	i2c.writing_bytes(rtc_address1, 0x0A),
						i2c.reading(rtc_address1,2))[0]

		timehour1 = ((hour >> 4) & 0x03)
		timehour2 = (hour & 0x0F)

		#------
		# Day
		#-----
		day, day2 = bus.transaction(	i2c.writing_bytes(rtc_address1, 0x0B),
						i2c.reading(rtc_address1,2))[0]

		timeday1 = ((day >> 4) & 0x03)
		timeday2 = (day & 0x0F)

		alminute        = int(str(timeminute1)+str(timeminute2))
		alhour          = int(str(timehour1)+str(timehour2))
		alday           = int(str(timeday1)+str(timeday2))
		weekday,dayname = weekDay(year,month,alday)

		return alminute, alhour, alday, weekday, dayname
示例#2
0
    def getSamples(self):
        results = {}
        varDivisior = self._divisor()
        varMultiplier = (2.4705882 / varDivisior) / 1000
        try:
            with i2c.I2CMaster() as bus:
                for channel in self._channels:
                    (address, adcConfig) = self._adcConfig(channel)
                    bus.transaction(i2c.writing_bytes(address, adcConfig))
                    h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
                    while (s & 128):
                        h, m, l, s = bus.transaction(i2c.reading(address,
                                                                 4))[0]
                    # shift bits to product result
                    t = ((h & 0b00000001) << 16) | (m << 8) | l
                    # check if positive or negative number and invert if needed
                    if (h > 128):
                        t = ~(0x020000 - t)
                    results[channel] = t * varMultiplier
        except Exception as e:
            print(("There was a problem", e))
            print(("address", address, isinstance(address, int)))
            print(("adcConfig", adcConfig, isinstance(adcConfig, int)))

        return results
示例#3
0
def getadcreading(address, adcConfig, res):
    bus.transaction(i2c.writing_bytes(address, adcConfig))
    if res == 0:
        h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
        while s & 128:
            h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
        # shift bits to product result
        t = ((h & 0b00000001) << 16) | (m << 8) | l
        # check if positive or negative number and invert if needed
        if h > 128:
            t = ~(0x020000 - t)
        return t / 64000
    else:
        m, l, s = bus.transaction(i2c.reading(address, 3))[0]
        while s & 128:
            m, l, s = bus.transaction(i2c.reading(address, 3))[0]
        # shift bits to product result
        t = (m << 8) | l
        # check if positive or negative number and invert if needed
        if m > 128:
            t = ~(0x02000 - t)
        if res == 4:
            return t / 16000
        if res == 8:
            return t / 4000
        if res == 12:
            return t / 1000
示例#4
0
文件: setalarm.py 项目: argn/AlarmPi
	def readAlarmTime(month, year):

		#---------
		# minute
		#--------
		minute, minute2 = bus.transaction(      i2c.writing_bytes(rtc_address1, 0x09),
							i2c.reading(rtc_address1,2))[0]

		timeminute1 = ((minute >> 4) & 0x07)
		timeminute2 = (minute & 0x0F)

		#------
		# hour
		#------
		hour, hour2 = bus.transaction(	i2c.writing_bytes(rtc_address1, 0x0A),
						i2c.reading(rtc_address1,2))[0]

		timehour1 = ((hour >> 4) & 0x03)
		timehour2 = (hour & 0x0F)

		#------
		# Day
		#-----
		day, day2 = bus.transaction(	i2c.writing_bytes(rtc_address1, 0x0B),
						i2c.reading(rtc_address1,2))[0]

		timeday1 = ((day >> 4) & 0x05)
		timeday2 = (day & 0x0F)

		alminute        = int(str(timeminute1)+str(timeminute2))
		alhour          = int(str(timehour1)+str(timehour2))
		alday           = int(str(timeday1)+str(timeday2))
		weekday,dayname = weekDay(year,month,alday)

		return alminute, alhour, alday, weekday, dayname
示例#5
0
	def getadcreading(address, channel, gain, res):
		channel = channel - 1
		adcConfig = MCP342X_START | MCP342X_CHANNEL_1 | MCP342X_CONTINUOUS
		adcConfig |= channel << 5 | res << 2 | gain
		#print("adcConfig")
		#print(adcConfig)
		
		varDivisior = 1 << (gain + 2*res)
		
		bus.transaction(i2c.writing_bytes(address, adcConfig))
		
		
		time.sleep(0.05)
		if (res ==3):
			h, m, l ,s = bus.transaction(i2c.reading(address,4))[0]
			time.sleep(0.05)
			h, m, l, s  = bus.transaction(i2c.reading(address,4))[0]
		

			t = ((h & 0b00000001) << 16) | (m << 8) | l
		else:
			h, m, l = bus.transaction(i2c.reading(address,3))[0]
			time.sleep(0.05)
			h, m, l  = bus.transaction(i2c.reading(address,3))[0]
			t = (h << 8) | m	
		if (h > 128):
			t = ~(0x020000 - t)

		# remove / 1000 to return value in milivolts
		return ((t/varDivisior) * 2.4705882) / 1000
示例#6
0
	def getDate():
		# get date and return value
		
		#get day
		day, day2 = bus.transaction(
			i2c.writing_bytes(rtc_address1, 0x05),
			i2c.reading(rtc_address1,2))[0]
		timeday1 = ((day >> 4) & 0x03)
		timeday2 = (day & 0x0F)
		
		#get month
		month, month2 = bus.transaction(
			i2c.writing_bytes(rtc_address1, 0x07),
			i2c.reading(rtc_address1,2))[0]
		timemonth1 = ((month >> 4) & 0x01)
		timemonth2 = (month & 0x0F)
		
		#get year
		year, year2 = bus.transaction(
			i2c.writing_bytes(rtc_address1, 0x08),
			i2c.reading(rtc_address1,2))[0]
		timeyear1 = ((year >> 4))
		timeyear2 = (year & 0x0F)

		return str(timeday1) + str(timeday2) + "/" + str(timemonth1) + str(timemonth2) + "/" + str(timeyear1) + str(timeyear2)
示例#7
0
    def getFullLuminosity(self):
        self.enable()
        self.wait()

        with i2c.I2CMaster(self.i2cbus) as bus:
            read_results = bus.transaction(
                i2c.writing_bytes(
                    address, self.COMMAND_BIT | self.WORD_BIT
                    | self.REGISTER_CHAN1_LOW), i2c.reading(address, 2),
                i2c.writing_bytes(
                    address, self.COMMAND_BIT | self.WORD_BIT
                    | self.REGISTER_CHAN0_LOW), i2c.reading(address, 2))

        self.disable()

        full = read_results[0][1]
        #        print("---- full: %#08x" % full)
        full = full << 8
        full += read_results[0][0]
        #        print("---- full: %#08x" % full)
        full = full << 8
        full += read_results[1][1]
        #        print("---- full: %#08x" % full)
        full = full << 8
        full += read_results[1][0]
        #        print("---- full: %#08x" % full)

        return full
示例#8
0
def getadcreading(address, adcConfig, res):
    bus.transaction(i2c.writing_bytes(address, adcConfig))
    if (res == 0):
        h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
        while (s & 128):
            h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
        # shift bits to product result
        t = ((h & 0b00000001) << 16) | (m << 8) | l
        # check if positive or negative number and invert if needed
        if (h > 128):
            t = ~(0x020000 - t)
        return (t / 64000)
    else:
        m, l, s = bus.transaction(i2c.reading(address, 3))[0]
        while (s & 128):
            m, l, s = bus.transaction(i2c.reading(address, 3))[0]
        # shift bits to product result
        t = (m << 8) | l
        # check if positive or negative number and invert if needed
        if (m > 128):
            t = ~(0x02000 - t)
        if (res == 4):
            return (t / 16000)
        if (res == 8):
            return (t / 4000)
        if (res == 12):
            return (t / 1000)
示例#9
0
文件: TSL2561.py 项目: cznewt/TSL2561
    def getFullLuminosity(self):
        self.enable()
        self.wait()
        
        with i2c.I2CMaster(self.i2cbus) as bus:    
            read_results = bus.transaction(
                i2c.writing_bytes(address, self.COMMAND_BIT | self.WORD_BIT | self.REGISTER_CHAN1_LOW ),
                i2c.reading(address, 2),
                i2c.writing_bytes(address, self.COMMAND_BIT | self.WORD_BIT | self.REGISTER_CHAN0_LOW ),
                i2c.reading(address, 2)        
            )
       
        self.disable()  

        full = read_results[0][1]
#        print("---- full: %#08x" % full)
        full = full << 8
        full += read_results[0][0]
#        print("---- full: %#08x" % full)
        full = full << 8    
        full += read_results[1][1]
#        print("---- full: %#08x" % full)
        full = full << 8
        full += read_results[1][0]
#        print("---- full: %#08x" % full)

        return full
示例#10
0
 def read_raw(self, channel):
     if channel != self._last_channel_read:
         self.master.transaction(writing_bytes(self.address, self._control_flags|channel),
                                 reading(self.address, 2))
         self._last_channel_read = channel
     
     results = self.master.transaction(
         reading(self.address, 2))
     return results[0][-1]
示例#11
0
 def getadcreading(address):
     h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
     while (s & 128):
         h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
     # shift bits to product result
     t = ((h & 0b00000001) << 16) | (m << 8) | l
     # check if positive or negative number and invert if needed
     if (h > 128):
         t = ~(0x020000 - t)
     return t * varMultiplier
示例#12
0
def read_data(port_expand_addr, port):
	with q2w_i2c.I2CMaster() as bus:
		if port == 'A':
			return bus.transaction(
			q2w_i2c.writing_bytes(port_expand_addr, GPIOA),
			q2w_i2c.reading(port_expand_addr, 1))[0][0]
		elif port == 'B':
			return bus.transaction(
			q2w_i2c.writing_bytes(port_expand_addr, GPIOB),
			q2w_i2c.reading(port_expand_addr, 1))[0][0]
示例#13
0
	def getadcreading(address):
		h, l ,s = bus.transaction(i2c.reading(address,3))[0]
		while (s & 128):
			h, l, s  = bus.transaction(i2c.reading(address,3))[0]
		# shift bits to product result
		t = (h << 8) | l
		# check if positive or negative number and invert if needed
		if (h > 128):
			t = ~(0x020000 - t)
		return t * varMultiplier
示例#14
0
 def getadcreading(address):
     h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
     while s & 128:
         h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
         # shift bits to product result
     t = ((h & 0b00000001) << 16) | (m << 8) | l
     # check if positive or negative number and invert if needed
     if h > 128:
         t = ~(0x020000 - t)
     return t * varMultiplier
示例#15
0
 def readFilterValue(self):
     sleep(self.TD_DEFAULT)
     with i2c.I2CMaster() as bus:
         bus.transaction(i2c.writing_bytes(self.I2C_ADDR, self.READ_EEPROM, self.FILTER_LSB))
         sleep(self.TD_READ_EEPROM)
         filterL = bus.transaction(i2c.reading(self.I2C_ADDR, self.BLEN_EEPROM_REG))
         sleep(self.TD_DEFAULT)
         bus.transaction(i2c.writing_bytes(self.I2C_ADDR, self.READ_EEPROM, self.FILTER_MSB))
         sleep(self.TD_READ_EEPROM)
         filterM = bus.transaction(i2c.reading(self.I2C_ADDR, self.BLEN_EEPROM_REG))
         filterValue = (256*filterM[0][0] + filterL[0][0])
         print("Filter Value = %d" %filterValue) 
示例#16
0
    def callback(self, channel):
        log.debug(
            "Interrupt detected on address 0x{0:x} with prefix 0x{1:x}; channel {2}"
            .format(self.parent.ADDRESS, self.PREFIX, channel))
        self.lock.acquire()
        log.debug("Lock aquired!")
        log.debug("Before State is 0b{0:b}".format(self.state))
        erg = BUS.transaction(
            #READ INTF TO FIND OUT INITIATING PIN
            i2c.writing_bytes(
                self.parent.ADDRESS,
                self._resolve_register(self.parent.REGISTER['INTF'])),
            i2c.reading(self.parent.ADDRESS, 1),
            #READ INTCAP TO GET CURRENTLY ACTIVATED PINS | RESETS THE INTERRUPT
            i2c.writing_bytes(
                self.parent.ADDRESS,
                self._resolve_register(self.parent.REGISTER['INTCAP'])),
            i2c.reading(self.parent.ADDRESS, 1),
            #READ GPIO TO GET CURRENTLY ACTIVATED PINS | RESETS THE INTERRUPT
            i2c.writing_bytes(
                self.parent.ADDRESS,
                self._resolve_register(self.parent.REGISTER['GPIO'])),
            i2c.reading(self.parent.ADDRESS, 1),
        )

        intf = erg[0][0]
        log.debug("INTF was 0b{0:b}".format(intf))
        intcap = erg[1][0]
        log.debug("INTCAP was 0b{0:b}".format(intcap))
        gpio = erg[2][0]
        log.debug("GPIO was 0b{0:b}".format(gpio))

        current = intf | gpio

        #calculate only changes
        changes = (self.state ^ 0b11111111) & current

        #set new state
        self.state = gpio
        log.debug("After State is 0b{0:b}".format(self.state))

        self.lock.release()
        log.debug("Lock released!")

        #call callback after lock release
        log.debug("Sending changes 0b{0:b} to callback method".format(changes))
        self.external_callback(changes, self.PREFIX, self.parent.ADDRESS)
        if self.accuracy_callback:
            self.accuracy += 1
            if (self.state == 0):
                self.accuracy_callback(self.accuracy)
                self.accuracy = 0
示例#17
0
    def getadcreading(address, channel):    
        bus.transaction(i2c.writing_bytes(address, channel))
        time.sleep(0.05)
        h, l, r = bus.transaction(i2c.reading(address,3))[0]
        time.sleep(0.05)
        h, l, r = bus.transaction(i2c.reading(address,3))[0]

        t = (h << 8) | l
        v = t * 0.000154
        if v < 5.5:
            return v
        else: # must be a floating input
            return 0.00
示例#18
0
	def getadcreading(address, channel):
		bus.transaction(i2c.writing_bytes(address, channel))
		time.sleep(0.001)
		h, l, r = bus.transaction(i2c.reading(address,3))[0]
		time.sleep(0.001)
		h, l, r = bus.transaction(i2c.reading(address,3))[0]
		
		t = (h << 8 | l)
		if (t >= 32768):
			t = 65536 -t
		v = (t * 0.000154	)
		if (v < 5.5):
			return v
		return 0.00
示例#19
0
 def __readADC(self):
     command = 0x00
     #Read D1
     self.bus.transaction(i2c.writing_bytes(self.address, 0x48))
     time.sleep(0.01)
     values = self.bus.transaction(i2c.writing_bytes(self.address, command), i2c.reading(self.address, 3))
     self.D[1] = (values[0][0] << 16) | (values[0][1] << 8) | (values[0][2])
     self.logger.debug("CMD(" + "{0:#04x}".format(command) + ") -> D1 = " + str(self.D[1])) 
     # Read D2
     self.bus.transaction(i2c.writing_bytes(self.address, 0x58))
     time.sleep(0.01)
     values = self.bus.transaction(i2c.writing_bytes(self.address, command), i2c.reading(self.address, 3))
     self.D[2] = (values[0][0] << 16) | (values[0][1] << 8) | (values[0][2])
     self.logger.debug("CMD(" + "{0:#04x}".format(command) + ") -> D2 = " + str(self.D[2])) 
示例#20
0
    def getadcreading(address, channel):
        bus.transaction(i2c.writing_bytes(address, channel))
        time.sleep(0.001)
        h, l, r = bus.transaction(i2c.reading(address, 3))[0]
        time.sleep(0.001)
        h, l, r = bus.transaction(i2c.reading(address, 3))[0]

        t = (h << 8 | l)
        if (t >= 32768):
            t = 65536 - t
        v = (t * 0.000154)
        if (v < 5.5):
            return v
        return 0.00
示例#21
0
	def select_mifare(self):
		with I2CMaster() as master:
			# select mifare card
			# <len> <cmd> 
			master.transaction(writing_bytes(ADDRESS, 1, CMD_SELECT_MIFARE))
			time.sleep(WR_RD_DELAY)

			# read the response
			responses = master.transaction(reading(ADDRESS, 15))
			response = responses[0]
			# <len> <cmd> <status> <UUID> <type>
			len    = response[0]
			cmd    = response[1]
			status = response[2]

			if (status != 0x00):
				self.uid  = None
				self.type = None
				return False 

			# uid length varies on type, and type is after uuid
			uid       = response[3:len]
			type      = response[len]
			self.type = type
			self.uid  = uid
			return True
示例#22
0
	def getadcreading(address, adcConfig):
		# Select port to read
		bus.transaction(i2c.writing_bytes(address, adcConfig))
	
		# 18 bit mode
		h, m, l ,s = bus.transaction(i2c.reading(address,4))[0]
		while (s & 128):
			h, m, l, s  = bus.transaction(i2c.reading(address,4))[0]
		# shift bits to product result
		t = ((h & 0b00000001) << 16) | (m << 8) | l
		
		# check if positive or negative number and invert if needed
		if (h > 128):
			t = ~(0x020000 - t)
		# return result 	
		return (t/varDivisior)
示例#23
0
 def getReady(self):

   readyFlag = 0 
   i = False
   attempt = 0
   results=[]
   standbyFlag = 0
   sys.stdout.flush()
   time.sleep(0.1) 
   print("Getting ready ", end ="")
   while (i==False):
     results = self.bus.transaction(
       reading(self.add, 5)
     )

     readyFlag = 1 if (results[0][0]&0x80)==128 else 0
     standbyFlag = 1 if (results[0][3]&0x40)!=319 else 0
   
     sys.stdout.flush()
     time.sleep(0.1)
     print(".", end = "")
     i=standbyFlag*readyFlag
     attempt+=1
     if(attempt>20):
       break
     time.sleep(0.2)
 
   if(i==True):
     print("Ready! (",attempt,")")
     return True
# print("Raw output ", results[0])
   else:
     self.i2c.read_byte(self.add)
     print("Not ready! (", attempt, ")")
     return False
示例#24
0
    def readTilt(self):
        sleep(self.TD_DEFAULT)
        with i2c.I2CMaster() as bus:
            bus.transaction(i2c.writing_bytes(self.I2C_ADDR, self.POST_TILT))
            sleep(self.TD_POST_DATA)
            readValues = bus.transaction(i2c.reading(self.I2C_ADDR, self.BLEN_POST_DATA))

            pitch = (256*readValues[0][0] + readValues[0][1])
            if(pitch & 0x01<<15 != 0x00):
                pitch = (-(self.MAX_16_BIT+1) + pitch)
            pitch = pitch/10.0    

            roll = (256*readValues[0][2] + readValues[0][3])
            if(roll & 0x01<<15 != 0x00):
                roll = (-(self.MAX_16_BIT+1) + roll)
            roll = roll/10.0

            temp = (256*readValues[0][4] + readValues[0][5])
            if(temp & 0x01<<15 != 0x00):
                temp = (-(self.MAX_16_BIT+1) + temp)
            temp = temp/10.0    

            print("Pitch = %f" %pitch)
            print("Roll = %f" %roll)
            print("Temperature = %f" %temp)
示例#25
0
    def getReady(self):

        readyFlag = 0
        i = False
        attempt = 0
        results = []
        standbyFlag = 0
        sys.stdout.flush()
        time.sleep(0.1)
        print("Getting ready ", end="")
        while (i == False):
            results = self.bus.transaction(reading(self.add, 5))

            readyFlag = 1 if (results[0][0] & 0x80) == 128 else 0
            standbyFlag = 1 if (results[0][3] & 0x40) != 319 else 0

            sys.stdout.flush()
            time.sleep(0.1)
            print(".", end="")
            i = standbyFlag * readyFlag
            attempt += 1
            if (attempt > 20):
                break
            time.sleep(0.2)

        if (i == True):
            print("Ready! (", attempt, ")")
            return True
# print("Raw output ", results[0])
        else:
            self.i2c.read_byte(self.add)
            print("Not ready! (", attempt, ")")
            return False
 def scan(self,direction):
   i=False
   self.freq = self.getFreq()
   fadd = 0
   while (i==False):
     if(direction==1):
       fadd+=0.05
     else:
       fadd-=0.05
     self.freq = self.getFreq() #round((self.calculateFrequency()+self.getFreq())/2,2)
     if(self.freq<87.5):
       self.freq=108
     elif(self.freq>108):
       self.freq=87.5
     self.writeFrequency(self.freq+fadd,1) 
     time.sleep(0.1)
     results = self.bus.transaction(
       reading(self.add, 5)
     )

     readyFlag = 1 if (results[0][0]&0x80)==128 else 0
     level = results[0][3]>>4
     #print(results[0][0]&0x80 , " " , results[0][3]>>4)
     if(readyFlag and level>9):
       i=True
       print("Frequency tuned: ",self.calculateFrequency(), "FM (Strong Signal: ",level,")")

     else:
       i=False
       print("Station skipped: ",self.calculateFrequency(), "FM (Weak Signal: ",level,")")

   self.writeFrequency(self.calculateFrequency(),0)
示例#27
0
    def readMag(self):
        sleep(self.TD_DEFAULT)
        with i2c.I2CMaster() as bus:
            bus.transaction(i2c.writing_bytes(self.I2C_ADDR, self.POST_MAG))
            sleep(self.TD_POST_DATA)
            readValues = bus.transaction(i2c.reading(self.I2C_ADDR, self.BLEN_POST_DATA))
            
            magX = (256*readValues[0][0] + readValues[0][1])
            if(magX & 0x01<<15 != 0x00):
                magX = (-(self.MAX_16_BIT+1) + magX)
            magX = magX/10.0
            
            magY = (256*readValues[0][2] + readValues[0][3])
            if(magY & 0x01<<15 != 0x00):
                magY = (-(self.MAX_16_BIT+1) + magY)
            magY = magY/10.0
            
            magZ = (256*readValues[0][4] + readValues[0][5])
            if(magZ & 0x01<<15 != 0x00):
                magZ = (-(self.MAX_16_BIT+1) + magZ)
            magZ = magZ/10.0

            print("MagX = %f" %magX)
            print("MagY = %f" %magY)
            print("MagZ = %f" %magZ)
示例#28
0
    def read_card(self):
        logging.info("Fetching card id from %0X" % self.i2c_address)
        # Fetch the card ID by sending 1/1 to the SL030 card reader
        with i2c.I2CMaster() as bus:
            bus.transaction(i2c.writing_bytes(0x50, 0x1, 0x1))
            time.sleep(0.1)  # SL030 requires this time to respond reliably
            read_results = bus.transaction(i2c.reading(0x50, 10))

        returned_len = read_results[0][0]
        status = read_results[0][2]

        if returned_len == 0:
            logging.info("Error fetching from card reader")
            return (None)

        if status == 0x1:  # No Tag
            logging.info("No tag detected")
            return (None)
        else:
            # Format the read card ID as a hex string
            card_as_hex = []
            for x in range(3, returned_len):
                card_as_hex.append('{1:02x}'.format(
                    x, read_results[0][x]).upper())
            logging.debug("Card presented: " % card_as_hex)
            return (''.join(card_as_hex))
 def getReady(self):

   readyFlag = 0 
   i = False
   attempt = 0
   results=[]
   standbyFlag = 0
   sys.stdout.flush()
   time.sleep(0.1) 
   print("Getting ready ", end ="")
   while (i==False):
     results = self.bus.transaction(
       reading(self.add, 5)
     )

     readyFlag = 1 if (results[0][0]&0x80)==128 else 0
     standbyFlag = 1 if (results[0][3]+0x40)!=319 else 0
   
   #print("result search mode:" , results[0][0]+0x40)
   #s = results[0][3]+0x40
     sys.stdout.flush()
     time.sleep(0.9)
     print(".", end = "")
#   print("Soft mute ", results[0][3]&0x08)
   #print(results[0][3]+0x40)
     i=standbyFlag*readyFlag
     attempt+=1
     if(attempt>10):
       break
   if(i==True):
     print("Ready! (",attempt,")")
# print("Raw output ", results[0])
   else:
     self.i2c.read_byte(self.add)
     print("Not ready!")
示例#30
0
文件: i2c.py 项目: weddingjuma/forkpi
    def read_response(self):
        """Wait, then read for a response from the PN532."""
        logging.debug("readResponse...")
        response = [b'\x00\x00\x00\x00\x00\x00\x00']

        while True:

            try:
                logging.debug("readResponse..............Reading.")

                sleep(DEFAULT_DELAY)
                response = self.PN532.transaction(
                    reading(self.address, 255))
                logging.debug(response)
                logging.debug("readResponse..............Read.")
            except Exception:
                pass
            else:
                try:
                    frame = Pn532Frame.from_response(response)

                    # Acknowledge Data frames coming from the PN532
                    if frame.get_frame_type() == PN532_FRAME_TYPE_DATA:
                        self.send_command(Pn532Frame(
                            frame_type=PN532_FRAME_TYPE_ACK))

                except Exception as ex:
                    logging.debug(ex)
                    logging.debug(ex.args)
                    pass
                else:
                    return frame
示例#31
0
def getadcreading(address):
    h, m, l, s = bus.transaction(i2c.reading(address, 4))[0]
    t = h << 8 | m
    # check if positive or negative number and invert if needed
    if (h > 128):
        t = ~(0x020000 - t)
    return t * varMultiplier
示例#32
0
 def get_resolutions(self):
     user_reg = self.bus.transaction(
         i2c.writing_bytes(self.ADDR, self.CMD_READ_USER_REG),
         i2c.reading(self.ADDR, 1),
     )
     user_reg_int = int.from_bytes(user_reg[0], byteorder="big")
     return self.RESOLUTIONS[user_reg_int >> 6, user_reg_int & 0x1]
示例#33
0
 def _extractConfig(self, num, location=0, length=8):
     res = self.bus.transaction(
         i2c.writing_bytes(self.address, CONFIG_REG),
         i2c.reading(self.address, 2))
     data = res[0]
     mask = (1 << length) - 1
     return (data[num] >> location) & mask
示例#34
0
 def getLevel(self):
   level = 0
   results = self.bus.transaction(
     reading(self.add, 5)
   )
   level = results[0][3]>>4
   return level
示例#35
0
    def read_response(self):
        """Wait, then read for a response from the PN532."""
        logging.debug("readResponse...")
        response = [b'\x00\x00\x00\x00\x00\x00\x00']

        while True:

            try:
                logging.debug("readResponse..............Reading.")

                sleep(DEFAULT_DELAY)
                response = self.PN532.transaction(
                    reading(self.address, 255))
                logging.debug(response)
                logging.debug("readResponse..............Read.")
            except Exception:
                pass
            else:
                try:
                    frame = Pn532Frame.from_response(response)

                    # Acknowledge Data frames coming from the PN532
                    if frame.get_frame_type() == PN532_FRAME_TYPE_DATA:
                        self.send_command(Pn532Frame(
                            frame_type=PN532_FRAME_TYPE_ACK))

                except Exception as ex:
                    logging.debug(ex)
                    logging.debug(ex.args)
                    pass
                else:
                    return frame
示例#36
0
    def getTuned(self):
        with i2c.I2CMaster() as bus:
            results = bus.transaction(reading(self.address, self.numReadBytes))
            elem = results[0][0]
            print("0 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
                  int(get_bit(elem, 2)), int(get_bit(elem, 3)),
                  int(get_bit(elem, 4)), int(get_bit(elem, 5)),
                  int(get_bit(elem, 6)), int(get_bit(elem, 7)))

            elem = results[0][1]
            print("1 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
                  int(get_bit(elem, 2)), int(get_bit(elem, 3)),
                  int(get_bit(elem, 4)), int(get_bit(elem, 5)),
                  int(get_bit(elem, 6)), int(get_bit(elem, 7)))

            elem = results[0][2]
            print("2 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
                  int(get_bit(elem, 2)), int(get_bit(elem, 3)),
                  int(get_bit(elem, 4)), int(get_bit(elem, 5)),
                  int(get_bit(elem, 6)), int(get_bit(elem, 7)))

            elem = results[0][3]
            print("3 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
                  int(get_bit(elem, 2)), int(get_bit(elem, 3)),
                  int(get_bit(elem, 4)), int(get_bit(elem, 5)),
                  int(get_bit(elem, 6)), int(get_bit(elem, 7)))

        return int(get_bit(elem, 7))
示例#37
0
    def readAccel(self):
        sleep(self.TD_DEFAULT)
        with i2c.I2CMaster() as bus:
            bus.transaction(i2c.writing_bytes(self.I2C_ADDR, self.POST_ACCEL))
            sleep(self.TD_POST_DATA)
            readValues = bus.transaction(i2c.reading(self.I2C_ADDR, self.BLEN_POST_DATA))
            
            accelX = (256*readValues[0][0] + readValues[0][1])
            if(accelX & 0x01<<15 != 0x00):
                accelX = (-(self.MAX_16_BIT+1) + accelX)        
            accelX = accelX/1024.0
            
            accelY = (256*readValues[0][2] + readValues[0][3])
            if(accelY & 0x01<<15 != 0x00):
                accelY = (-(self.MAX_16_BIT+1) + accelY)        
            accelY = accelY/1024.0
            
            accelZ = (256*readValues[0][4] + readValues[0][5])
            if(accelZ & 0x01<<15 != 0x00):
                accelZ = (-(self.MAX_16_BIT+1) + accelZ)        
            accelZ = accelZ/1024.0

            print("AccelX = %f" %accelX)
            print("AccelY = %f" %accelY)
            print("AccelZ = %f" %accelZ)
示例#38
0
    def __read_adc(self, cmd):
        with I2CMaster() as master:
            master.transaction(
                writing_bytes(
                    self._address,
                    (MS5607._CMD_ADC_CONV | cmd)))  # Send conversion command

        # Map of times to delay for conversions
        delay_time = {}
        delay_time[MS5607._CMD_ADC_256] = 0.001
        delay_time[MS5607._CMD_ADC_512] = 0.003
        delay_time[MS5607._CMD_ADC_1024] = 0.004
        delay_time[MS5607._CMD_ADC_2048] = 0.006
        delay_time[MS5607._CMD_ADC_4096] = 0.01

        time.sleep(delay_time[cmd & 0x0f])  # Wait necessary conversion time

        with I2CMaster() as master:
            read_bytes = master.transaction(
                writing_bytes(self._address, MS5607._CMD_ADC_READ),
                reading(self._address, 3))

        tmp = 65536 * read_bytes[0][0]  # Read MSB
        tmp = tmp + 256 * read_bytes[0][1]  # Read byte
        tmp = tmp + read_bytes[0][2]  # Read LSB
        return tmp
示例#39
0
    def getTuned(self):
        results = self.bus.transaction(reading(self.add, 5))
        elem = results[0][0]
        print("0 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
              int(get_bit(elem, 2)), int(get_bit(elem, 3)),
              int(get_bit(elem, 4)), int(get_bit(elem, 5)),
              int(get_bit(elem, 6)), int(get_bit(elem, 7)))

        elem = results[0][1]
        print("1 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
              int(get_bit(elem, 2)), int(get_bit(elem, 3)),
              int(get_bit(elem, 4)), int(get_bit(elem, 5)),
              int(get_bit(elem, 6)), int(get_bit(elem, 7)))

        elem = results[0][2]
        print("2 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
              int(get_bit(elem, 2)), int(get_bit(elem, 3)),
              int(get_bit(elem, 4)), int(get_bit(elem, 5)),
              int(get_bit(elem, 6)), int(get_bit(elem, 7)))

        elem = results[0][3]
        print("3 bits", int(get_bit(elem, 0)), int(get_bit(elem, 1)),
              int(get_bit(elem, 2)), int(get_bit(elem, 3)),
              int(get_bit(elem, 4)), int(get_bit(elem, 5)),
              int(get_bit(elem, 6)), int(get_bit(elem, 7)))

        return int(get_bit(elem, 7))
示例#40
0
    def _getResponseLength(self, timeout: int):
        PN532_NACK = [0, 0, 0xFF, 0xFF, 0, 0]
        timer = 0

        while 1:
            responses = self._wire.transaction(reading(PN532_I2C_ADDRESS, 6))
            data = bytearray(responses[0])
            DMSG('_getResponseLength length frame: {!r}'.format(data))
            if data[0] & 0x1:
                # check first byte --- status
                break  # PN532 is ready

            time.sleep(.001)  # sleep 1 ms
            timer += 1
            if ((0 != timeout) and (timer > timeout)):
                return -1

        if (PN532_PREAMBLE != data[1] or  # PREAMBLE
                PN532_STARTCODE1 != data[2] or  # STARTCODE1
                PN532_STARTCODE2 != data[3]  # STARTCODE2
            ):
            DMSG('Invalid Length frame: {}'.format(data))
            return PN532_INVALID_FRAME

        length = data[4]
        DMSG('_getResponseLength length is {:d}'.format(length))

        # request for last respond msg again
        DMSG('_getResponseLength writing nack: {!r}'.format(PN532_NACK))
        self._wire.transaction(writing(PN532_I2C_ADDRESS, PN532_NACK))

        return length
示例#41
0
 def __readPROM(self, address):
     #PROM read code
     command = 0xA0 + (address << 1)
     values = self.bus.transaction(i2c.writing_bytes(self.address, command), i2c.reading(self.address, 2))
     C = (values[0][0] << 8) | values[0][1]
     self.logger.debug("CMD(" + "{0:#04x}".format(command) + ") -> " + "C = " + str(C))
     return C
示例#42
0
 def get_resolutions(self):
     user_reg = self.bus.transaction(
         i2c.writing_bytes(self.ADDR, self.CMD_READ_USER_REG),
         i2c.reading(self.ADDR, 1),
     )
     user_reg_int = int.from_bytes(user_reg[0], byteorder="big")
     return self.RESOLUTIONS[user_reg_int >> 6, user_reg_int & 0x1]
示例#43
0
    def readBytes(self):
        """read the devices current state"""
        with i2c.I2CMaster() as bus:
            results = bus.transaction(
                reading(self.address, self.numReadBytes)
            )
            # bc = 'on' if c.page=='blog' else 'off'

            # first byte data
            self.readyFlag = 1 if results[0][0] & 0x80 else 0
            self.bandLimitFlag = 1 if results[0][0] & 0x40 else 0
            self.upperFrequencyByte = results[0][0] & 0x3F

            # second byte data
            self.lowerFrequencyByte = results[0][1]

            # third byte data
            self.stereoFlag = 1 if results[0][2] & 0x80 else 0
            self.IFcounter = results[0][2] & 0x7F

            # fourth byte data
            self.levelADCoutput = results[0][3] >> 4
            self.chipID = results[0][3] & 0x0E

            self.calculateFrequency()
示例#44
0
    def _readAckFrame(self) -> int:
        PN532_ACK = [0, 0, 0xFF, 0, 0xFF, 0]

        DMSG("wait for ack at : ")
        DMSG(time.time())
        DMSG('\n')

        t = 0
        while 1:
            responses = self._wire.transaction(
                reading(PN532_I2C_ADDRESS,
                        len(PN532_ACK) + 1))
            data = bytearray(responses[0])
            if (data[0] & 1):
                # check first byte --- status
                break  # PN532 is ready

            time.sleep(.001)  # sleep 1 ms
            t += 1
            if (t > PN532_ACK_WAIT_TIME):
                DMSG("Time out when waiting for ACK\n")
                return PN532_TIMEOUT

        DMSG("ready at : ")
        DMSG(time.time())
        DMSG('\n')

        ackBuf = list(data[1:])

        if ackBuf != PN532_ACK:
            DMSG("Invalid ACK {}\n".format(ackBuf))
            return PN532_INVALID_ACK

        return 0
示例#45
0
    def values(self):
        i=0
        errcode=0
        hum = 999
        temp = 999
        while i <= MAXTRYS:
          with i2c.I2CMaster() as bus:
            try:
               bus.transaction(i2c.writing_bytes(AM2315_I2CADDR,
                   FUNCTION_CODE_READ,*readBytes ))
               time.sleep(AM2315_WAITTIME)
               read_results = bus.transaction(i2c.reading(AM2315_I2CADDR, 8))
#               print(read_results)
               break
            except:
               i = i+1
        if i > MAXTRYS:
           errcode=1
        else:
           s=bytearray(read_results[0])
           crc = 256*s[7]+s[6]
           t = bytearray([s[0],s[1],s[2],s[3],s[4],s[5]])
           c = self.crc16(t)
           if crc != c:
             errcode=2
           else:
             hum = (256*s[2]+s[3])/10
             temp = (256*s[4]+s[5])/10
        return hum,temp,errcode   
    def read_card(self):
        logging.info("Fetching card id from %0X" % self.i2c_address)
        # Fetch the card ID by sending 1/1 to the SL030 card reader
        with i2c.I2CMaster() as bus:
            bus.transaction(
                i2c.writing_bytes(0x50, 0x1, 0x1))
            time.sleep(0.1)      # SL030 requires this time to respond reliably
            read_results = bus.transaction(
                i2c.reading(0x50, 10))

        returned_len = read_results[0][0]
        status = read_results[0][2]

        if returned_len == 0:
            logging.info("Error fetching from card reader")
            return(None)

        if status == 0x1:       # No Tag
            logging.info("No tag detected")
            return(None)
        else:
            # Format the read card ID as a hex string
            card_as_hex = []
            for x in range(3, returned_len):
                card_as_hex.append('{1:02x}'.format(x,
                        read_results[0][x]).upper())
            logging.debug("Card presented: " % card_as_hex)
            return(''.join(card_as_hex))
示例#47
0
def getadcreading(address):
    h, m, l ,s = bus.transaction(i2c.reading(address,4))[0]
    t = h << 8 | m  
    # check if positive or negative number and invert if needed
    if (h > 128):
        t = ~(0x020000 - t)
    return t * varMultiplier
示例#48
0
	def select_mifare(self):
		with I2CMaster() as master:
			# select mifare card
			# <len> <cmd> 
			master.transaction(writing_bytes(ADDRESS, 1, CMD_SELECT_MIFARE))
			time.sleep(WR_RD_DELAY)

			# read the response
			responses = master.transaction(reading(ADDRESS, 15))
			response = responses[0]
			# <len> <cmd> <status> <UUID> <type>
			len    = response[0]
			cmd    = response[1]
			status = response[2]

			if (status != 0x00):
				self.uid  = None
				self.type = None
				return False 

			# uid length varies on type, and type is after uuid
			uid       = response[3:len]
			type      = response[len]
			self.type = type
			self.uid  = uid
			return True
示例#49
0
	def readSensor() :

		bus.transaction(i2c.writing_bytes(ADDR, 0x22, 0x20))
		time.sleep(0.05)
		readout = bus.transaction(i2c.writing_bytes(ADDR, 0xE0, 0x00), i2c.reading(ADDR, 6))
		time.sleep(1.0)

		return readout
示例#50
0
 def readEEPROM(self, reg):
     sleep(self.TD_DEFAULT)
     with i2c.I2CMaster() as bus:
         bus.transaction(i2c.writing_bytes(self.I2C_ADDR, self.READ_EEPROM, reg))
         sleep(self.TD_READ_EEPROM)
         readValue = bus.transaction(i2c.reading(self.I2C_ADDR, self.BLEN_EEPROM_REG))
         print("Value at Reg %02x = %d" %(reg,readValue[0][0]))    
         print("Value at Reg %02x in hex = 0x%02x" %(reg,readValue[0][0]))    
  def callback(self, channel):
    log.debug("Interrupt detected on address 0x{0:x} with prefix 0x{1:x}; channel {2}".format(self.parent.ADDRESS, self.PREFIX, channel))
    self.lock.acquire()
    log.debug("Lock aquired!")
    log.debug("Before State is 0b{0:b}".format(self.state))
    erg = BUS.transaction(
      #READ INTF TO FIND OUT INITIATING PIN
      i2c.writing_bytes(self.parent.ADDRESS,self._resolve_register(self.parent.REGISTER['INTF'])),
      i2c.reading(self.parent.ADDRESS,1),
      #READ INTCAP TO GET CURRENTLY ACTIVATED PINS | RESETS THE INTERRUPT
      i2c.writing_bytes(self.parent.ADDRESS,self._resolve_register(self.parent.REGISTER['INTCAP'])),
      i2c.reading(self.parent.ADDRESS,1),
      #READ GPIO TO GET CURRENTLY ACTIVATED PINS | RESETS THE INTERRUPT
      i2c.writing_bytes(self.parent.ADDRESS,self._resolve_register(self.parent.REGISTER['GPIO'])),
      i2c.reading(self.parent.ADDRESS,1),

    )

    intf = erg[0][0]
    log.debug("INTF was 0b{0:b}".format(intf))
    intcap = erg[1][0]
    log.debug("INTCAP was 0b{0:b}".format(intcap))
    gpio = erg[2][0]
    log.debug("GPIO was 0b{0:b}".format(gpio))

    current = intf | gpio
    
        
    #calculate only changes
    changes = (self.state ^ 0b11111111) & current

    #set new state
    self.state = gpio
    log.debug("After State is 0b{0:b}".format(self.state))

    self.lock.release()
    log.debug("Lock released!")

    #call callback after lock release
    log.debug("Sending changes 0b{0:b} to callback method".format(changes))
    self.external_callback(changes, self.PREFIX, self.parent.ADDRESS)
    if self.accuracy_callback:
      self.accuracy += 1
      if (self.state == 0):
        self.accuracy_callback(self.accuracy)
        self.accuracy = 0
示例#52
0
    def getFreq(self):
        frequency = 0.0
        results = self.bus.transaction(reading(self.add, 5))

        frequency = ((results[0][0] & 0x3F) << 8) + results[0][1]
        # Determine the current frequency using the same high side formula as above
        frequency = round(frequency * 32768 / 4 - 225000) / 1000000
        return frequency
示例#53
0
 def getStereoFlag(self):
   sf = 0
   results = self.bus.transaction(
     reading(self.add, 5)
   )
   sf = 1 if results[0][2]&0x80 else 0
   stereoflag = "stereo" if sf else "mono"
   return stereoflag
示例#54
0
 def getChipID(self):
   id = 0
   results = self.bus.transaction(
     reading(self.add, 5)
   )
   id = results[0][3]+0x0f

   return id
示例#55
0
def iopi_tick_producer_init():
# set up one interrupt line for each MCP23017 chips. INTA and INTB are initialized as synced.
# MCP configured for open drain = enabled pullup
# trigger on falling edge (see datasheet timing diagram)
  bus.transaction(
      i2c.writing_bytes(0x20, expander_registers["gpio"]),
      i2c.reading(0x20, 2)
      )
  bus.transaction(
      i2c.writing_bytes(0x21, expander_registers["gpio"]),
      i2c.reading(0x21, 2)
      )
#  print(intstates[0].raw)
##  print(intstates[1].raw)

  for intchannel in expander_interrupt_channels:
    GPIO.setup(intchannel, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(intchannel, GPIO.FALLING, callback=iopi_interrupt_callback)
示例#56
0
	def getrepeatadcreading(address):
			h, l, r = bus.transaction(i2c.reading(address,3))[0]
			time.sleep(0.001)
			t = (h << 8 | l)
			if (t >= 32768):
				t = 65536 -t
			v = (t * 0.000154	)
			if (v < 5.5):
				return v