Example #1
0
 def read_bme280(self):
     """
     @brief Read bme280 raspberry pi i2c bus
     Get temperatue, humidity, pressure, altitude
     """
     self._humidity_compensation = 13
     self._temperature_compensation = 3
     try:
         with I2C(self._bus) as i2c:
             bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, self._addr)
             # Change this to match the location's
             # pressure (hPa) at sea level
             bme280.sea_level_pressure = 1013.25
             bme280.mode = adafruit_bme280.MODE_NORMAL
             bme280.standby_period = adafruit_bme280.STANDBY_TC_500
             bme280.iir_filter = adafruit_bme280.IIR_FILTER_X16
             bme280.overscan_pressure = adafruit_bme280.OVERSCAN_X16
             bme280.overscan_humidity = adafruit_bme280.OVERSCAN_X1
             bme280.overscan_temperature = adafruit_bme280.OVERSCAN_X2
             # The sensor will need a moment to gather initial readings
             time.sleep(1)
             temperature = bme280.temperature - self._temperature_compensation
             humidity = bme280.humidity + self._humidity_compensation
             if self._debug:
                 print("Temperature: %.3f °c" % temperature)
                 print("Humidity: %.3f %%" % humidity)
                 print("Pressure: %.3f hPa" % bme280.pressure)
                 print("Altitude: %.3f meters" % bme280.altitude)
             return temperature, humidity, bme280.pressure, bme280.altitude
     except Exception as e:
         print("cannot read bme280, An exception occurred: {}".format(e))
Example #2
0
 def __init__(self, i2c_port=1):
     i2c = I2C(i2c_port)  # Create I2C bus.
     #self.sensor_interface = sensor_interface.VL6180X(i2c) # Create sensor instance.
     self.sensor_interface = adafruit_vl6180x.VL6180X(
         i2c)  # Create sensor instance.
     self.handle_exit_signals()
     time.sleep(2)
Example #3
0
    def __init__(self, config, queue, level):
        self._log = Logger("bno055", level)
        if config is None:
            raise ValueError("no configuration provided.")
        self._config = config
        self._queue = queue

        _config = self._config['ros'].get('bno055')
        self._quaternion_accept = _config.get(
            'quaternion_accept')  # permit Quaternion once calibrated
        self._loop_delay_sec = _config.get('loop_delay_sec')
        _i2c_device = _config.get('i2c_device')

        # use `ls /dev/i2c*` to find out what i2c devices are connected
        self._bno055 = adafruit_bno055.BNO055_I2C(
            I2C(_i2c_device))  # Device is /dev/i2c-1

        self._thread = None
        self._enabled = False
        self._closed = False
        self._heading = None
        self._pitch = None
        self._roll = None
        self._is_calibrated = False
        self._log.info('ready.')
Example #4
0
    def __init__(self, config, queue, level):
        self._log = Logger("bno055", level)
        if config is None:
            raise ValueError("no configuration provided.")
        self._queue = queue

        self._config = config
        # config
        _config = self._config['ros'].get('bno055')
        self._loop_delay_sec = _config.get('loop_delay_sec')
        _i2c_device = _config.get('i2c_device')
        self._pitch_trim = _config.get('pitch_trim')
        self._roll_trim = _config.get('roll_trim')
        self._heading_trim = _config.get('heading_trim')
        self._error_range = 5.0  # permitted error between Euler and Quaternion (in degrees) to allow setting value, was 3.0
        self._rate = Rate(_config.get('sample_rate'))  # e.g., 20Hz

        # use `ls /dev/i2c*` to find out what i2c devices are connected
        self._bno055 = adafruit_bno055.BNO055_I2C(
            I2C(_i2c_device))  # Device is /dev/i2c-1
        # some of the other modes provide accurate compass calibration but are very slow to calibrate
        #       self._bno055.mode = BNO055Mode.COMPASS_MODE.mode
        #       self._bno055.mode = BNO055Mode.NDOF_FMC_OFF_MODE.mode

        self._counter = itertools.count()
        self._thread = None
        self._enabled = False
        self._closed = False
        self._heading = 0.0  # we jauntily default at zero so we don't return a None
        self._pitch = None
        self._roll = None
        self._is_calibrated = Calibration.NEVER
        self._log.info('ready.')
