Exemplo n.º 1
7
Arquivo: i2c.py Projeto: jcollie/rpiwr
class Device(object):
    def __init__(self, address, bus):
        self._bus = SMBus(bus)
        self._address = address

    def writeRaw8(self, value):
        value = value & 0xff
        self._bus.write_byte(self._address, value)

    def readRaw8(self):
        result = self._bus.read_byte(self._address) & 0xff
        return result

    def write8(self, register, value):
        value = value & 0xff
        self._bus.write_byte_data(self._address, register, value)

    def readU8(self, register):
        result = self._bus.read_byte_data(self._address, register) & 0xFF
        return result

    def readS8(self, register):
        result = self.readU8(register)
        if result > 127:
            result -= 256
        return result

    def write16(self, register, value):
        value = value & 0xffff
        self._bus.write_word_data(self._address, register, value)

    def readU16(self, register, little_endian = True):
        result = self._bus.read_word_data(self._address,register) & 0xFFFF
        if not little_endian:
            result = ((result << 8) & 0xFF00) + (result >> 8)
        return result

    def readS16(self, register, little_endian = True):
        result = self.readU16(register, little_endian)
        if result > 32767:
            result -= 65536
        return result

    def writeList(self, register, data):
        self._bus.write_i2c_block_data(self._address, register, data)

    def readList(self, register, length):
        results = self._bus.read_i2c_block_data(self._address, register, length)
        return results
Exemplo n.º 2
0
class PCF8574(object):

    def __init__(self, bus_id, address):
        super().__init__()
        self.__bus = SMBus(bus_id)
        self.__address = address
        self.__value = self.__getRealValue()

    @property
    def value(self):
        return self.__value

    @value.setter
    def value(self, value):
        self.__bus.write_byte(self.__address,
                              (~value) & 0xff
                              )
        self.__value = value

    def flipBits(self, changeBits):
        self.value ^= changeBits

    def __getRealValue(self):
        value = self.__bus.read_byte(self.__address)
        return (~value) & 0xff
Exemplo n.º 3
0
class HTU21D():
    """Class for accessing HTU21D sensors via I2C.

    Code taken from https://github.com/jasiek/HTU21D.

    Args:
        busno (int): The I2C bus (0 or 1, default is 1).
        address (byte): The I2C address of the sensor.
    """
    CMD_TRIG_TEMP_HM = 0xE3
    CMD_TRIG_HUMID_HM = 0xE5
    CMD_TRIG_TEMP_NHM = 0xF3
    CMD_TRIG_HUMID_NHM = 0xF5
    CMD_WRITE_USER_REG = 0xE6
    CMD_READ_USER_REG = 0xE7
    CMD_RESET = 0xFE

    def __init__(self, busno=1, address=config.SENSOR_ID_HUMIDITY_EXT):
        self.bus = SMBus(busno)
        self.i2c_address = address

    def read_temperature(self):
        self.reset()
        msb, lsb, crc = self.bus.read_i2c_block_data(
            self.i2c_address, self.CMD_TRIG_TEMP_HM, 3)
        return -46.85 + 175.72 * (msb * 256 + lsb) / 65536

    def read_humidity(self):
        self.reset()
        msb, lsb, crc = self.bus.read_i2c_block_data(
            self.i2c_address, self.CMD_TRIG_HUMID_HM, 3)
        return (-6 + 125 * (msb * 256 + lsb) / 65536.0) / 100.0

    def reset(self):
        self.bus.write_byte(self.i2c_address, self.CMD_RESET)
Exemplo n.º 4
0
class MTSMBus(I2CBus):
    """ Multi-thread compatible SMBus bus.

    This is just a wrapper of SMBus, serializing I/O on the bus for use
    in multi-threaded context and adding _i2c_ variants of block transfers.
    """

    def __init__(self, bus_id=1, **kwargs):
        """
        :param int bus_id: the SMBus id (see Raspberry Pi documentation)
        :param kwargs: parameters transmitted to :py:class:`smbus.SMBus` initializer
        """
        I2CBus.__init__(self, **kwargs)
        self._bus = SMBus(bus_id)
        # I/O serialization lock
        self._lock = threading.Lock()

    def read_byte(self, addr):
        with self._lock:
            return self._bus.read_byte(addr)

    def write_byte(self, addr, data):
        with self._lock:
            self._bus.write_byte(addr, data)

    def read_byte_data(self, addr, reg):
        with self._lock:
            return self._bus.read_byte_data(addr, reg)

    def write_byte_data(self, addr, reg, data):
        with self._lock:
            self._bus.write_byte_data(addr, reg, data)

    def read_word_data(self, addr, reg):
        with self._lock:
            return self._bus.read_word_data(addr, reg)

    def write_word_data(self, addr, reg, data):
        with self._lock:
            self._bus.write_word_data(addr, reg, data)

    def read_block_data(self, addr, reg):
        with self._lock:
            return self._bus.read_block_data(addr, reg)

    def write_block_data(self, addr, reg, data):
        with self._lock:
            self._bus.write_block_data(addr, reg, data)

    def read_i2c_block_data(self, addr, reg, count):
        with self._lock:
            return self._bus.read_i2c_block_data(addr, reg, count)

    def write_i2c_block_data(self, addr, reg, data):
        with self._lock:
            self._bus.write_i2c_block_data(addr, reg, data)
Exemplo n.º 5
0
class Pines(object):
    """docstring for Pines"""
    def __init__(self,address):
        conf.estado = 0b11111111
        self.address = address
        self.bus = SMBus(1)
    def cero(self,pin):
        conf.estado &=~(1<<pin)
        self.bus.write_byte(self.address , conf.estado)
        return conf.estado

    def uno(self , pin):
        conf.estado |=(1<<pin)
        self.bus.write_byte(self.address , conf.estado)
        return conf.estado
            
    def toggle(self,pin):
        numero = 2**pin
        conf.estado = conf.estado^numero
        self.bus.write_byte(self.address , conf.estado)
        return conf.estado

    def toggle2(self,pin1,pin2):
        self.toggle(pin1)
        self.toggle(pin2)   
    
    def reset(self):
        self.estado = self.estado|255
        self.bus.write_byte(address , self.estado)  
Exemplo n.º 6
0
class i2cDevice:
    def __init__(self, bus_number):
        self.BC_addr = 0x25
        self.bus = SMBus(bus_number)

    def read_register(self, address):
        self.bus.write_byte(self.BC_addr, address)
        time.sleep(0.02)
        data = struct.pack('B', self.bus.read_byte(self.BC_addr))
        return data

    def write_register(self, address, data):
        self.bus.write_byte_data(self.BC_addr, address, data)
        time.sleep(0.02)
Exemplo n.º 7
0
    def get(self):
        lStatus = 'ok'
        lArgs = self.__mParser.parse_args()
        lBusId = int(lArgs['bus_id'], 0)
        lAddress = int(lArgs['address'], 0)
        lValue = int(lArgs['value'], 0)
        lBus = SMBus(lBusId)

        try:
            if lArgs['cmd'] is None:
                lBus.write_byte(lAddress, lValue)
            else:
                lCommand = int(lArgs['cmd'], 0)
                lBus.write_byte_data(lAddress, lCommand, lValue)
        except IOError, pExc:
            lStatus = "Error writing data: " + str(pExc)
Exemplo n.º 8
0
class HTU21D:
    def __init__(self, busno):
        self.bus = SMBus(busno)

    def read_temperature(self):
        self.reset()
        msb, lsb, crc = self.bus.read_i2c_block_data(I2C_ADDR, CMD_TRIG_TEMP_HM, 3)
        return -46.85 + 175.72 * (msb * 256 + lsb) / 65536
     
    def read_humidity(self):
        self.reset()
        msb, lsb, crc = self.bus.read_i2c_block_data(I2C_ADDR, CMD_TRIG_HUMID_HM, 3)
        return -6 + 125 * (msb * 256 + lsb) / 65536.0

    def reset(self):
        self.bus.write_byte(I2C_ADDR, CMD_RESET)
Exemplo n.º 9
0
class Pcf8574Gpio(object):
    BCM = 0
    OUT = 0
    def __init__(self, busnum, address):
        self.bus = SMBus(busnum)
        self.address = address
        # Set all outputs off
        self.bus.write_byte(self.address, 0x00)
        # Store P-port state
        self.byte = 0x00
    
    def _changebit(self, bit, new_value):
        if new_value == 0:
            self.byte &= ~(1 << bit)
        elif new_value == 1:
            self.byte |= (1 << bit)

    def output(self, pin, value):
        self._changebit(pin, value)
        self.bus.write_byte(self.address, self.byte)

    def setmode(self, mode):
        pass
    
    def setup(self, pin, mode):
        pass

    def cleanup(self):
        # Set all outputs off
        self.bus.write_byte(self.address, 0x00)
Exemplo n.º 10
0
class Pcf8574Gpio(object):
    BCM = 0
    OUT = 0

    def __init__(self, busnum, address):
        self.bus = SMBus(busnum)
        self.address = address
        # Set all outputs off
        self.bus.write_byte(self.address, 0x00)
        # Store P-port state
        self.byte = 0x00

    def _changebit(self, bit, new_value):
        if new_value == 0:
            self.byte &= ~(1 << bit)
        elif new_value == 1:
            self.byte |= (1 << bit)

    def output(self, pin, value):
        self._changebit(pin, value)
        self.bus.write_byte(self.address, self.byte)

    def setmode(self, mode):
        pass

    def setup(self, pin, mode):
        pass

    def cleanup(self):
        # Set all outputs off
        self.bus.write_byte(self.address, 0x00)
Exemplo n.º 11
0
class I2CDevice:
    def __init__(self, addr=None, addr_default=None, bus=BUS_NUMBER):
        if not addr:
            # try autodetect address, else use default if provided
            try:
                self.addr = 0x3f  #int('0x{}'.format(
                #findall("[0-9a-z]{2}(?!:)", check_output(['/usr/sbin/i2cdetect', '-y', BUS_NUMBER]))[0]), base=16) \
                #if exists('/usr/sbin/i2cdetect') else addr_default
            except:
                self.addr = addr_default
        else:
            self.addr = addr
        self.bus = SMBus(bus)

    # write a single command
    def write_cmd(self, cmd):
        self.bus.write_byte(self.addr, cmd)
        sleep(0.0001)

    # write a command and argument
    def write_cmd_arg(self, cmd, data):
        self.bus.write_byte_data(self.addr, cmd, data)
        sleep(0.0001)

    # write a block of data
    def write_block_data(self, cmd, data):
        self.bus.write_block_data(self.addr, cmd, data)
        sleep(0.0001)

    # read a single byte
    def read(self):
        return self.bus.read_byte(self.addr)

    # read
    def read_data(self, cmd):
        return self.bus.read_byte_data(self.addr, cmd)

    # read a block of data
    def read_block_data(self, cmd):
        return self.bus.read_block_data(self.addr, cmd)
Exemplo n.º 12
0
class TemperatureSensor(object):
    def __init__(self):
        log.debug("Initialising temperature/humidity sensor")
        self.bus = SMBus(1)

        self.address = 0x40
        self.MEASURE_RELATIVE_TEMPERATURE = 0xE3
        self.MEASURE_RELATIVE_HUMIDITY = 0xE5

        self.READ_FIRMWARE_VERSION = '\x84\xb8'

    def read_firmware_version(self):

        self.bus.write_byte(self.address, 0x84)
        self.bus.write_byte(self.address, 0xB8)
        response = self.bus.read_byte(self.address)
        print 'firmware version:', response
        # response = self.bus.read_byte_data(self.address,
        #                                    0xB8)
        # print 'firmware version:', response
        return response

    def read_temperature(self):
        # Return dummy data for now
        # return 20. + random.random()

        response = self.bus.read_byte_data(self.address,
                                           self.MEASURE_RELATIVE_TEMPERATURE)
        print 'temperature:', response
        return response

    def read_humidity(self):
        # Return dummy data for now
        # return random.randint(40, 90)

        response = self.bus.read_byte_data(self.address,
                                           self.MEASURE_RELATIVE_HUMIDITY)
        print 'humidity:', response
        return response
Exemplo n.º 13
0
class HSC:
    def __init__(self, busno):
        self.bus = SMBus(1)

    # This function returns the pressure in PSI
    def read_pressure(self):

        # Trigger the pressure sensor to read data
        self.bus.write_byte(I2C_ADDR, 0)

        # Read the response
        data = self.bus.read_i2c_block_data(I2C_ADDR, 0, 4)

        # If the data isn't valid keep polling until it is.
        while ((data[0] & 0xC0) == 0x80):
            data = self.bus.read_i2c_block_data(I2C_ADDR, 0, 4)

        # Combine data bytes
        press_raw = (data[0] << 8) + data[1]

        # Return the pressure in PSI
        return round(((press_raw - 1638) * 1600) / 13107 + 23, 2)
Exemplo n.º 14
0
class Si7021(Sensor):
    def __init__(self, url):
        super().__init__(url)
        smbus_num = int(url.netloc)
        self.bus = SMBus(smbus_num)

    def get_metrics(self):
        # SI7021 address, 0x40(64)
        # 0xF5(245)	Select Relative Humidity NO HOLD master mode
        self.bus.write_byte(0x40, 0xF5)

        time.sleep(0.3)

        # SI7021 address, 0x40(64)
        # Read data back, 2 bytes, Humidity MSB first
        data0 = self.bus.read_byte(0x40)
        data1 = self.bus.read_byte(0x40)

        # Convert the data
        humidity = ((data0 * 256 + data1) * 125 / 65536.0) - 6

        time.sleep(0.3)

        # SI7021 address, 0x40(64)
        # 0xF3(243)	Select temperature NO HOLD master mode
        self.bus.write_byte(0x40, 0xF3)

        time.sleep(0.3)

        # SI7021 address, 0x40(64)
        # Read data back, 2 bytes, Temperature MSB first
        data0 = self.bus.read_byte(0x40)
        data1 = self.bus.read_byte(0x40)

        # Convert the data
        temp = ((data0 * 256 + data1) * 175.72 / 65536.0) - 46.85
        return {'humidity': humidity, 'temperature': temp}
