Esempio n. 1
0
class Si7021Sensor:
    def __init__(self):
        self._bus = SMBus(1)
        self._address = 0x40

    def __del__(self):
        self._bus.close()

    def _send_command(self, command_code):
        self._bus.write_byte(self._address, command_code)
        time.sleep(0.3)

    def _read_data(self):
        data0 = self._bus.read_byte(self._address)
        data1 = self._bus.read_byte(self._address)
        time.sleep(0.3)
        return data0, data1

    def humidity(self):
        """
        :return: relative humidity in percent.
        """
        self._send_command(0xF5)
        data0, data1 = self._read_data()
        humidity = ((data0 * 256 + data1) * 125 / 65536.0) - 6
        return humidity

    def temperature(self):
        """
        :return: temperature in celsius degrees.
        """
        self._send_command(0xF3)
        data0, data1 = self._read_data()
        cels_temp = ((data0 * 256 + data1) * 175.72 / 65536.0) - 46.85
        return cels_temp
Esempio n. 2
0
class HD44780:
    def __init__(self,
                 addr=HD44780_DEFAULT_ADDRESS,
                 channel=I2C_DEFAULT_CHANNEL):
        self.__addr = addr
        self.__bus = SMBus(channel)

        # initialization
        self.__write(0x03)
        self.__write(0x03)
        self.__write(0x03)
        self.__write(0x02)

        self.__write(FUNCTION_SET | FOUR_BITS_MODE | TWO_LINES | FIVE_EIGHT)
        self.__write(DISPLAY_CONTROL | DISPLAY_ON | CURSOR_OFF)
        self.__write(CLEAR_DISPLAY)
        self.__write(ENTRY_MODE_SET | ENTRY_LEFT)
        sleep(0.2)

    def __write_four_bits(self, data):
        self.__bus.write_byte(self.__addr, data | BACKLIGHT_ON)
        sleep(0.0002)
        self.__bus.write_byte(self.__addr, data | En | BACKLIGHT_ON)
        sleep(0.0006)
        self.__bus.write_byte(self.__addr, data | BACKLIGHT_ON)
        sleep(0.0002)

    def __write(self, data, RwRs=0b00):
        self.__write_four_bits((data & 0xF0) | RwRs)
        self.__write_four_bits(((data << 4) & 0xF0) | RwRs)

    def backlight(self, state=BacklightMode.ON):
        if state == BacklightMode.OFF:
            self.__bus.write_byte(self.__addr, BACKLIGHT_OFF)
        else:
            self.__bus.write_byte(self.__addr, BACKLIGHT_ON)

    def clear(self):
        self.__write(CLEAR_DISPLAY)
        self.__write(RETURN_HOME)

    def print(self, string, line=1, align_mode=AlignMode.LEFT):
        if len(string) > 0:
            if line == 2:
                self.__write(LINE_2)
            else:
                self.__write(LINE_1)

            if len(string) > MAX_LINE_LENGTH:
                string_to_be_printed = string[:MAX_LINE_LENGTH]
            else:
                if align_mode == AlignMode.CENTER:
                    string_to_be_printed = string.center(MAX_LINE_LENGTH)
                elif align_mode == AlignMode.RIGHT:
                    string_to_be_printed = string.rjust(MAX_LINE_LENGTH)
                else:
                    string_to_be_printed = string.ljust(MAX_LINE_LENGTH)

            for char in string_to_be_printed:
                self.__write(ord(char), Rs)
Esempio n. 3
0
    def __init__(self, name, i2c_addr):
        self.I2Caddr = i2c_addr
        
        directory = "/tmp/" + name
        if not os.path.exists(directory):
            os.makedirs(directory)

        self.FptrTC = directory + "/tc"
        self.FptrRH = directory + "/rh"
        self.FptrTD = directory + "/td"
        self.FptrAH = directory + "/ah"
        
        # For file handeling, maintaining the moving averages
        self.temp_buff  = [ 0 ] * HTU21D_MAX
        self.temp_ptr   = 0
        self.humid_buff = [ 0 ] * HTU21D_MAX
        self.humid_ptr  = 0  

        self.init_buff = 1 # flag to fill buffers
        
        try:
            bus = SMBus(I2CBUS)
            bus.write_byte( self.I2Caddr, HTU21D_SOFT_RESET )
            time.sleep(0.05)        
            bus.close()
            
        except:
            bus.close()
            print "htu21d.init() failed"
class i2c_device:
	def __init__(self, addr, port=I2CBUS):
		self.addr = addr
		self.bus = SMBus(port)

	# 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)
Esempio n. 5
0
class RotEncThread(threading.Thread):
    global clk_last_state

    def __init__(self):
        threading.Thread.__init__(self)
        self.read_volume = 0
        self.last_read_volume = 0
        self.vol_change_func = None
        self.arduino_addr = 0x08
        self.bus = SMBus(1)
        self.get_vol_arr = [103, 101, 116, 118, 0]

    def set_vol_change_func(self, func):
        self.vol_change_func = func

    def run(self):
        #try:
        while True:
            #lock.acquire()
            try:
                #self.bus.write_i2c_block_data(self.arduino_addr, 0x00, self.get_vol_arr)
                self.bus.write_byte(self.arduino_addr, 0x01)
                time.sleep(0.1)
                self.read_volume = self.bus.read_byte_data(
                    self.arduino_addr, 0)
                #print(self.read_volume)
                if self.read_volume != self.last_read_volume:
                    self.vol_change_func(self.read_volume)
                self.last_read_volume = self.read_volume
            finally:
                #lock.release()
                time.sleep(0.01)
Esempio n. 6
0
class MAX11644(object):
    def __init__(self, bus=_DEFAULT_BUS, address=_DEFAULT_ADDRESS, internal_reference=True,
                 v_ref_internal=_V_REF_INTERNAL):
        # I2C bus object
        self._i2c = SMBus(bus)
        # added to avoid communication problems
        time.sleep(1)
        self._address = address
        self._SETUP = 0x80
        self._CONF = 0x00

        if internal_reference:
            self._SETUP = 0xD0
            self._ref_volt = v_ref_internal
        else:
            self._SETUP = 0x82
            self._ref_volt = _VDD

        self._SETUP = (self._SETUP | 0x02)  # internal clock, unipolar, no action
        self._send_data_(self._SETUP)

    def _send_data_(self, byte):
        """Send a byte to device"""
        self._i2c.write_byte(self._address, byte)
        time.sleep(0.1)

    def _read_data(self, address):
        """Read 2 bytes from address address."""
        data = self._i2c.read_i2c_block_data(self._address, address, 2)
        return data

    def get_value(self, channel=0):
        """Get Full scale value (12 bits)"""
        if channel == 0:
            self._CONF = 0x61
            data = self._read_data(self._CONF)

        elif channel == 1:
            self._CONF = 0x63
            data = self._read_data(self._CONF)
        else:
            raise Exception("Channel doesn't exist")
        data = ((data[0] & 0x0F) << 8) | data[1]
        return data

    def convert_to_volt(self, value):
        """Convert Full scale value (12 bits) into volts"""
        return self._ref_volt * value / 4096.

    def get_voltage(self, channel=0, factor=1):
        return self.convert_to_volt(self.get_value(channel) / factor)
