def Backlight(self, Enable): # draw a line -> val : 0:white 1:black 2:xor if Enable: self.i2c.transaction(writing(self.i2cSlaveAddr, [0xC1])) else: self.i2c.transaction(writing(self.i2cSlaveAddr, [0xC2])) time.sleep(0.03)
def GlyphToEeprom(self, filename, addr): # the i2c function can transfer may 32 bytes, so we optimize for that im = Image.open(filename) bytesPerRow = int(math.ceil(float(im.size[0]) / 8)) pix = im.load() data = [0xD1] for j in range(im.size[1]): # for all rows curraddr = addr + j * bytesPerRow if len(data) == 1: data = [0xD1, curraddr >> 8, curraddr & 0xFF, bytesPerRow] # address, num bytes else: data[3] = data[3] + bytesPerRow for i in range(bytesPerRow): bb = 0 for k in range(8): # for every bit in the byte xx = i * 8 + k if xx < im.size[0]: pixel = pix[xx, j] if im.mode != 'P': pxbri = pixel[0] + pixel[1] + pixel[2] if pxbri < 300: bb |= 0x1 << k else: if pixel != 0: bb |= 0x1 << k data.append(bb) if len(data) + bytesPerRow > 31: self.i2c.transaction(writing(self.i2cSlaveAddr, data)) # transfer data to eeprom time.sleep(0.18) # give the micro processor some time to swallow the data data = [0xD1] if len(data) > 0: self.i2c.transaction(writing(self.i2cSlaveAddr, data)) # transfer data to eeprom time.sleep(0.18) # give the micro processor some time to swallow the data
def send_command(self, frame): """Sends a command frame to the PN532. Arguments: @param[in] frame Pn532Frame to send. """ logging.debug("send_command...") while True: try: logging.debug("send_command...........Sending.") sleep(DEFAULT_DELAY) self.PN532.transaction( writing(self.address, frame.to_tuple())) logging.debug(frame.to_tuple()) logging.debug("send_command...........Sent.") except Exception as ex: logging.debug(ex) self.reset_i2c() sleep(DEFAULT_DELAY) else: return True
def writeCommand(self, header: bytearray, body: bytearray = bytearray()): self._command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len( body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0xFF) + 1) # checksum of length data_out.append(PN532_HOSTTOPN532) dsum = PN532_HOSTTOPN532 + sum(header) + sum(body) # sum of TFI + DATA data_out += list(header) data_out += list(body) checksum = ((~dsum & 0xFF) + 1) & 0xFF # checksum of TFI + DATA data_out += [checksum, PN532_POSTAMBLE] DMSG("writeCommand: {} {} {}".format(header, body, data_out)) try: # send data self._wire.transaction(writing(PN532_I2C_ADDRESS, tuple(data_out))) except Exception as e: DMSG(e) DMSG( "\nToo many data to send, I2C doesn't support such a big packet\n" ) # I2C max packet: 32 bytes return PN532_INVALID_FRAME return self._readAckFrame()
def SetPixel(self, xpos, ypos, val=1): # set a single pixel : 0:white 1:black 2:xor self.i2c.transaction( writing(self.i2cSlaveAddr, [0xB4, xpos, ypos, val])) time.sleep(0.02)
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
def i2cWrite(self, data): with I2CMaster() as i2c: try: i2c.transaction(writing(self.address, data)) except: print("Display powered off") pass sleep(0.0001)
def send(sendStr): byteList = [] for i in sendStr: byteList.append(ord(i)) byteList.append(0x0A) with i2c.I2CMaster() as bus: bus.transaction(i2c.writing(address, bytes(byteList)))
def send(sendStr): byteList = [] for i in sendStr: byteList.append(ord(i)) byteList.append(0x0A) with i2c.I2CMaster() as bus: bus.transaction( i2c.writing(address, bytes(byteList)))
def change_output(self): try: with i2c.I2CMaster(1) as bus: bus.transaction( i2c.writing(self.__address, bytearray([2, self.__bit_register[0], self.__bit_register[1]]))) return self.__bit_register except IOError: # print("Err: No hybridIO detected") return -1
def LineOut(self, x1, y1, x2, y2, val=1): # draw a line -> val : 0:white 1:black 2:xor self.i2c.transaction( writing(self.i2cSlaveAddr, [0xB5, x1, y1, x2, y2, val])) time.sleep( 0.05) # give the micro processor some time to swallow the data
def TextOut(self, xpos, ypos, text, big=False): # write text at a given position data = [0xB3, xpos, ypos, 1 if big == True else 0, len(text)] for i in range(len(text)): data.append(ord(text[i])) self.i2c.transaction(writing(self.i2cSlaveAddr, data)) time.sleep( 0.05) # give the micro processor some time to swallow the data
def AnimateGlyphsFromEeprom(self, numloop, delay, positions, addrs, sizeX = 32, sizeY = 32): if len(positions) != 2 * len(addrs): raise RuntimeError('number of positions and addresses dont match') numimg = len(addrs) data = [0xD3, numimg, numloop, delay, sizeX, sizeY] for i in range(2 * numimg): data.append(positions[i]) for i in range(numimg): data.append(addrs[i] >> 8) data.append(addrs[i] & 0xFF) self.i2c.transaction(writing(self.i2cSlaveAddr, data)) time.sleep(0.02) # give the micro processor some time to swallow the data
def GlyphToEeprom(self, filename, addr): # the i2c function can transfer may 32 bytes, so we optimize for that im = Image.open(filename) bytesPerRow = int(math.ceil(float(im.size[0]) / 8)) pix = im.load() data = [0xD1] for j in range(im.size[1]): # for all rows curraddr = addr + j * bytesPerRow if len(data) == 1: data = [0xD1, curraddr >> 8, curraddr & 0xFF, bytesPerRow] # address, num bytes else: data[3] = data[3] + bytesPerRow for i in range(bytesPerRow): bb = 0 for k in range(8): # for every bit in the byte xx = i * 8 + k if xx < im.size[0]: pixel = pix[xx, j] if im.mode != 'P': pxbri = pixel[0] + pixel[1] + pixel[2] if pxbri < 300: bb |= 0x1 << k else: if pixel != 0: bb |= 0x1 << k data.append(bb) if len(data) + bytesPerRow > 31: self.i2c.transaction(writing(self.i2cSlaveAddr, data)) # transfer data to eeprom time.sleep( 0.18 ) # give the micro processor some time to swallow the data data = [0xD1] if len(data) > 0: self.i2c.transaction(writing(self.i2cSlaveAddr, data)) # transfer data to eeprom time.sleep( 0.18) # give the micro processor some time to swallow the data
def writeNFCData(addr,data): # print("actual write:"+str(data)) for retries in range(10): try: with I2CMaster() as master: while len(data)>0: master.transaction( writing(NFC_ADDR,[addr>>8,addr&0xff]+[c for c in data[0:4]])) time.sleep(0.01) data=data[4:] addr+=4 break except IOError as e: print(type(e),str(e)," retrying write")
def sendArd(sendStr): global onRPi if (onRPi): try: address = 0x04 byteList = [] for i in sendStr: byteList.append(ord(i)) byteList.append(0x0A) with i2c.I2CMaster() as bus: bus.transaction(i2c.writing(address, bytes(byteList))) except: print("i2c Error: Couldn't send...")
def sendArd(sendStr): global onRPi if (onRPi): try: address = 0x04 byteList = [] for i in sendStr: byteList.append(ord(i)) byteList.append(0x0A) with i2c.I2CMaster() as bus: bus.transaction( i2c.writing(address, bytes(byteList))) except: print("i2c Error: Couldn't send...")
def writeNFCData(addr, data): # print("actual write:"+str(data)) for retries in range(10): try: with I2CMaster() as master: while len(data) > 0: master.transaction( writing(NFC_ADDR, [addr >> 8, addr & 0xff] + [c for c in data[0:4]])) time.sleep(0.01) data = data[4:] addr += 4 break except IOError as e: print(type(e), str(e), " retrying write")
def __init__(self): self.__address = 0x20 self.__bit_register = [0b01000100, 0b00000000] self.__direction_register = [0b00011100, 0b00000000] # Output is 0, input is 1 try: with i2c.I2CMaster(1) as bus: bus.transaction( i2c.writing(self.__address, [6, self.__direction_register[0], self.__direction_register[1]])) except IOError: print("Err: No hybridIO detected") return self.change_output()
def testI2C(): x = None while x != ord('\n'): screen.clear() screen.border(0) screen.addstr(2, 2, menu_data['title'], curses.A_STANDOUT) screen.addstr(4, 4, 'I2C test') screen.addstr(6, 4, 'EEPROM address: 0x%x' % EEPROM_ADDRESS) screen.addstr(7, 4, 'Writing EEPROM...') screen.refresh() sleep(1) try: with i2c.I2CMaster() as bus: array = random.sample(range(10), 5) array[0] = 0 bus.transaction( i2c.writing(EEPROM_ADDRESS, bytes(array)), ) screen.addstr(8, 4, 'Reading EEPROM...') screen.refresh() sleep(1) read_results = bus.transaction( i2c.writing_bytes(EEPROM_ADDRESS, 0x00), i2c.reading(EEPROM_ADDRESS, 4) ) for i in range(0, 4): if read_results[0][i] != array[i + 1]: raise else: screen.addstr(9, 4, 'Ok !') except: screen.addstr(9, 4, 'Error !') sleep(2) finally: x = screen.getch()
def send_command(self, frame): logging.debug("send_command...") while True: try: logging.debug("send_command...........Sending.") sleep(DEFAULT_DELAY) self.PN532.transaction( writing(self.address, frame.to_tuple())) logging.debug("send_command...........Sent.") except Exception as ex: logging.debug(ex) self.reset_i2c() sleep(DEFAULT_DELAY) else: return True
def AnimateGlyphsFromEeprom(self, numloop, delay, positions, addrs, sizeX=32, sizeY=32): if len(positions) != 2 * len(addrs): raise RuntimeError('number of positions and addresses dont match') numimg = len(addrs) data = [0xD3, numimg, numloop, delay, sizeX, sizeY] for i in range(2 * numimg): data.append(positions[i]) for i in range(numimg): data.append(addrs[i] >> 8) data.append(addrs[i] & 0xFF) self.i2c.transaction(writing(self.i2cSlaveAddr, data)) time.sleep( 0.02) # give the micro processor some time to swallow the data
def ws2812set(self, pin, colors): if (self.modes[pin] != self.MODE_MULTI_COLOR_WS2812 and self.modes[pin] != self.MODE_SINGLE_COLOR_WS2812): self.warn("pin " + str(pin) + " not configured for ws2812 output") self.warn("Please configure the pin accordingly") return -1 if (self.modes[pin] == self.MODE_SINGLE_COLOR_WS2812): if (not (isinstance(colors, Color))): self.warn("color argument is not of type 'Color'") return -1 self.bus.transaction( i2c.writing_bytes(self.address, self.START_BYTE, self.CMD_SET, pin, colors.red, colors.green, colors.blue)) time.sleep(self.delay) else: type_check = 0 if (isinstance(colors, list)): if (isinstance(colors[0], Color)): type_check = 1 if (not (type_check)): self.warn("color argument is not a list of Color") return -1 if (len(colors) != self.ws2812count[pin]): self.warn("you submitted " + str(len(colors)) + " Colors, but " + str(self.ws2812count[pin]) + " are required") return -1 # ok, lets transmit, we have to send blocks of 8 LEDs or less for ii in range(0, self.ws2812count[pin] // 8 + 1): msg = [] msg.append(self.START_BYTE) msg.append(self.CMD_SET) msg.append(pin) msg.append(ii * 8) for i in range(0, min(self.ws2812count[pin] - ii * 8, 8)): msg.append(colors[i + ii * 8].red) msg.append(colors[i + ii * 8].green) msg.append(colors[i + ii * 8].blue) self.bus.transaction(i2c.writing(self.address, msg)) time.sleep(self.delay) return 0
def ws2812set(self,pin,colors): if(self.modes[pin]!=self.MODE_MULTI_COLOR_WS2812 and self.modes[pin]!=self.MODE_SINGLE_COLOR_WS2812): self.warn("pin "+str(pin)+" not configured for ws2812 output") self.warn("Please configure the pin accordingly") return -1 if(self.modes[pin]==self.MODE_SINGLE_COLOR_WS2812): if(not(isinstance(colors, Color))): self.warn("color argument is not of type 'Color'") return -1 self.bus.transaction(i2c.writing_bytes(self.address, self.START_BYTE, self.CMD_SET, pin, colors.red, colors.green, colors.blue)) time.sleep(self.delay) else: type_check=0 if(isinstance(colors, list)): if(isinstance(colors[0], Color)): type_check=1 if(not(type_check)): self.warn("color argument is not a list of Color") return -1 if(len(colors)!=self.ws2812count[pin]): self.warn("you submitted "+str(len(colors))+" Colors, but "+str(self.ws2812count[pin])+" are required") return -1 # ok, lets transmit, we have to send blocks of 8 LEDs or less for ii in range(0,self.ws2812count[pin]//8+1): msg = [] msg.append(self.START_BYTE) msg.append(self.CMD_SET) msg.append(pin) msg.append(ii*8) for i in range(0,min(self.ws2812count[pin]-ii*8,8)): msg.append(colors[i+ii*8].red) msg.append(colors[i+ii*8].green) msg.append(colors[i+ii*8].blue) self.bus.transaction(i2c.writing(self.address,msg)) time.sleep(self.delay) return 0
def send_command(self, frame): """Sends a command frame to the PN532. Arguments: @param[in] frame Pn532Frame to send. """ logging.debug("send_command...") while True: try: logging.debug("send_command...........Sending.") sleep(DEFAULT_DELAY) data = frame.to_tuple() logging.debug(data) if sys.version_info > (3, 0): self.PN532.transaction( writing(self.address, data)) else: cmd = data[0] data[0] = len(data) - 1 ldata = [] for byte in data: ldata.append(int(byte)) logging.debug(len(ldata[1:])) self.PN532.write_i2c_block_data(self.address, data[0], ldata[1:]) logging.debug("send_command...........Sent.") except Exception as ex: logging.debug(ex) self.reset_i2c() sleep(DEFAULT_DELAY) else: return True
def send_command(self, frame): """Sends a command frame to the PN532. Arguments: @param[in] frame Pn532Frame to send. """ logging.debug("send_command...") while True: try: logging.debug("send_command...........Sending.") sleep(DEFAULT_DELAY) data = frame.to_tuple() logging.debug(data) if sys.version_info > (3, 0): self.PN532.transaction(writing(self.address, data)) else: cmd = data[0] data[0] = len(data) - 1 ldata = [] for byte in data: ldata.append(int(byte)) logging.debug(len(ldata[1:])) self.PN532.write_i2c_block_data(self.address, data[0], ldata[1:]) logging.debug("send_command...........Sent.") except Exception as ex: logging.debug(ex) self.reset_i2c() sleep(DEFAULT_DELAY) else: return True
def ClearDisplay(self): # sets all pixels to white self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB0])) time.sleep(0.02) # give the micro processor some time to swallow the data
def LoadGlyphFromEeprom(self, xpos, ypos, addr, sizeX = 32, sizeY = 32): data = [0xD2, xpos, ypos, addr >> 8, addr & 0xFF, sizeX, sizeY] self.i2c.transaction(writing(self.i2cSlaveAddr, data)) time.sleep(0.02) # give the micro processor some time to swallow the data
def StartScreen(self): # show the start screen self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB6])) time.sleep( 0.1) # give the micro processor some time to swallow the data
def PlayTone(self, frequency, duration): # play a tone on the piezzo buzzer self.i2c.transaction(writing(self.i2cSlaveAddr, [0xCA, frequency, duration])) time.sleep(0.02)
def PlayTone(self, frequency, duration): # play a tone on the piezzo buzzer self.i2c.transaction( writing(self.i2cSlaveAddr, [0xCA, frequency, duration])) time.sleep(0.02)
def LedGreen(self, val): # set the brightness of the green LED -> 0-255 self.i2c.transaction(writing(self.i2cSlaveAddr, [0xC4, val])) time.sleep(0.02)
def TextOut(self, xpos, ypos, text, big = False): # write text at a given position data = [0xB3, xpos, ypos, 1 if big == True else 0, len(text)] for i in range(len(text)): data.append(ord(text[i])) self.i2c.transaction(writing(self.i2cSlaveAddr, data)) time.sleep(0.05) # give the micro processor some time to swallow the data
def LineOut(self, x1, y1, x2, y2, val = 1): # draw a line -> val : 0:white 1:black 2:xor self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB5, x1, y1, x2, y2, val])) time.sleep(0.05) # give the micro processor some time to swallow the data
def UpdateDisplay(self): # send buffer to the LCD self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB1])) time.sleep(0.05) # give the micro processor some time to swallow the data
def data(self): """ Reads the humidity and temperature from the AS2315. Args: None Returns: Tuple containing the following fields: humidity - float temperature - float (Celsius) temperature - float (Fahrenheit) """ data = None with i2c.I2CMaster() as bus: try: # Send a wakeup call to the sensor. This call will always fail bus.transaction( i2c.writing(self.address, bytes([0x03, 0x0, 0x04]))) except: pass time.sleep(0.125) # Now that the device is awake, read the data try: bus.transaction( i2c.writing(self.address, bytes([0x03, 0x0, 0x04]))) data = bus.transaction(i2c.reading(self.address, 0x08)) data = bytearray(data[0]) except IOError as e: self.lastError = 'I/O Error({0}): {1}'.format( e.errno, e.strerror) print(self.lastError) return None # 0x03-returned command, 0x04-no bytes read. if data[0] != 0x03 and data[1] != 0x04: self.lastError = 'Error reading data from AM2315 device. ({:02x} {:02x})'.format( data[0], data[1]) print(self.lastError) return None # Parse the data list cmd_code = data[0] byte_cnt = data[1] humid_H = data[2] humid_L = data[3] temp_H = data[4] temp_L = data[5] crc_H = data[6] crc_L = data[7] negative = False humidity = (humid_H * 256 + humid_L) / 10 # Check for negative temp # 16-Sep-2014 # Thanks to Ethan for pointing out this bug! # [email protected] if temp_H & 0x08: negative = True # Mask the negative flag temp_H &= 0x7F tempC = (temp_H * 256 + temp_L) / 10 tempF = self.c_to_f(tempC) # Verify CRC here crc = 256 * data[7] + data[6] t = bytearray([data[0], data[1], data[2], data[3], data[4], data[5]]) c = self.verify_crc(t) if crc != c: # assert(0) self.lastError = 'CRC error in sensor data.' return None if negative: tempC = -abs(tempC) tempF = -abs(tempF) return (humidity, tempC, tempF)
def SetContrast(self, val): # adjust the contrast. max is 0x7F self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB2, val])) time.sleep( 0.02) # give the micro processor some time to swallow the data
def LedBlue(self, val): # set the brightness of the blue LED -> 0-255 self.i2c.transaction(writing(self.i2cSlaveAddr, [0xC5, val])) time.sleep(0.02)
def SetContrast(self, val): # adjust the contrast. max is 0x7F self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB2, val])) time.sleep(0.02) # give the micro processor some time to swallow the data
def _send_i2c(self,msg): with i2c.I2CMaster() as master: master.transaction( i2c.writing(self.i2cAddr, msg))
def SetPixel(self, xpos, ypos, val = 1): # set a single pixel : 0:white 1:black 2:xor self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB4, xpos, ypos, val])) time.sleep(0.02)
def wakeup(self): time.sleep(.05) # wait for all ready to manipulate pn532 return self._wire.transaction(writing(PN532_I2C_ADDRESS, [0]))
def StartScreen(self): # show the start screen self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB6])) time.sleep(0.1) # give the micro processor some time to swallow the data
def LedRed(self, val): # set the brightness of the red LED -> 0-255 self.i2c.transaction(writing(self.i2cSlaveAddr, [0xC3, val])) time.sleep(0.02)
def ClearDisplay(self): # sets all pixels to white self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB0])) time.sleep( 0.02) # give the micro processor some time to swallow the data
def _request(self, text): return self.master.transaction( writing(self.address, text.encode(encoding)), reading(self.address, buffer_size))[0]
def UpdateDisplay(self): # send buffer to the LCD self.i2c.transaction(writing(self.i2cSlaveAddr, [0xB1])) time.sleep( 0.05) # give the micro processor some time to swallow the data
def sendbuf ( self, bytelist ): with i2c.I2CMaster() as bus: bus.transaction ( i2c.writing ( self.slave_address, bytes ( bytelist ) ) ) return None
from time import sleep address = 0x04 #hexstrings = ['0x76', '0x65', '0x72', '0x73', '0x69', '0x6f', '0x6e', '0x0'] while True : ecmdString = [] read_results=[] with I2CMaster() as i2c: while True: ecmd = "version" for ecmdChar in ecmd: ecmdString.append(ord(ecmdChar)) i2c.transaction(writing(address,ecmdString)) print (ecmd) print (ecmdString) sleep(1) read_results=i2c.transaction(reading(address,37)) print(read_results) ecmdString = [] print ("---------") ecmd = "fuse" for ecmdChar in ecmd: ecmdString.append(ord(ecmdChar)) i2c.transaction(writing(address,ecmdString)) print (ecmd) print (ecmdString) sleep(1)
def LoadGlyphFromEeprom(self, xpos, ypos, addr, sizeX=32, sizeY=32): data = [0xD2, xpos, ypos, addr >> 8, addr & 0xFF, sizeX, sizeY] self.i2c.transaction(writing(self.i2cSlaveAddr, data)) time.sleep( 0.02) # give the micro processor some time to swallow the data