Example #5
0
    def __init__(self, config, queue, level):
        self._log = Logger("bno055", level)
        if config is None:
            raise ValueError("no configuration provided.")
        self._config = config
        self._queue = queue

        #       # verbose will print some start-up info on the IMU sensors
        #       self._imu = IMU(gs=4, dps=2000, verbose=True)
        #       # setting a bias correction for the accel only; the mags/gyros are not getting a bias correction
        #       self._imu.setBias((0.1,-0.02,.25), None, None)

        _config = self._config['ros'].get('bno055')
        self._quaternion_accept = _config.get(
            'quaternion_accept')  # permit Quaternion once calibrated
        self._loop_delay_sec = _config.get('loop_delay_sec')
        _i2c_device = _config.get('i2c_device')
        self._pitch_trim = _config.get('pitch_trim')
        self._roll_trim = _config.get('roll_trim')
        self._heading_trim = _config.get('heading_trim')

        # use `ls /dev/i2c*` to find out what i2c devices are connected
        self._bno055 = adafruit_bno055.BNO055_I2C(
            I2C(_i2c_device))  # Device is /dev/i2c-1

        self._thread = None
        self._enabled = False
        self._closed = False
        self._heading = 0.0
        self._pitch = None
        self._roll = None
        self._is_calibrated = False
        self._h_max = 3.3  # TEMP
        self._h_min = 3.3  # TEMP
        self._log.info('ready.')
Example #6
0
    def __init__(self, config, level):
        self._log = Logger("bno055", level)
        if config is None:
            raise ValueError("no configuration provided.")

        self._config = config
        # config
        _config = self._config['ros'].get('bno055')
        self._bno_mode = BNO055Mode.from_name(_config.get('mode'))
        self._pitch_trim = _config.get('pitch_trim')
        self._roll_trim = _config.get('roll_trim')
        self._euler_heading_trim = _config.get('euler_heading_trim')
        self._quat_heading_trim = _config.get('quat_heading_trim')
        self._log.info('trim: heading: {:>5.2f}°(Euler) / {:>5.2f}°(Quat); pitch: {:>5.2f}°; roll: {:>5.2f}°'.format(\
                self._euler_heading_trim, self._quat_heading_trim, self._pitch_trim, self._roll_trim))
        self._error_range = 5.0  # permitted error between Euler and Quaternion (in degrees) to allow setting value, was 3.0
        # use `ls /dev/i2c*` to find out what i2c devices are connected
        _i2c_device = _config.get('i2c_device')
        self._bno055 = adafruit_bno055.BNO055_I2C(
            I2C(_i2c_device))  # Device is /dev/i2c-1
        # some of the modes provide accurate compass calibration but are very slow to calibrate
        #       self.set_mode(BNO055Mode.CONFIG_MODE)
        #       self._bno055.mode = BNO055Mode.COMPASS_MODE.mode
        #       self._bno055.mode = BNO055Mode.NDOF_FMC_OFF_MODE.mode
        self.set_mode(self._bno_mode)
        self._heading = 0.0
        #       self._pitch   = None
        #       self._roll    = None
        self._is_calibrated = Calibration.NEVER
        self._log.info('ready.')
Example #7
0
 def list_i2c_devices(self):
     """
     @brief save the current address so we can restore it after
     """
     with I2C(self._bus_number) as i2c:
         scan = i2c.scan()
         if self._debug:
             print("I2c devices found: ", scan)
         return scan
Example #8
0
    def getRawData(self):
        i2c = I2C(3)
        imu = adafruit_lsm6ds.LSM6DS33(i2c)
        accel_array = np.array(imu.acceleration)
        angvel_array = np.array(imu.gyro)

        print("Acceleration: X:%.2f, Y: %.2f, Z: %.2f m/s^2" %
              (imu.acceleration))
        #print("Gyro X:%.2f, Y: %.2f, Z: %.2f radians/s"%(imu.gyro))
        return accel_array, angvel_array