Esempio n. 7
0
class Motors:
    def __init__(self, motorsList):
        self.motors = motorsList
        self.motorCount = 0
        self.bus = SMBus(1)

    def start_motor(self):
        if self.motorCount < self.motors.count:
            self.bus.write_byte(self.motors[self.motorCount], 0x01)

    def add_counter(self):
        if self.motorCount < len(self.motors) - 1:
            self.motorCount += 1
        else:
            self.motorCount = 0

    def read_motor_info(self):
        b = self.bus.read_byte(self.motors[self.motorCount])
        return b

    def set_status_counter(self):
        self.bus.write_byte(self.motors[self.motorCount], 0x02)

    def set_status_sensor(self):
        self.bus.write_byte(self.motors[self.motorCount], 0x03)

    def set_status_reset(self):
        self.bus.write_byte(self.motors[self.motorCount], 0x09)

    def get_actual_status(self):
        b = self.bus.read_byte(self.motors[self.motorCount])
        return b
Esempio n. 8
0
class Cobra:
    def __init__(self):
        ''' Creates a object 
        '''
        self.HOST = '192.168.0.102'
        self.PORT = 2017
        self.server = SocketServer.TCPServer((self.HOST, self.PORT),
                                             TCPHandler)

        self.i2c = SMBus(1)
        self.i2c.write_byte(0x40, 0)
        self.i2c.write_byte(0x41, 0)
        self.i2c.write_byte(0x42, 0)
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        self.server.serve_forever()
Esempio n. 9
0
def callback(data):
    #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    left = data.linear.x - data.angular.z
    right = data.linear.x + data.angular.z
    i2c = SMBus(1)
    i2c.write_byte(0x40, 101)
    i2c.write_byte(0x40, int(left))
    i2c.write_byte(0x40, 102)
    i2c.write_byte(0x40, int(right))
    i2c.close()
Esempio n. 10
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)
Esempio n. 11
0
class Device(object):
    """Class for communicating with an I2C device using the adafruit-pureio pure
    python smbus library, or other smbus compatible I2C interface. Allows reading
    and writing 8-bit, 16-bit, and byte array values to registers
    on the device."""
    def __init__(self, address, busnum):
        """Create an instance of the I2C device at the specified address on the
        specified I2C bus number."""
        self._address = address
        self._bus = SMBus(busnum)
        self._logger = logging.getLogger('Rover_log')

    def writeByte(self, value):
        """Write an 8-bit value"""
        value = value & 0xFF
        self._bus.write_byte(self._address, register, value)
        self._logger.debug("Wrote 0x%02X to register 0x%02X", value, register)

    def write8(self, value, register=0):
        """Write an 8-bit value to the specified register. use register 0 if not needed"""
        value = value & 0xFF
        self._bus.write_byte_data(self._address, register, value)
        self._logger.debug("Wrote 0x%02X to register 0x%02X", value, register)

    def readU8(self, register=0):
        """Read an unsigned byte from the specified register. use 0 if egister is not needed"""
        result = self._bus.read_byte_data(self._address, register) & 0xFF
        self._logger.debug("Read 0x%02X from register 0x%02X", result,
                           register)
        return result

    def writeList(self, data, register=0):
        """Write bytes to the specified register. Use 0 if register is not needed"""
        self._bus.write_i2c_block_data(self._address, register, data)
        self._logger.debug("Wrote to register 0x%02X: %s", register, data)

    def readList(self, length, register=0):
        """Read a length number of bytes from the specified register, use 0 if register is not needed.  Results
        will be returned as a bytearray."""
        results = self._bus.read_i2c_block_data(self._address, register,
                                                length)
        self._logger.debug("Read the following from register 0x%02X: %s",
                           register, results)
        return results
Esempio n. 12
0
class WiiController:
    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:
            raise OSError("Unable to determine Raspberry Pi revision.")
        self.bus = SMBus(i2c_bus)
        self.bus.write_byte_data(0x52, 0x40, 0x00)
        time.sleep(0.1)

    @cached(TTLCache(maxsize=1, ttl=0.0166))
    def read(self):
        self.bus.write_byte(0x52, 0x00)
        time.sleep(self.delay)
        return [(0x17 + (0x17 ^ self.bus.read_byte(0x52))) % 256
                for _ in range(6)]
Esempio n. 13
0
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024)
        print "{} wrote:".format(self.client_address[0])

        speed = self.data.split(':')

        speed_left = int(100 * float(speed[0]))
        speed_right = int(100 * float(speed[1]))

        if speed_left < 0:
            speed_left = 256 + speed_left

        if speed_right < 0:
            speed_right = 256 + speed_right

        print(speed_left, speed_right)
        i2c = SMBus(1)
        i2c.write_byte(0x41, speed_left)
        i2c.write_byte(0x42, speed_right)
        i2c.close()
Esempio n. 14
0
    class I2CBus():
        def __init__(self, I2C_bus_number, address):
            self.bus = SMBus(I2C_bus_number)
            self.address = address

        def write_register(self, reg_address, device_address=None):
            device_address = self.address
            return self.bus.write_byte(device_address, reg_address)

        def read_registers(self, reg_address, device_address=None):
            device_address = self.address
            return self.bus.read_i2c_block_data(device_address, reg_address, 6)
Esempio n. 15
0
def main(argv):
    print("Hello world!")

    bus = SMBus(1)

    for i in range(0, 128, 16):
        vals = []
        for j in range(0, 16):
            res = True
            try:
                k = i + j
                if (k >= 0x30 and k <= 0x37) or (k >= 0x50 and k <= 0x5f):
                    bus.read_byte(i + j)
                else:
                    bus.write_byte(i + j, 0)
            except Exception as e:
                res = False
            if res:
                vals.append("{}: {:3}".format(j, i + j))
            else:
                vals.append("{}: ---".format(j))
        print("{:3}".format(i), ", ".join(vals))
