# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # Written by BitHead (Britany Head) # Step 1) Enable I2C in Raspi-Config (Interfacing Options) # Step 2) sudo apt-get install i2c-tools python3-smbus # Step 3) plug it in (don't forget your pull-up resistors) and run this program import smbus import time import threading bus = smbus.SMBus(1) # /dev/i2c-1, in my case class VEML6040(object): def __init__(self, i2c_driver=None, bus=None, resetPin=None): """ This method initializes the class object. If no 'address' or 'i2c_driver' are inputed or 'None' is specified, the method will use the defaults. :param address: The I2C address to use for the device. If not provided, the method will default to the 0x10 :param i2c_driver: An existing SMBus driver object.If not parsed, it is created :param bus: bus number of i2c bus on rpi. Defaults to 1 is nothing passed """ self.VEML6040_ADDR = 0x10 #default i2c address of
def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.i2c_bus = smbus.SMBus(self.i2c_bus)
def __init__(self, name, address, bus_nr, address_sensor): self.name = name self.address = address self.bus_nr = bus_nr self.bus = smbus.SMBus(bus_nr) self.address_sensor = address_sensor
import smbus bus = smbus.SMBus(1) # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1) fichero = open('/usr/lib/python2.7/dist-packages/RPi/volumen.txt') if fichero.read() == '0': print('no se puede mas') else: fichero.seek(0) numero = fichero.read() fichero.close() numero = int(numero) + 2 bus.write_byte_data(0x44, 0x02, numero) numero = str(numero) fichero = open('/usr/lib/python2.7/dist-packages/RPi/volumen.txt','w') fichero.seek(0) fichero.write(numero) fichero.close() fichero = open('/usr/lib/python2.7/dist-packages/RPi/volumen.txt') numero = fichero.read() print(numero) fichero.close()
def dist(a, b): return math.sqrt((a * a) + (b * b)) def get_y_rotation(x, y, z): radians = math.atan2(x, dist(y, z)) return -math.degrees(radians) def get_x_rotation(x, y, z): radians = math.atan2(y, dist(x, z)) return math.degrees(radians) bus = smbus.SMBus(1) # or bus = smbus.SMBus(1) for Revision 2 boards address = 0x68 # This is the address value read via the i2cdetect command # Now wake the 6050 up as it starts in sleep mode bus.write_byte_data(address, power_mgmt_1, 0) #---------------------------------- main ------------------------------------------- learning_rate = 0.1 X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) W1 = tf.Variable(tf.random_normal([6, 4]), name='weight1') b1 = tf.Variable(tf.random_normal([4]), name='bias1') layer1 = tf.nn.relu(tf.matmul(X, W1) + b1) W2 = tf.Variable(tf.random_normal([4, 2]), name='weight2') b2 = tf.Variable(tf.random_normal([2]), name='bias2')
from lcddriver import lcd from time import time from time import sleep from datetime import datetime import smbus i2c = smbus.SMBus(0) address = 0x5c lcd = lcd() lcd.display_string("LCD", 1) lcd.display_string("Hello World", 2) sleep(5) lcd.clear() def read(): hum = 0.0 tmp = 0.0 try: sleep(0.003) i2c.write_i2c_block_data(address, 0x03, [0x00, 0x04]) sleep(0.015) block = i2c.read_i2c_block_data(address, 0, 6) hum = float(block[2] << 8 | block[3]) / 10 tmp = float(block[4] << 8 | block[5]) / 10 except: pass return (tmp, hum)
def __init__(self): self.address = 0x18 #address of the I2C device self.bus = smbus.SMBus(1) #initialize bus
import time import smbus import logx import logging BUS = smbus.SMBus(1) LCD_ADDR = 0x27 BLEN = 1 #turn on/off background light def turn_light(key): global BLEN BLEN = key if key ==1 : BUS.write_byte(LCD_ADDR ,0x08) logging.info('LCD executed turn on BLight') else: BUS.write_byte(LCD_ADDR ,0x00) logging.info('LCD executed turn off BLight') def write_word(addr, data): global BLEN temp = data if BLEN == 1: temp |= 0x08 else: temp &= 0xF7 BUS.write_byte(addr ,temp) def send_command(comm): # Send bit7-4 firstly buf = comm & 0xF0 buf |= 0x04 # RS = 0, RW = 0, EN = 1
class _Basic_class(object): _class_name = '_Basic_class' _DEBUG = 0 DEBUG_LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } DEBUG_NAMES = ['critical', 'error', 'warning', 'info', 'debug'] bus = smbus.SMBus(1) SYS_ADDRESS = 0x10 def __init__(self): self.logger_setup() def logger_setup(self): self.logger = logging.getLogger(self._class_name) self.ch = logging.StreamHandler() form = "%(asctime)s [%(levelname)s] %(message)s" self.formatter = logging.Formatter(form) self.ch.setFormatter(self.formatter) self.logger.addHandler(self.ch) self._debug = self.logger.debug self._info = self.logger.info self._warning = self.logger.warning self._error = self.logger.error self._critical = self.logger.critical @property def DEBUG(self): return self._DEBUG @DEBUG.setter def DEBUG(self, debug): if debug in range(5): self._DEBUG = self.DEBUG_NAMES[debug] elif debug in self.DEBUG_NAMES: self._DEBUG = debug else: raise ValueError( 'Debug value must be 0(critical), 1(error), 2(warning), 3(info) or 4(debug), not \"{0}\".' .format(debug)) self.logger.setLevel(self.DEBUG_LEVELS[self._DEBUG]) self.ch.setLevel(self.DEBUG_LEVELS[self._DEBUG]) self._debug('Set logging level to [%s]' % self._DEBUG) def run_command(self, cmd): self._debug('Run command: "%s"' % cmd) with tempfile.TemporaryFile() as f: subprocess.call(cmd, shell=True, stdout=f, stderr=f) f.seek(0) output = f.read() return output def _map(self, x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min def _write_sys_byte(self, value): self._info('Write "0x%02X" to I2C_dev(0x%02X)' % (value, self.SYS_ADDRESS)) self._debug('└─Write "0x%02X" to I2C_dev(0x%02X) start' % (value, self.SYS_ADDRESS)) self.bus.write_byte(self.SYS_ADDRESS, value) self._debug("└─Done") def _read_sys_byte(self, reg, delay=0): self._info('Read from I2C_dev(0x%02X) at "0x%02X"' % (self.SYS_ADDRESS, reg)) self._debug('└─Write "0x%02X" to I2C_dev(0x%02X)' % (reg, self.SYS_ADDRESS)) self.bus.write_byte(self.SYS_ADDRESS, reg) self._debug("└─Done") if delay != 0: time.sleep(delay) self._debug('└─Read from I2C_dev(0x%02X)' % (self.SYS_ADDRESS)) number = self.bus.read_byte(self.SYS_ADDRESS) self._debug('└─Done, read value: "0x%02X"' % number) if delay != 0: time.sleep(delay) return number def end(self): pass
# -*- coding: utf-8 -*- """ Created on Sun Jan 17 18:50:15 2021 @author: Administrator """ import smbus device = smbus.SMBus(1) dev_addr = 0x30 identi_addr = 0x39 inter_control = 0x1b X_H_add = 0x00 X_L_add = 0x01 Y_H_add = 0x02 Y_L_add = 0x03 Z_H_add = 0x04 Z_L_add = 0x05 class Mag: def __init__(self): self.device = device def all_data(self): self.device.write_byte_data(dev_addr,inter_control,0b00100001) self.X_L = self.device.read_byte_data(dev_addr,X_L_add) self.X_H = self.device.read_byte_data(dev_addr,X_H_add) self.Y_L = self.device.read_byte_data(dev_addr,Y_L_add) self.Y_H = self.device.read_byte_data(dev_addr,Y_H_add) self.Z_L = self.device.read_byte_data(dev_addr,Z_L_add)
#!/usr/bin/env python3 # Reads a TMP101 sensor and posts its temp on ThinkSpeak # https://thingspeak.com/channels/538706 # source setup.sh to set THING_KEY # Edited by James Werne, 11/4/2020 # Reads values of TMP101 sensors, then prints them to a Thingspeak channel: # https://thingspeak.com/channels/1220211/private_show import requests import os, sys import time import smbus import time bus = smbus.SMBus(2) TMPleft = 0x48 TMPright = 0x4a #TMP101a='/sys/class/i2c-adapter/i2c-2/2-0048/hwmon/hwmon0/' #TMP101b='/sys/class/i2c-adapter/i2c-2/2-0049/hwmon/hwmon1/' # Get the key (See setup.sh) key = os.getenv('THING_KEY', default="") if (key == ""): print("THING_KEY is not set") sys.exit() url = 'https://api.thingspeak.com/update' print(url)
def __init__(self): # Initialize connection to peripheral self.bus = smbus.SMBus(1)
#!/usr/bin/env python import smbus import sys I2C_BUS = 1 install_mode = False if len(sys.argv) > 1: if "--install" in sys.argv: install_mode = True try: bus = smbus.SMBus(I2C_BUS) except IOError: print("Unable to access /dev/i2c-{}, please ensure i2c is enabled!".format(I2C_BUS)) sys.exit() def get_device(line): parts=[x.strip() for x in line.split(":")] return int(parts[0], 16), parts[1], parts[2], parts[3] devices = [get_device(line) for line in open("breakouts.config").read().strip().split("\n")] addresses = [device[0] for device in devices] def identify(find_i2c_addr): for i2c_addr, library, module, name in devices: if i2c_addr == find_i2c_addr: installed = True try:
def __init__(self, bus, addr=ADDR): self.addr = addr self.bus = smbus.SMBus(bus) self.banks = [GPIOA, GPIOB]
def __init__(self, addr, port=I2CBUS): self.addr = addr self.bus = smbus.SMBus(port)
#!/usr/bin/env python3 import smbus # install python3-smbus with apt import time i2c = smbus.SMBus(1) addr = 0x28 def read(reg): v = i2c.read_byte_data(addr, reg) return v def readw(reg): v = i2c.read_word_data(addr, reg) return v & 0x00ff, (v & 0xff00) >> 8 def write(reg, v): i2c.write_byte_data(addr, reg, v) def setup(): read(0x00) read(0x0a) read(0x01) read(0x40) read(0x41) read(0x48)
def __init__(self): self.bus = smbus.SMBus(1) self.device_address = 0x6c self.full_range = 1000.0 self.init_device()
import smbus import sys import getopt import time bus = smbus.SMBus(0) address = 0x20 # I2C address of MCP23017 bus.write_byte_data(0x20, 0x00, 0x00) # Set all of bank A to outputs bus.write_byte_data(0x20, 0x01, 0x00) # Set all of bank B to outputs def set_led(data, bank): if bank == 1: bus.write_byte_data(address, 0x12, data) else: bus.write_byte_data(address, 0x13, data) return # Handle the command line arguments def main(): a = 0 delay = 0.05 while True: # Move led left for x in range(0, 8): a = 1 << x
log_directory = parameters["log_directory"] if not os.path.isdir(log_directory): os.makedirs(log_directory) logging.basicConfig( level=log_level, format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s', datefmt="%d-%m-%Y %H:%M:%S", filename=log_directory + "/dump_spectra_" + datetime.datetime.now().strftime("%d%m%Y_%H%M%S") + ".log", filemode='w') logger = logging.getLogger("dump_spectra") i2c_bus = smbus.SMBus(1) rtc = ds3231.DS3231(i2c_bus, 0x68) snap_board = parameters["snap-board"] firmware = parameters["firmware"] synthesizer = parameters["synthesizer"] adcs = parameters["adcs"] pfb = parameters["pfb"] test_vector_generator = parameters["test-vector-generator"] xcorr = parameters["xcorr"] output_control = parameters["output-control"] packetiser = parameters["packetiser"] baseband = parameters["baseband"] mount_directory = parameters["mount_directory"] harddrives = parameters["hard-drives"] spectra = parameters["spectra"]
LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line LCD_BACKLIGHT = 0x08 # On #LCD_BACKLIGHT = 0x00 # Off ENABLE = 0b00000100 # Enable bit # Timing constants E_PULSE = 0.0005 E_DELAY = 0.0005 #Open I2C interface bus = smbus.SMBus(2) # Rev C Beaglebone Black uses 2 def lcd_init(): # Initialise display lcd_byte(0x33, LCD_CMD) # 110011 Initialise lcd_byte(0x32, LCD_CMD) # 110010 Initialise lcd_byte(0x06, LCD_CMD) # 000110 Cursor move direction lcd_byte(0x0C, LCD_CMD) # 001100 Display On,Cursor Off, Blink Off lcd_byte(0x28, LCD_CMD) # 101000 Data length, number of lines, font size lcd_byte(0x01, LCD_CMD) # 000001 Clear display time.sleep(E_DELAY) def lcd_byte(bits, mode): # Send byte to data pins
# ---------------------------------------------------------- # i2c bus interface # DS1621 register addresses stopConv = 0x22 accessTH = 0xa1 accessTL = 0xa2 readCount = 0xa8 readSlope = 0xa9 readTemp = 0xaa accessCfg = 0xac startConv = 0xee # enable interface in one-shot mode try: import smbus i2cBus = smbus.SMBus(bus=1) cfg = i2cBus.read_byte_data(ds1621Addr, accessCfg) if 0 == (cfg & 0x01): cfg |= 0x01 # set one-shot bit print('Writing config register: {0}'.format(hex(cfg))) i2cBus.write_byte_data(ds1621Addr, accessCfg, cfg) time.sleep(0.01) print('DS1621 intialized at addr: {0}'.format(hex(ds1621Addr))) except (IOError, OSError, ImportError) as e: i2cBus = None print('Failed to initialize hardware: {0}'.format(e)) print(' Running in simulation mode.') # function to read and report temperature
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import time from ctypes import * import smbus VL53L0X_GOOD_ACCURACY_MODE = 0 # Good Accuracy mode VL53L0X_BETTER_ACCURACY_MODE = 1 # Better Accuracy mode VL53L0X_BEST_ACCURACY_MODE = 2 # Best Accuracy mode VL53L0X_LONG_RANGE_MODE = 3 # Longe Range mode VL53L0X_HIGH_SPEED_MODE = 4 # High Speed mode i2cbus_zero = smbus.SMBus(0) i2cbus_one = smbus.SMBus(1) # i2c bus read callback def i2c_read(address, reg, data_p, length, bus_number): ret_val = 0 result = [] # print("Python i2c_read to bus ", bus_number) try: if (bus_number == 0): result = i2cbus_zero.read_i2c_block_data(address, reg, length) if (bus_number == 1): result = i2cbus_one.read_i2c_block_data(address, reg, length) except IOError:
LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line LCD_BACKLIGHT = 0x08 # On #LCD_BACKLIGHT = 0x00 # Off ENABLE = 0b00000100 # Enable bit # Timing constants E_PULSE = 0.0005 E_DELAY = 0.0005 #Open I2C interface bus = smbus.SMBus(0) # Rev 1 Pi uses 0 #bus = smbus.SMBus(1) # Rev 2 Pi uses 1 def get_ip_address(): ip_address = '' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] s.close() return ip_address def lcd_init(): # Initialise display lcd_byte(0x33, LCD_CMD) # 110011 Initialise
# the integer division and input() # mind your parentheses! import smbus import time import math import RPi.GPIO as GPIO import struct import operator import pickle debug = 0 rev = GPIO.RPI_REVISION if rev == 2 or rev == 3: bus = smbus.SMBus(1) else: bus = smbus.SMBus(0) # I2C Address of Arduino address = 0x06 # Command Format # analogRead() command format header aRead_cmd = [3] # This allows us to be more specific about which commands contain unused bytes unused = 0 #Add a multipler to each sensor multp = [-10, -5, 0, 5, 10]
def __init__(self, address, bus=1): self.address = address self.bus = smbus.SMBus(bus) # Wake up the MPU-6050 since it starts in sleep mode self.bus.write_byte_data(self.address, self.PWR_MGMT_1, 0x00)
def __init__(self, address, bus=1): self.address = address self.bus = smbus.SMBus(bus)
def read_raw_data(addr): #Accelero and Gyro value are 16-bit high = bus.read_byte_data(DeviceAddress, addr) low = bus.read_byte_data(DeviceAddress, addr+1) #concatenate higher and lower value value = ((high << 8) | low) #to get signed value from mpu6050 if(value > 32768): value = value - 65536 return value bus = smbus.SMBus(1) # or bus = smbus.SMBus(0) for older version boards DeviceAddress = 0x68 # MPU6050 device address MPU_Init() time.sleep(1) #Read Accelerometer raw value accX = read_raw_data(ACCEL_XOUT_H) accY = read_raw_data(ACCEL_YOUT_H) accZ = read_raw_data(ACCEL_ZOUT_H) #print(accX,accY,accZ) #print(math.sqrt((accY**2)+(accZ**2))) def init(): if (RestrictPitch): roll = math.atan2(accY,accZ) * radToDeg
LCD_CHR = 1 # sending data LCD_CMD = 0 # sending command LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line LCD_BACKLIGHT = 0x08 # On ENABLE = 0b00000100 # Enable bit E_PULSE = 0.0005 E_DELAY = 0.0005 bus = smbus.SMBus(1) # Rev 2 Pi uses 1 def lcd_init(): # Initialise display lcd_byte(0x33, LCD_CMD) # 110011 Initialise lcd_byte(0x32, LCD_CMD) # 110010 Initialise lcd_byte(0x06, LCD_CMD) # 000110 Cursor move direction lcd_byte(0x0C, LCD_CMD) # 001100 Display On,Cursor Off, Blink Off lcd_byte(0x28, LCD_CMD) # 101000 Data length, number of lines, font size lcd_byte(0x01, LCD_CMD) # 000001 Clear display time.sleep(E_DELAY) def lcd_byte(bits, mode): # Send byte to data pins
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import time from ctypes import * import smbus VL53L0X_GOOD_ACCURACY_MODE = 0 # Good Accuracy mode VL53L0X_BETTER_ACCURACY_MODE = 1 # Better Accuracy mode VL53L0X_BEST_ACCURACY_MODE = 2 # Best Accuracy mode VL53L0X_LONG_RANGE_MODE = 3 # Longe Range mode VL53L0X_HIGH_SPEED_MODE = 4 # High Speed mode i2cbus = smbus.SMBus(1) # i2c bus read callback def i2c_read(address, reg, data_p, length): ret_val = 0 result = [] try: result = i2cbus.read_i2c_block_data(address, reg, length) except IOError: ret_val = -1 if (ret_val == 0): for index in range(length): data_p[index] = result[index]
def __init__(self): self.bus = smbus.SMBus(1)