Example #9
0
 def __init__(self, measure, unit, device, address):
     """Initialize the sensor."""
     self._measure = measure
     self._unit = unit
     i2c_bus = I2C(device)
     self._device = device
     self._address = address
     self.ina219 = INA219(i2c_bus, address)
     value = getattr(self.ina219, self._measure)
     self._state = round(value, 2)
Example #10
0
    def read(self):
        try:
            i2c = I2C(3)
            imu = adafruit_lsm6ds.LSM6DS33(i2c)
            accel_array = imu.acceleration
            angvel_array = imu.gyro
        except RuntimeError as error:
            accel_array = (None, None, None)
            angvel_array = (None, None, None)

        return accel_array, angvel_array
Example #11
0
    def __init__(self, poll_delay=0.01):
        self.on = True
        self.poll_delay = poll_delay
        # optional, parameter p1
        i2c = I2C(6)  # Device is /dev/i2c-1
        self.sensor = adafruit_bno055.BNO055_I2C(i2c)

        self.heading = self.roll = self.pitch = self.sys = self.gyro = self.accel = self.mag = \
            self.ori_x = self.ori_y = self.ori_z = self.ori_w = self.temp_c = self.mag_x = self.mag_y = \
            self.mag_z = self.gyr_x = self.gyr_y = self.gyr_z = self.acc_x = self.acc_y = self.acc_z = \
            self.lacc_x = self.lacc_y = self.lacc_z = self.gra_x = self.gra_y = self.gra_z = 0
 def list_i2c_devices(self):
     """
     @brief list all i2c device on the current bus
     @return list of addresses
     """
     try:
         with I2C(self._bus) as i2c:
             scan = i2c.scan()
             if self._debug:
                 print("I2c devices found: ", scan)
             return scan
     except Exception as e:
         print("ERROR: Exception occured during get i2c devices list", e)
Example #13
0
 def read_bh1750(self):
     """
     @brief Read bh1750 raspberry pi i2c bus
     Get lux
     """
     try:
         with I2C(self._bus) as i2c:
             sensor = adafruit_bh1750.BH1750(i2c, address=self._addr)
             lux = sensor.lux
             if self._debug:
                 print("Light: %.3f lx" % lux)
             return lux
     except Exception as e:
         print("cannot read bh1750, An exception occurred: {}".format(e))
Example #14
0
 def read_sht40(self):
     """
     @brief Read sht40 raspberry pi i2c bus
     Get temperatue, humidity
     """
     try:
         with I2C(self._bus) as i2c:
             sht = adafruit_sht4x.SHT4x(i2c)
             sht.mode = adafruit_sht4x.Mode.NOHEAT_HIGHPRECISION
             time.sleep(1)
             temperature, humidity = sht.measurements
             if self._debug:
                 print("Temperature: %.3f °c" % temperature)
                 print("Humidity: %.3f %%" % humidity)
             return temperature, humidity
     except Exception as e:
         print("cannot read sht40, An exception occurred: {}".format(e))
Example #15
0
    def collect(i2c_bus):
        # collect imu data
        try:
            i2c = I2C(3)
            imu = adafruit_lsm6ds.LSM6DS33(i2c)
            accel_array = imu.acceleration
            angvel_array = imu.gyro
        except RuntimeError as error:
            accel_array = (None, None, None)
            angvel_array = (None, None, None)
        # collect dht data

        try:
            temperature = dht_device.temperature
            humidity = dht_device.humidity
        except RuntimeError as error:
            # Errors happen fairly often, DHT's are hard to read, just keep going
            temperature = None
            humidity = None
            print(error.args[0])
        t1 = time.time()

        return accel_array, angvel_array, temperature, humidity, t1