Esempio n. 16
0
def main():

    #  MCP4725 defaults to address 0x60
    address = 0x7f

    # Initialize I2C (SMBus)
    bus = SMBus(1)

    #bus.write_byte(address, 0x01)
    byte_to_send = 0
    '''
		Values greater than a byte, 0-255, are overflowed back around.
		For example, sending 256 results in a 0, 257 -> 1, etc.
	'''

    while byte_to_send <= 255:
        print("Writing", byte_to_send)
        try:
            bus.write_byte(address, byte_to_send)
            byte_to_send += 1
        except OSError:
            print("OSError: Failed to write to specified peripheral")
        sleep(.2)
        '''
Esempio n. 17
0
class PCF8754:
    def __init__(self, address, busnum=1):
        self._address = address
        self._i2c = SMBus(busnum)
        self._access_error = False

    def set_out(self, output):
        try:
            self._i2c.write_byte(self._address, (~output & 0xFF))
            self._access_error = False

        except OSError:
            if not self._access_error:
                self._access_error = True
                log.warning('I2C device at address ' +
                            str(hex(self._address)) +
                            ' could not be accessed.')
                # print('I2C device at address ' + str(hex(self._address)) + ' could not be accessed.')

        return self._access_error

    def get_out(self):
        try:
            value = ~self._i2c.read_byte(self._address) & 0xFF
            self._access_error = False

        except OSError:
            if not self._access_error:
                self._access_error = True
                log.warning('I2C device at address ' +
                            str(hex(self._address)) +
                            ' could not be accessed.')
                # print('I2C device at address ' + str(hex(self._address)) + ' could not be accessed.')
            value = 0x00

        return value, self._access_error
Esempio n. 18
0
class Tsl2561Sensor(RestoreEntity):
    """Representation of a Sensor."""

    def __init__(self):
        """Initialize the sensor."""
        self._state = None
        self._bus = SMBus(1)

    @property
    def name(self):
        """Return the name of the sensor."""
        return 'Luminosita'

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return "lux"

    def update(self):
        """Fetch new state data for the sensor."""
        self._state = self._lightcheck()

    def _lightcheck(self):
        self._bus.write_byte(TSLaddr, 0x00 | TSLcmd, TSLon) #Power On
        #Gain x1 at 402ms is the default so this line not required but change for different sensitivity
        self._bus.write_byte(TSLaddr, 0x01 | TSLcmd,LowLong) #Gain x1 402ms

        time.sleep(1) #give time sensor to settle

        #Read Ch0 Word
        data = self._bus.read_i2c_block_data(TSLaddr, chan0 | TSLcmd, 2)
        #Read CH1 Word
        data1 = self._bus.read_i2c_block_data(TSLaddr, chan1 | TSLcmd, 2)

        # Convert the data to Integer
        ch0 = data[1] * 256 + data[0]
        ch1 = data1[1] * 256 + data1[0]
        vResults = ch0-ch1 #get visable light results
        self._bus.write_byte(TSLaddr, 0x00 | TSLcmd, TSLoff) #switch off

        return str(vResults)
Esempio n. 19
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the Chirp's moisture, temperature
    and light

    """

    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev, testing=testing, name=__name__)

        if not testing:
            self.i2c_address = int(str(input_dev.i2c_location), 16)
            self.i2c_bus = input_dev.i2c_bus
            self.bus = SMBus(self.i2c_bus)
            self.filter_average('lux', init_max=3)

    def get_measurement(self):
        """ Gets the light, moisture, and temperature """
        self.return_dict = measurements_dict.copy()

        if self.is_enabled(0):
            self.value_set(0, self.filter_average('lux', measurement=self.light()))

        if self.is_enabled(1):
            self.value_set(1, self.moist())

        if self.is_enabled(2):
            self.value_set(2, self.temp() / 10.0)

        return self.return_dict

    def get_reg(self, reg):
        # read 2 bytes from register
        val = self.bus.read_word_data(self.i2c_address, reg)
        # return swapped bytes (they come in wrong order)
        return (val >> 8) + ((val & 0xFF) << 8)

    def reset(self):
        # To reset the sensor, write 6 to the device I2C address
        self.bus.write_byte(self.i2c_address, 6)

    def set_addr(self, new_addr):
        # To change the I2C address of the sensor, write a new address
        # (one byte [1..127]) to register 1; the new address will take effect after reset
        self.bus.write_byte_data(self.i2c_address, 1, new_addr)
        self.reset()
        # self.address = new_addr

    def moist(self):
        # To read soil moisture, read 2 bytes from register 0
        return self.get_reg(0)

    def temp(self):
        # To read temperature, read 2 bytes from register 5
        return self.get_reg(5)

    def light(self):
        # To read light level, start measurement by writing 3 to the
        # device I2C address, wait for 3 seconds, read 2 bytes from register 4
        self.bus.write_byte(self.i2c_address, 3)
        time.sleep(1.5)
        lux = self.get_reg(4)
        if lux == 0:
            return 65535.0
        else:
            return(1 - (lux / 65535.0)) * 65535.0
Esempio n. 20
0
class MCP3425:
    def __init__(self,
                 bus=1,
                 ready=MCP3425_CONF_RDY,
                 channel=MCP3425_CONF_CHANNEL_1,
                 mode=MCP3425_CONF_MODE_CONTINUOUS,
                 rate=MCP3425_CONF_SIZE_12BIT,
                 gain=MCP3425_CONF_GAIN_1X,
                 resolution=MCP3425_BITS_RESOLUTION,
                 vref=2.048):
        try:
            self._bus = SMBus(bus)
        except:
            print("Bus %d is not available." % bus)
            print("Available busses are listed as /dev/i2c*")
            self._bus = None

        self._ready = ready
        self._channel = channel
        self._mode = mode
        self._rate = rate
        self._gain = gain
        self._resolution = resolution
        self._vref = vref

    def init(self):

        if self._bus is None:
            print("No bus!")
            return False

        self.setReady(self._ready)
        self.setChannel(self._channel)
        self.setMode(self._mode)
        self.setSampleRate(self._rate)
        self.setGain(self._gain)

        return True

    def setReady(self, ready):
        """
        Set Ready Bit
        In read mode, it indicates the output register has been updated with a new conversion.
        In one-shot Conversion mode, writing initiates a new conversion.
        """
        if self._bus:
            self._bus.write_byte(MCP3425_DEFAULT_ADDRESS, ready)

    def setChannel(self, channel):
        """
        Set Channel Selection for MCP3426, MCP3427, MCP3428
        Channels are not used for MCP3425
        """
        if self._bus:
            self._bus.write_byte(MCP3425_DEFAULT_ADDRESS, channel)

    def setMode(self, mode):
        """
        Set Conversion Mode
        1 = Continous Conversion Mode
        0 = One-shot Conversion Mode
        """
        if self._bus:
            self._bus.write_byte(MCP3425_DEFAULT_ADDRESS, mode)

    def setSampleRate(self, rate):
        """
        Set Sample rate selection bit
        00 : 240 SPS-12 bits
        01 : 60 SPS 14 bits
        10 : 15 SPS 16 bits
        """
        if self._bus:
            self._bus.write_byte(MCP3425_DEFAULT_ADDRESS, rate)

    def setGain(self, gain):
        """
        # Set the PGA gain
        00 : 1 V/V
        01 : 2 V/V
        10 : 4 V/V
        11 : 8 V/V
        """
        if self._bus:
            self._bus.write_byte(MCP3425_DEFAULT_ADDRESS, gain)

    def read(self):
        """
        Get the measurement for the ADC values  from the register using the General Calling method
        """
        if self._bus:
            data = self._bus.read_i2c_block_data(MCP3425_DEFAULT_ADDRESS, 0x00,
                                                 2)
            value = ((data[0] << 8) | data[1])
            if (value >= 32768):
                value = 65536 - value
            return value
        else:
            return 0

    def convert(self, factor=1.0, offset=0.0):
        """
        Shows the output codes of input level using 16-bit conversion mode
        The output code is proportional to the voltage difference b/w two analog points
        """
        code = self.read()
        voltage = offset + (2 * self._vref *
                            code) / (2**self._resolution) * factor
        return voltage
Esempio n. 21
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the SHT2x's humidity and temperature
    and calculates the dew point
    """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev,
                                          testing=testing,
                                          name=__name__)

        if not testing:
            self.initialize_input()

    def initialize_input(self):
        from smbus2 import SMBus

        self.i2c_address = int(str(self.input_dev.i2c_location), 16)
        self.sht2x = SMBus(self.input_dev.i2c_bus)

    def get_measurement(self):
        """ Gets the humidity and temperature """
        if not self.sht2x:
            self.logger.error("Input not set up")
            return

        self.return_dict = copy.deepcopy(measurements_dict)

        for _ in range(2):
            try:
                # Send temperature measurement command
                # 0xF3(243) NO HOLD master
                self.sht2x.write_byte(self.i2c_address, 0xF3)
                time.sleep(0.5)
                # Read data back, 2 bytes
                # Temp MSB, Temp LSB
                data0 = self.sht2x.read_byte(self.i2c_address)
                data1 = self.sht2x.read_byte(self.i2c_address)
                temperature = -46.85 + ((
                    (data0 * 256 + data1) * 175.72) / 65536.0)
                # Send humidity measurement command
                # 0xF5(245) NO HOLD master
                self.sht2x.write_byte(self.i2c_address, 0xF5)
                time.sleep(0.5)
                # Read data back, 2 bytes
                # Humidity MSB, Humidity LSB
                data0 = self.sht2x.read_byte(self.i2c_address)
                data1 = self.sht2x.read_byte(self.i2c_address)
                humidity = -6 + (((data0 * 256 + data1) * 125.0) / 65536.0)

                if self.is_enabled(0):
                    self.value_set(0, temperature)

                if self.is_enabled(1):
                    self.value_set(1, humidity)

                if self.is_enabled(2) and self.is_enabled(
                        0) and self.is_enabled(1):
                    self.value_set(
                        2,
                        calculate_dewpoint(self.value_get(0),
                                           self.value_get(1)))

                if self.is_enabled(3) and self.is_enabled(
                        0) and self.is_enabled(1):
                    self.value_set(
                        3,
                        calculate_vapor_pressure_deficit(
                            self.value_get(0), self.value_get(1)))

                return self.return_dict
            except Exception as e:
                self.logger.exception(
                    "Exception when taking a reading: {err}".format(err=e))

            # Send soft reset and try a second read
            self.sht2x.write_byte(self.i2c_address, 0xFE)
            time.sleep(0.1)
Esempio n. 22
0
if __name__ == "__main__":
    slave_addr = 0x0F
    user_input = 1
    payload = 0
    response = 0
    other_response = 0
    bomba2 = 7

    bus = SMBus(1)
    wiringpi.wiringPiSetup()
    wiringpi.pinMode(bomba2, wiringpi.OUTPUT)

    while (user_input != 0):
        user_input = int(input('Qual ação deseja realizar? '))

        bus.write_byte(slave_addr, user_input)
        sleep(0.2)
        response = bus.read_byte(slave_addr)

        print(INPUT[user_input], response)

        if (user_input == 9):
            if (response == 10):
                payload = 3

                bus.write_byte(slave_addr, payload)
                sleep(1)
                other_response = bus.read_byte(slave_addr)

                while (other_response1 < 20):
                    i = 0
Esempio n. 23
0
        if speed_left < 0:
            speed_left = 256 + speed_left

        if speed_right < 0:
            speed_right = 256 + speed_right

        print(speed_left, speed_right)
        i2c = SMBus(1)
        i2c.write_byte(0x41, speed_left)
        i2c.write_byte(0x42, speed_right)
        i2c.close()


server = SocketServer.TCPServer((HOST, PORT), TCPHandler)
i2c = SMBus(1)
i2c.write_byte(0x40, 1)
i2c.write_byte(0x41, 0)
i2c.write_byte(0x42, 0)
i2c.close()

server.serve_forever()
'''
i2c = SMBus(1)

