def main(): max7219 = spi.SPI(clk=SPI_CLK, cs=SPI_CS, mosi=SPI_MOSI, miso=None, verbose=True) ### Disable code B decode mode on all digits max7219.put(int("100100000000", 2), 16) ### Set intensity low max7219.put(int("101000000000", 2), 16) ### Enable all digits in scan-limit register max7219.put(int("101100000111", 2), 16) ### Disable test mode max7219.put(int("111100000000", 2), 16) ### Disable shutdown mode max7219.put(int("110000000001", 2), 16) # run_demo(max7219) # run_coordinate_setter(max7219) run_pulse(max7219, delay=0.1, max_intensity=6) ### Enable shutdown mode max7219.put(int("110000000000", 2), 16)
def setup(self): SP.call(['modprobe', '-r', self.spi_module]) SP.call(['modprobe', self.spi_module]) self.spi = SPI.SPI('/dev/spidev0.0') self.spi.mode = SPI.SPI.MODE_0 self.spi.bits_per_word = 8 self.spi.speed = 100000000
def test_gamma_out(): SPI = spi.SPI() rainfall_data = np.genfromtxt('data/rainfall_test2.csv', delimiter=',') SPI.set_rolling_window_params(span=10, window_type='boxcar', center=False) SPI.set_distribution_params(dist_type='gam') result = SPI.calculate(rainfall_data, starting_month=1) assert np.round(result[-1][0], 4) == np.round(-0.09562831, 4)
def __init__(self, dna=None, ip=None): UDPFPGA.__init__(self) if ip != None: UDPFPGA.assign_ip(self, dna, ip) elif UDPFPGA.connect(self, dna): print "Connected to device %x" % self.target_dna self.resetI2C() self.spi = spi.SPI(spi.AXIQuadSPI(self, 0x3000, 0))
def __init__(self): self.max7219 = spi.SPI(clk=11, cs=8, mosi=10, miso=None) self.buffer = [] for m in range(self.TOTAL_MATRICES): one_matrix_buffer = [] for c in range(self.FIELD_SIZE): one_matrix_buffer.append([False] * self.FIELD_SIZE) self.buffer.append(one_matrix_buffer) self.reset() self.init()
def __init__(self, dimensions=(12, 10), gamma=2.2, devname='/dev/spidev0.0'): """ Initialise a SPIScreen object. >>> screen = SPIScreen() """ import spi ledscreen.LedScreen.__init__(self, dimension=dimensions, gamma=gamma) self.spi = spi.SPI(devname, 0, 1000000)
def __init__(self, dev='/dev/spidev0.0', spd=1000000): self.spi_handle = spi.SPI(device=dev, speed=spd) self.MFRC522_Reset() self.Write_MFRC522(self.TModeReg, 0x8D) self.Write_MFRC522(self.TPrescalerReg, 0x3E) self.Write_MFRC522(self.TReloadRegL, 30) self.Write_MFRC522(self.TReloadRegH, 0) self.Write_MFRC522(self.TxAutoReg, 0x40) self.Write_MFRC522(self.ModeReg, 0x3D) self.AntennaOn()
def start(self): self.modeList = [] pkg = 'modes' __import__(pkg) package = sys.modules[pkg] prefix = pkg + "." for importer,modname,ispkg in pkgutil.iter_modules(package.__path__,prefix): module = __import__(modname,locals(),[],-1) for name,cls in inspect.getmembers(module): if inspect.isclass(cls): self.modeList.append(cls()) self.modeIndex = 0 self.mode = self.modeList[self.modeIndex] self.delayTimer = None self.speed = 0 reactor.callInThread(self.run) self.isRunning = True if socket.gethostname() == "blitterbike": import spi self.spi_conn = spi.SPI(2, 0) self.spi_conn.msh = 1000000 self.blit = self.blitScreen open('/sys/kernel/debug/omap_mux/lcd_data0', 'wb').write("%X" % 39) try: # check to see if the pin is already exported open('/sys/class/gpio/gpio70/direction').read() except: open('/sys/class/gpio/export', 'w').write('70') # set Port 8 Pin 3 for output open('/sys/class/gpio/gpio70/direction', 'w').write('in') self.speed = Value("f", 0.0) self.sensor = Process(target=self.readSensor, args=(self.speed,)) self.sensor.start() self.isBlitterBike = True self.clear() else: self.isBlitterBike = False; self.onChangeMode()
def execute(vdd, num_channels, order='down'): """ Cycle digipot output and take measurements off of ADC channels. Returns a list of tuples; one list element per digipot value, and each tuple contains the outputs of all measured ADC channels. """ ### use two independent SPI buses, but daisy chaining then is also valid adc = spi.SPI(clk=18, cs=25, mosi=24, miso=23, verbose=False) digipot = spi.SPI(clk=19, cs=13, mosi=26, miso=None, verbose=False) results = [] ### order refers to the voltage, which is the inverse of the resistance if order == 'down': indices = range(2**8) elif order == 'up': indices = range(2**8 - 1, 0, -1) elif order == 'downup': indices = range(2**8) + range(2**8 - 1, 0, -1) elif order == 'updown': indices = range(2**8 - 1, 0, -1) + range(2**8) else: raise Exception("order must be one of: up down downup updown") ### iterate over all possible resistance values for resist_val in indices: ### set resistance on digipot set_digipot(digipot, resist_val) ### wait to allow voltage transients to subside time.sleep(0.01) ### get the voltage from the MCP3008 ############################### adc_values = get_adc(adc)[0:num_channels] results.append(tuple([x * vdd for x in adc_values])) return results
def set_get_digipot(): parser = argparse.ArgumentParser() parser.add_argument('--vdd', type=float, default=5.0, help="VDD voltage (default=5.0)") parser.add_argument("value", nargs="?", default=None, type=int, help="value to set digipot (0-1023)") args = parser.parse_args() adc = spi.SPI(clk=18, cs=25, mosi=24, miso=23, verbose=False) digipot = spi.SPI(clk=19, cs=13, mosi=26, miso=None, verbose=False) if args.value is not None: experiment.set_digipot(digipot, args.value) time.sleep(0.01) print "Digipot set to %d Ohms" % (10000.0 * args.value / 1023.0) values = experiment.get_adc(adc) for channel, value in enumerate(values): print "Channel %d: %.2f" % (channel, value * args.vdd)
def vspi(pinnum_dc=None, pinnum_rst=None, pinnum_cs=None): sck_hz = 6 * 1000 * 1000 # 6MHz if pinnum_dc is None: pinnum_dc = config.pin_dc if pinnum_rst is None: pinnum_rst = config.pin_rst if pinnum_cs is None: pinnum_cs = config.pin_cs vspi = spi.SPI(spi.ID_VSPI, polarity=1, phase=1, bits=8, baudrate=sck_hz) disp = SSD1331( spi=vspi, pinnum_cs=pinnum_cs, # Chip Select pinnum_dc=pinnum_dc, # Data/Command pinnum_rst=pinnum_rst) # Reset disp.init() return disp
def __init__(self, i2c, displayType, flipDisplay): self._width = 128 self._height = 64 self._i2c = i2c self._flipDisplay = flipDisplay self._displayType = displayType self._pages = self._height // 8 self._image = [0] * (self._width * self._height) self.bus = None if self._displayType != "128x64-ssd1309 spi": try: self.bus = SMBus(BUSNUMBER) except IOError: xbmcgui.Dialog().notification( "OLED IO Error", "Please check your I2C address and controller type.", xbmcgui.NOTIFICATION_ERROR, 5000) else: self.spi = spi.SPI("/dev/spidev32766.0") self.spi.mode = spi.SPI.MODE_0 self.spi.bits_per_word = 8 self.spi.speed = 5000000 gpio.initGPIO() gpio.gpioWriteDC(0) gpio.gpioDoReset() if self._displayType == "128x64-sh1106": self.displayHeight32 = False self._initSH1106() self.display = self._displaySH1106 elif self._displayType == "128x64-ssd1306": self.displayHeight32 = False self._initSSD1306_64() self.display = self._displaySSD1306 elif self._displayType == "128x32-ssd1306": self.displayHeight32 = True self._initSSD1306_32() self.display = self._displaySSD1306 elif self._displayType == "128x64-ssd1309 spi": self.displayHeight32 = False self._initSSD1309SPI() self.display = self._displaySSD1309SPI self.clear() self.display()
def run(self): # set things up so we can cleanup on stop atexit.register(self.cleanup) signal(SIGTERM, lambda signum, stack_frame: sys.exit(1)) self.spi_conn = spi.SPI(2, 0) self.spi_conn.msh = 8000000 # wake up the screen writeToStrip(LATCH) fill(0) im = Image.open("gifs/load.gif") # open the socket server # self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # self.sock.bind((HOST, PORT)) # self.sock.listen(1) # self.conn, self.addr = self.sock.accept() last_time = time.time() self.index = 0 # setup the main input loop while True: self.draw() # data = self.conn.recv(1) # if data: # self.conn.sendall(data) new_time = time.time() # see how many milliseconds we have to sleep for # then divide by 1000.0 since time.sleep() uses seconds sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0 if sleep_time > 0: time.sleep(sleep_time) last_time = new_time
import time import spi if __name__ == '__main__': register = spi.SPI(clk=22, cs=27, mosi=17, miso=None, verbose=True) for i in range(16): register.put((i + 1) << 8, 12) ### Set the scan limit register and disable shutdown mode register.put(int("101100000111", 2), 12) register.put(int("110000000001", 2), 12) # register.put(int('010011100111', 2), 12) heart = [ '00000000', '01100110', '11111111', '11111111', '01111110', '00111100', '00011000', '00000000', ] for i in range(8): loc = (i + 1) << 8 register.put(loc + int(heart[i], 2), 12)
#!/usr/bin/env python """ Set a resistance on MCP41010 (digital potentiometer), then measure the effect using MCP3008 (analog-digital converter). """ import spi import time ### use two independent SPI buses, but daisy chaining then is also valid adc = spi.SPI(clk=18, cs=25, mosi=24, miso=23, verbose=False) digipot = spi.SPI(clk=19, cs=13, mosi=26, miso=None, verbose=False) ### iterate over all possible resistance values (8 bits = 256 values) for resist_val in range(256): ### set the resistance on the MCP41010 ############################# cmd = int("00010001", 2) # make room for resist_val's 8 bits cmd <<= 8 digipot.put(cmd | resist_val, bits=16) ### wait to allow voltage transients to subside time.sleep(0.2) ### get the voltage from the MCP3008 ############################### voltages = [0, 0, 0] for channel in range(len(voltages)): # set the start bit, single-ended mode bit, and 3 channel select bits cmd = int("11000", 2) | channel # read 1 null bit, then 10 data bits cmd <<= 10 + 1
def read_data(self): v = self.read(_REG_DATAX0, 6) return (_int16((v[1] << 8) | v[0]), _int16((v[3] << 8) | v[2]), _int16((v[5] << 8) | v[4])) def read_fifo_ctl(self): v = self.read(_REG_FIFO_CTL) return self.FIFO_CTL((0xC0 & v) >> 6, (0x20 & v) >> 5, (0x1F & v) >> 0) def write_fifo_ctl(self, fifo_mode=0, trigger=0, samples=0): self._mv[0] = ((fifo_mode << 6) | (trigger << 5) | (samples << 0)) self.write(_REG_FIFO_CTL, self._mv[:1]) def read_fifo_status(self): v = self.read(_REG_FIFO_STATUS) return self.FIFO_STATUS((0x80 & v) >> 7, (0x2f & v) >> 0) import spi vspi = spi.SPI(spi.ID_VSPI, polarity=1, phase=1, bits=8, baudrate=6*1000*1000) ad = ADXL345(vspi, 32) ad.write_power_ctl()
def get_spi_handler(): return spi.SPI(0, 0) # spi.SPI(X,Y) is /dev/spidevX.Y
# this script was used with an AVR8 testboard which sent back # the written value plus one, just to test the SPI interface # so a write () of [0,0,1,2,3,0,0] would result in a read () # of [X,1,1,2,3,4,1] import spi from time import sleep a = spi.SPI(0, 1) print "PY: initialising SPI mode, speed, delay" a.mode = 3 a.msh = 2000000 # 2 MHz are okay for my setup # 4 MHz are definitly to much delay = 5000 i = 0 while (i < 16): print "tx:", i a.write([i]) print "rx:", a.read(1) sleep(0.2) i += 1 sleep(2) i = 0 while (i < 16): liste = [i, i, i, i, i, i, i] print "tx:", liste print "rx:", a.msg(liste, delay)
#!/usr/bin/python # -*- coding: utf-8 -*- # http://elecrow.com/ # original author: https://github.com/glennklockwood/raspberrypi import random import time import spi import numpy as np ### Initialize an SPI connection using BCM-mode pins 21, 20, and 16 max7219 = spi.SPI(clk=21, cs=20, mosi=16, miso=None) ### Zero out all registers for cmd in range(16): packet = cmd << 8 max7219.put(packet, 12) ### Enable all columns via the scan limit register max7219.put(int("101100000111", 2), 12) ### Disable shutdown mode max7219.put(int("110000000001", 2), 12) ### Define the values for each column that gives us a heart shape heart_shape = np.array([ [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0],
#!/usr/bin/env python from dropbox import client, rest, session import RPi.GPIO as GPIO, feedparser, time import datetime import sys, os import subprocess import spi now1 = datetime.datetime.now() fo = open(now1.strftime("%Y%m%d_%H%M%S"), "wb") a = spi.SPI(0,0) voltage = [0]*12 print "PY: Starting Program" runCount = raw_input("Enter the number of iterations: ") runCount = int(runCount) speed1 = raw_input("Enter the delay between readings (in seconds): ") speed = int(speed1) details = raw_input("Enter test description: ") fo.write("User Details:\n") fo.write(details) fo.write("\n") fo.write("Delay between readings: ") fo.write(speed1) fo.write(" seconds") fo.write("\n") fo.write("\n")
#!/usr/bin/env python """Change the state of a single LED in an 8x8 matrix. """ import spi ### Initialize an SPI connection using BCM-mode pins 21, 20, and 16 max7219 = spi.SPI(clk=21, cs=20, mosi=16, miso=None, verbose=True) ### Zero out all registers for cmd in range(16): packet = cmd << 8 max7219.put(packet,12) ### Set the scan limit register and disable shutdown mode max7219.put(int("101100000111",2),12) max7219.put(int("110000000001",2),12) ### We zeroed out all registers, so all LEDs are off (0) led_state = [0]*64 def set_led(row, column, state): ### update our saved state led_state[column*8 + row] = state ### convert the new column into an SPI command register = (column+1) << 8 value = 0 for row in range(8): value <<= 1 if led_state[column*8+row]:
#Python example for SPI bus, written by Brian Hensley #This script will take any amount of Hex values and determine #the length and then transfer the data as a string to the "spi" module import spi from time import sleep #At the beginning of the program open up the SPI port. #this is port /dev/spidevX.Y #Being called as as spi.SPI(X,Y) a = spi.SPI(2, 0) a.msh = 8000 print "PY: initialising SPI mode, reading data, reading length . . . \n" #This is my data that I want sent through my SPI bus latch = [0, 0, 0] data = [255, 128, 128, 128, 255, 128, 128, 128, 255, 255, 255, 255] #transfers data string a.writebytes(latch) for i in range(9): a.writebytes(data) a.writebytes(latch) #At the end of your program close the SPI port #a.close()
def __init__(self, crystal=50e6, reset=True): self.crystal = crystal self.spi = spi.SPI('/dev/spidev32766.0', 0, 1000000) atexit.register(self.cleanup) if reset: self.reset()
# 59 PB27 27 # N.C. 29 # N.C. 31 # 3.3V 33 # 3.3V 35 orgval = 0 orgpin = gpio.GPIO(59, "out") # set to 8bit mode orgpin.value = orgval time.sleep(1) mcp93lc46 = spi.SPI(1,1) # to protect against unwanted writes, the EEPROM uses CS active high mcp93lc46.cshigh = True mcp93lc46.mode = 0 mcp93lc46.msh = 500000 # read some addresses addresses = [0x0, 0x0, 0x1,0x5,0x11, 0x15, 0xF, 0x70, 0x0] for address in addresses: print "read from", address, bin(address) print mcp93lc46_read(mcp93lc46, orgval, address) print "" # mcp93lc46.cshigh = True time.sleep(0.1)
# Requires python-spi module available at https://github.com/beli-sk/python-spi # import spi import time import struct import RPi.GPIO as GPIO SS_PIN = 25 # GPIO init GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(SS_PIN, GPIO.OUT, initial=GPIO.HIGH) # SPI init spicon = spi.SPI("/dev/spidev0.0") spicon.set_speed(10000) spicon.set_mode(spi.SPI_MODE_2) # pull SS low to start ADC and wait GPIO.output(SS_PIN, GPIO.LOW) time.sleep(0.1) # receive data send = struct.pack(">H", 0) recv = spicon.transfer(send) Vraw = struct.unpack(">H", recv)[0] # put SS high again GPIO.output(SS_PIN, GPIO.HIGH)
#!/bin/python2 import spi as spidev import RPi.GPIO as gpio channel = 40 CE = 15 gpio.setmode(gpio.BOARD) gpio.setup(CE, gpio.OUT, initial=gpio.LOW) spi = spidev.SPI("/dev/spidev0.0") spi.mode = spidev.SPI.MODE_0 spi.bits_per_word = 8 spi.speed = 80000 def write_register(address, value): spi.transfer([0x20 | (0x1f & address), value]) print(read_register(address)) def read_register(address): result = spi.transfer([0x1f & address, 0x00]) return result[1] def read_status(): status = spi.transfer([0xff]) return status[0]
# channel 0 to channel 1 difference: 3348 # # channel 0: 4085 # channel 1: 736 # channel 2: 0 # channel 1 to channel 0 difference: 3358 # channel 0 to channel 1 difference: 3353 # # channel 0: 4084 # channel 1: 735 # channel 2: 0 # channel 1 to channel 0 difference: 3358 # channel 0 to channel 1 difference: 3346 mcp3304 = spi.SPI(1,1) mcp3304.mode = 0 mcp3304.cshigh = False mcp3304.msh = 150000 # prepare control masks # for channel 0 and 1 ch0mask = [0x0C, 0x00] # 0000 1100, 0000 0000 ch1mask = [0x0C, 0x80] # 0000 1100, 1000 0000 ch2mask = [0x0D, 0x00] # 0000 1101, 0000 0000 df0to1mask = [0x08, 0x00] # 0000 1000, 0000 0000 df1to0mask = [0x08, 0x80] # 0000 1000, 1000 0000 def parse_mcp3304(returnmask): # retmask[0] is not used retval = ( ( returnmask[1] & 0xF ) << 8) + returnmask[2]
GPIO.setup(channel, GPIO.OUT) import smbus from time import sleep bus = smbus.SMBus(1) address = 0x48 while (True): GPIO.output(channel, GPIO.LOW) bus.write_i2c_block_data(address, 0x01, [229, 131]) sleep(0.00028) a2 = bus.read_i2c_block_data(address, 0x00, 2) sleep(0.00004) GPIO.output(channel, GPIO.HIGH) sleep(0.0968) print(a2[0] * 256 + a2[1]) # SPI - RC522 (13.56MHz RIFD NFC) - Connect ... # https://github.com/mxgxw/MFRC522-python # ... # echo spi-bcm2708 >> /etc/modules # echo dtparam=spi=on >> /boot/config.txt # apt-get install python-pip # pip install spi import spi s = spi.SPI("/dev/spidev0.0") s.read(1000) # SPI - nRF24L01 (2.4GHz Tranceiver) - http://tmrh20.github.io/RF24/
write_ram_cmd = [0xA0, 0xFF] # CONTROL REGISTER (READ 0FH, WRITE 8FH) read_ctl_cmd = 0x0F write_ctl_cmd = 0x8F # Serial Interface Mode. The SERMODE pin offers the flexibility to choose # between two serial interface modes. When connected to GND, standard 3-wire # communication is selected. When connected to VCC, SPI communication is # selected. print "ds1305 testing script: setting SERMODE to SPI (Vcc)" pin_sermode = gpio.GPIO(59, "out") pin_sermode.value = 1 print "ds1305 testing script: opening device SPI-bus 1, CS 1" ds1305 = spi.SPI(1, 1) # Supports Motorola SPI (Serial Peripheral Interface) Modes 1 and 3 # or Standard 3-Wire Interface print "ds1305 testing script: setting mode 3" ds1305.mode = 1 print "ds1305 testing script: switching to cs_active_high" ds1305.cshigh = True print "ds1305 testing script: changing msh" ds1305.msh = 150000 # BIT7 BIT6 BIT5 BIT4 BIT3 BIT2 BIT1 BIT0 # EOSC WP 0 0 0 INTCN AIE1 AIEO
def initSPI(self): self.spi_conn = spi.SPI(2, 0) self.spi_conn.msh = 1000000