Exemplo n.º 15
0
class ArduinoI2C():
    """
    Define I2C Interface protocol to arduino pro mini
    """
      
    def __init__(self):

        # Set LEGO port for arduino i2c
        lego_port = LegoPort(INPUT_4)
        lego_port.mode = 'other-i2c'
        sleep(0.5)
        # Settings for I2C (SMBus(4) for INPUT_2)
        self.lego_bus = SMBus(6)

        # HTU21D address
        self.address = ARDUINO_ADDRESS

    def read_arduino(self, command, string_length):
        """
        Connect arduino pro send command to read data
        """
        while True:
            try:
                self.lego_bus.write_byte(self.address, command)
                break
            except:
                sleep(0.1)
            
        sleep(0.01)
        while True:
            try:
                block = self.lego_bus.read_i2c_block_data(self.address, 0, string_length)
                break
            except:
                sleep(0.1)
        
        return block
Exemplo n.º 16
0
class control:
    def echo(self, content):
        if (self.debug == True):
            print str(content)

    def __init__(self, bus=1, addr=0x3f, clearbyte=True, debug=False):
        self.debug = debug
        self.echo("Debug:" + str(debug))

        self.bus = bus
        self.addr = addr
        self.bus = SMBus(self.bus)

        if clearbyte:
            self.bus.write_byte(self.addr, 0xff)
            self.echo("Sent clear byte")
        else:
            self.echo("Did not sent clear byte")

    def change_state(self, pin):
        act_byte = self.bus.read_byte(self.addr)
        self.echo("Actual dec:" + str(act_byte))
        self.echo("Actual bin:" + str(bin(int(act_byte))))
        self.echo("Changing state of " + str(pin))
        abin = int(str(bin(int(act_byte)))[2:])
        pins = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000]
        a = 8 - pin
        b = a - 1
        if (str(abin).zfill(8)[b:a] == "0"):
            bbin = int(str(abin).zfill(8)) + pins[pin]
        else:
            bbin = int(str(abin).zfill(8)) - pins[pin]

        self.echo("New bin:" + str(bbin))
        self.echo("New dec:" + str(int(str(bbin), 2)))
        self.bus.write_byte(self.addr, int(int(str(bbin), 2)))
Exemplo n.º 17
0
def range_dist():
    
    sonar=False
    lidar_sens=True # lidar sensing True, else EZ4 sonar or VL53L1X

    if sonar:
        # does not work well on grass
        from smbus import SMBus
##        i2cbus = SMBus(1)
        while True:
            try:
                i2cbus = SMBus(1)
                i2cbus.write_byte(0x70, 0x51)
                time.sleep(0.12)
                val = i2cbus.read_word_data(0x70, 0xE1)
                distance_in_cm=val>>8 | (val & 0x0F)<<8
##                print distance_in_cm, 'cm'
                print>>f,distance_in_cm,'cm'
                msg_sensor(distance_in_cm,25,400), #sonar facing down
                
            except IOError, err:
                print err

            time.sleep(0.1)
Exemplo n.º 18
0
def watering(watering_time):
	wet_level = 200 # выставляем уровень влажности почвы, который необходимо достичь при поливе
	watering.output = False

	addr = 0x48
	channel = 0b1000010
	bus = SMBus(1)
	#datetime.datetime.today().weekday()

	while(True):
		if (datetime.datetime.now().weekday() == watering_time['weekday'] and datetime.datetime.now().hour == watering_time['acthour']) and watering.output == False:

			watering.output = True
			bus.write_byte(addr, channel)
			value = bus.read_byte(addr)

			if 255-value == 0:			 # начинаем полив только если земля полностью сухая
				logging.info("watering is on")
				с = 0
				while(255-value < wet_level):
					if c==3 and 255-value==0:
						sendmessage(1)
					GPIO.output(9, True) # включаем помпу на 3 секунды
					time.sleep(3)
					GPIO.output(9, False)# выключаем
					time.sleep(10)		 # ждем пока вода впитается в землю
					value = bus.read_byte(addr) # считываем данные с модуля влажности почвы
					c+=1
				logging.info("watering is off")
				sendmessage(0)
			else:
				logging.warning("the plant is already watered")
				sendmessage(2)
		if  not (watering_time['acthour'] == datetime.datetime.now().hour):
			watering.output = False
		time.sleep(1*60*10)
Exemplo n.º 19
0
class LCD(object):
    def __init__(self, address=0x27, bus=1, width=20, rows=4, backlight=True):
        self.address = address
        self.bus = SMBus(bus)
        self.delay = 0.0005
        self.rows = rows
        self.width = width
        self.backlight_status = backlight

        self.write(0x33)
        self.write(0x32)
        self.write(0x06)
        self.write(0x0C)
        self.write(0x28)
        self.write(CLEAR_DISPLAY)
        sleep(self.delay)

    def _write_byte(self, byte):
        self.bus.write_byte(self.address, byte)
        self.bus.write_byte(self.address, (byte | ENABLE_BIT))
        sleep(self.delay)
        self.bus.write_byte(self.address, (byte & ~ENABLE_BIT))
        sleep(self.delay)

    def write(self, byte, mode=0):
        backlight_mode = LCD_BACKLIGHT if self.backlight_status else LCD_NOBACKLIGHT
        self._write_byte(mode | (byte & 0xF0) | backlight_mode)
        self._write_byte(mode | ((byte << 4) & 0xF0) | backlight_mode)

    def text(self, text, line, align='left'):
        self.write(LINES.get(line, LINES[1]))
        text, other_lines = self.get_text_line(text)
        text = getattr(text, ALIGN_FUNC.get(align, 'ljust'))(self.width)
        for char in text:
            self.write(ord(char), mode=1)
        if other_lines and line <= self.rows - 1:
            self.text(other_lines, line + 1, align=align)

    def backlight(self, turn_on=True):
        self.backlight_status = turn_on
        self.write(0)

    def get_text_line(self, text):
        line_break = self.width
        if len(text) > self.width:
            line_break = text[:self.width + 1].rfind(' ')
        if line_break < 0:
            line_break = self.width
        return text[:line_break], text[line_break:].strip()

    def clear(self):
        self.write(CLEAR_DISPLAY)
Exemplo n.º 20
0
class SHT20():
    SOFT_RESET_DELAY = 0.02
    TEMPERATURE_DELAY = 0.1
    HUMIDITY_DELAY = 0.04
    RESOLUTION_12BITS = 0b00000000
    RESOLUTION_11BITS = 0b10000001
    RESOLUTION_10BITS = 0b10000000
    RESOLUTION_8BITS = 0b00000001

    def __init__(self, bus=1, resolution=RESOLUTION_12BITS):
        self.bus = SMBus(bus)

        self._resolution = resolution
        self._onchip_heater = _DISABLE_ONCHIP_HEATER
        self._otp_reload = _DISABLE_OTP_RELOAD
        self.reset()

    def reset(self):
        try:
            self.bus.write_byte(SHT20_I2C, SHT20_RESET)
            time.sleep(self.SOFT_RESET_DELAY)

            config = self.bus.read_byte_data(SHT20_I2C, SHT20_READ_USER_REG)
            config = ((config & _RESERVED_BITMASK) | self._resolution
                      | self._onchip_heater | self._otp_reload)
            #self.bus.write_byte(SHT20_I2C, SHT20_WRITE_USER_REG)
            self.bus.write_byte_data(SHT20_I2C, SHT20_WRITE_USER_REG, config)
        except Exception as e:
            logging.error("Could not initialize SHT20: " + str(e))

    async def humidity(self):
        self.reset()
        self.bus.write_byte(SHT20_I2C, SHT20_HUMID_HM)
        time.sleep(self.HUMIDITY_DELAY)
        msb, lsb, crc = self.bus.read_i2c_block_data(SHT20_I2C, SHT20_HUMID_HM,
                                                     3)
        return -6.0 + 125.0 * (msb * 256.0 + lsb) / 65536.0

    async def temperature(self):
        self.reset()
        self.bus.write_byte(SHT20_I2C, SHT20_TEMP_HM)
        time.sleep(self.TEMPERATURE_DELAY)
        msb, lsb, crc = self.bus.read_i2c_block_data(SHT20_I2C, SHT20_TEMP_HM,
                                                     3)
        return -46.85 + 175.72 * (msb * 256.0 + lsb) / 65536
Exemplo n.º 21
0
class SHT20():
    SOFT_RESET_DELAY   = 0.02
    TEMPERATURE_DELAY  = 0.1
    HUMIDITY_DELAY     = 0.04
    RESOLUTION_12BITS  = 0b00000000
    RESOLUTION_11BITS  = 0b10000001
    RESOLUTION_10BITS  = 0b10000000
    RESOLUTION_8BITS   = 0b00000001

    def __init__(self, bus=3, resolution=RESOLUTION_12BITS):
        self.bus = SMBus(bus)

        self._resolution = resolution
        self._onchip_heater = _DISABLE_ONCHIP_HEATER
        self._otp_reload = _DISABLE_OTP_RELOAD

        self.bus.write_byte(SHT20_I2C, SHT20_RESET)
        time.sleep(self.SOFT_RESET_DELAY)

        config = self.bus.read_byte_data(SHT20_I2C, SHT20_READ_USER_REG)
        config = ((config & _RESERVED_BITMASK) | self._resolution | self._onchip_heater | self._otp_reload)
        #self.bus.write_byte(SHT20_I2C, SHT20_WRITE_USER_REG)
        self.bus.write_byte_data(SHT20_I2C, SHT20_WRITE_USER_REG, config)

    def humidity(self):
        self.bus.write_byte(SHT20_I2C, SHT20_HUMID_HM)
        time.sleep(self.HUMIDITY_DELAY)
        msb, lsb, crc = self.bus.read_i2c_block_data(SHT20_I2C, SHT20_HUMID_HM, 3)
        return -6.0 + 125.0 * (msb * 256.0 + lsb) / 65536.0

    def temperature(self):
        self.bus.write_byte(SHT20_I2C, SHT20_TEMP_HM)
        time.sleep(self.TEMPERATURE_DELAY)
        msb, lsb, crc = self.bus.read_i2c_block_data(SHT20_I2C, SHT20_TEMP_HM, 3)
        return -46.85 + 175.72 * (msb * 256.0 + lsb) / 65536

    def temperature_f(self):
        return (self.temperature * 1.8 + 32)

    def connected(self):
        retval = self.bus.read_byte_data(SHT20_I2C, SHT20_READ_USER_REG)
        if retval != 0xFF:
            return True
        else:
            return False
Exemplo n.º 22
0
class TCA9548A:

    def __init__(self, bus=1, addr=0x70):
        self._addr = addr
        self._bus = SMBus(bus=bus)

    def use_channel(self, ch):
        """If ch is in {0..7}, select channel ch; if ch is None, deselect all channels."""
        if ch is None:
            # Deselect all/any channel
            self._bus.write_byte(self._addr, 0)
            return
            
        if ch not in range(8):
            raise ValueError('Channel must be one of {0,1,2,3,4,5,6,7}')
        self._bus.write_byte(self._addr, 1 << ch)

    # the mux allows fan-out/fan-in. use at own risk
    def use_channel_combo(self, chs):
        self._bus.write_byte(self._addr, chs)
Exemplo n.º 23
0
class sgh_PCF8591P:

    # Constructor
    def __init__(self, busNum):
        #print "init PCF8591"
        if busNum == 0:
            self.__bus = SMBus(0) # on a Rev 1 board
            #print "bus 0"
        else:
            self.__bus = SMBus(1) # on a Rev 2 board
        self.__addr = self.__checkI2Caddress(0x48)
        self.__DACEnabled = 0x00
        #print self.readADC() # dummy call to raise exception if no chip present on the i2c bus
        #print "PCF8591 init completed"
        
        # self.__bus = __i2cBus
        # self.__addr = self.__checkI2Caddress(__addr)
        # self.__DACEnabled = 0x00
        
   
# i2c = SMBus(0) # on a Rev 1 board
# # i2c = SMBus(1) # if on a Rev 2 board

# # Create a PCF8591P object
# sensor = PCF8591P(i2c, 0x48)
    

    # Read single ADC Channel
    def readADC(self, __chan = 0):
        __checkedChan = self.__checkChannelNo(__chan)
 
        self.__bus.write_byte(self.__addr, 0x40 | __checkedChan & 0x03)  # mod my Max - says it more reliable
#       self.__bus.write_byte(self.__addr, __checkedChan  | self.__DACEnabled)
 
        __reading = self.__bus.read_byte(self.__addr) # seems to need to throw away first reading
        __reading = self.__bus.read_byte(self.__addr) # read A/D
        return __reading        
    
    # Read all ADC channels
    def readAllADC(self):
        __readings = []
        self.__bus.write_byte(self.__addr, 0x04  | self.__DACEnabled)
        __reading = self.__bus.read_byte(self.__addr) # seems to need to throw away first reading
        for i in range (4):
            __readings.append(self.__bus.read_byte(self.__addr)) # read ADC
        return __readings   
    
    # Set DAC value and enable output
    def writeDAC(self, __val=0):
        __checkedVal = self.__checkDACVal(__val)
        self.__DACEnabled = 0x40
        self.__bus.write_byte_data(self.__addr, self.__DACEnabled, __checkedVal)
    
    # Enable DAC output    
    def enableDAC(self):
        self.__DACEnabled = 0x40
        self.__bus.write_byte(self.__addr, self.__DACEnabled)
    
    # Disable DAC output
    def disableDAC(self):
        self.__DACEnabled = 0x00
        self.__bus.write_byte(self.__addr, self.__DACEnabled)
    
    # Check I2C address is within bounds
    def __checkI2Caddress(self, __addr):
        if type(__addr) is not int:
            raise I2CaddressOutOfBoundsError
        elif (__addr < 0):
            raise I2CaddressOutOfBoundsError
        elif (__addr > 127):
            raise I2CaddressOutOfBoundsError
        return __addr

    # Check if ADC channel number is within bounds
    def __checkChannelNo(self, __chan):
        if type(__chan) is not int:
            raise PCF8591PchannelOutOfBoundsError
        elif (__chan < 0):
            raise PCF8591PchannelOutOfBoundsError
        elif (__chan > 3):
            raise PCF8591PchannelOutOfBoundsError
        return __chan

    # Check if DAC output value is within bounds
    def __checkDACVal(self, __val):
        if type(__val) is not int:
            raise PCF8591PDACvalueOutOfBoundsError
        elif (__val < 0):
            raise PCF8591PDACvalueOutOfBoundsError
        elif (__val > 255):
            raise PCF8591PDACvalueOutOfBoundsError
        return __val