result = i2c.write_byte(0x40, 0)

result = i2c.write_byte(0x41, 5)

result = i2c.write_byte(0x42, 5)

print(result)
Esempio n. 24
0
from smbus2 import SMBus

i2c = SMBus(1)

result = i2c.write_byte(0x40, 101)

result = i2c.write_byte(0x40, 55)

result = i2c.write_byte(0x40, 102)

result = i2c.write_byte(0x40, -55)

i2c.close()
Esempio n. 25
0
class InputModule(AbstractInput):
    """A sensor support class that monitors the DS18B20's lux."""
    def __init__(self, input_dev, testing=False):
        super().__init__(input_dev, testing=testing, name=__name__)

        self.i2c_address = None
        self.i2c_bus = None
        self.resolution = None

        if not testing:
            self.try_initialize()

    def initialize(self):
        from smbus2 import SMBus

        self.i2c_address = int(str(self.input_dev.i2c_location), 16)
        self.resolution = self.input_dev.resolution
        self.i2c_bus = SMBus(self.input_dev.i2c_bus)
        self.power_down()
        self.set_sensitivity(sensitivity=self.input_dev.sensitivity)

    @property
    def lux(self):
        """BH1750 luminosity in lux."""
        if self._measurements is None:  # update if needed
            self.read()
        return self._measurements

    def get_measurement(self):
        """Gets the BH1750's lux."""
        self.return_dict = copy.deepcopy(measurements_dict)

        if self.resolution == 0:
            lux = self.measure_low_res()
        elif self.resolution == 1:
            lux = self.measure_high_res()
        elif self.resolution == 2:
            lux = self.measure_high_res2()
        else:
            return None

        self.value_set(0, lux)

        return self.return_dict

    def _set_mode(self, mode):
        self.mode = mode
        self.i2c_bus.write_byte(self.i2c_address, self.mode)

    def power_down(self):
        self._set_mode(POWER_DOWN)

    def power_on(self):
        self._set_mode(POWER_ON)

    def reset(self):
        self.power_on()  # It has to be powered on before resetting
        self._set_mode(RESET)

    def cont_low_res(self):
        self._set_mode(CONTINUOUS_LOW_RES_MODE)

    def cont_high_res(self):
        self._set_mode(CONTINUOUS_HIGH_RES_MODE_1)

    def cont_high_res2(self):
        self._set_mode(CONTINUOUS_HIGH_RES_MODE_2)

    def oneshot_low_res(self):
        self._set_mode(ONE_TIME_LOW_RES_MODE)

    def oneshot_high_res(self):
        self._set_mode(ONE_TIME_HIGH_RES_MODE_1)

    def oneshot_high_res2(self):
        self._set_mode(ONE_TIME_HIGH_RES_MODE_2)

    def set_sensitivity(self, sensitivity=69):
        """
        Set the sensor sensitivity.
        Valid values are 31 (lowest) to 254 (highest), default is 69.
        """
        if sensitivity < 31:
            self.mtreg = 31
        elif sensitivity > 254:
            self.mtreg = 254
        else:
            self.mtreg = sensitivity
        self.power_on()
        self._set_mode(0x40 | (self.mtreg >> 5))
        self._set_mode(0x60 | (self.mtreg & 0x1f))
        self.power_down()

    def get_result(self):
        """Return current measurement result in lux."""
        data = self.i2c_bus.read_word_data(self.i2c_address, self.mode)
        count = data >> 8 | (data & 0xff) << 8
        mode2coeff = 2 if (self.mode & 0x03) == 0x01 else 1
        ratio = 1 / (1.2 * (self.mtreg / 69.0) * mode2coeff)
        return ratio * count

    def wait_for_result(self, additional=0):
        basetime = 0.018 if (self.mode & 0x03) == 0x03 else 0.128
        time.sleep(basetime * (self.mtreg / 69.0) + additional)

    def do_measurement(self, mode, additional_delay=0):
        """
        Perform complete measurement using command specified by parameter
        mode with additional delay specified in parameter additional_delay.
        Return output value in Lx.
        """
        self.reset()
        self._set_mode(mode)
        self.wait_for_result(additional=additional_delay)
        return self.get_result()

    def measure_low_res(self, additional_delay=0):
        return self.do_measurement(ONE_TIME_LOW_RES_MODE, additional_delay)

    def measure_high_res(self, additional_delay=0):
        return self.do_measurement(ONE_TIME_HIGH_RES_MODE_1, additional_delay)

    def measure_high_res2(self, additional_delay=0):
        return self.do_measurement(ONE_TIME_HIGH_RES_MODE_2, additional_delay)