and does require the i2c-gpio kernel module to be
installed and enabled. Most Raspberry Pis will
already have it installed, however most do not
have it enabled. You will have to manually enable it
"""

import time
from adafruit_extended_bus import ExtendedI2C as I2C
import adafruit_bno055

# To enable i2c-gpio, add the line `dtoverlay=i2c-gpio` to /boot/config.txt
# Then reboot the pi

# Create library object using our Extended Bus I2C port
# Use `ls /dev/i2c*` to find out what i2c devices are connected
i2c = I2C(1)  # Device is /dev/i2c-1
sensor = adafruit_bno055.BNO055_I2C(i2c)

while True:
    print("Temperature: {} degrees C".format(sensor.temperature))
    print("Accelerometer (m/s^2): {}".format(sensor.acceleration))
    print("Magnetometer (microteslas): {}".format(sensor.magnetic))
    print("Gyroscope (rad/sec): {}".format(sensor.gyro))
    print("Euler angle: {}".format(sensor.euler))
    print("Quaternion: {}".format(sensor.quaternion))
    print("Linear acceleration (m/s^2): {}".format(sensor.linear_acceleration))
    print("Gravity (m/s^2): {}".format(sensor.gravity))
    print()

    time.sleep(1)
Example #17
0
#from adafruit_blinka.microcontroller.bcm283x import pin
from adafruit_extended_bus import ExtendedI2C as I2C

from adafruit_ina219 import ADCResolution, BusVoltageRange, INA219

#i2c_bus2  = smbus.SMBus(3) # 3 
#b1 = i2c_bus2.read_i2c_block_data(0x45, 0x01, 2)
#print (b1)

#p = busio.I2C(scl, sda)
#p = busio.I2C(pin.D1,pin.D0)
#p = board.I2C(pin.D1,pin.D0)
#p.deinit()

# Create library object using our Extended Bus I2C port
i2c_bus = I2C(11) # 1 Device is /dev/i2c-1


#i2c_bus = board.I2C()
#i2c_bus = p

print(i2c_bus)

ina219 = INA219(i2c_bus, 0x45)

print("ina219 test")

# display some of the advanced field (just to test)
print("Config register:")
print("  bus_voltage_range:    0x%1X" % ina219.bus_voltage_range)
print("  gain:                 0x%1X" % ina219.gain)
Example #18
0
    if (len(sys.argv)) > 1:
        #   print("There are arguments!")
        #   if (('a' == sys.argv[1]) or ('afsk' in sys.argv[1])):
        bus = int(sys.argv[1], base=10)
        if (len(sys.argv)) > 2:
            address = int(sys.argv[2], base=16)
        else:
            address = 0x40
    else:
        bus = 1
        address = 0x40

    try:
        # Create library object using  Extended Bus I2C port
        i2c_bus = I2C(bus)  # 1 Device is /dev/i2c-1

        ina219 = INA219(i2c_bus, address)

        # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage
        ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_1S  # 32S
        ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_1S  # 32S
        # optional : change voltage range to 16V
        ina219.bus_voltage_range = BusVoltageRange.RANGE_16V

        current = ina219.current  # current in mA
        print("{:9.1f}".format(current))

    except:
        print("0.0 Error")
Example #19
0
import time
import adafruit_lsm6ds
from adafruit_extended_bus import ExtendedI2C as I2C

i2c = I2C(3)
sox = adafruit_lsm6ds.LSM6DS33(i2c)

while True:

    print(sox.acceleration)
    print(sox.gyro)
    #print("Acceleration: X:%.2f, Y: %.2f, Z: %.2f m/s^2"%(sox.acceleration))
    #print("Gyro X:%.2f, Y: %.2f, Z: %.2f radians/s"%(sox.gyro))
    print("")
    time.sleep(0.1)
Example #20
0
#https://docs.google.com/document/d/1GRzY3Ll2JtlGXUPw1XQmhMr6sUkBdZnunfvKTPCG4-4/edit#
import time
import board
import busio
import adafruit_mpu6050
from adafruit_extended_bus import ExtendedI2C as I2C  # sudo pip3 install adafruit-extended-bus
import math
import adafruit_ssd1306
from PIL import Image, ImageDraw, ImageFont

i2c = I2C(11)  # GPIO23 = SDA, GPIO24 = SCL for this interface
mpu = adafruit_mpu6050.MPU6050(i2c)
i2c_display = busio.I2C(board.SCL, board.SDA)

#this part is going to be setting up the OLED display so you can print the steps onto it.

display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c_display)

width = display.width
height = display.height

image = Image.new('1', (width, height))

draw = ImageDraw.Draw(image)

draw.rectangle((0, 0, width, height), outline=0, fill=0)

font = ImageFont.truetype("Mario-Kart-DS.ttf", size=32)

# These two lines are initializing the connection between the accelerometer and the raspberry pi.
Example #21
0
from adafruit_extended_bus import ExtendedI2C as I2C  # sudo pip3 install adafruit-extended-bus
import adafruit_mpu6050  # sudo pip3 install adafruit-circuitpython-mpu6050
import board, digitalio, busio, math, time
import numpy as np
from tensorflow import lite as tflite
import adafruit_ssd1306
from PIL import Image, ImageDraw, ImageFont

i2c_accel = I2C(11)
i2c_display = busio.I2C(board.SCL, board.SDA)

accelerometer = adafruit_mpu6050.MPU6050(i2c_accel)

display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c_display)

width = display.width
height = display.height

image = Image.new('1', (width, height))

draw = ImageDraw.Draw(image)

draw.rectangle((0, 0, width, height), outline=0, fill=0)

font = ImageFont.truetype("Mario-Kart-DS.ttf", size=32)

print("Calibration time!")
calibration = []


def calibrate():
Example #22
0
    def __init__(self, min_speed=10, max_speed=26):
        # Create I2C interfaces.
        self.i2c_display = busio.I2C(board.SCL, board.SDA)
        self.i2c_accel = I2C(
            11)  # GPIO23 = SDA, GPIO24 = SCL -- enable the i2c-gpio overlay!

        # Update minimum and maximum speeds (in pixels / second)
        self.min_speed = min_speed
        self.max_speed = max_speed
        self.current_speed = min_speed  # to start

        # Create list of obstacles (empty to start)
        self.obstacles = []

        # Create a variable to hold the score
        self.score = 0

        # Create a dino 🦖
        self.dino = Dino(self)

        # The PiOLED is 128 pixels x 32 pixels, and communicates over I2C, so we need to give it the I2C interface created above.
        self.display = adafruit_ssd1306.SSD1306_I2C(128, 32, self.i2c_display)

        # Initialize the accelerometer.
        self.accelerometer = adafruit_mpu6050.MPU6050(self.i2c_accel)

        # Initialize the UI button.
        self.button = digitalio.DigitalInOut(board.D26)
        self.button.direction = digitalio.Direction.INPUT
        self.button.pull = digitalio.Pull.UP

        # Variable to hold acceleration (updated often from the MPU6050)
        self.acceleration = [0, 0, 0]

        # Variable to hold gyro data (updated often from the MPU6050)
        self.gyro = [0, 0, 0]

        # Time that we last added an obstacle
        self.last_added_obstacle = time.time_ns() / 1000000000

        # Get display width & height.
        self.width = self.display.width
        self.height = self.display.height

        # Create blank image for drawing.
        # Make sure to create image with mode '1' for 1-bit color.
        # 1-bit color means the only options are full brightness (fill=255) or off (fill=0) -- this display is monochrome.
        self.image = Image.new('1', (self.width, self.height))

        # Get drawing object to draw on image.
        self.draw = ImageDraw.Draw(self.image)

        # Draw a black filled box to clear the image.
        self.draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)

        # Draw a line at the bottom of the screen (height = 31 & width = 127 because they start at 0, so we are drawing from (0, 31) to (128, 31)).
        # This is the ground for the dino game. The line also is at full brightness (fill=255), 3 pixels high (width=3), and has curved edges (joint="curve").
        # self.draw.line([(0, self.height), (self.width, self.height)], fill=255, width=3, joint="curve")

        # Draw the ground for the dino game (see where we make the bitmap on line 18). Fill = white (255). TODO get final line #
        self.draw.bitmap((0, 27), bitmap(bitmaps["ground"]), fill=255)

        # Update display. (not the obstacles because we haven't started yet)
        self.update_display()

        if not self.dino.calibration_exists:
            print(
                "Calibrating gyro in 3 seconds. Please put the MPU6050 down on a flat surface with the Z axis (chip) pointing up."
            )
            time.sleep(3)
        self.dino.calibrate()

        # Time that the game started (for screen recording)
        self.start = time.time_ns() / 1000000  # milliseconds

        # Start the game! Call the update() function every 0.01 seconds.
        # This returns a function that will stop the loop.
        self.stop1 = call_repeatedly(0.01, self.update)

        self.stop2 = call_repeatedly(0.0001, self.get_acceleration)
Example #23
0
from adafruit_extended_bus import ExtendedI2C as I2C  # sudo pip3 install adafruit-extended-bus
import adafruit_mpu6050  # sudo pip3 install adafruit-circuitpython-mpu6050
import board, digitalio, math, time

i2c = I2C(11)

accelerometer = adafruit_mpu6050.MPU6050(i2c)

print(
    "This is the step counter training program, for aspiring AI-powered step counters."
)

print("Calibration time!")
calibration = []


def calibrate():
    global calibration
    total = [0, 0, 0]
    for i in range(100):
        acceleration = accelerometer.acceleration
        total[0] += acceleration[0]
        total[1] += acceleration[1]
        total[2] += acceleration[2]
    total[0] /= 100.0
    total[1] /= 100.0
    total[2] /= 100.0
    calibration = total


calibrate()
Example #24
0
import locale

# Set your desired locale for date and time formats
locale.setlocale(locale.LC_ALL, 'ca_ES.utf8')

# Setting some variables for our reset pin etc.
RESET_PIN = digitalio.DigitalInOut(board.D4)

# Using extended I2C library because I created two I2C buses for my Pi
# First one is for the OLED and second (number 11) is for the temp sensor

# Modify the numbers here to match your setup

# Here take into account that your screen could be 128x32, so change that '64' with '32'
# Also some models like mine have address 0x3C in I2C, but others use 0x3D. Please check it with command like 'i2cdetect' if this value doesn't work.
i2c = I2C(1)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C, reset=RESET_PIN)

# My BME280 model has 0x76 address, but some others have 0x77. Check it with 'i2cdetect' if this value is not working.
i2c11 = I2C(11)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c11, address=0x76)

# This is not even needed as we don't need to calculate altitude, but
# if you need it, just adjust this parameter to your daily sea level pressure
bme280.sea_level_pressure = 1013.25

# Clear display.
oled.fill(0)
oled.show()

# Create blank image for drawing.
    if (len(sys.argv)) > 1:
        #   print("There are arguments!")
        #   if (('a' == sys.argv[1]) or ('afsk' in sys.argv[1])):
        buses[0] = int(sys.argv[1], base=10)
        if (len(sys.argv)) > 2:
            buses[1] = int(sys.argv[2], base=10)
            if (len(sys.argv)) > 3:
                if sys.argv[3] == "c":
                    config = True
                    from adafruit_ina219 import ADCResolution, BusVoltageRange

    addresses = [0x40, 0x41, 0x44, 0x45]  #INA219 addresses on the bus
    #  print("buses: ", buses, " addr: ", addresses)
    for x in buses:
        try:
            i2c_bus = I2C(x)  # Device is /dev/i2c-x
            for y in addresses:
                #     print(x,y)
                try:
                    # Create library object using  Extended Bus I2C port
                    #         print("bus: ", x, " addr: ", y)
                    if x == 0 and y == 0x45:
                        #           print("Reading INA219 in MoPower Board")
                        i2c_bus = I2C(1)
                        ina219 = INA219(i2c_bus, 0x4a)
                    else:
                        ina219 = INA219(i2c_bus, y)

#       print("ina219 test")
                    if config:
                        #           print("Configuring")
Example #26
0
# add 2 rows into /boot/config.txt
# # Additional overlays and parameters are documented /boot/overlays/README
# dtoverlay=i2c6

# pip3 install adafruit-extended-bus
# pip3 install adafruit-circuitpython-bno055

import time
from adafruit_extended_bus import ExtendedI2C as I2C
import adafruit_bno055

# To enable i2c-gpio, add the line `dtoverlay=i2c-gpio` to /boot/config.txt
# Then reboot the pi

# Create library object using our Extended Bus I2C port
# Use `ls /dev/i2c*` to find out what i2c devices are connected
i2c = I2C(6)  # Device is /dev/i2c-1
sensor = adafruit_bno055.BNO055_I2C(i2c)

while True:
    print("Temperature: {} degrees C".format(sensor.temperature))
    print("Accelerometer (m/s^2): {}".format(sensor.acceleration))
    print("Magnetometer (microteslas): {}".format(sensor.magnetic))
    print("Gyroscope (rad/sec): {}".format(sensor.gyro))
    print("Euler angle: {}".format(sensor.euler))
    print("Quaternion: {}".format(sensor.quaternion))
    print("Linear acceleration (m/s^2): {}".format(sensor.linear_acceleration))
    print("Gravity (m/s^2): {}".format(sensor.gravity))
    print()

    time.sleep(1)
Example #27
0
Einfaches Zweitskript, das nebenher einen REST-Server zum Einstellen von
Lautstärke u.Ä. betreibt.
"""