Exemplo n.º 24
0
from smbus import SMBus
addr = 8
bus = SMBus(1)
bus.write_byte(addr, 1)
input("press return to exit")
bus.write_byte(addr, 0)
import sys
import serial
import struct

from smbus import SMBus
from time import sleep
from icsp import *

sel = sys.argv[1] if len(sys.argv) > 1 else "N"

i2c0 = SMBus(0)
i2c2 = SMBus(2)

if sel == "A":                                  # toggle A_!RST 
    print("selecting RFW [bus A] ...")
    i2c2.write_byte(0x70, 0x5)                  # steer mux
    ioa = i2c0.read_byte_data(0x23, 0x14)
    i2c0.write_byte_data(0x23, 0x14, ioa&~0x10)
    i2c0.write_byte_data(0x23, 0x14, ioa|0x10)

elif sel == "B":                                # toggle B_!RST
    print("selecting RFE [bus B] ...")
    i2c2.write_byte(0x70, 0x4)                  # steer mux
    iob = i2c0.read_byte_data(0x22, 0x14)
    i2c0.write_byte_data(0x22, 0x14, iob&~0x10)
    i2c0.write_byte_data(0x22, 0x14, iob|0x10)

elif sel == "N":                               
    print("disabling MUX ...")
    i2c2.write_byte(0x70, 0x0)                  # disable mux
Exemplo n.º 26
0
#  Raspberry Pi Master for Arduino Slave
#  i2c_master_pi.py
#  Connects to Arduino via I2C

#  DroneBot Workshop 2019
#  https://dronebotworkshop.com

from smbus import SMBus
from time import sleep

addr_list = [0x8, 0x9]  # adresses des temoins
bus = SMBus(1)  # indicates /dev/ic2-1

print(F"Start!")
limit = 0
while limit < 8:
    for addr in addr_list:
        print(F"{addr}")
        bus.write_byte(addr, 0x1)
        sleep(1)
        bus.write_byte(addr, 0x0)
        sleep(1)
    limit += 1
Exemplo n.º 27
0
class LCD(object):
    PCF8574T_addr = 0x27
    RS = 0
    RW = 1
    E = 2
    BL = 3
    DB4 = 4
    DB5 = 5
    DB6 = 6
    DB7 = 7
    
    def __init__(self,bus=1,address=0x27):
        self._bus = SMBus(bus)
        self._state = 0
        self.PCF8574T_addr = address

        self.backlight(True)

        self.clear_RW()    # write
        self.clear_RS()    # instruction

        # 4-bit mode
        self.set_E()
        self.setbit(self.DB5)
        self.setbit(self.DB4)
        time.sleep(0.001)
        self.clear_E()
        time.sleep(0.01)
        self.set_E()
        self.setbit(self.DB5)
        self.setbit(self.DB4)
        time.sleep(0.001)
        self.clear_E()
        time.sleep(0.01)
        self.set_E()
        self.setbit(self.DB5)
        self.setbit(self.DB4)
        time.sleep(0.001)
        self.clear_E()
        time.sleep(0.01)
        self.set_E()
        self.setbit(self.DB5)
        self.clearbit(self.DB4)
        time.sleep(0.001)
        self.clear_E()
        time.sleep(0.01)

        # 4-bit mode, continue
        self.sendbyte(0b00101000)
        time.sleep(0.005)

        self.clear()
        self.home()

        # cursor direction... the default is good.
        #self.sendbyte(0b00000111)
        # turn ON display; turn OFF cursor and blink
        self.sendbyte(0b00001100)

    def write_lines(self,lines):
        while len(lines) < 4:
            lines.append([])
        for line in [lines[k] for k in (0,2,1,3)]:
            self.write_str(line)
            if len(line) < 20:
                self.write_str(' '*(20 - len(line)))

    def write_str(self,s):
        for c in s:
            self.write_char(c)

    def write_char(self,c):
        self.set_RS()
        self.sendbyte(ord(c))

    def clear(self):
        self.clear_RS()
        self.sendbyte(1)
        #self.set_RS()
        time.sleep(0.005)

    def home(self):
        self.clear_RS()
        self.sendbyte(2)
        #self.set_RS()
        time.sleep(0.005)

    def sendbyte(self,byte):
        #print bin(self._state)
        self.set_E()
        self._state = (byte & 0xF0) | (self._state & 0x0F)
        self._bus.write_byte(self.PCF8574T_addr,self._state)
        self.clear_E()

        self.set_E()
        self._state = (self._state & 0x0F) | ((byte & 0x0F) << 4)
        self._bus.write_byte(self.PCF8574T_addr,self._state)
        self.clear_E()
        
    #def writebyte(self,byte):
        #self._bus.write_byte(self.PCF8574T_addr,byte)
        # don't do this - it changes the other nibble as well

    def backlight(self,b):
        if b:
            self.setbit(self.BL)
        else:
            self.clearbit(self.BL)

    def setbit(self,bit):
        self._state = self._state | 1 << bit
        self._bus.write_byte(self.PCF8574T_addr,self._state)

    def clearbit(self,bit):
        self._state = self._state & (255 - (1 << bit))
        self._bus.write_byte(self.PCF8574T_addr,self._state)
        
    def set_RS(self):
        self.setbit(self.RS)

    def clear_RS(self):
        self.clearbit(self.RS)

    def set_RW(self):
        self.setbit(self.RW)

    def clear_RW(self):
        self.clearbit(self.RW)

    def set_E(self):
        self.setbit(self.E)

    def clear_E(self):
        self.clearbit(self.E)
Exemplo n.º 28
0
Arquivo: pixyz.py Projeto: lrvick/pixy
        dir_pin = y_dir_pin
    if axis == 1:
        step_pin = x_step_pin
        dir_pin = x_dir_pin
    print('joy_x',joy_x,'joy_y',joy_y,'button_c',button_c,'button_z',button_z)
    GPIO.output(dir_pin, direction)
    GPIO.output(led_pin, True)
    GPIO.output(step_pin, True)
    sleep(speed)
    GPIO.output(led_pin, False)
    GPIO.output(step_pin, False)
    sleep(speed)

while 1:

    bus.write_byte(0x52,0x00)

    sleep(0.000001)

    data = []
    for i in xrange(6):
        data.append(bus.read_byte(0x52))

    joy_x = data[0] -121
    joy_y = data[1] -112
    if (joy_y > 119): joy_y = -90
    accel_x = (data[2] << 2) + ((data[5] & 0x0c) >> 2)
    accel_y = (data[3] << 2) + ((data[5] & 0x30) >> 4)
    accel_z = (data[4] << 2) + ((data[5] & 0xc0) >> 6)
    button_c = (data[5] & 0x1) ^ ((data[5] & 0x2) >> 1)
    button_z = (data[5] & 0x1) ^ 1
Exemplo n.º 29
0
class I2C(object):
    """ Class to set up and access I2C devices.
    """

    ##
    ## Class methods
    ##

    ## Private methods
    def __init__(self, busId = 1):
        """ Initialize the I2C bus. """
        self._i2c = SMBus(busId)


    def __del__(self):
        """ Clean up routines. """
        try:
            # Remove SMBus connection
            del(self._i2c)
        except:
            pass


    def _combineLoHi(self, loByte, hiByte):
        """ Combine low and high bytes to an unsigned 16 bit value. """
        return (loByte | hiByte << 8)


    def _combineSignedLoHi(self, loByte, hiByte):
        """ Combine low and high bytes to a signed 16 bit value. """
        combined = self._combineLoHi (loByte, hiByte)
        return combined if combined < 32768 else (combined - 65536)


    def _combineXLoLoHi(self, xloByte, loByte, hiByte):
        """ Combine extra low, low, and high bytes to an unsigned 24 bit
            value.
        """
        return (xloByte | loByte << 8 | hiByte << 16)


    def _combineSignedXLoLoHi(self, xloByte, loByte, hiByte):
        """ Combine extra low, low, and high bytes to a signed 24 bit
            value.
        """
        combined = self._combineXLoLoHi(xloByte, loByte, hiByte)
        return combined if combined < 8388608 else (combined - 16777216)


    def _getSensorRawLoHi1(self, address, outRegs):
        """ Return a scalar representing the combined raw signed 16 bit
            value of the output registers of a one-dimensional sensor,
            e.g. temperature.
            'address' is the I2C slave address.
            'outRegs' is a list of the output registers to read.
        """
        # Read register outputs and combine low and high byte values
        xl = self._readRegister(address, outRegs[0])
        xh = self._readRegister(address, outRegs[1])

        xVal = self._combineSignedLoHi(xl, xh)
        # Return the scalar
        return xVal


    def _getSensorRawXLoLoHi1(self, address, outRegs):
        """ Return a scalar representing the combined raw signed 24 bit
            value of the output registers of a one-dimensional sensor,
            e.g. temperature.
            'address' is the I2C slave address.
            'outRegs' is a list of the output registers to read.
        """
        # Read register outputs and combine low and high byte values
        xxl = self._readRegister(address, outRegs[0])
        xl = self._readRegister(address, outRegs[1])
        xh = self._readRegister(address, outRegs[2])

        xVal = self._combineSignedXLoLoHi(xxl, xl, xh)
        # Return the scalar
        return xVal


    def _getSensorRawLoHi3(self, address, outRegs):
        """ Return a vector (i.e. list) representing the combined
            raw signed 16 bit values of the output registers of a
            3-dimensional (IMU) sensor.
            'address' is the I2C slave address.
            'outRegs' is a list of the output registers to read.
        """
        # Read register outputs and combine low and high byte values
        xl = self._readRegister(address, outRegs[0])
        xh = self._readRegister(address, outRegs[1])
        yl = self._readRegister(address, outRegs[2])
        yh = self._readRegister(address, outRegs[3])
        zl = self._readRegister(address, outRegs[4])
        zh = self._readRegister(address, outRegs[5])

        xVal = self._combineSignedLoHi(xl, xh)
        yVal = self._combineSignedLoHi(yl, yh)
        zVal = self._combineSignedLoHi(zl, zh)

        # Return the vector
        return [xVal, yVal, zVal]


    def _readRegister(self, address, register):
        """ Read a single I2C register. """
        return self._i2c.read_byte_data(address, register)


    def _readRegisters(self, address, register, count):
        """ Read (up to 32) 'count' consecutive I2C registers. """
        return self._i2c.read_i2c_block_data(address, register, count)


    def _read(self, address):
        """ Read a single byte from the I2C device without specifying a
            register.
        """
        return self._i2c.read_byte(address)


    def _writeRegister(self, address, register, value):
        """ Write a single byte to a I2C register. Return the value the
            register had before the write.
        """
        valueOld = self._readRegister(address, register)
        self._i2c.write_byte_data(address, register, value)
        return valueOld


    def _write(self, address, value):
        """ Write a single byte to the I2C device without specifying a
            register.
        """
        return self._i2c.write_byte(address, value)


    def _testRegister(self, address, register):
        """ Check, if a I2C register is readable/accessible. """
        try:
            return self._readRegister(address, register)
        except:
            return -1
Exemplo n.º 30
0
Arquivo: SHT21.py Projeto: Miaou/BBB
class SHT21 :
    RHmeasure_noHold = 0xF5
    Tmeasure_noHold  = 0xF3
    RHmeasure_Hold   = 0xE5
    Tmeasure_Hold    = 0xE3
    Soft_Reset       = 0xFE
    Write_Reg        = 0xE6
    Read_Reg         = 0xE7
##############################################################################
##  Experimental register found by looking for each one individually        ##
##  with a 10 seconds wait between each try. CheckCRC says true for all.    ##
    RH_Reg           = 0x05                                                 ##
    T_Reg            = 0x03                                                 ##