Esempio n. 26
0
class LCD_Generic:
    """Output to a generic I2C LCD (16x2 and 20x4 LCD with I2C backpack)"""
    def __init__(self, lcd_dev=None, lcd_settings_dict=None):
        self.lcd_initialized = False
        self.lcd_is_on = False

        if lcd_dev:
            self.logger = logging.getLogger("{}_{}".format(
                __name__,
                lcd_dev.unique_id.split('-')[0]))
            self.i2c_address = int(lcd_dev.location, 16)
            self.i2c_bus = lcd_dev.i2c_bus
            self.lcd_x_characters = lcd_dev.x_characters
            self.lcd_y_lines = lcd_dev.y_lines
        elif lcd_settings_dict:
            self.logger = logging.getLogger("{}_{}".format(
                __name__, lcd_settings_dict["unique_id"].split('-')[0]))
            self.i2c_address = int(lcd_settings_dict["i2c_address"], 16)
            self.i2c_bus = lcd_settings_dict["i2c_bus"]
            self.lcd_x_characters = lcd_settings_dict["x_characters"]
            self.lcd_y_lines = lcd_settings_dict["y_lines"]

        self.LCD_LINE = {1: 0x80, 2: 0xC0, 3: 0x94, 4: 0xD4}

        self.LCD_CHR = 1  # Mode - Sending data
        self.LCD_CMD = 0  # Mode - SenLCDding command

        self.LCD_BACKLIGHT = 0x08  # On
        self.LCD_BACKLIGHT_OFF = 0x00  # Off

        self.ENABLE = 0b00000100  # Enable bit

        # Timing constants
        self.E_PULSE = 0.0005
        self.E_DELAY = 0.0005

        self.LCD_WIDTH = self.lcd_x_characters  # Max characters per line

        # Setup I2C bus
        try:
            self.bus = SMBus(self.i2c_bus)
        except Exception as except_msg:
            self.logger.exception(
                "Could not initialize I2C bus: {err}".format(err=except_msg))

        self.I2C_ADDR = self.i2c_address

    def lcd_init(self):
        """ Initialize LCD display """
        try:
            self.lcd_byte(0x33, self.LCD_CMD)  # 110011 Initialise
            self.lcd_byte(0x32, self.LCD_CMD)  # 110010 Initialise
            self.lcd_byte(0x06, self.LCD_CMD)  # 000110 Cursor move direction
            self.lcd_byte(
                0x0C, self.LCD_CMD)  # 001100 Display On,Cursor Off, Blink Off
            self.lcd_byte(
                0x28,
                self.LCD_CMD)  # 101000 Data length, number of lines, font size
            self.lcd_byte(0x01, self.LCD_CMD)  # 000001 Clear display
            time.sleep(self.E_DELAY)
        except Exception as err:
            self.logger.error(
                "Could not initialize LCD. Check your configuration and wiring. Error: {err}"
                .format(err=err))

    def lcd_backlight(self, state):
        """ Turn the backlight on or off """
        if state:
            self.lcd_byte(0x01, self.LCD_CMD, self.LCD_BACKLIGHT)
        else:
            self.lcd_byte(0x01, self.LCD_CMD, self.LCD_BACKLIGHT_OFF)

    def lcd_byte(self, bits, mode, backlight=None):
        """ Send byte to data pins """
        if backlight is None:
            backlight = self.LCD_BACKLIGHT
        # bits = the data
        # mode = 1 for data
        #        0 for command
        bits_high = mode | (bits & 0xF0) | backlight
        bits_low = mode | ((bits << 4) & 0xF0) | backlight
        # High bits
        self.bus.write_byte(self.I2C_ADDR, bits_high)
        self.lcd_toggle_enable(bits_high)
        # Low bits
        self.bus.write_byte(self.I2C_ADDR, bits_low)
        self.lcd_toggle_enable(bits_low)

    def lcd_toggle_enable(self, bits):
        """ Toggle enable """
        time.sleep(self.E_DELAY)
        self.bus.write_byte(self.I2C_ADDR, (bits | self.ENABLE))
        time.sleep(self.E_PULSE)
        self.bus.write_byte(self.I2C_ADDR, (bits & ~self.ENABLE))
        time.sleep(self.E_DELAY)

    def lcd_string_write(self, message, line):
        """ Send strings to display """
        line_write = self.LCD_LINE[line]
        message = message.ljust(self.LCD_WIDTH, " ")
        self.lcd_byte(line_write, self.LCD_CMD)
        for i in range(self.LCD_WIDTH):
            self.lcd_byte(ord(message[i]), self.LCD_CHR)

    def lcd_write_lines(self, line_1, line_2, line_3, line_4):
        if line_1:
            self.lcd_string_write(line_1, 1)
        if line_2:
            self.lcd_string_write(line_2, 2)
        if line_3:
            self.lcd_string_write(line_3, 3)
        if line_4:
            self.lcd_string_write(line_4, 4)