# Voraussetzungen:
# sudo pip3 install adafruit-blinka
# sudo pip3 install adafruit-extended-bus
# sudo pip3 install adafruit-circuitpython-tpa2016
# sudo pip3 install flask

from adafruit_extended_bus import ExtendedI2C as I2C
import adafruit_tpa2016
from flask import Flask, abort, jsonify

# TPA-Objekt erstellen
i2c = I2C(0)
tpa = adafruit_tpa2016.TPA2016(i2c)

# Voreinstellungen vornehmen
tpa.attack_time = 1
tpa.compression_ratio = tpa.COMPRESSION_4_1
tpa.hold_time = 0
tpa.noise_gate_enable = True
tpa.noise_gate_threshold = tpa.NOISE_GATE_4
tpa.release_time = 1

# REST-Server erstellen
app = Flask("Stundengeläut")


@app.route('/volume/')
Example #28
0
#  The Raspberry Pi I2C buses need to be enabled in /boot/config.txt like this:
#  
#  for I2C-0: # for SDA = GPIO0 (pin 27) and SCL = GPIO1 (pin 28)        - fixed pin #
#  ==========
#  dtparam=i2c_arm=on
#
#  for I2C-1: # for SDA = GPIO2 (pin 3) and SCL = GPIO3 (pin 5)          - fixed pin #
#  ==========
#  dtparam=i2c_vc=on
#
#  for I2c-4  # for SDA = GPIO6 (pin 31) and SCL = GPIO7 (pin 26) - configurable pin #
#  ==========
#  dtoverlay=i2c-gpio,bus=4,i2c_gpio_delayUs=1,i2c_gpio_sda=6,i2c_gpio_scl=7
#
#####################################################################################
i2c0 = I2C(0)
i2c1 = I2C(1)
i2c4 = I2C(4)