##  read_reg?          0x06                                                 ##
##  read_reg           0x07                                                 ##
##  unknown            0x09     result was 6,0,90(constant over time)       ##
##  unknown            0x0F     result was 2,68,32(constant over time)      ##
##  serial number?     0x1A     periodic on 64 bits?                        ##
##  result was      [25, 203, 218, 223, 71, 170, 137, 242, 217, 140, 232    ##
##                  , 120, 231, 86, 128, 122, 7, 151, 248, 59, 252, 255,    ##
##                  232, 120, 54, 99, 129, 75, 30, 92, 80, 126]             ##
##  serial number?     0x1B     same as 0x1A with random shift              ##
##  T_reg?             0xE3     result was 103,88,60(made a new measure?)   ##
##  RH_reg?            0xE5     result was 83,206,146(new measure?)         ##
##  read_reg           0xE6     result was 58,30                            ##
##  read_reg           0xE7     result was 58,30                            ##
##  unknown            0xE9     result was 6,0,90                           ##
##  unknown            0xEF     result was 2,68,32                          ##
##  serial number      0xFA     same as 1A, check sensirion(says 64 bits ID)##
##  serial number?     0xFB     same as 1B                                  ##
##  device ID?         0xFF     check i2c full specs, results seems random  ##
############################1#################################################
    class CRCError(Exception):
        pass

    def __init__(self, addr, busnum = 1) :
        self.address = addr
        self.bus = SMBus(busnum)
        #self.bus.open(busnum)
        self.Reset()
        #reg = self.ReadReg()
        reg = 0
        if (reg & 0x80) and (reg & 0x01):
            self.RH_res = 11
            self.T_res  = 11
        elif (reg & 0x80) and not(reg & 0x01):
            self.RH_res = 10
            self.T_res  = 13
        elif not(reg & 0x80) and not(reg & 0x01):
            self.RH_res = 12
            self.T_res  = 14
        else:
            self.RH_res = 8
            self.T_res  = 12

    def getRH(self):
        self.bus.write_byte(self.address, self.RHmeasure_noHold)
        time.sleep(0.1)
        RH = self.bus.read_i2c_block_data(self.address, self.RH_Reg, 3)
        #print RH
        if self.CheckCRC(RH):
            self.RHum = RH
            RH[1] &= ~0x03      #reset 2 status bits(LSB)
            return -6+125.*(RH[0]*256+RH[1])/65536.
        else:
            #print 'CRC checksum failed, data was corrupted(RH reading)'
            #return -1
            raise self.CRCError


    def getT(self):
        self.bus.write_byte(self.address, self.Tmeasure_noHold)
        time.sleep(0.1)
        T = self.bus.read_i2c_block_data(self.address, self.T_Reg, 3)
        #print T
        if self.CheckCRC(T):
            self.Temp = T
            T[1] &= ~0x03       #reset 2 status bits(LSB)
            return -46.85+175.72*(T[0]*256+T[1])/65536.
        else:
            #print 'CRC checksum failed, data was corrupted(temp reading)'
            #return -1
            raise self.CRCError
    
    def Reset(self):
        self.bus.write_byte(self.address, self.Soft_Reset)
        time.sleep(0.02) #must wait 15ms

    def ReadReg(self):
        reg = self.bus.read_word_data(self.address, self.Read_Reg)
        crc = [ reg & 0xFF, (reg & 0xFF00) >> 8]
        
        if self.CheckCRC(crc):
            return reg & 0xFF
        else:
            #print 'Error : CRC not matching !'
            #return 0
            raise self.CRCError
        
    def WriteReg(self, val):
        reg = self.ReadReg()
        reg &= 0x38
        self.bus.write_byte_data(self.address, self.Write_Reg, val)

    def test(self):
        self.T = []
        self.getRH()
        self.getT()
        for i in range(256):
            try :
                time.sleep(10)
                self.T.append((hex(i), self.bus.read_i2c_block_data(sensor.address, i)))
                print(hex(i), 'success reading')
            except IOError as err:
                print(hex(i), 'failed reading')
        return self.T

    def CheckCRC(self, buf):
        poly = 0x131
        crc = 0
        #print buf[2]
        for by in buf:
            crc ^= by
            for i in range(8):
                if crc & 0x80 :
                    crc = (crc << 1)^poly
                else:
                    crc <<= 1
                #print crc
        return crc==0
Exemplo n.º 31
0
    class LinuxI2cBus:
        """A Linux I²C device, which is itself an I²C bus.

        Should not be instantiated directly; use `LinuxI2c.find_devices`
        instead.

        This type mimics the `smbus.SMBus` read/write/close APIs.  However,
        `open` does not take any parameters, and not all APIs are available.
        """

        # note: this is not a liquidctl BaseBus, as that would cause
        # find_liquidctl_devices to try to directly instantiate it

        def __init__(self, i2c_dev):
            self._i2c_dev = i2c_dev
            self._smbus = None

            try:
                assert i2c_dev.name.startswith('i2c-')
                self._number = int(i2c_dev.name[4:])
            except:
                raise ValueError(f'cannot infer bus number')

        def find_devices(self, drivers, **kwargs):
            """Probe drivers and find compatible devices in this bus."""
            for drv in drivers:
                yield from drv.probe(self, **kwargs)

        def open(self):
            """Open the I²C bus."""
            if not self._smbus:
                try:
                    self._smbus = SMBus(self._number)
                except FileNotFoundError:
                    if Path('/sys/class/i2c-dev').exists():
                        raise
                    raise OSError('kernel module i2c-dev not loaded') from None

        def read_byte(self, address):
            """Read a single byte from a device."""
            value = self._smbus.read_byte(address)
            _LOGGER.debug('read byte @ 0x%02x: 0x%02x', address, value)
            return value

        def read_byte_data(self, address, register):
            """Read a single byte from a designated register."""
            value = self._smbus.read_byte_data(address, register)
            _LOGGER.debug('read byte data @ 0x%02x:0x%02x: 0x%02x', address,
                          register, value)
            return value

        def read_word_data(self, address, register):
            """Read a single 2-byte word from a given register."""
            value = self._smbus.read_word_data(address, register)
            _LOGGER.debug('read word data @ 0x%02x:0x%02x: 0x%04x', address,
                          register, value)
            return value

        def read_block_data(self, address, register):
            """Read a block of up to  32 bytes from a given register."""
            data = self._smbus.read_block_data(address, register)
            _LOGGER.debug('read block data @ 0x%02x:0x%02x: %r', address,
                          register, LazyHexRepr(data))
            return data

        def write_byte(self, address, value):
            """Write a single byte to a device."""
            _LOGGER.debug('writing byte @ 0x%02x: 0x%02x', address, value)
            return self._smbus.write_byte(address, value)

        def write_byte_data(self, address, register, value):
            """Write a single byte to a designated register."""
            _LOGGER.debug('writing byte data @ 0x%02x:0x%02x: 0x%02x', address,
                          register, value)
            return self._smbus.write_byte_data(address, register, value)

        def write_word_data(self, address, register, value):
            """Write a single 2-byte word to a designated register."""
            _LOGGER.debug('writing word data @ 0x%02x:0x%02x: 0x%04x', address,
                          register, value)
            return self._smbus.write_word_data(address, register, value)

        def write_block_data(self, address, register, data):
            """Write a block of byte data to a given register."""
            _LOGGER.debug('writing block data @ 0x%02x:0x%02x: %r', address,
                          register, LazyHexRepr(data))
            return self._smbus.write_block_data(address, register, data)

        def close(self):
            """Close the I²C connection."""
            if self._smbus:
                self._smbus.close()
                self._smbus = None

        def load_eeprom(self, address):
            """Return EEPROM name and data in `address`, or None if N/A."""

            # uses kernel facilities to avoid directly reading from the EEPROM
            # or managing its pages, also avoiding the need for unsafe=smbus

            dev = f'{self._number}-{address:04x}'
            try:
                name = self._i2c_dev.joinpath(dev, 'name').read_text().strip()
                eeprom = self._i2c_dev.joinpath(dev, 'eeprom').read_bytes()
                return LinuxEeprom(name, eeprom)
            except Exception as err:
                return None

        @property
        def name(self):
            return self._i2c_dev.name

        @property
        def description(self):
            return self._try_sysfs_read('name')

        @property
        def parent_vendor(self):
            return self._try_sysfs_read_hex('device/vendor')

        @property
        def parent_device(self):
            return self._try_sysfs_read_hex('device/device')

        @property
        def parent_subsystem_vendor(self):
            return self._try_sysfs_read_hex('device/subsystem_vendor')

        @property
        def parent_subsystem_device(self):
            return self._try_sysfs_read_hex('device/subsystem_device')

        @property
        def parent_driver(self):
            try:
                return Path(
                    os.readlink(self._i2c_dev.joinpath('device/driver'))).name
            except FileNotFoundError:
                return None

        def __str__(self):
            if self.description:
                return f'{self.name}: {self.description}'
            return self.name

        def __repr__(self):
            def hexid(maybe):
                if maybe is not None:
                    return f'{maybe:#06x}'
                return 'None'

            return f'{self.__class__.__name__}: name: {self.name!r}, ' \
                   f'description: {self.description!r}, ' \
                   f'parent_vendor: {hexid(self.parent_vendor)}, ' \
                   f'parent_device: {hexid(self.parent_device)}, ' \
                   f'parent_subsystem_vendor: {hexid(self.parent_subsystem_vendor)}, ' \
                   f'parent_subsystem_device: {hexid(self.parent_subsystem_device)}, ' \
                   f'parent_driver: {self.parent_driver!r}'

        def _try_sysfs_read(self, *sub, default=None):
            try:
                return self._i2c_dev.joinpath(*sub).read_text().rstrip()
            except FileNotFoundError:
                return default

        def _try_sysfs_read_hex(self, *sub, default=None):
            try:
                return int(self._i2c_dev.joinpath(*sub).read_text(), base=16)
            except FileNotFoundError:
                return default
Exemplo n.º 32
0

deg = u'\N{DEGREE SIGN}'

# sqlite config
# CREATE TABLE temp_humidity(id INTEGER primary key, datetime DATETIME DEFAULT CURRENT_TIMESTAMP, temp_c REAL NOT NULL, temp_f REAL NOT NULL, humidity INTEGER NOT NULL);
sqliteCon = sqlite.connect(dbPath)


# Main loop
while True:
    # Get the current system date and time
    datetime = time.strftime('%m/%d/%Y %H:%M:%S')

    # Read data from sensor
    bus.write_byte(ADDR, 0x00)
    ans = bus.read_i2c_block_data(ADDR, 0x00, 4)

    # Convert to human readable humdidity
    humidity = ((ans[0] & 0x3f) << 8) + ans[1]
    humidity = humidity * float('6.10e-3')
    humidity = '{:.0f}'.format(humidity)

    # Convert to human readable temperature
    tempC = (ans[2] << 8) + ans[3]
    tempC = tempC >> 2
    tempC = (tempC * float('1.007e-2')) - 40
    tempF = (tempC * 1.8) + 32

    #insert into SQLITE database
    cursor = sqliteCon.cursor()
Exemplo n.º 33
0
# -*- encoding: latin-1 -*-

# Dette program læser analog input fra PCF8591P chipens kanal #0.
from smbus import SMBus
from time import sleep

# Opret forbindelse til enheden(chipen).
bus = SMBus(1) # 1 Indikere at vi bruger enhedsfilen /dev/i2c-1.
# Addressen på chipen.
addresse = 74
# Referencespænding.
Vref = 4.25
konvateret = Vref / 256

print("Læs kanal 0 fra A/D.")
print("Udskriver aflæsningen når den forandres.")
print("Tryk CTRL+C for at stoppe.")

bus.write_byte(addresse, 0) # 0 Indikere at vi vil have data fra kanal 0.
sidste_aflaesning = -1

# Start en uendelig løkke og afbryd hvis ctrl+c bliver trykket.
while True:
	aflaesning = bus.read_byte(addresse)
	if (abs(sidste_aflaesning - aflaesning) > 1 ):
		print "A/D læsning ", aflaesning, " som betyder ", round(konvateret * aflaesning, 2), " V."
		sidste_aflaesning = aflaesning

	sleep(0.01)
Exemplo n.º 34
0
class Nunchuk(object):
	"""
	Créait un objet "Nunchuk" qui gére l'acquisition des données de la manette nunchuk.
	"""
	def __init__(self):
		"""
		Initialise la manette nunchuk.
		"""
		self.bus = SMBus(1)
		self.bus.write_byte_data(0x52,0x40,0x00)
		sleep(0.1)

	def read(self):
		"""
		Renvoi les informations de la manette.

		Returns:
			int[] -- Tableau des différentes informations de la manette.
				[0]: Position du joystick sur l'axe horizontal.
				[1]: Position du joystick sur l'axe vertical.
				[2]: Axe X de l'accelerometre de la manette.
				[3]: Axe Y de l'accelerometre de la manette.
				[4]: Axe Z de l'accelerometre de la manette.
				[5]: État des boutons de la manette.
		"""
		self.bus.write_byte(0x52,0x00)
		sleep(0.0001)
		temp = [(0x17 + (0x17 ^ self.bus.read_byte(0x52))) for i in range(6)]
		return temp

	def getJoystickPosition(self):
		"""
		Renvoi la position du joystick de la manette.

		Returns:
			int[] -- Tableau des position du joystick de la manette.
				[0]: Position du joystick sur l'axe horizontal.
				[1]: Position du joystick sur l'axe vertical.
		"""
		data = self.read()
		return data[0],data[1]
	def getAccelerometerAxis(self):
		"""
		Renvoi les trois axes de l'accelerometre de la manette.

		Returns:
			int[] -- Tableau des trois axes de l'accelerometre de la manette.
				[0]: Axe X de l'accelerometre de la manette.
				[1]: Axe Y de l'accelerometre de la manette.
				[2]: Axe Z de l'accelerometre de la manette.
		"""
		x = 0
		y = 0
		z = 0
		stability = 5

		for i in range(stability):
			data = self.read()
			x+=data[2]
			y+=data[3]
			z+=data[4]
		return x/stability,y/stability,z/stability
	def getButtons(self):
		"""
		Renvoi les état des boutons de la manette.

		Returns:
			int[] -- Tableau des états des boutons de la manette.
				[0]: État du bouton "C".
				[1]: État du bouton "Z".
		"""
		data = self.read()
		butc = (data[5] & 0x02)
		butz = (data[5] & 0x01)
		return butc == 0,butz == 0