Esempio n. 27
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the SHT2x's humidity and temperature
    and calculates the dew point

    """

    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.sht2x")

        if not testing:
            from smbus2 import SMBus
            self.logger = logging.getLogger(
                "mycodo.sht2x_{id}".format(id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.i2c_address = int(str(input_dev.i2c_location), 16)
            self.i2c_bus = input_dev.i2c_bus
            self.sht2x = SMBus(self.i2c_bus)

    def get_measurement(self):
        """ Gets the humidity and temperature """
        return_dict = measurements_dict.copy()

        for _ in range(2):
            try:
                # Send temperature measurement command
                # 0xF3(243) NO HOLD master
                self.sht2x.write_byte(self.i2c_address, 0xF3)
                time.sleep(0.5)
                # Read data back, 2 bytes
                # Temp MSB, Temp LSB
                data0 = self.sht2x.read_byte(self.i2c_address)
                data1 = self.sht2x.read_byte(self.i2c_address)
                temperature = -46.85 + (((data0 * 256 + data1) * 175.72) / 65536.0)
                # Send humidity measurement command
                # 0xF5(245) NO HOLD master
                self.sht2x.write_byte(self.i2c_address, 0xF5)
                time.sleep(0.5)
                # Read data back, 2 bytes
                # Humidity MSB, Humidity LSB
                data0 = self.sht2x.read_byte(self.i2c_address)
                data1 = self.sht2x.read_byte(self.i2c_address)
                humidity = -6 + (((data0 * 256 + data1) * 125.0) / 65536.0)

                if self.is_enabled(0):
                    return_dict[0]['value'] = temperature

                if self.is_enabled(1):
                    return_dict[1]['value'] = humidity

                if (self.is_enabled(2) and
                        self.is_enabled(0) and
                        self.is_enabled(1)):
                    return_dict[2]['value'] = calculate_dewpoint(
                        return_dict[0]['value'], return_dict[1]['value'])

                if (self.is_enabled(3) and
                        self.is_enabled(0) and
                        self.is_enabled(1)):
                    return_dict[3]['value'] = calculate_vapor_pressure_deficit(
                        return_dict[0]['value'], return_dict[1]['value'])

                return return_dict
            except Exception as e:
                self.logger.exception(
                    "Exception when taking a reading: {err}".format(err=e))
            # Send soft reset and try a second read
            self.sht2x.write_byte(self.i2c_address, 0xFE)
            time.sleep(0.1)
Esempio n. 28
0
class VL53L1X:
    """VL53L1X ToF."""
    def __init__(self,
                 i2c_bus=1,
                 i2c_address=0x29,
                 tca9548a_num=255,
                 tca9548a_addr=0):
        """Initialize the VL53L1X ToF Sensor from ST"""
        self._i2c_bus = i2c_bus
        self.i2c_address = i2c_address
        self._tca9548a_num = tca9548a_num
        self._tca9548a_addr = tca9548a_addr

        self._i2c = SMBus(i2c_bus)
        try:
            if tca9548a_num == 255:
                self._i2c.read_byte_data(self.i2c_address, 0x00)
        except IOError:
            raise RuntimeError("VL53L1X not found on adddress: {:02x}".format(
                self.i2c_address))

        self._dev = None
        # Register Address
        self.ADDR_UNIT_ID_HIGH = 0x16  # Serial number high byte
        self.ADDR_UNIT_ID_LOW = 0x17  # Serial number low byte
        self.ADDR_I2C_ID_HIGH = 0x18  # Write serial number high byte for I2C address unlock
        self.ADDR_I2C_ID_LOW = 0x19  # Write serial number low byte for I2C address unlock
        self.ADDR_I2C_SEC_ADDR = 0x8a  # Write new I2C address after unlock

    def open(self, reset=False):
        self._i2c.open(bus=self._i2c_bus)
        self._configure_i2c_library_functions()
        self._dev = _TOF_LIBRARY.initialise(self.i2c_address,
                                            self._tca9548a_num,
                                            self._tca9548a_addr, reset)

    def close(self):
        self._i2c.close()
        self._dev = None

    def _configure_i2c_library_functions(self):
        # I2C bus read callback for low level library.
        def _i2c_read(address, reg, data_p, length):
            ret_val = 0

            msg_w = i2c_msg.write(address, [reg >> 8, reg & 0xff])
            msg_r = i2c_msg.read(address, length)

            self._i2c.i2c_rdwr(msg_w, msg_r)

            if ret_val == 0:
                for index in range(length):
                    data_p[index] = ord(msg_r.buf[index])

            return ret_val

        # I2C bus write callback for low level library.
        def _i2c_write(address, reg, data_p, length):
            ret_val = 0
            data = []

            for index in range(length):
                data.append(data_p[index])

            msg_w = i2c_msg.write(address, [reg >> 8, reg & 0xff] + data)

            self._i2c.i2c_rdwr(msg_w)

            return ret_val

        # I2C bus write callback for low level library.
        def _i2c_multi(address, reg):
            ret_val = 0

            # Write to the multiplexer
            self._i2c.write_byte(address, reg)

            return ret_val

        # Pass i2c read/write function pointers to VL53L1X library.
        self._i2c_multi_func = _I2C_MULTI_FUNC(_i2c_multi)
        self._i2c_read_func = _I2C_READ_FUNC(_i2c_read)
        self._i2c_write_func = _I2C_WRITE_FUNC(_i2c_write)
        _TOF_LIBRARY.VL53L1_set_i2c(self._i2c_multi_func, self._i2c_read_func,
                                    self._i2c_write_func)

    def start_ranging(self, mode=VL53L1xDistanceMode.LONG):
        """Start VL53L1X ToF Sensor Ranging"""
        _TOF_LIBRARY.startRanging(self._dev, mode)

    def set_distance_mode(self, mode):
        """Set distance mode

        :param mode: One of 1 = Short, 2 = Medium or 3 = Long

        """
        _TOF_LIBRARY.setDistanceMode(self._dev, mode)

    def stop_ranging(self):
        """Stop VL53L1X ToF Sensor Ranging"""
        _TOF_LIBRARY.stopRanging(self._dev)

    def get_distance(self):
        """Get distance from VL53L1X ToF Sensor"""
        return _TOF_LIBRARY.getDistance(self._dev)

    def set_timing(self, timing_budget, inter_measurement_period):
        """Set the timing budget and inter measurement period.

        A higher timing budget results in greater measurement accuracy,
        but also a higher power consumption.

        The inter measurement period must be >= the timing budget, otherwise
        it will be double the expected value.

        :param timing_budget: Timing budget in microseconds
        :param inter_measurement_period: Inter Measurement Period in milliseconds

        """
        if (inter_measurement_period * 1000) < timing_budget:
            raise ValueError(
                "The Inter Measurement Period must be >= Timing Budget")

        self.set_timing_budget(timing_budget)
        self.set_inter_measurement_period(inter_measurement_period)

    def set_timing_budget(self, timing_budget):
        """Set the timing budget in microseocnds"""
        _TOF_LIBRARY.setMeasurementTimingBudgetMicroSeconds(
            self._dev, timing_budget)

    def set_inter_measurement_period(self, period):
        """Set the inter-measurement period in milliseconds"""
        _TOF_LIBRARY.setInterMeasurementPeriodMilliSeconds(self._dev, period)

    # This function included to show how to access the ST library directly
    # from python instead of through the simplified interface
    def get_timing(self):
        budget = c_uint(0)
        budget_p = pointer(budget)
        status = _TOF_LIBRARY.VL53L1_GetMeasurementTimingBudgetMicroSeconds(
            self._dev, budget_p)
        if status == 0:
            return budget.value + 1000
        else:
            return 0

    def change_address(self, new_address):
        status = _TOF_LIBRARY.setDeviceAddress(self._dev, new_address)
        if status == 0:
            self.i2c_address = new_address
        else:
            raise RuntimeError(
                "change_address failed with code: {}".format(status))
        return True

    def get_RangingMeasurementData(self):
        '''
        Returns the full RangingMeasurementData structure.
        (it ignores the fields that are not implemented according to en.DM00474730.pdf)
        '''
        contents = _getRangingMeasurementData(self._dev).contents
        return {
            'StreamCount': contents.StreamCount,
            'SignalRateRtnMegaCps': contents.SignalRateRtnMegaCps / 65536,
            'AmbientRateRtnMegaCps': contents.AmbientRateRtnMegaCps / 65536,
            'EffectiveSpadRtnCount': contents.EffectiveSpadRtnCount / 256,
            'SigmaMilliMeter': contents.SigmaMilliMeter / 65536,
            'RangeMilliMeter': contents.RangeMilliMeter,
            'RangeStatus': contents.RangeStatus
        }
Esempio n. 29
0
    def task(self):

        temp  = 99999
        humid = 99999
        tdew  = 99999
        
        status = 0
        
        try:
            bus = SMBus(I2CBUS)
            bus.write_byte( self.I2Caddr, HTU21D_READ_TEMP_NOHOLD )
            time.sleep(0.05)
            read = i2c_msg.read( self.I2Caddr, 3 )
            bus.i2c_rdwr(read)
            resp = list(read)

            if ( self.crc8(resp) == 0 ):
                status += 1
                # data sheet 15/21 Temperature Conversion
                t = (resp[0] << 8) | (resp[1] & HTU21D_STATUS_LSBMASK)
                temp = ((175.72 * t) / 65536.0) - 46.86 

                self.temp_buff[self.temp_ptr] = temp
                self.temp_ptr += 1
                if self.temp_ptr >= HTU21D_MAX:
                    self.temp_ptr = 0

                # runs first pass only
                if self.init_buff :
                    for i in range(HTU21D_MAX):
                        self.temp_buff[i] = temp
                # need to init humid_buff[] too
                # so don't clear self.init_buff flag here
            
                avg_temp = 0
                for i in range(HTU21D_MAX):
                    avg_temp += self.temp_buff[i]
                avg_temp /= HTU21D_MAX_FLOAT

                f = open(self.FptrTC,"w")
                f.write("%3.1f" % avg_temp)
                f.close()
                
            bus.write_byte( self.I2Caddr, HTU21D_READ_HUM_NOHOLD )
            time.sleep(0.05)
            read = i2c_msg.read( self.I2Caddr, 3 )
            bus.i2c_rdwr(read)
            resp = list(read)
            bus.close()

            if( self.crc8( resp ) == 0 ):
                status += 1
                # data sheet 15/21 Relative Humidity
                h = (resp[0] << 8) | (resp[1] & HTU21D_STATUS_LSBMASK)
                humid = ((125.0 * h) / 65536.0) - 6.0 
            
                # limit for out of range values
                # per data sheet page 15/21
                if humid < 0.0 :
                    humid = 0.0
                if humid > 100.0:
                    humid = 100.0
                
                # RH compensation per datasheet page: 4/12    
                # JUN 28, 2018 changed to avg_temp
                rh = humid + ( 25.0 - avg_temp) * -0.15    

                self.humid_buff[self.humid_ptr] = rh
                self.humid_ptr += 1
                if self.humid_ptr >= HTU21D_MAX:
                    self.humid_ptr = 0
            
                # runs first pass only
                if self.init_buff :
                    for i in range(HTU21D_MAX):
                        self.humid_buff[i] = rh
                        self.init_buff = 0
           
                avg_humid = 0
                for i in range(HTU21D_MAX):
                    avg_humid += self.humid_buff[i]
                avg_humid /= HTU21D_MAX_FLOAT

                f = open(self.FptrRH,"w")
                f.write("%3.1f" % avg_humid)
                f.close()
    
            # with both valid temperature and RH 
            # calculate the dew point and absolute humidity using average values
            if status > 1:
            
                # Calculate dew point
            
                # because log of zero is not possible
                if avg_humid < 0.1:
                    avg_humid = 0.1
                A = 8.1332
                B = 1762.39
                C = 235.66
                # data sheet page 16/21 Partial Pressure & Dew Point  
                pp = 10**( A - ( B / ( avg_temp + C )))            
                tdew = -(( B / ( log10( avg_humid * pp / 100.0) - A )) + C ) 
            
                f = open(self.FptrTD,"w")
                f.write("%3.1f" % tdew)
                f.close()

                # Calculate absolute humidity in grams/M^3
                e = 2.71828
                a = 13.2473
                b = e**((17.67 * avg_temp)/(avg_temp + 243.5))
                c = 273.15 + avg_temp
                ah = a * b * avg_humid / c
            
                f = open(self.FptrAH,"w")
                f.write("%3.1f" % ah)
                f.close()

            #print "htu21d.task() T: %3.1f RH: %3.1f Tdew: %3.1f AH: %3.1f" %  ( avg_temp, avg_humid, tdew, ah )
        
        except:
            bus.close()
            print "htu21d.task() failed"
            
        # returning average values
        return [ temp, humid, tdew ]        
Esempio n. 30
0
class InputModule(AbstractInput):
    """ A sensor support class that monitors the DS18B20's lux """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.bh1750")

        if not testing:
            from smbus2 import SMBus
            self.logger = logging.getLogger(
                "mycodo.bh1750_{id}".format(id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.i2c_address = int(str(input_dev.i2c_location), 16)
            self.resolution = input_dev.resolution
            self.sensitivity = input_dev.sensitivity
            self.i2c_bus = SMBus(input_dev.i2c_bus)
            self.power_down()
            self.set_sensitivity(sensitivity=self.sensitivity)

    @property
    def lux(self):
        """ BH1750 luminosity in lux """
        if self._measurements is None:  # update if needed
            self.read()
        return self._measurements

    def get_measurement(self):
        """ Gets the BH1750's lux """
        return_dict = measurements_dict.copy()

        if self.resolution == 0:
            lux = self.measure_low_res()
        elif self.resolution == 1:
            lux = self.measure_high_res()
        elif self.resolution == 2:
            lux = self.measure_high_res2()
        else:
            return None

        return_dict[0]['value'] = lux

        return return_dict

    def _set_mode(self, mode):
        self.mode = mode
        self.i2c_bus.write_byte(self.i2c_address, self.mode)

    def power_down(self):
        self._set_mode(POWER_DOWN)

    def power_on(self):
        self._set_mode(POWER_ON)

    def reset(self):
        self.power_on()  # It has to be powered on before resetting
        self._set_mode(RESET)

    def cont_low_res(self):
        self._set_mode(CONTINUOUS_LOW_RES_MODE)

    def cont_high_res(self):
        self._set_mode(CONTINUOUS_HIGH_RES_MODE_1)

    def cont_high_res2(self):
        self._set_mode(CONTINUOUS_HIGH_RES_MODE_2)

    def oneshot_low_res(self):
        self._set_mode(ONE_TIME_LOW_RES_MODE)

    def oneshot_high_res(self):
        self._set_mode(ONE_TIME_HIGH_RES_MODE_1)

    def oneshot_high_res2(self):
        self._set_mode(ONE_TIME_HIGH_RES_MODE_2)

    def set_sensitivity(self, sensitivity=69):
        """
        Set the sensor sensitivity.
        Valid values are 31 (lowest) to 254 (highest), default is 69.
        """
        if sensitivity < 31:
            self.mtreg = 31
        elif sensitivity > 254:
            self.mtreg = 254
        else:
            self.mtreg = sensitivity
        self.power_on()
        self._set_mode(0x40 | (self.mtreg >> 5))
        self._set_mode(0x60 | (self.mtreg & 0x1f))
        self.power_down()

    def get_result(self):
        """ Return current measurement result in lx. """
        data = self.i2c_bus.read_word_data(self.i2c_address, self.mode)
        count = data >> 8 | (data & 0xff) << 8
        mode2coeff = 2 if (self.mode & 0x03) == 0x01 else 1
        ratio = 1 / (1.2 * (self.mtreg / 69.0) * mode2coeff)
        return ratio * count

    def wait_for_result(self, additional=0):
        basetime = 0.018 if (self.mode & 0x03) == 0x03 else 0.128
        time.sleep(basetime * (self.mtreg / 69.0) + additional)

    def do_measurement(self, mode, additional_delay=0):
        """
        Perform complete measurement using command specified by parameter
        mode with additional delay specified in parameter additional_delay.
        Return output value in Lx.
        """
        self.reset()
        self._set_mode(mode)
        self.wait_for_result(additional=additional_delay)
        return self.get_result()

    def measure_low_res(self, additional_delay=0):
        return self.do_measurement(ONE_TIME_LOW_RES_MODE, additional_delay)

    def measure_high_res(self, additional_delay=0):
        return self.do_measurement(ONE_TIME_HIGH_RES_MODE_1, additional_delay)

    def measure_high_res2(self, additional_delay=0):
        return self.do_measurement(ONE_TIME_HIGH_RES_MODE_2, additional_delay)
import time
from smbus2 import SMBus

address = 0x48
A0 = 0x40
A1 = 0x41
A2 = 0x42
A3 = 0x43

bus = SMBus(1)

while True:
    bus.write_byte(address, A0)
    value = bus.read_byte(address)
    if (value < 3):
        print("- No Pressure")
    elif (value < 50):
        print("- Light Touch")
    elif (value < 125):
        print("- Light Squeeze")
    elif (value < 200):
        print("- Meduim Squeeze")
    else:
        print("- Big Squeeze")
    time.sleep(1)
Esempio n. 32
0
#----------------------------------------------------------------------------
i2c = SMBus(1)
adc = MCP3208()

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)

fan_L = GPIO.PWM(12, 500)
fan_R = GPIO.PWM(18, 500)
fan_L.start(fan_L_sp)
fan_R.start(fan_R_sp)

val = (1 << OE_1) | (1 << OE_2) | (1 << OE_3) | (0 << CLR) | (1 << CLK_EN)
i2c.write_byte(PCF_CTRL, val)
val = (1 << OE_1) | (1 << OE_2) | (1 << OE_3) | (1 << CLR) | (1 << CLK_EN)
i2c.write_byte(PCF_CTRL, val)

while True:
    sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, T_SENSOR_1)
    temp_1 = sensor.get_temperature()
    sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, T_SENSOR_2)
    temp_2 = sensor.get_temperature()

    left_fan = GetRPM(0)
    right_fan = GetRPM(1)

    u_psu = 0
    u_bat = 0
    i_bat = 0