def i2c_scan(devices):
    for device in devices:
        for name, addresses in pair:
            for address in addresses:
                if device == address:
                    print("{} device at : {}".format(name, hex(device)))

def main():
    print("Scan i2c-0 bus...")
    devices = i2c0.scan()
    print("i2c devices found on bus 0:",len(devices))
    i2c_scan(devices)
Example #29
0
    #          ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S     # 1S
    # optional : change voltage range to 16V
    #          ina219.bus_voltage_range = BusVoltageRange.RANGE_16V
    #        except:
    #          print("Python Error 2", file=sys.stderr, flush=True)
    #    except:
    #      print("Python Error 1", file=sys.stderr, flush=True)
    # No try checking yet

    #  if buses[0] == 0 and addresses[0] == 0x45:
    #    print("Reading INA219 in MoPower Board")
    #    ina219_one = INA219(I2C(1), 0x4a)
    #  else:
    if (buses[0] != -1):
        try:
            i2c_one = I2C(buses[0])
            try:
                ina219_one = INA219(i2c_one, addresses[0])
                ina219_one.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S  # 1S
                time.sleep(0.001)
                ina219_one.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S  # 1S
                time.sleep(0.001)
                ina219_one.bus_voltage_range = BusVoltageRange.RANGE_16V
                time.sleep(0.01)
                one = 1
            except:
                #        print("Python Error 3", file=sys.stderr, flush=True)
                one = 0
            try:
                ina219_two = INA219(i2c_one, addresses[1])
                ina219_two.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S  # 1S