Exemplo n.º 35
0
class SHT21:
    """Class to read temperature and humidity from SHT21"""

	## Control constants
    _SOFTRESET                      = 0xFE
    _SLAVE_ADDRESS                  = 0x40
    _TRIGGER_TEMPERATURE_NO_HOLD    = 0xF3
    _TRIGGER_HUMIDITY_NO_HOLD       = 0xF5
    _STATUS_BITS_MASK               = 0xFFFC

	# Wait a bit more than recommended
    _TEMPERATURE_WAIT_TIME          = 0.086  # (datasheet: typ=66, max=85)
    _HUMIDITY_WAIT_TIME             = 0.030  # (datasheet: typ=22, max=29)


    def __init__(self, device_number = 1):
        """Opens the i2c device (assuming that the kernel modules have been
        loaded) & run soft reset. (user register leaved to default value)"""
        self.bus = SMBus(device_number)
        self.bus.write_byte(self._SLAVE_ADDRESS, self._SOFTRESET)
        time.sleep(0.015)
        if DEBUG:
            print("SHT21 init done.")

    def getTemperature(self):
        """Reads the temperature from the sensor.  Not that this call blocks
        for ~86ms to allow the sensor to return the data """
        self.bus.write_byte(self._SLAVE_ADDRESS, self._TRIGGER_TEMPERATURE_NO_HOLD)
        data = []
        time.sleep(self._TEMPERATURE_WAIT_TIME)

        data.append(self.bus.read_byte(self._SLAVE_ADDRESS))
        data.append(self.bus.read_byte(self._SLAVE_ADDRESS))

        Temperature = self._get_temperature_from_buffer(data)
        if DEBUG:
            print("Temp[C] = ", Temperature)
        return Temperature

    def getHumidity(self):
        """Reads the humidity from the sensor.  Not that this call blocks
        for ~30ms to allow the sensor to return the data"""
        self.bus.write_byte(self._SLAVE_ADDRESS, self._TRIGGER_HUMIDITY_NO_HOLD)
        data = []
        time.sleep(self._HUMIDITY_WAIT_TIME)

        data.append(self.bus.read_byte(self._SLAVE_ADDRESS))
        data.append(self.bus.read_byte(self._SLAVE_ADDRESS))

        Humidity = self._get_humidity_from_buffer(data)
        if DEBUG:
            print("Humidity[%] = ", Humidity)

        return Humidity

    @staticmethod
    def _get_temperature_from_buffer(data):
        """This function reads the first two bytes of data and
            returns the temperature in C by using the following function:
            T = =46.82 + (172.72 * (ST/2^16))where ST is the value from the sensor  """
        unadjusted = ((data[0]) << 8) + (data[1])
        unadjusted &= SHT21._STATUS_BITS_MASK  # zero the status bits
        unadjusted *= 175.72
        unadjusted /= 1 << 16  # divide by 2^16
        unadjusted -= 46.85
        return unadjusted


    @staticmethod
    def _get_humidity_from_buffer(data):
        """This function reads the first two bytes of data and returns
            the relative humidity in percent by using the following function:
            RH = -6 + (125 * (SRH / 2 ^16)) where SRH is the value read from the sensor """
        unadjusted = (data[0] << 8) + data[1]
        unadjusted &= SHT21._STATUS_BITS_MASK  # zero the status bits
        unadjusted *= 125.0
        unadjusted /= 1 << 16  # divide by 2^16
        unadjusted -= 6
        return unadjusted


    @staticmethod
    def _calculate_checksum(data, number_of_bytes):
        """5.7 CRC Checksum using the polynomial given in the datasheet"""
        # CRC
        POLYNOMIAL = 0x131  # //P(x)=x^8+x^5+x^4+1 = 100110001
        crc = 0
        # calculates 8-Bit checksum with given polynomial
        for byteCtr in range(number_of_bytes):
            crc ^= (data[byteCtr])
            for bit in range(8, 0, -1):
                if crc & 0x80:
                    crc = (crc << 1) ^ POLYNOMIAL
                else:
                    crc = (crc << 1)
        return crc
Exemplo n.º 36
0
from smbus import SMBus

addr = 0x8  # bus address
bus = SMBus(1)  # indicates /dev/ic2-1
bus.write_byte(addr, 0x1)  # switch it on
input("Press return to exit")
bus.write_byte(addr, 0x0)  # switch it on
Exemplo n.º 37
0
# Button to terminate

from smbus import SMBus
import sys
import time
from Disp4tronix import Disp4tronix
from ButtonLib import *

def myButtonListener(event):
    global isRunning
    isRunning = False

i2c_address = 0x48
dp = Disp4tronix()

print "starting"
channel = 0
bus = SMBus(1) # For revision 2 Raspberry Pi
bus.write_byte(i2c_address, channel) # set control register
addButtonListener(myButtonListener)
data_old = -1
isRunning = True
while isRunning:
    data = bus.read_byte(i2c_address)
    if data != data_old:
         dp.showText("%4d" %data) # right adjusted
         data_old = data
    time.sleep(0.1)  # needed because multiplexed display uses processing power!!
dp.showText("donE")
time.sleep(3)
dp.clear()  # needed to stop the display thread
class Board:
	# Methods list
	# * __init__(gpio_en, gpio_stby, i2cbus = None, gpio_mode_bcm = False)
	# * power(on = None)
	# * reset()
	# * mute(on = None)
	
	# Constants list
	# * DSP - holding instance of DSP control class
	# * TUNER - holding instance of TUNER control class
	
	# Internal variables list
	# * _gpio_en - GPIO pin connected to the EN pin of the board
	# * _gpio_stby - GPIO pin connected to the ST-BY pin of the board
	# * _bus - holding instance of SMBus providing I2C bus for communication with chips on the board
	# * _state - dictionary holding current setup of the board
	
	
	#*
	#* Inits class
	#* @param int gpio_en - GPIO pin connected to the EN pin of board
	#* @param int gpio_stby - GPIO pin connected to the ST-BY pin of board
	#* @param int i2cbus - number of i2c bus the board is connected to
	#* @param bool gpio_mode_bcm - if the mode of GPIO module used for specifying GPIO pins is BCM (True) or BOARD (False)
	#*
	def __init__(self, gpio_en, gpio_stby, i2cbus = None, gpio_mode_bcm = False):
		if i2cbus == None:
			raise Exception()#TODO auto selection based on RPI board revision
		
		self._gpio_en = gpio_en
		self._gpio_stby = gpio_stby
		
		self._bus = SMBus(i2cbus)
		sleep(0.5)
		
		GPIO.setmode(GPIO.BCM if gpio_mode_bcm else GPIO.BOARD)
		GPIO.setup(self._gpio_en, GPIO.OUT, GPIO.LOW)
		GPIO.setup(self._gpio_stby, GPIO.OUT, GPIO.LOW)
		
		self._state = {
			"power": False,
			"mute": True
		}
		
		self.DSP = DSP(self)
		self.TUNER = TUNER(self)
		
		# init GPIOs
		self.power(False)
		self.mute(True)
	# end of method __init__
	
	#*
	#* Destructor
	#*
	def __del__(self):
		self.power(False)
		GPIO.cleanup()
	# end of method __del__
	
	
	#*
	#* Turns on-board voltage regulators on or off
	#* @param bool on - True/False for setting the power state, None to return current state only
	#* @return bool - if the voltage regulators are on or off (software only)
	#*
	def power(self, on = None):
		if on != None:
			old_state = self._state["power"]
			
			self._state["power"] = bool(on)
			
			if not self._state["power"]:
				self.mute(True)
				self.DSP.beforePowerOff()
				self.TUNER.beforePowerOff()
				sleep(0.2)
			
			GPIO.output(self._gpio_en, self._state["power"])
			
			if not old_state and self._state["power"]:
				sleep(0.5)
				self.DSP.afterPowerOn()
				self.TUNER.afterPowerOn()
		
		return self._state["power"]
	# end of method power
	
	#*
	#* Resets board by turning it off and then on after 2 seconds
	#*
	def reset(self):
		self.power(False)
		sleep(2)
		self.power(True)
	# end of method reset
	
	#*
	#* Enables or disables amplifier stand-by mode
	#* @param bool on - True/False for setting the mute, None to return current state only
	#* @return bool - if the amplifier is muted or not (software only)
	#*
	def mute(self, on = None):
		if on != None:
			on = bool(on)
			
			if self._state["power"] or on:
				self._state["mute"] = on
				GPIO.output(self._gpio_stby, not self._state["mute"])
		
		return self._state["mute"]
	# end of method mute
	
	
	#*
	#* Send data over I2C if the Board is powered on
	#* @param int address - address byte
	#* @param tuple/list data - data bytes to be sent
	#*
	def _i2c_write(self, address, data):
		if address < 0 or len(data) < 1:
			return
		
		if not self._state["power"]:# send data to board but only if it is powered
			return
		
		if len(data) > 1:
			self._bus.write_i2c_block_data(address, data[0], data[1:])
		else:
			self._bus.write_byte(address, data[0])
Exemplo n.º 39
0
import optparse
from smbus import SMBus
import time

#######################
# Get options
#######################

parser = optparse.OptionParser("usage: %prog [options] <decimal to write>")

#parser.add_option ('-a', dest='address', type='string',
#                   default = '70',
#                   help="Hex value of address of i2c device.")

options, args = parser.parse_args()

if len(args) != 1:
	print "Please specify decimal integer to write via i2c"
	sys.exit()


byteToWrite = int(args[0])
#######################

bus = SMBus(1)
address = 0x70

print bus.read_byte(address)
bus.write_byte(address, byteToWrite)
print bus.read_byte(address)
Exemplo n.º 40
0
from smbus import SMBus

addr = 0x04
bus = SMBus(1)

while True:
    k = input()
    bus.write_byte(addr, (int)(k))
    print(bus.read_byte(addr))
Exemplo n.º 41
0
#referenced :https://www.thegeekpub.com/18263/raspberry-pi-to-arduino-i2c-communication/

import RPi.GPIO as GPIO
from smbus import SMBus

address = 0x8  #bus address
bus = SMBus(1)  #indicates /dev/i2c-1

print("Type 1 for led to ON and 0 to OFF")
try:
    while True:

        value = input("Value :  ")

        if value == "1":
            bus.write_byte(address, 0x1)  #switch on
        elif value == "0":
            bus.write_byte(address, 0x0)  #switch off

except KeyboardInterrupt:
    GPIO.cleanup()
Exemplo n.º 42
0
class MS5611:
    """Driver for reading temperature/pressure MS5611 Pressure Sensor."""
    
    def __init__(self, bus = 1, i2c = 0x76, elevation = 0):
        """Initialize the Driver.

        Default bus is 1.  If you have a Rev 1 RPi then you will need to use bus 0.
        A bus object can also be passed in if you are sharing it among other modules
        
        Arguments (All optional):
        bus -- 0, 1, or a bus object
        i2c -- I2C address
        elevation -- Elevation in meters"""
        
        if(bus == 0 or bus == 1):
            self.bus = SMBus(bus)
        else:
            self.bus = bus
        self.i2c = i2c
        self.elevation = elevation


    def setElevation(self, elevation):
        self.elevation = elevation


    def setElevationFt(self, elevation):
        self.elevation = elevation / 3.2808


    def setI2c(self, i2c):
        self.i2c = i2c


    def read(self):
        ## Get raw pressure
        self.bus.write_byte(self.i2c, 0x48)
        time.sleep(0.05)

        D1 = self.bus.read_i2c_block_data(self.i2c, 0x00)
        D1 = D1[0] * 65536 + D1[1] * 256.0 + D1[2]
        time.sleep(0.05)

        ## Get raw temperature
        self.bus.write_byte(self.i2c, 0x58)
        time.sleep(0.05)
        D2 = self.bus.read_i2c_block_data(self.i2c, 0x00)
        D2 = D2[0] * 65536 + D2[1] * 256.0 + D2[2]
        time.sleep(0.05)

        
        ## Read Constants from Sensor
        if hasattr(self, 'C1'):
            C1 = self.C1
        else:
            C1 = self.bus.read_i2c_block_data(self.i2c, 0xA2) #Pressure Sensitivity
            C1 = C1[0] * 256.0 + C1[1]
            self.C1 = C1
            time.sleep(0.05)

        if hasattr(self, 'C2'):
            C2 = self.C2
        else:
            C2 = self.bus.read_i2c_block_data(self.i2c, 0xA4) #Pressure Offset
            C2 = C2[0] * 256.0 + C2[1]
            self.C2 = C2
            time.sleep(0.05)

        if hasattr(self, 'C3'):
            C3 = self.C3
        else:
            C3 = self.bus.read_i2c_block_data(self.i2c, 0xA6) #Temperature coefficient of pressure sensitivity
            C3 = C3[0] * 256.0 + C3[1]
            self.C3 = C3
            time.sleep(0.05)

        if hasattr(self, 'C4'):
            C4 = self.C4
        else:
            C4 = self.bus.read_i2c_block_data(self.i2c, 0xA8) #Temperature coefficient of pressure offset
            C4 = C4[0] * 256.0 + C4[1]
            self.C4 = C4
            time.sleep(0.05)

        if hasattr(self, 'C5'):
            C5 = self.C5
        else:
            C5 = self.bus.read_i2c_block_data(self.i2c, 0xAA) #Reference temperature
            C5 = C5[0] * 256.0 + C5[1]
            self.C5 = C5
            time.sleep(0.05)

        if hasattr(self, 'C6'):
            C6 = self.C6
        else:
            C6 = self.bus.read_i2c_block_data(self.i2c, 0xAC) #Temperature coefficient of the temperature
            C6 = C6[0] * 256.0 + C6[1]
            self.C6 = C6
            time.sleep(0.05)

        
        ## These are the calculations provided in the datasheet for the sensor.
        dT = D2 - C5 * 2**8
        TEMP = 2000 + dT * C6 / 2**23

        ## Set Values to class to be used elsewhere
        self.tempC = TEMP/100.0
        self.tempF = TEMP/100.0 * 9.0/5 + 32
        self.tempK = TEMP/100.0 + 273.15

        ## These calculations are all used to produce the final pressure value
        OFF = C2 * 2**16 + (C4 * dT) / 2**7
        SENS = C1 * 2**15 + (C3 * dT) / 2**8
        P = (D1 * SENS / 2**21 - OFF) / 2**15
        self.pressure = P/100.0

        ## Calculate an offset for the pressure.  This is required so that the readings are correct.
        ##   Equation can be found here: http://en.wikipedia.org/wiki/Barometric_formula
        altOffset = math.exp( (-9.80665 * 0.0289644 * self.elevation) / (8.31432 * self.tempK) )
        self.pressureAdj = ( P/altOffset ) / 100.0 

    def getTempC(self):
        return self.tempC

    def getTempF(self):
        return self.tempF

    def getPressure(self):
        return self.pressure

    def getPressureAdj(self):
        return self.pressureAdj

    def getBus(self):
        return self.bus

    def printResults(self):
        print "Temperature:", round(self.tempC, 2), "C"
        print "            ", round(self.tempF, 2), "F"

        print "Pressure Absolute:", round(self.pressure, 2), "hPa"
        print "         Adjusted:", round(self.pressureAdj, 2), "hPa"
        print "         Adjusted:", round(self.convert2In(self.pressureAdj), 2), "in"

    def convert2In(self, pressure):
        return pressure * 0.0295301