Esempio n. 33
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the Chirp's moisture, temperature
    and light

    """

    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.chirp")

        if not testing:
            self.logger = logging.getLogger(
                "mycodo.chirp_{id}".format(id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.i2c_address = int(str(input_dev.i2c_location), 16)
            self.i2c_bus = input_dev.i2c_bus
            self.bus = SMBus(self.i2c_bus)
            self.filter_average('lux', init_max=3)

    def get_measurement(self):
        """ Gets the light, moisture, and temperature """
        return_dict = measurements_dict.copy()

        if self.is_enabled(0):
            return_dict[0]['value'] = self.filter_average('lux', measurement=self.light())

        if self.is_enabled(1):
            return_dict[1]['value'] = self.moist()

        if self.is_enabled(2):
            return_dict[2]['value'] = self.temp() / 10.0

        return return_dict

    def get_reg(self, reg):
        # read 2 bytes from register
        val = self.bus.read_word_data(self.i2c_address, reg)
        # return swapped bytes (they come in wrong order)
        return (val >> 8) + ((val & 0xFF) << 8)

    def reset(self):
        # To reset the sensor, write 6 to the device I2C address
        self.bus.write_byte(self.i2c_address, 6)

    def set_addr(self, new_addr):
        # To change the I2C address of the sensor, write a new address
        # (one byte [1..127]) to register 1; the new address will take effect after reset
        self.bus.write_byte_data(self.i2c_address, 1, new_addr)
        self.reset()
        # self.address = new_addr

    def moist(self):
        # To read soil moisture, read 2 bytes from register 0
        return self.get_reg(0)

    def temp(self):
        # To read temperature, read 2 bytes from register 5
        return self.get_reg(5)

    def light(self):
        # To read light level, start measurement by writing 3 to the
        # device I2C address, wait for 3 seconds, read 2 bytes from register 4
        self.bus.write_byte(self.i2c_address, 3)
        time.sleep(1.5)
        lux = self.get_reg(4)
        if lux == 0:
            return 65535.0
        else:
            return(1 - (lux / 65535.0)) * 65535.0