def __init__(self, i2c_address, queue): self.bus = SMBus(1) self.address = i2c_address self.queue = queue self.rot_enc_thread = None self.vol_change_cb = None
def __init__(self, address): """Create an instance of the MCP4725 DAC.""" self._device = SMBus(1) self._address = address
import ltr559 from numpy import interp from bme280 import BME280 from modules import e_paper, mqtt, influxdb from modules import gas as GAS from pms5003 import PMS5003 try: from smbus2 import SMBus except ImportError: from smbus import SMBus logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s - %(message)s') BUS = SMBus(1) INTERVAL = int(os.getenv('INTERVAL', '300')) DEVICE_NAME = os.getenv('DEVICE_NAME', 'AirTower') MQTT_SERVER = os.getenv('MQTT_SERVER', 'localhost') MQTT_ENABLED = MQTT_SERVER.lower() != 'disabled' MQTT_PORT = int(os.getenv('MQTT_PORT', '1883')) MQTT_BASE_TOPIC = os.getenv('MQTT_BASE_TOPIC', 'homeassistant') MQTT_KEEPALIVE = int(os.getenv('MQTT_KEEPALIVE', '60')) METRICS = { 'temperature': { 'name': 'Temperature', 'unit': 'C', 'class': 'temperature',
def send_homing_speed(value): with SMBus(i2c_bus) as bus: msg = i2c_msg.write(address, set_home(value)) bus.i2c_rdwr(msg)
def main(_): if FLAGS.detect: # Initialize ambient sensors. try: ambient = bme680.BME680(i2c_addr=bme680.I2C_ADDR_PRIMARY,i2c_device=SMBus(1)) except IOError: ambient = bme680.BME680(i2c_addr=bme680.I2C_ADDR_SECONDARY,i2c_device=SMBus(1)) # TODO: Tune settings. ambient.set_humidity_oversample(bme680.OS_2X) ambient.set_pressure_oversample(bme680.OS_4X) ambient.set_temperature_oversample(bme680.OS_8X) ambient.set_filter(bme680.FILTER_SIZE_3) ambient.set_gas_status(bme680.DISABLE_GAS_MEAS) # Load the face detection model. face_detector = DetectionEngine(FLAGS.face_model) # Start the frame processing loop. with PureThermal() as camera: # Initialize thermal image buffers. input_shape = (camera.height(), camera.width()) raw_buffer = np.zeros(input_shape, dtype=np.int16) scaled_buffer = np.zeros(input_shape, dtype=np.uint8) if FLAGS.detect: rgb_buffer = np.zeros((*input_shape, 3), dtype=np.uint8) if FLAGS.visualize: window_buffer = np.zeros((WINDOW_HEIGHT, WINDOW_WIDTH, 3), dtype=np.uint8) raw_scale_factor = ( FLAGS.max_temperature - FLAGS.min_temperature) // 255 window_scale_factor_x = WINDOW_WIDTH / camera.width() window_scale_factor_y = WINDOW_HEIGHT / camera.height() if FLAGS.visualize: # Initialize the window. cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL) cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) while (not FLAGS.visualize or cv2.getWindowProperty(WINDOW_NAME, 0) != -1): try: start_time = time() if FLAGS.detect: # Acquire ambient sensor readings. if not ambient.get_sensor_data(): logging.warning('Ambient sensor data not ready') ambient_data = ambient.data logging.debug('Ambient temperature: %.f C' % ambient_data.temperature) logging.debug('Ambient pressure: %.f hPa' % ambient_data.pressure) logging.debug('Ambient humidity: %.f %%' % ambient_data.humidity) # Get the latest frame from the thermal camera and copy it. with camera.frame_lock(): np.copyto(dst=raw_buffer, src=camera.frame()) # Map the raw temperature data to a normal range before # reducing the bit depth and min/max normalizing for better # contrast. np.clip((raw_buffer - FLAGS.min_temperature) // raw_scale_factor, 0, 255, out=scaled_buffer) cv2.normalize(src=scaled_buffer, dst=scaled_buffer, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) if FLAGS.detect: # Convert to the expected RGB format. cv2.cvtColor(src=scaled_buffer, dst=rgb_buffer, code=cv2.COLOR_GRAY2RGB) # Detect any faces in the frame. faces = face_detector.detect_with_image( Image.fromarray(rgb_buffer), threshold=FLAGS.face_confidence, top_k=FLAGS.max_num_faces, keep_aspect_ratio=True, # Better quality. relative_coord=False, # Expect pixel coordinates. resample=Image.BILINEAR) # Good enough and fast. # TODO: Estimate distance based on face size. # TODO: Model thermal attenuation based on distance and # ambient temperature, pressure, and humidity. # Find the (highest) temperature of each face. if len(faces) == 1: logging.info('1 person') else: logging.info('%d people' % len(faces)) for face in faces: temperature = get_temperature(raw_buffer, face.bounding_box) if not temperature: logging.warning('Empty crop') continue logging.info(format_temperature(temperature)) if FLAGS.visualize: # Apply the colormap. turbo_buffer = TURBO_COLORMAP[scaled_buffer] # Resize for the window. cv2.cvtColor(src=turbo_buffer, dst=turbo_buffer, code=cv2.COLOR_RGB2BGR) cv2.resize(src=turbo_buffer, dst=window_buffer, dsize=(WINDOW_WIDTH, WINDOW_HEIGHT), interpolation=cv2.INTER_CUBIC) if FLAGS.detect: # Draw the face bounding boxes and temperature. for face in faces: bbox = face.bounding_box top_left = ( int(window_scale_factor_x * bbox[0, 0]), int(window_scale_factor_y * bbox[0, 1])) bottom_right = ( int(window_scale_factor_x * bbox[1, 0]), int(window_scale_factor_y * bbox[1, 1])) cv2.rectangle(window_buffer, top_left, bottom_right, LINE_COLOR, LINE_THICKNESS) temperature = get_temperature(raw_buffer, face.bounding_box) if not temperature: continue label = format_temperature(temperature, add_unit=False) label_size, _ = cv2.getTextSize(label, LABEL_FONT, LABEL_SCALE, LABEL_THICKNESS) label_position = ( (top_left[0] + bottom_right[0]) // 2 - label_size[0] // 2, (top_left[1] + bottom_right[1]) // 2 + label_size[1] // 2) cv2.putText(window_buffer, label, label_position, LABEL_FONT, LABEL_SCALE, LABEL_COLOR, LABEL_THICKNESS, cv2.LINE_AA) # Draw the frame. cv2.imshow(WINDOW_NAME, window_buffer) cv2.waitKey(1) # Calculate timing stats. duration = time() - start_time logging.debug('Frame took %.f ms (%.2f Hz)' % ( duration * 1000, 1 / duration)) # Stop on SIGINT. except KeyboardInterrupt: break if FLAGS.visualize: cv2.destroyAllWindows()
def send_reset(): with SMBus(i2c_bus) as bus: msg = i2c_msg.write(address, reset()) bus.i2c_rdwr(msg)
def send_mode_pnumatic(): with SMBus(i2c_bus) as bus: msg = i2c_msg.write(address, mode_pnumatic()) bus.i2c_rdwr(msg)
def __enter__(self): if SimpleSMBus._bus is not None: raise Exception("Device conflict") self._logger.debug("Opening "+self.dev.get_name()) SimpleSMBus._bus = SMBus(self.dev.get_bus_number(), self.force) return self
Signal processing ''' t = np.arange(0, N / Fbit, 1 / Fs) # time to send all bits m = np.zeros(0) for bit in data_in: if bit == 0: m = np.hstack((m, np.multiply(np.ones(int(Fs / Fbit)), Fc - Fdev))) else: m = np.hstack((m, np.multiply(np.ones(int(Fs / Fbit)), Fc + Fdev))) y = np.zeros(0) y = A * np.cos(2 * np.pi * np.multiply(m, t)) + zero_line ''' Signal sending ''' port = SMBus(bus=i2c_folder) port.open(i2c_folder) time_point = 0 input('Press Enter to start') GPIO.output('P8_7', GPIO.HIGH) # Trigger line high for i in y: i = int(i) while time.time() - time_point < DAC_T: # Time management control None send(i) time_point = time.time() GPIO.output('P8_7', GPIO.LOW) # Trigger line low port.close()
# * Author : Jiankai Li # * Create Time: Nov 2015 # * Change Log : Seth Dec. 2019 w/ help from #beagle at Freenode # FileName : MotorBridge.py # by Jiankai.li from smbus2 import SMBus import time import pathlib # reset pin is P9.23, i.e. gpio1.17 reset_pin = pathlib.Path('/sys/class/gpio/gpio49/direction') reset_pin.write_text('low') MotorBridge = SMBus('/dev/i2c-2') ReadMode = 0 WriteMode = 1 DeAddr = 0X4B ConfigValid = 0x3a6fb67c DelayTime = 0.005 # TB_WORKMODE TB_SHORT_BREAK = 0 TB_CW = 1 TB_CCW = 2 TB_STOP = 3 TB_WORKMODE_NUM = 4
def smbus_init(): # Initialise the BMP280 bus = SMBus(1) bmp280 = BMP280(i2c_dev=bus) print("smbus_init Init ...") return bmp280
hwDate = datetime.strptime(hwDate[:24], "%a %b %d %X %Y") if hwDate > datetime(2021, 1, 1): #the date in the HW clock is probably accurate. it goes back to 1970 if it looses power subprocess.check_output("hwclock --rtc /dev/rtc1 --hctosys") else: #we dont have NTP or a valid RTC so we will just guess that the time is 1 min after the last time we had a reading with open('/www/pages/live.json', 'r') as outfile: data = json.load(outfile) theTime = list(data.keys())[0] subprocess.run(["date", "--set=%s" % theTime.split('.')[0]]) subprocess.check_output("hwclock --rtc /dev/rtc1 --systohc", shell=True) subprocess.run(["systemctl", "restart", "hostapd.service"]) with SMBus(2) as bus: #init ###light level sensor # make sure sensor is on, we are not worried about power consuption # ALS_GAIN: 1/8, ALS_IT 200 bus.write_word_data(0x10, 0x00, 0x1040) ###Pressure and temp #reset device bus.write_byte(0x76, 0x1E) #read the calibration data c0 = int.from_bytes(bytes(bus.read_i2c_block_data(0x76, 0xA0, 2)), 'big') c1 = int.from_bytes(bytes(bus.read_i2c_block_data(0x76, 0xA2, 2)), 'big') c2 = int.from_bytes(bytes(bus.read_i2c_block_data(0x76, 0xA4, 2)),
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('Adafruit_I2C.Device.Bus.{0}.Address.{1:#0X}'.format(busnum, address))
import time import binascii from smbus2 import SMBus, i2c_msg PN532_I2C_ADDRESS = (0x48 >> 1) _wire = SMBus(1) PN532_PREAMBLE = (0x00) PN532_STARTCODE1 = (0x00) PN532_STARTCODE2 = (0xFF) PN532_POSTAMBLE = (0x00) PN532_HOSTTOPN532 = (0xD4) PN532_PN532TOHOST = (0xD5) PN532_ACK_WAIT_TIME = (10) # ms, timeout of waiting for ACK PN532_INVALID_ACK = (-1) PN532_TIMEOUT = (-2) PN532_INVALID_FRAME = (-3) PN532_NO_SPACE = (-4) PN532_COMMAND_DIAGNOSE = (0x00) PN532_COMMAND_GETFIRMWAREVERSION = (0x02) PN532_COMMAND_GETGENERALSTATUS = (0x04) PN532_COMMAND_READREGISTER = (0x06) PN532_COMMAND_WRITEREGISTER = (0x08) PN532_COMMAND_READGPIO = (0x0C) PN532_COMMAND_WRITEGPIO = (0x0E) PN532_COMMAND_SETSERIALBAUDRATE = (0x10) PN532_COMMAND_SETPARAMETERS = (0x12) PN532_COMMAND_SAMCONFIGURATION = (0x14) PN532_COMMAND_POWERDOWN = (0x16) PN532_COMMAND_RFCONFIGURATION = (0x32)
def __init__(self, busId=1): super().__init__() self.bus = SMBus(bus=busId)
def __init__(self): self._device = SMBus(1) self.led_current = 20 self.frequency = FREQUENCY_390K625 self.write(_VCNL4010_INTCONTROL, 0x08)
def get(): with SMBus(i2c_bus) as bus: block = bytes(bus.read_i2c_block_data(address, 1, 16)) out = unpack("<ffff", block) return out
def read(self, address): # Read an 8-bit unsigned value from the specified 8-bit address. with SMBus(1) as self._device: read = self._device.read_byte_data(_VCNL4010_I2CADDR_DEFAULT, address) return read
def send_enable(state): with SMBus(i2c_bus) as bus: msg = i2c_msg.write(address, enable(state)) bus.i2c_rdwr(msg)
def write(self, address, val): # Write an 8-bit unsigned value to the specified 8-bit address. with SMBus(1) as self._device: self._device.write_byte_data(_VCNL4010_I2CADDR_DEFAULT, address, val)
def send_target(value): with SMBus(i2c_bus) as bus: msg = i2c_msg.write(address, set_target(value)) bus.i2c_rdwr(msg)
def read_16(self, address): with SMBus(1) as self._device: read_block = self._device.read_i2c_block_data( _VCNL4010_I2CADDR_DEFAULT, address, 2) return (read_block[0] << 8) | read_block[1]
def send_encoder_pol(value): with SMBus(i2c_bus) as bus: msg = i2c_msg.write(address, encoder_polarity(value)) bus.i2c_rdwr(msg)
def read_byte(self, address): with SMBus(1) as self._device: read = self._device.read_byte(address)
logging.basicConfig( format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') logging.info("""compensated-temperature.py - Use the CPU temperature to compensate temperature readings from the BME280 sensor. Method adapted from Initial State's Enviro pHAT review: https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441 Press Ctrl+C to exit! """) bus = SMBus(1) bme280 = BME280(i2c_dev=bus) # Get the temperature of the CPU for compensation def get_cpu_temperature(): with open("/sys/class/thermal/thermal_zone0/temp", "r") as f: temp = f.read() temp = int(temp) / 1000.0 return temp # Tuning factor for compensation. Decrease this number to adjust the # temperature down, and increase to adjust up factor = 2.25
def __init__(self, bus=None) -> None: if not bus: bus = SMBus(1) self.bus = bus self.addr = self.MAX44009_I2C_DEFAULT_ADDRESS self.configure()
def get_RPi_i2c(cls, bus_id=1): from smbus2 import SMBus return SMBus(bus_id)
def initialize_input(self): from smbus2 import SMBus self.i2c_address = int(str(self.input_dev.i2c_location), 16) self.bus = SMBus(self.input_dev.i2c_bus)
import time import serial from datetime import datetime i2c_dev = "/dev/i2c-1" i2c_addr = 0x44 result_reg = 0x00 config_reg = 0x01 config = 0b1100111000000000 ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1) data_file = open("sensor_data.dat", "w") data_file.write( "YYYY-MM-DD HH:mm:ss.ffffff,lux,b'r,mag/arcsec^2,Hz,idk,idk,Celcius,GPS\n") print(hex(config)) i2c = SMBus(1) #i2c.write_word_data(i2c_addr, config_reg, config) i2c.write_i2c_block_data(i2c_addr, config_reg, [0b11001110, 0b00000000]) for byte in i2c.read_i2c_block_data(i2c_addr, 0x7E, 2): print(hex(byte)) for byte in i2c.read_i2c_block_data(i2c_addr, 0x7F, 2): print(hex(byte)) print(hex(i2c.read_word_data(i2c_addr, config_reg))) while (1): conversion_ready = i2c.read_word_data(i2c_addr, config_reg) if ((conversion_ready & 0x80) == 0x80): reading = i2c.read_word_data(i2c_addr, result_reg) lux = 0.01 * (1 << ((reading & 0xF000) >> 12)) * (reading & 0x0FFF) ser.write(b'rx') sqm = ser.readline()
def __init__(self): self.factor = 2.5 self.cpu_temps = [self.get_cpu_temperature()] * 5 self.bus = SMBus(1) self.bme280 = BME280(i2c_dev=self.bus) self.ltr559 = LTR559()