Exemplo n.º 43
0
Arquivo: main.py Projeto: gfsduog/prom
 for note in SONG:
     p.ChangeFrequency(note[0])
     sleep(note[1])
 p.stop()
 p.ChangeFrequency(N_BOUNCE)
 for led in LEDS: gpio.setup(led, gpio.OUT)
 oldBugger = WIDTH * HEIGHT * [None]
 oldTime = time()
 counter = 0
 sorry = True
 while 1:
     newTime = time()
     counter += newTime - oldTime
     if newTime - sfxStartTime > sfxLength:
         p.stop()
     adc.write_byte(33, 128)
     knob = adc.read_word_data(33, 0)
     knob = ((knob & 15) << 8 | knob >> 8) - 683
     if knob < 0: knob = 0
     elif knob > 2730: knob = 2730
     Player0Bat = HEIGHT - int(round(knob * (HEIGHT - Player0Height) / 2731.)) - Player0Height
     if sorry:
         knob = adc.read_byte_data(36,0) - 9
         if knob < 0: knob = 0
         elif knob > 220: knob = 220
         Player1Bat = HEIGHT - int(round(knob * (HEIGHT - Player1Height) / 220.)) - Player1Height
         gpio.output(17, 1)
         gpio.output(17, 0)
     sorry = not sorry
     if Player0SizeCounter < 15: Player0SizeCounter += newTime - oldTime
     else: Player0Height = 3
Exemplo n.º 44
0
    lcd_display_temperature(bme280.temperature)
    lcd_display_humidity(bme280.humidity)
    lcd_display_pressure(bme280.pressure)
    lcd_display_info()
    
print ("System running...")
lcd_config()
lcd_clear()

ledstate = "0"
while True:
    #ledstate = input(">>>>   ")
    ledstate = int(ledstate)+1
    if(3<ledstate):
        ledstate = "0"
    ledstate = str(ledstate)
    time.sleep(1)
    lcd_display_sensor_data()
    
    if ledstate == "1":
        bus.write_byte(addr, 0x1) # switch it on
    elif ledstate == "2":
        bus.write_byte(addr, 0x2) # switch it on
    elif ledstate == "3":
        bus.write_byte(addr, 0x3) # switch it on
    elif ledstate == "55":
        bus.write_byte(addr, 0x55) # switch it on
    elif ledstate == "aa":
        bus.write_byte(addr, 0xaa) # switch it on

Exemplo n.º 45
0
class MS5611:

    __MS5611_ADDRESS_CSB_LOW = 0x76
    __MS5611_ADDRESS_CSB_HIGH = 0x77
    __MS5611_DEFAULT_ADDRESS = 0x77

    __MS5611_RA_ADC = 0x00
    __MS5611_RA_RESET = 0x1E

    __MS5611_RA_C0 = 0xA0
    __MS5611_RA_C1 = 0xA2
    __MS5611_RA_C2 = 0xA4
    __MS5611_RA_C3 = 0xA6
    __MS5611_RA_C4 = 0xA8
    __MS5611_RA_C5 = 0xAA
    __MS5611_RA_C6 = 0xAC
    __MS5611_RA_C7 = 0xAE

    __MS5611_RA_D1_OSR_256 = 0x40
    __MS5611_RA_D1_OSR_512 = 0x42
    __MS5611_RA_D1_OSR_1024 = 0x44
    __MS5611_RA_D1_OSR_2048 = 0x46
    __MS5611_RA_D1_OSR_4096 = 0x48

    __MS5611_RA_D2_OSR_256 = 0x50
    __MS5611_RA_D2_OSR_512 = 0x52
    __MS5611_RA_D2_OSR_1024 = 0x54
    __MS5611_RA_D2_OSR_2048 = 0x56
    __MS5611_RA_D2_OSR_4096 = 0x58

    def __init__(self, I2C_bus_number=1, address=0x77):
        self.bus = SMBus(I2C_bus_number)
        self.address = address
        self.C1 = 0
        self.C2 = 0
        self.C3 = 0
        self.C4 = 0
        self.C5 = 0
        self.C6 = 0
        self.D1 = 0
        self.D2 = 0
        self.TEMP = 0.0  # Calculated temperature
        self.PRES = 0.0  # Calculated Pressure

    def initialize(self):
        ## The MS6511 Sensor stores 6 values in the EPROM memory that we need in order to calculate the actual temperature and pressure
        ## These values are calculated/stored at the factory when the sensor is calibrated.
        ##      I probably could have used the read word function instead of the whole block, but I wanted to keep things consistent.
        C1 = self.bus.read_i2c_block_data(
            self.address, self.__MS5611_RA_C1)  #Pressure Sensitivity
        #time.sleep(0.05)
        C2 = self.bus.read_i2c_block_data(
            self.address, self.__MS5611_RA_C2)  #Pressure Offset
        #time.sleep(0.05)
        C3 = self.bus.read_i2c_block_data(
            self.address, self.__MS5611_RA_C3
        )  #Temperature coefficient of pressure sensitivity
        #time.sleep(0.05)
        C4 = self.bus.read_i2c_block_data(
            self.address,
            self.__MS5611_RA_C4)  #Temperature coefficient of pressure offset
        #time.sleep(0.05)
        C5 = self.bus.read_i2c_block_data(
            self.address, self.__MS5611_RA_C5)  #Reference temperature
        #time.sleep(0.05)
        C6 = self.bus.read_i2c_block_data(
            self.address,
            self.__MS5611_RA_C6)  #Temperature coefficient of the temperature

        ## Again here we are converting the 2 8bit packages into a single decimal
        self.C1 = C1[0] * 256.0 + C1[1]
        self.C2 = C2[0] * 256.0 + C2[1]
        self.C3 = C3[0] * 256.0 + C3[1]
        self.C4 = C4[0] * 256.0 + C4[1]
        self.C5 = C5[0] * 256.0 + C5[1]
        self.C6 = C6[0] * 256.0 + C6[1]

        self.update()

    def refreshPressure(self, OSR=__MS5611_RA_D1_OSR_4096):
        self.bus.write_byte(self.address, OSR)

    def refreshTemperature(self, OSR=__MS5611_RA_D2_OSR_4096):
        self.bus.write_byte(self.address, OSR)

    def readPressure(self):
        D1 = self.bus.read_i2c_block_data(self.address, self.__MS5611_RA_ADC)
        self.D1 = D1[0] * 65536 + D1[1] * 256.0 + D1[2]

    def readTemperature(self):
        D2 = self.bus.read_i2c_block_data(self.address, self.__MS5611_RA_ADC)
        self.D2 = D2[0] * 65536 + D2[1] * 256.0 + D2[2]

    def calculatePressureAndTemperature(self):
        dT = self.D2 - self.C5 * 2**8
        self.TEMP = 2000 + dT * self.C6 / 2**23

        OFF = self.C2 * 2**16 + (self.C4 * dT) / 2**7
        SENS = self.C1 * 2**15 + (self.C3 * dT) / 2**8

        if (self.TEMP >= 2000):
            T2 = 0
            OFF2 = 0
            SENS2 = 0
        elif (self.TEMP < 2000):
            T2 = dT * dT / 2**31
            OFF2 = 5 * ((self.TEMP - 2000)**2) / 2
            SENS2 = OFF2 / 2
        elif (self.TEMP < -1500):
            OFF2 = OFF2 + 7 * ((self.TEMP + 1500)**2)
            SENS2 = SENS2 + 11 * (self.TEMP + 1500)**2 / 2

        self.TEMP = self.TEMP - T2
        OFF = OFF - OFF2
        SENS = SENS - SENS2

        self.PRES = (self.D1 * SENS / 2**21 - OFF) / 2**15

        self.TEMP = self.TEMP / 100  # Temperature updated
        self.PRES = self.PRES / 100  # Pressure updated

    def returnPressure(self):
        return self.PRES

    def returnTemperature(self):
        return self.TEMP

    def update(self):
        self.refreshPressure()
        time.sleep(0.01)  # Waiting for pressure data ready
        self.readPressure()

        self.refreshTemperature()
        time.sleep(0.01)  # Waiting for temperature data ready
        self.readTemperature()

        self.calculatePressureAndTemperature()

    def test(self):
        self.initialize()
        self.update()
        is_pressure_valid = 1000 <= self.PRES <= 1050
        is_temp_valid = -40 <= self.TEMP <= 80

        return is_pressure_valid and is_temp_valid
Exemplo n.º 46
0
from smbus import SMBus
import time
bus = SMBus(1)  #i2c port 1 /dev/12c-1

address = 0x8

while True:
    try:
        ledstate = input('Put LED in state : ')
        if ledstate == "1":
            bus.write_byte(address, 0x1)  #on
        elif ledstate == "0":
            bus.write_byte(address, 0x0)
        elif ledstate == "b":
            while True:
                bus.write_byte(address, 0x1)  #on
                time.sleep(0.5)
                bus.write_byte(address, 0x0)
                time.sleep(0.5)

        else:
            break
    except OSError:
        print("Possible disconnection of I/O pins")
        break
Exemplo n.º 47
0
class I2C(_Basic_class):
    MASTER = 0
    SLAVE = 1
    RETRY = 5

    def __init__(self, *args,
                 **kargs):  # *args表示位置参数(形式参数),可无,; **kargs表示默认值参数,可无。
        super().__init__()
        self._bus = 1
        self._smbus = SMBus(self._bus)

    def _i2c_write_byte(self, addr, data):  # i2C 写系列函数
        self._debug("_i2c_write_byte: [0x{:02X}] [0x{:02X}]".format(
            addr, data))
        return self._smbus.write_byte(addr, data)

    def _i2c_write_byte_data(self, addr, reg, data):
        self._debug(
            "_i2c_write_byte_data: [0x{:02X}] [0x{:02X}] [0x{:02X}]".format(
                addr, reg, data))
        return self._smbus.write_byte_data(addr, reg, data)

    def _i2c_write_word_data(self, addr, reg, data):
        self._debug(
            "_i2c_write_word_data: [0x{:02X}] [0x{:02X}] [0x{:04X}]".format(
                addr, reg, data))
        return self._smbus.write_word_data(addr, reg, data)

    def _i2c_write_i2c_block_data(self, addr, reg, data):
        self._debug(
            "_i2c_write_i2c_block_data: [0x{:02X}] [0x{:02X}] {}".format(
                addr, reg, data))
        return self._smbus.write_i2c_block_data(addr, reg, data)

    def _i2c_read_byte(self, addr):  # i2C 读系列函数
        self._debug("_i2c_read_byte: [0x{:02X}]".format(addr))
        return self._smbus.read_byte(addr)

    def _i2c_read_i2c_block_data(self, addr, reg, num):
        self._debug(
            "_i2c_read_i2c_block_data: [0x{:02X}] [0x{:02X}] [{}]".format(
                addr, reg, num))
        return self._smbus.read_i2c_block_data(addr, reg, num)

    def is_ready(self, addr):
        addresses = self.scan()
        if addr in addresses:
            return True
        else:
            return False

    def scan(self):  # 查看有哪些i2c设备
        cmd = "i2cdetect -y %s" % self._bus
        _, output = self.run_command(
            cmd)  # 调用basic中的方法,在linux中运行cmd指令,并返回运行后的内容

        outputs = output.split('\n')[1:]  # 以回车符为分隔符,分割第二行之后的所有行
        self._debug("outputs")
        addresses = []
        for tmp_addresses in outputs:
            if tmp_addresses == "":
                continue
            tmp_addresses = tmp_addresses.split(':')[1]
            tmp_addresses = tmp_addresses.strip().split(
                ' ')  # strip函数是删除字符串两端的字符,split函数是分隔符
            for address in tmp_addresses:
                if address != '--':
                    addresses.append(int(address, 16))
        self._debug("Conneceted i2c device: %s" %
                    addresses)  # append以列表的方式添加address到addresses中
        return addresses

    def send(self, send, addr, timeout=0):  # 发送数据,addr为从机地址,send为数据
        if isinstance(send, bytearray):
            data_all = list(send)
        elif isinstance(send, int):
            data_all = []
            d = "{:X}".format(send)
            d = "{}{}".format(
                "0" if len(d) % 2 == 1 else "", d
            )  # format是将()中的内容对应填入{}中,()中的第一个参数是一个三目运算符,if条件成立则为“0”,不成立则为“”(空的意思),第二个参数是d,此行代码意思为,当字符串为奇数位时,在字符串最强面添加‘0’,否则,不添加, 方便以下函数的应用
            # print(d)
            for i in range(len(d) - 2, -1, -2):  # 从字符串最后开始取,每次取2位
                tmp = int(d[i:i + 2], 16)  # 将两位字符转化为16进制
                # print(tmp)
                data_all.append(tmp)  # 添加到data_all数组中
            data_all.reverse()
        elif isinstance(send, list):
            data_all = send
        else:
            raise ValueError(
                "send data must be int, list, or bytearray, not {}".format(
                    type(send)))

        if len(data_all) == 1:  # 如果data_all只有一组数
            data = data_all[0]
            self._i2c_write_byte(addr, data)
        elif len(data_all) == 2:  # 如果data_all只有两组数
            reg = data_all[0]
            data = data_all[1]
            self._i2c_write_byte_data(addr, reg, data)
        elif len(data_all) == 3:  # 如果data_all只有三组数
            reg = data_all[0]
            data = (data_all[2] << 8) + data_all[1]
            self._i2c_write_word_data(addr, reg, data)
        else:
            reg = data_all[0]
            data = list(data_all[1:])
            self._i2c_write_i2c_block_data(addr, reg, data)

    def recv(self, recv, addr=0x00, timeout=0):  # 接收数据
        if isinstance(recv, int):  # 将recv转化为二进制数
            result = bytearray(recv)
        elif isinstance(recv, bytearray):
            result = recv
        else:
            return False
        for i in range(len(result)):
            result[i] = self._i2c_read_byte(addr)
        return result

    def mem_write(self,
                  data,
                  addr,
                  memaddr,
                  timeout=5000,
                  addr_size=8):  #memaddr match to chn
        if isinstance(data, bytearray):
            data_all = list(data)
        elif isinstance(data, list):
            data_all = data
        elif isinstance(data, int):
            data_all = []
            data = "%x" % data
            if len(data) % 2 == 1:
                data = "0" + data
            # print(data)
            for i in range(0, len(data), 2):
                # print(data[i:i+2])
                data_all.append(int(data[i:i + 2], 16))
        else:
            raise ValueError(
                "memery write require arguement of bytearray, list, int less than 0xFF"
            )
        # print(data_all)
        self._i2c_write_i2c_block_data(addr, memaddr, data_all)

    def mem_read(self, data, addr, memaddr, timeout=5000, addr_size=8):  # 读取数据
        if isinstance(data, int):
            num = data
        elif isinstance(data, bytearray):
            num = len(data)
        else:
            return False
        result = bytearray(self._i2c_read_i2c_block_data(addr, memaddr, num))
        return result

    def readfrom_mem_into(self, addr, memaddr, buf):
        buf = self.mem_read(len(buf), addr, memaddr)
        return buf

    def writeto_mem(self, addr, memaddr, data):
        self.mem_write(data, addr, memaddr)


