def __init__(self, bus=0, device=0, dc_pin="P9_15", reset_pin="P9_13", buffer_rows=128, buffer_cols=128, rows=128, cols=128): self.cols = cols self.rows = rows self.buffer_rows = buffer_rows self.mem_bytes = self.buffer_rows * self.cols / 8 # total bytes in SSD1306 display ram self.dc_pin = dc_pin self.reset_pin = reset_pin self.spi = SPI.SPI(bus, device) self.spi.mode = 3 # necessary! self.gpio = GPIO self.gpio.setup(self.reset_pin, self.gpio.OUT) self.gpio.output(self.reset_pin, self.gpio.HIGH) self.gpio.setup(self.dc_pin, self.gpio.OUT) self.gpio.output(self.dc_pin, self.gpio.LOW) self.font = font5x8.Font5x8 self.col_offset = 0 self.bitmap = self.SimpleBitmap(buffer_cols, buffer_rows) self.flipped = False
def __init__(self, dev=0, spi_clk_freq=10000000): GPIO.setup("P9_12", GPIO.OUT) #enable pin for 2.5V bus drivers GPIO.output("P9_12", GPIO.LOW) #enable for 2.5V bus drivers self.spi0 = SPI.SPI(dev, 0) #setup SPI0 self.spi0.mode = 0 try: self.spi0.msh = spi_clk_freq except IOError: pass #hardware does not support this speed..
def __init__(self, spi_clk_freq=10000000, dualBoard=False): if not os.path.isfile('/sys/class/gpio/gpio60/value'): GPIO.setup("P9_12", GPIO.OUT) #enable pin for 2.5V bus drivers GPIO.output("P9_12", GPIO.LOW) #enable for 2.5V bus drivers self.BUS_MASTER = 0 self.BUS_SLAVE = 1 self.spi={} self.spi[0]=SPI.SPI(self.BUS_MASTER,0) #setup SPI0 self.spi[0].mode = 0 self.spi[1]=SPI.SPI(self.BUS_SLAVE,0) self.spi[1].mode = 0 self.dualBoard = dualBoard try: self.spi[0].msh = spi_clk_freq self.spi[1].msh = spi_clk_freq except IOError: pass #hardware does not support this speed.. self.current_buffer = 0 self.current_trigger= 0
def __init__(self, input=0): if (input == 0): self.spi = SPI.SPI(1, 1) self.v_led_sense = V_LED_0_SENSE self.v_batt_sense = V_BATT_0_SENSE self.led_enable = DUT_0_LED_ENABLE self.reset = DUT_0_RESET self.radio_ce = DUT_0_RADIO_CE self.radio_csn = DUT_0_RADIO_CSN # TODO: Handle me externally GPIO.setup(self.reset, GPIO.IN) self.spi.mode = 0 self.spi.msh = 10000
def __init__(self, spi_clk_freq=10000000): if not os.path.isfile('/sys/class/gpio/gpio61/value'): GPIO.setup("P8_26", GPIO.OUT) #enable pin for 2.5V bus drivers GPIO.output("P8_26", GPIO.LOW) #enable for 2.5V bus drivers self.BUS_FLOWER = 1 self.DEV_FLOWER = 0 #these are confusing definitions, sorry to future self (BUS=BBB spi bus; DEV=enumeration) self.spi = {} self.spi[0] = SPI.SPI(self.BUS_FLOWER, 0) self.spi[0].mode = 0 try: self.spi[0].msh = spi_clk_freq except IOError: pass #hardware does not support this speed.. self.current_buffer = 0 self.current_trigger = 0
def __init__(self, deviceType, spiBus, resetPin): self.reset = resetPin GPIO.setup(self.reset, GPIO.IN) self.spi = SPI.SPI(spiBus, 1) self.spi.open(1, 1) self.spi.mode = 0 self.spi.msh = 100000 if(deviceType == 'ATTINY25'): self.signature = ATTINY25_SIGNATURE self.pageSize = ATTINY25_PAGE_SIZE elif(deviceType == 'ATTINY45'): self.signature = ATTINY45_SIGNATURE self.pageSize = ATTINY45_PAGE_SIZE else: print("Unsupported device type!")
def spi(self): spi = SPI(1, 0) spi.mode = self.mode spi.cshigh = False spi.msh = 1000000 spi.bpw = 8 spi.lsbfirst = False spi.open(1, 0) # set cycle counts spi.writebytes([0x04, 0x03, 0x20, 0x03, 0x20, 0x03, 0x20]) # 800 cycle counts time.sleep(.01) resolution = 3.3 # nT/LSB; corresponding to 800 cycle counts # set sampling rate, in hertz rate = 32 # display device settings cycleX = spi.xfer2([0x84, 0x00, 0x00]) cycleY = spi.xfer2([0x86, 0x00, 0x00]) cycleZ = spi.xfer2([0x88, 0x00, 0x00]) sensor_settings1 = 'Cycle count [x, y, z]: [' + str( int(hex(cycleX[1]) + hex(cycleX[2])[2:], 16)) + ', ' + str( int(hex(cycleY[1]) + hex(cycleY[2])[2:], 16)) + ', ' + str( int(hex(cycleZ[1]) + hex(cycleZ[2])[2:], 16)) + ']' sensor_settings2 = 'Measurement rate: ' + str(rate) + ' Hz' print(sensor_settings1) print(sensor_settings2) # list of timestamps for each measurement read timestamp = [] # list to store raw data raw = [] # set the total measuring time, in seconds run_time = 30 print('Total measuring time: ' + str(run_time) + ' seconds') t_end = time.time() + run_time # main loop trigger = time.time() while time.time() < t_end: timestamp.append(time.time()) target = (len(raw) + 1) * (1 / rate) + trigger # initiate single measurement spi.writebytes([0x00, 0x70]) condition = True # loop to keep checking until measurement is completed while condition: # if DRDY is high (measurement is completed) if format(spi.xfer2([0xB4, 0x00])[1], '#010b')[2] == '1': # read measurement results raw.append( spi.xfer2([ 0xA4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ])) condition = False # if there is time remaining before next measurement if time.time() < target: # wait until appropriate time time.sleep(target - time.time()) else: print('Timing error.') return spi.close() magX = [] magY = [] magZ = [] magn = [] for i in range(len(raw)): results = [] for j in range(0, 9, 3): data = float( self.recast24to32(raw[i][j + 1], raw[i][j + 2], raw[i][j + 3])) * resolution status = float results.append(data) magX.append(results[0]) magY.append(results[1]) magZ.append(results[2]) magn.append(np.sqrt(results[0]**2 + results[1]**2 + results[2]**2)) start_time = timestamp[0] time_diff = [0] for k in range(len(timestamp)): timestamp[k] = timestamp[k] - start_time if k > 0: time_diff.append(timestamp[k] - timestamp[k - 1]) mag_data = np.transpose( np.array([magX, magY, magZ, magn, timestamp, time_diff])) np.savetxt('mag_data_short_32Hz.txt', mag_data, header=sensor_settings1 + ' ; ' + sensor_settings2) print('Successful measurement.') return
MPUREG_WHOAMI = 0x75 MPUREG_INT_STATUS = 0x3A #Other constants K_ADC = 1.80 * 10.65 THRESHOLD_BATT_NOLOAD = 11.1 #for 3cell, default is 11.1 THRESHOLD_BATT_LOSS = 0.4 #Line loss voltage. See DJI NAZA Manual. You need change battery if this value is 0.3 per cell #true value is 0.5 THRESHOLD_BATT = THRESHOLD_BATT_NOLOAD - THRESHOLD_BATT_LOSS THRESHOLD_BATT_WARNING_OFFSET = 0.5 # Warning Offset THRESHOLD_BATT_WARNING = THRESHOLD_BATT + THRESHOLD_BATT_WARNING_OFFSET PWM_FREQUENCY = 200 # = 1000 BLYNK_AUTH = '7ee767c8cf2b42c19ee9c1e3f48028a9' #hadler spi = SPI.SPI(1, 0) calc = cpphelper_calc.CalcHelper() blynk = blynklib.Blynk(BLYNK_AUTH) ### Varients #global varient target_ypr = np.asarray([0, 0, 0], dtype=np.float32) throttle = 0.0 flag_main = True #flag_controler = True flag_led_set = 0 flag_start = 0 flag_entry = 0 words_entry = '' #thread hadler t_batt = None
#!/usr/bin/python3 ## Перед первым запуском необходимо запустить SPI_init.py import time import Adafruit_BBIO.SPI as SPI # Библиотека для работы с SPI на BeagleBone Black # Настройка SPI spi = SPI.SPI( 1, 0) # Используем SPI 1 (он же SPI 0, нумерация с 1), cheap select 0 spi.msh = 16000000 # частота SPI spi.mode = 0 # По-умолчанию: 1 try: while True: time.sleep(1) # Задержка в 1 секунду freq = spi.readbytes(4) # Чтение 4 байт 32-битного значения частоты print( 'freq =', freq[0] + freq[1] * (2**8) + freq[2] * (2**16) + freq[3] * (2**24), '\n') except KeyboardInterrupt: #отработка прерывания программы при помощи CTRL+C spi.close print(' Programm finished')
def simar(): """ Simar """ logger.info("SIMAR") simar = Simar_addr() if simar.identified: boards = [] spi = SPI.SPI(0, 0) spi.bpw = 8 spi.lsbfirst = False spi.cshigh = False spi.mode = 3 spi.msh = 1000000 for board_addr in range(0, 16): parity = False for char in '{0:04b}'.format(board_addr): if char == "1": parity = not parity GPIO.output(PIN_SIMAR_DS, GPIO.LOW) spi.writebytes([(board_addr << 3) + (1 if parity else 0)]) GPIO.output(PIN_SIMAR_DS, GPIO.HIGH) rec = 0 info = "" address = 0 while rec != 125: while (spi.xfer2([5, 0])[1] == 1): pass rec = spi.xfer2([3, address // 256, address % 256, 0])[3] if (rec == 0 or rec == 255): break info += chr(rec) address += 1 if info: boards.append({**json.loads(info), **{"address": board_addr}}) sensor_type = {0x58: "BMP280", 0x60: "BME280"} sensors = [] GPIO.setup(PIN_SIMAR_LSB, GPIO.OUT) GPIO.setup(PIN_SIMAR_MSB, GPIO.OUT) for i in range(0, 4): GPIO.output(PIN_SIMAR_LSB, GPIO.HIGH if (i >> 1) & 1 else GPIO.LOW) GPIO.output(PIN_SIMAR_MSB, GPIO.HIGH if (i >> 0) & 1 else GPIO.LOW) for addr in ["0x76", "0x77"]: try: # Using check_output for backwards compatibility sensor_reply = int( subprocess.check_output( ["i2cget", "-y", "2", addr, "0xD0"]), 16) if sensor_reply: sensors.append("{} - Ch. {} ({})".format( sensor_type[sensor_reply], i, addr)) except (subprocess.CalledProcessError, KeyError, ValueError, TypeError): pass key_list = list(Device_Type.keys()) val_list = list(Device_Type.values()) file = open(RES_FILE, "w+") file.writelines("SIMAR") file.close() file = open(DEVICE_JSON, "w+") file.writelines( json.dumps( { "name": "SIMAR", "device": key_list[val_list.index("SIMAR")], "sensors": sensors, "details": "SIMAR - Connected: [{}]".format(simar.addr()), "baudrate": 0, "boards": boards, "time": str(datetime.now()) }) + "\n") file.close() exit(0)
def __init__(self, length, iface_addr=(0,1), background=[0,0,0]): self.background = background #[background[i] + 128 for i in background] self.interface = SPI.SPI(*iface_addr) self.length = length self.slow_clear_gradient = None
def __init__(self, length, iface_addr=(0,1), default_background=(0,0,0)): self.background = default_background self.interface = SPI.SPI(*iface_addr) self.length = length
writedata(0x00) writedata(x0 + 2) writedata(0x00) writedata(x1 + 2) writecomm(ST7735_RASET) writedata(0x00) writedata(y0 + 1) writedata(0x00) writedata(y1 + 1) writecomm(ST7735_RAMWR) def drawPixel(x, y, color): if ((x < 0) or (x >= ST7735_TFTWIDTH) or (y < 0) or (y >= ST7735_TFTHEIGHT)): return setAddrWindow(x, y, x + 1, y + 1) writedata(color >> 8) writedata(color) spi = SPI(0, 1) #spi.bpw(8) spi.open(0, 1) st_init() drawPixel(0x23, 0x23, 0x0000) drawPixel(0x24, 0x24, 0x0000)
import time debug_mode = False status = ['OK'] if not debug_mode: import Adafruit_BBIO.SPI as SPI # Библиотеку Adafruit_BBIO надо будет ещё # скачать через pip # Настроим наш SPI if not debug_mode: spi = SPI.SPI(1,0) # Используем SPI 1 (он же SPI 0, нумерация с 1) spi.msh = 1000000 # По-умолчанию тут 16 000 000 spi.mode = int('11', 2) spi.cshigh = False set_adr = 0 # Команда на считывание адреса set_write = int('01000000',2) # Запись в регистр set_inc_write = int('01100000',2) # Запись с инкрементом адреса регистра first_adr = 0 # Самый первый номер регистра #_______________________________________ Functions-helpers def is_integer(n): try: int(n) return True
#Encoder test import Adafruit_BBIO.SPI as SPI spi = SPI(0,0) spi.open() while True: print spi.readbytes(1)
def spi(self): spi = SPI(1, 0) spi.mode = self.mode spi.cshigh = False spi.msh = 1000000 spi.bpw = 8 spi.lsbfirst = False spi.open(1, 0) # set cycle counts spi.writebytes([0x04, 0x03, 0xE8, 0x03, 0xE8, 0x03, 0xE8]) # 1000 cycle counts time.sleep(.01) # set continuous measurement mode spi.writebytes([0x01, 0x79]) time.sleep(.01) # set measurement rate spi.writebytes([0x0B, 0x95]) time.sleep(.01) resolution = 2.7 # nT/LSB; corresponding to 800 cycle counts # display device settings cycleX = spi.xfer2([0x84, 0x00, 0x00]) cycleY = spi.xfer2([0x86, 0x00, 0x00]) cycleZ = spi.xfer2([0x88, 0x00, 0x00]) sensor_settings1 = 'Cycle count [x, y, z]: [' + str( int(hex(cycleX[1]) + hex(cycleX[2])[2:], 16)) + ', ' + str( int(hex(cycleY[1]) + hex(cycleY[2])[2:], 16)) + ', ' + str( int(hex(cycleZ[1]) + hex(cycleZ[2])[2:], 16)) + ']' sensor_settings2 = 'Measurement rate: ' + hex( spi.xfer2([0x8B, 0x00])[1]) print(sensor_settings1) print(sensor_settings2) # list of timestamps for each measurement read timestamp = [] # list to check for rate errors: use this list to display an error if there are consecutive measurements where DRDY (status) is high. error_check = [] # list to store the time values corresponding to each error error_log = [] # list to store export data mag_data = [] # set the total measuring time, in seconds run_time = 10 print('Total measuring time: ' + str(run_time) + ' seconds') t_end = time.time() + run_time # Main loop while time.time() < t_end: # if the DRDY (status) pin is high if format(spi.xfer2([0xB4, 0x00])[1], '#010b')[2] == '1': # append appropriate values to lists timestamp.append(time.time()) error_check.append(1) # read measurement results raw = spi.xfer2([ 0xA4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]) results = [] for i in range(0, 9, 3): data = float( self.recast24to32(raw[i + 1], raw[i + 2], raw[i + 3])) * resolution status = float results.append(data) magXYZ = results magn = np.sqrt(magXYZ[0]**2 + magXYZ[1]**2 + magXYZ[2]**2) # if mag_data already contains some data if len(mag_data) > 0: # if DRDY was high two times in a row if error_check[-2] == 1: # store and display the error error_log.append(timestamp[-1] - timestamp[0]) print('Error at t = ' + str(error_log[-1]) + ': Consecutive iterations with DRDY high.') # append results to mag_data mag_data = np.vstack( (mag_data, np.array([ magXYZ[0], magXYZ[1], magXYZ[2], magn, timestamp[-1] - timestamp[0], timestamp[-1] - timestamp[-2] ]))) # if mag_data contains nothing else: # create first line in mag_data mag_data = np.array( [magXYZ[0], magXYZ[1], magXYZ[2], magn, 0, 0]) # if the DRDY pin was NOT high else: # store appropriate value in error_check error_check.append(0) spi.close() # if mag_data is empty, display error if len(mag_data) == 0: print('Error: DRDY never went high.') return # save data as txt file np.savetxt('mag_data_short.txt', mag_data, header=sensor_settings1 + ' ; ' + sensor_settings2, comments='') # if there was a rate error -> save an additional txt file containing the corresponding time values if len(error_log) > 0: error_log = np.array(error_log) np.savetxt( 'error_log_short.txt', error_log, header= 'Time values for which DRDY was high for consecutive measurements' ) print('Successful measurement, with DRDY errors.') return print('Successful measurement.') return