# i2c = I2C()
# i2c.scan()
# i2c.mem_write(0xff53773, 20, 20)
Exemplo n.º 48
0
#Read a value from analogue input 0
#in A/D in the PCF8591P @ address 0x48
from smbus import SMBus

bus = SMBus(0)

print("Read the A/D")
print("Ctrl C to stop")
bus.write_byte(0x48, 0) # set control register to read channel 0
last_reading =-1

while(0 == 0): # do forever
   reading = bus.read_byte(0x48) # read A/D
   if(abs(last_reading - reading) > 2):
      print(reading)
      last_reading = reading
class MAX30105(object):
    def __init__(self, bus, address):
        self.address = address
        self.bus = SMBus(bus)
        self._led_mode = None
        self._pulse_width_set = None

        try:
            self.bus.read_byte(self.address)
        except:
            print("Sensor not found. Check wiring.")
            raise SystemExit()
        else:
            print("Found MAX30105 Particle Sensor on bus {}: [{}]".format(
                bus, hex(self.address)))

    def read_register(self, REG, n_bytes=1):
        self.bus.write_byte(self.address, REG)
        return self.bus.read_i2c_block_data(self.address, REG, n_bytes)

    def write_register(self, REG, VALUE):
        self.bus.write_i2c_block_data(self.address, REG, [VALUE])
        return

    def bit_mask(self, REG, MASK, NEW_VALUE):
        newCONTENTS = (self.byte_to_int(self.read_register(REG))
                       & MASK) | NEW_VALUE
        self.write_register(REG, newCONTENTS)
        return

    def setup_sensor(self, LED_MODE=2, LED_POWER=0x1F, PULSE_WIDTH=0x01):
        self.bit_mask(0x09, 0xBF, 0x40)
        time.sleep(1)

        # 3: 69 (15-bit), 2: 118 (16-bit), 1: 215 (17-bit), 0: 411 (18-bit)
        self.bit_mask(0x0A, 0xFC, PULSE_WIDTH)
        self._pulse_width_set = PULSE_WIDTH

        if LED_MODE not in [1, 2, 3]:
            raise ValueError('wrong LED mode:{0}!'.format(LED_MODE))
        elif LED_MODE == 1:
            self.bit_mask(0x09, 0xF8, 0x02)
            self.write_register(0x0C, LED_POWER)
        elif LED_MODE == 2:
            self.bit_mask(0x09, 0xF8, 0x03)
            self.write_register(0x0C, LED_POWER)
            self.write_register(0x0D, LED_POWER)
        elif LED_MODE == 3:
            self.bit_mask(0x09, 0xF8, 0x07)
            self.write_register(0x0C, LED_POWER)
            self.write_register(0x0D, LED_POWER)
            self.write_register(0x0E, LED_POWER)
            self.write_register(0x11, 0b00100001)
            self.write_register(0x12, 0b00000011)
        self._led_mode = LED_MODE

        self.bit_mask(0x0A, 0xE3, 0x0C)  # sampl. rate: 50
        # 50: 0x00, 100: 0x04, 200: 0x08, 400: 0x0C,
        # 800: 0x10, 1000: 0x14, 1600: 0x18, 3200: 0x1C

        self.bit_mask(0x0A, 0x9F, 0x60)  # ADC range: 2048
        # 2048: 0x00, 4096: 0x20, 8192: 0x40, 16384: 0x60

        self.bit_mask(0x08, ~0b11100000, 0x00)  # FIFO sample avg: (no)
        # 1: 0x00, 2: 0x20, 4: 0x40, 8: 0x60, 16: 0x80, 32: 0xA0

        self.bit_mask(0x08, 0xEF, 0x01)  # FIFO rollover: enable
        # 0x00/0x01: dis-/enable

        self.write_register(0x04, 0)
        self.write_register(0x05, 0)
        self.write_register(0x06, 0)

    def set_red_led_power(self, LED_POWER):
        self.bit_mask(0x09, 0xF8, 0x02)
        self.write_register(0x0C, LED_POWER)

    def set_ir_led_power(self, LED_POWER):
        self.bit_mask(0x09, 0xF8, 0x03)
        self.write_register(0x0D, LED_POWER)

    def set_green_led_power(self, LED_POWER):
        self.bit_mask(0x09, 0xF8, 0x07)
        self.write_register(0x0E, LED_POWER)

    def byte_to_int(self, byte_data):
        return int.from_bytes(byte_data, byteorder='big', signed=False)

    def read_sensor(self, pointer_position):
        self.write_register(0x06, pointer_position)
        fifo_bytes = self.read_register(0x07, self._led_mode * 3)
        red_int = self.byte_to_int(fifo_bytes[0:3])
        IR_int = self.byte_to_int(fifo_bytes[3:6])
        green_int = self.byte_to_int(fifo_bytes[6:9])
        return red_int, IR_int, green_int

    def clear_fifo(self):
        self.write_register(0x04, 0)
        self.write_register(0x05, 0)
        self.write_register(0x06, 0)
Exemplo n.º 50
0
import boto
import json
import time
import datetime
import boto.kinesis
from boto import kinesis
from boto.kinesis.exceptions import ResourceNotFoundException
from random import randint
from smbus import SMBus

bus = SMBus(1)
print("Read the A/D and put record Kinesis")
print("Ctrl C to stop")
bus.write_byte(0x48, 0)
last_reading =-1

ACCESS_KEY="AKIAIMV6XL4QVZA5GB2Q"
SECRET_KEY="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"
region_name="us-west-2"


kinesis =boto.kinesis.connect_to_region(region_name,aws_access_key_id = ACCESS_KEY,aws_secret_access_key = SECRET_KEY)
streamName="sound"
partitionKey="IoTExample"
shardCount=1
global stream

def readSoundSensor():
     return bus.read_byte(0x48)

def runController():
Exemplo n.º 51
0
class sgh_PCF8591P:

    def __init__(self, busNum):
#       Remove annoying init message (The Raspberry Pi Guy) 
        if busNum == 0:
            self.__bus = SMBus(0)
        else:
            self.__bus = SMBus(1)
        self.__addr = self.__checkI2Caddress(72)
        self.__DACEnabled = 0

    def readADC(self, _sgh_PCF8591P__chan = 0):
        __checkedChan = self.__checkChannelNo(__chan)
        self.__bus.write_byte(self.__addr, __checkedChan | self.__DACEnabled)
        __reading = self.__bus.read_byte(self.__addr)
        __reading = self.__bus.read_byte(self.__addr)
        return __reading

    def readAllADC(self):
        __readings = []
        self.__bus.write_byte(self.__addr, 4 | self.__DACEnabled)
        __reading = self.__bus.read_byte(self.__addr)
        for i in range(4):
            __readings.append(self.__bus.read_byte(self.__addr))

        return __readings

    def writeDAC(self, _sgh_PCF8591P__val = 0):
        __checkedVal = self.__checkDACVal(__val)
        self.__DACEnabled = 64
        self.__bus.write_byte_data(self.__addr, self.__DACEnabled, __checkedVal)

    def enableDAC(self):
        self.__DACEnabled = 64
        self.__bus.write_byte(self.__addr, self.__DACEnabled)

    def disableDAC(self):
        self.__DACEnabled = 0
        self.__bus.write_byte(self.__addr, self.__DACEnabled)

    def __checkI2Caddress(self, _sgh_PCF8591P__addr):
        if type(__addr) is not int:
            raise I2CaddressOutOfBoundsError
        elif __addr < 0:
            raise I2CaddressOutOfBoundsError
        elif __addr > 127:
            raise I2CaddressOutOfBoundsError
        return __addr

    def __checkChannelNo(self, _sgh_PCF8591P__chan):
        if type(__chan) is not int:
            raise PCF8591PchannelOutOfBoundsError
        elif __chan < 0:
            raise PCF8591PchannelOutOfBoundsError
        elif __chan > 3:
            raise PCF8591PchannelOutOfBoundsError
        return __chan

    def __checkDACVal(self, _sgh_PCF8591P__val):
        if type(__val) is not int:
            raise PCF8591PDACvalueOutOfBoundsError
        elif __val < 0:
            raise PCF8591PDACvalueOutOfBoundsError
        elif __val > 255:
            raise PCF8591PDACvalueOutOfBoundsError
        return __val
from smbus import SMBus
import pyfiglet

addr = 0x8
bus = SMBus(1)

welcome_screen = pyfiglet.figlet_format("POMODORO\n", font="digital")
print(welcome_screen)

print("Press 1 to open the box and press 2 to close it.\n")

run = 1
while (run == 1):

    comd = input("> ")

    if comd == "2":
        bus.write_byte(addr, 0x39)
        print("Box has been closed!\n")
    elif comd == "1":
        bus.write_byte(addr, 0x0)
        print("Box has been opened!\n")
    else:
        run = 0
Exemplo n.º 53
0
class PM2:
    '''Handle display'''

    # Translation value from String to Display
    digits = {
        '': 0,
        '1': 96,
        '2': 167,
        '3': 227,
        '4': 106,
        '5': 203,
        '6': 207,
        '7': 224,
        '8': 239,
        '9': 235,
        '0': 237
    }

    buffer = [0 for i in xrange(20)]  # Buffer for device RAM

    def __init__(self,
                 defaultBus=PI_DEFAULT_BUS,
                 defaultAddr=PM2_DEFAULT_ADDRESS):
        self.bus = SMBus(defaultBus)
        self.busNum = defaultBus
        self.defaultAddr = defaultAddr
        self.bus.close()
        self.bus.open(self.busNum)
        self.bus.write_byte(self.defaultAddr, PM2_MODE_SET)
        self.clear()
        self.set_mode('normal')
        self.top_right('00')
        self.middle('000')
        self.top_left('0000')
        self.bottom_left('0000')

    def write_bit(self, addr, position, value):
        '''write one bit to buffer
           @addr : buffer address -> int
           @position : bit position -> int
           @value : bit value -> boolean
        '''
        mask = ~(1 << position)
        value = value << position
        self.buffer[addr] = (self.buffer[addr] & mask) | value

    def write_digit(self, addr, value):
        '''write single/multiple digit(s) to buffer
           @addr : buffer address -> int
           @value : single/mutiple digit -> string
        '''
        i = addr
        for x in reversed(value):
            intVal = self.digits[x]
            mask = 1 << 4  # Preserve DP bit
            self.buffer[i] = (self.buffer[i] & mask) | intVal
            i += 1

    def set_mode(self, mode):
        '''Toggle between different possible mode :
            -normal
            -cal/hr
            -watts
            -heart rate
        '''
        if (mode == 'normal'):
            """Time, /500m, Distance"""
            self.set_segment_colon_top_left(False)
            self.set_segment_colon_top_right(True)
            self.set_segment_dp_top(False)
            self.set_segment_time_top(True)
            self.set_segment_meters_top(False)
            self.set_segment_spm_top(True)
            self.set_segment_int_top(False)
            self.set_segment_1_middle(False)
            self.set_segment_colon_middle(True)
            self.set_segment_500m_middle(True)
            self.set_segment_calhr_middle(False)
            self.set_segment_watts_middle(False)
            self.set_segment_rest_time_middle(False)
            self.set_segment_int_middle(False)
            self.set_segment_colon_bottom_left(False)
            self.set_segment_colon_bottom_right(False)
            self.set_segment_dp_bottom(False)
            self.set_segment_ave_bottom(False)
            self.set_segment_500m_bottom(False)
            self.set_segment_watts_bottom(False)
            self.set_segment_split_bottom(False)
            self.set_segment_cal_bottom(False)
            self.set_segment_proj_bottom(False)
            self.set_segment_time_bottom(False)
            self.set_segment_meters_bottom(True)
            self.set_segment_dragfactor_bottom(False)
        elif (mode == 'watts'):
            """Time, Watts, Distance"""
            self.set_segment_colon_top_left(False)
            self.set_segment_colon_top_right(True)
            self.set_segment_dp_top(False)
            self.set_segment_time_top(True)
            self.set_segment_meters_top(False)
            self.set_segment_spm_top(True)
            self.set_segment_int_top(False)
            self.set_segment_1_middle(False)
            self.set_segment_colon_middle(False)
            self.set_segment_500m_middle(False)
            self.set_segment_calhr_middle(False)
            self.set_segment_watts_middle(True)
            self.set_segment_rest_time_middle(False)
            self.set_segment_int_middle(False)
            self.set_segment_colon_bottom_left(False)
            self.set_segment_colon_bottom_right(False)
            self.set_segment_dp_bottom(False)
            self.set_segment_ave_bottom(True)
            self.set_segment_500m_bottom(False)
            self.set_segment_watts_bottom(True)
            self.set_segment_split_bottom(False)
            self.set_segment_cal_bottom(False)
            self.set_segment_proj_bottom(False)
            self.set_segment_time_bottom(False)
            self.set_segment_meters_bottom(False)
            self.set_segment_dragfactor_bottom(False)
        elif (mode == 'heart rate'):
            self.set_segment_colon_middle(isHeartRate)

    def set_segment_colon_top_left(self, enabled):
        '''Set first : segment at the top from the left'''
        self.write_bit(13, 5, enabled)

    def set_segment_colon_top_right(self, enabled):
        '''Set 2nd : segment at the top from the left'''
        self.write_bit(18, 1, enabled)

    def set_segment_int_top(self, enabled):
        '''Set INT segment in the top right corner'''
        self.write_bit(19, 0, enabled)

    def set_segment_spm_top(self, enabled):
        '''Set SPM segment in the top right corner'''
        self.write_bit(14, 4, enabled)

    def set_segment_meters_top(self, enabled):
        '''Set METERS segment in at the top'''
        self.write_bit(19, 4, enabled)

    def set_segment_time_top(self, enabled):
        '''Set TIME segment in at the top'''
        self.write_bit(0, 4, enabled)

    def set_segment_dp_top(self, enabled):
        '''Set DP segment (decimal point) in at the top'''
        self.write_bit(1, 4, enabled)

    def set_segment_calhr_middle(self, enabled):
        '''Set CAL/HR segment in the middle'''
        self.write_bit(19, 7, enabled)

    def set_segment_500m_middle(self, enabled):
        '''Set /500M segment in the middle'''
        self.write_bit(19, 5, enabled)

    def set_segment_int_middle(self, enabled):
        '''Set INT segment in the middle'''
        self.write_bit(19, 2, enabled)

    def set_segment_watts_middle(self, enabled):
        '''Set WATTS segment in the middle'''
        self.write_bit(19, 6, enabled)

    def set_segment_colon_middle(self, enabled):
        '''Set : segment in the middle'''
        self.write_bit(19, 1, enabled)

    def set_segment_1_middle(self, enabled):
        '''Set '1' segment in the middle'''
        self.write_bit(13, 6, enabled)

    def set_segment_rest_time_middle(self, enabled):
        '''Set REST TIME segment in the middle'''
        self.write_bit(10, 4, enabled)

    def set_segment_ave_bottom(self, enabled):
        '''Set AVE segment in the bottom'''
        self.write_bit(13, 7, enabled)

    def set_segment_500m_bottom(self, enabled):
        '''Set /500M segment in the bottom'''
        self.write_bit(13, 4, enabled)

    def set_segment_watts_bottom(self, enabled):
        '''Set WATTS segment in the bottom'''
        self.write_bit(12, 4, enabled)

    def set_segment_split_bottom(self, enabled):
        '''Set SPLIT segment in the bottom'''
        self.write_bit(11, 4, enabled)

    def set_segment_cal_bottom(self, enabled):
        '''Set CAL segment in the bottom'''
        self.write_bit(9, 4, enabled)

    def set_segment_proj_bottom(self, enabled):
        '''Set PROJ segment in the bottom'''
        self.write_bit(8, 4, enabled)

    def set_segment_dp_bottom(self, enabled):
        '''Set DP segment (decimal point) in the bottom'''
        self.write_bit(6, 4, enabled)

    def set_segment_time_bottom(self, enabled):
        '''Set TIME segment in the bottom'''
        self.write_bit(7, 4, enabled)

    def set_segment_meters_bottom(self, enabled):
        '''Set METERS segment in the bottom'''
        self.write_bit(13, 0, enabled)

    def set_segment_dragfactor_bottom(self, enabled):
        '''Set DRAG FACTOR segment in the bottom'''
        self.write_bit(18, 0, enabled)

    def set_segment_heartrate_bottom(self, enabled):
        '''Set HEART RATE segment in the bottom'''
        self.write_bit(17, 4, enabled)

    def set_segment_colon_bottom_left(self, enabled):
        '''Set 1st : segment at the bottom from the left'''
        self.write_bit(18, 5, enabled)

    def set_segment_colon_bottom_right(self, enabled):
        '''Set 2nd : segment at the bottom from the left'''
        self.write_bit(13, 1, enabled)

    def top_right(self, value):
        '''Display value to the top rigth corner of the screen'''
        startAddr = 14
        if (int(value) <= 99):
            self.write_digit(startAddr, value)
            self.refresh()
            return True
        else:
            return False

    def middle(self, value):
        '''Display value to the middle of the screen'''
        startAddr = 10
        if (int(value) <= 999):
            self.write_digit(startAddr, value)
            self.refresh()
            return True
        elif (int(value) > 999 & int(value) <= 1999):
            self.set_segment_middle_1(True)
            self.write_digit(startAddr, value)
            self.refresh()
        else:
            return False

    def bottom_right(self, value):
        '''Display value to the bottom right corner of the screen'''
        startAddr = 17
        if (int(value) <= 399):
            self.write_digit(startAddr, value)
            self.refrsh()
            return True
        else:
            return False

    def top_left(self, value):
        '''Display value to the top left corner of the screen'''
        startAddr = 0
        if (int(value) <= 99999):
            self.write_digit(startAddr, value)
            self.refresh()
            return True
        else:
            return False

    def bottom_left(self, value):
        '''Display value to the bottom left corner of the screen'''
        startAddr = 5
        if (int(value) <= 99999):
            self.write_digit(startAddr, value)
            self.refresh()
            return True
        else:
            return False

    def refresh(self):
        '''Push buffer content to device RAM at once for display'''
        # Do nothing special execpt avoiding an I2C communication error
        self.bus.write_byte(self.defaultAddr, 0b01100000)
        self.bus.write_i2c_block_data(self.defaultAddr, 0, self.buffer)
        # Do nothing special execpt avoiding an I2C communication error
        self.bus.write_byte(self.defaultAddr, 0b01100000)

    def clear(self):
        '''Clear screen'''
        self.buffer = [0 for x in xrange(20)]
        self.refresh()

    def display_all(self):
        '''Display all possible character on the screen'''
        self.buffer = [255 for x in xrange(20)]
        self.refresh()

    def loop(self):
        self.bus.write_byte_data(self.defaultAddr, 0, 255)
        for x in range(2, 40, 2):
            self.bus.write_byte_data(self.defaultAddr, x - 2, 0)
            self.bus.write_byte_data(self.defaultAddr, x, 255)
            sleep(1)
            if (x > 36):
                self.bus.write_byte(self.defaultAddr, 0b01100000)
Exemplo n.º 54
0
    parity = serial.PARITY_NONE,
    stopbits = serial.STOPBITS_ONE,
    # interCharTimeout = 0.2,
    timeout = 10.0,
    xonxoff = False,
    rtscts = False,
    dsrdtr = False);

i2c0 = SMBus(0)
i2c2 = SMBus(2)

print(icsp_cmd(ser, b'Z'))                      # tristate MCLR (icsp)

if sel == "A":                                  # toggle A_!RST 
    print("selecting RFW ...")
    i2c2.write_byte(0x70, 0x5)                  # steer mux
    ioa = i2c0.read_byte_data(0x23, 0x14)
    i2c0.write_byte_data(0x23, 0x14, ioa&~0x10)
    i2c0.write_byte_data(0x23, 0x14, ioa|0x10)

elif sel == "B":                                # toggle B_!RST
    print("selecting RFE ...")
    i2c2.write_byte(0x70, 0x4)                  # steer mux
    iob = i2c0.read_byte_data(0x22, 0x14)
    i2c0.write_byte_data(0x22, 0x14, iob&~0x10)
    i2c0.write_byte_data(0x22, 0x14, iob|0x10)

elif sel == "N":                               
    print("disabling MUX ...")
    i2c2.write_byte(0x70, 0x0)                  # disable mux
Exemplo n.º 55
0
class I2CDevice(object):
    """
    Class for communicating with an I2C device.

    Allows reading and writing 8-bit, 16-bit, and byte array values to
    registers on the device.

    It can handle signed, unsigned and endianness.

    :var uint address: Assigned I2C address.
    :var uint8 busid: Assigned IC2 bus identifier.

    :param uint address: I2C address.
    :param uint busid: IC2 bus identifier.
    :param class i2c_class: Class implementing the I2C reading interface.
     If None, smbus.SMBus will be used.
    """

    def __init__(self, busnum, address, i2c_class=None):
        self._busnum = busnum
        self._address = address

        if i2c_class is None:
            from smbus import SMBus
            self._bus = SMBus(busnum)
        else:
            self._bus = i2c_class(busnum)

        self._logger = logging.getLogger(
            '/dev/i2c-{}/{:#x}'.format(busnum, address)
        )

    def _debug(self):
        self._logger.setLevel(logging.DEBUG)
        self._logger.addHandler(logging.StreamHandler())

    @property
    def busnum(self):
        return self._busnum

    @property
    def address(self):
        return self._address

    def write(self, value):
        """
        Write the specified 8-bit value to the device base address.
        """
        assert bound_bits(value, 8)

        self._bus.write_byte(self._address, value)
        self._logger.debug(
            'Wrote value {:#x}'.format(value)
        )

    def register_write_u8(self, register, value):
        """
        Write an 8-bit value to the specified 8-bit register.
        """
        assert bound_bits(register, 8)
        assert bound_bits(value, 8)

        self._bus.write_byte_data(self._address, register, value)
        self._logger.debug(
            'Wrote to register {:#x} value {:#x}'.format(register, value)
        )

    def register_write_u16(self, register, value):
        assert bound_bits(register, 8)
        assert bound_bits(value, 16)

        self._bus.write_word_data(self._address, register, value)
        self._logger.debug(
            'Wrote to register pair {:#x}, {:#x} value {:#x} '.format(
                register, register + 1, value
            )
        )

    def read(self):
        """
        Read the device base address and return a 8-bit value.
        """
        result = self._bus.read_byte(self._address) & 0xFF
        self._logger.debug(
            'Read value {:#x}'.format(result)
        )
        return result

    def register_read_u8(self, register):
        """
        Read the specified 8-bit register and return a 8-bit value.
        """
        assert bound_bits(register, 8)

        result = self._bus.read_byte_data(self._address, register) & 0xFF
        self._logger.debug(
            'Read from register {:#x} returns {:#x}'.format(register, result)
        )

        return result

    def register_read_s8(self, register):
        """
        Read the specified 8-bit register and return a signed 7-bit value.
        """
        result = self.register_read_u8(register)
        if result > 127:
            result -= 256
            self._logger.debug('... as signed: {:#x}'.format(result))
        return result

    def register_read_u16(self, register, little_endian=True):
        """
        Read the specified 8-bit register and return a 16-bit value with the
        specified endianness.

        Default is little endian, or least significant byte first.
        """
        assert bound_bits(register, 8)

        result = self._bus.read_word_data(self._address, register) & 0xFFFF
        self._logger.debug(
            'Read from register pair {:#x}, {:#x} value {:#x} '.format(
                register, register + 1, result
            )
        )

        # Swap bytes if using big endian because read_word_data assumes little
        # endian on ARM (little endian) systems.
        if not little_endian:
            result = ((result << 8) & 0xFF00) + (result >> 8)
            self._logger.debug('... as big endian: {:#x}'.format(result))
        return result

    def register_read_s16(self, register, little_endian=True):
        """
        Read the specified 8-bit register and return a signed 15-bit value
        with the specified endianness.

        Default is little endian, or least significant byte first.
        """
        result = self.register_read_u16(register, little_endian)
        if result > 32767:
            result -= 65536
            self._logger.debug('... as signed: {:#x}'.format(result))
        return result

    def register_read_u16le(self, register):
        """
        Same as register_read_u16 with endianness set to little endian.
        """
        return self.register_read_u16(register, little_endian=True)

    def register_read_u16be(self, register):
        """
        Same as register_read_u16 with endianness set to big endian.
        """
        return self.register_read_u16(register, little_endian=False)

    def register_read_s16le(self, register):
        """
        Same as register_read_s16 with endianness set to little endian.
        """
        return self.register_read_s16(register, little_endian=True)

    def register_read_s16be(self, register):
        """
        Same as register_read_s16 with endianness set to big endian.
        """
        return self.register_read_s16(register, little_endian=False)
from smbus import SMBus
from time import sleep
from bitarray import bitarray
from jtag import *


devid = { 
    "00000001001010111001000001000011" : "MXO2-640HC",
    "00000001001010111010000001000011" : "MXO2-1200HC",
    "00000001001010111011000001000011" : "MXO2-2000HC" }

i2c = SMBus(2)


i2c.write_byte(0x38, 0x01)  # TDO_W input
i2c.write_byte(0x3A, 0xFF)  # all pullups

i2c.write_byte(0x39, 0x00) 

jtag_tms(i2c, "11111111")   # goto reset
jtag_tms(i2c, "01100")      # goto Shift-IR
# shift in IDCODE [11100000]
jtag_tdi(i2c, "00000111")
jtag_tms(i2c, "1100")       # goto Shift-DR
idcode = jtag_tdo(i2c, 32)  # read idcode
dev = devid[idcode]
print("found %s [%s]" % (dev, idcode))

if dev == "MXO2-640HC":
    cso = [ 21, 31, 29, 23]
Exemplo n.º 57
0
class nunchuck:

  def __init__(self,delay = 0.05):
    self.delay = delay
    if rpi.RPI_REVISION == 1:
      i2c_bus = 0
    elif rpi.RPI_REVISION == 2:
      i2c_bus = 1
    elif rpi.RPI_REVISION == 3:
      i2c_bus = 1
    else:
      print "Unable to determine Raspberry Pi revision."
      exit
    self.bus = SMBus(i2c_bus)
    self.bus.write_byte_data(0x52,0x40,0x00)
    time.sleep(0.1)

  def read(self):
    self.bus.write_byte(0x52,0x00)
    time.sleep(self.delay)
    temp = [(0x17 + (0x17 ^ self.bus.read_byte(0x52))) for i in range(6)]
    return temp

  def raw(self):
    data = self.read()
    return data

  def joystick(self):
    data = self.read()
    return data[0],data[1]

  def accelerometer(self):
    data = self.read()
    return data[2],data[3],data[4]

  def button_c(self):
    data = self.read()
    butc = (data[5] & 0x02)

    return butc == 0

  def button_z(self):
    data = self.read()
    butc = (data[5] & 0x01)

    return butc == 0

  def joystick_x(self):
    data = self.read()
    return data[0]

  def joystick_y(self):
    data = self.read()
    return data[1]

  def accelerometer_x(self):
    data = self.read()
    return data[2]

  def accelerometer_y(self):
    data = self.read()
    return data[3]

  def accelerometer_z(self):
    data = self.read()
    return data[4]
    
  def setdelay(self,delay):
    self.delay = delay


  def scale(self,value,_min,_max,_omin,_omax):
    return (value - _min) * (_omax - _omin) // (_max - _min) + _omin