def __init__(self,pwm=None,uart=None,uart_divisor=None,**kwargs): log.info("start build") log.info(str(*kwargs)) super().__init__(**kwargs) #test = Testing() #self.add(test) for i in range(4): temp = TimerPeripheral(32,name="timer_"+str(i)) self.add(temp) borker = BorkPeripheral() self.add(borker) blinky = LedPeripheral(Signal(2)) self.add(blinky) counter = CounterPeripheral(10) self.add(counter) spi_interface = SPI() self.add(spi_interface) if uart is not None: serial1 = AsyncSerialPeripheral(divisor=uart_divisor) self.add(serial1) if pwm is not None: pwm = PWM(pwm) self.add(pwm)
def ping(self): """ Returns True if OPSOROHAT rev3 is connected. :return: True if shield is connected :rtype: bool """ return SPI.command(CMD_PING, returned=1)[0] == 0xAA
def create_spi_dbg(dev_name, reg_size): spi_dbg = SPIBusDebugger() if dev_name == '': spi_dbg.spi_bus = SPIBusEmulator('spi_emulator', reg_size) else: if utility.is_pl_device(dev_name): axi4_bus = AXI4LiteBus(dev_name, reg_size) spi_dbg.spi_bus = PLSPIBus(axi4_bus) else: spi_dbg.spi_bus = SPI(dev_name) return spi_dbg
def __init__(self): self.verbose = True self.u = katcp_wrapper.FpgaClient('roach2') print 'Connected...' time.sleep(1) self.u.progdev('tclk_2012_Oct_15_1635.bof') print 'Programmed...' self.s = SPI(self.u) self.tap = 0 ## Make sure that SPI interface is flushed ## and initialize self.start()
#!/usr/bin/env python import sys import time try: from termcolor import colored except ImportError: print "Termcolor module is not installed." print '' print 'Loading SPI-MODULE.....', try: from spi import SPI lcd = SPI(0, 0) lcd.msh = 1000000 try: print colored('Done', 'green') except NameError: print 'Done' except ImportError: try: print colored('Fail', 'red') except NameError: print 'Fail' sys.exit(0) print 'Loading GPIO-MODULE.....', try: import RPi.GPIO as GPIO try:
D2 = MODE1 = X D3 = MODE2 = X D4 = nRESET = 1 D5 = nSLEEP = 1 D6 = nENABLE = 0 D7 = - = X """ import time import logging from Path import Path try: from spi import SPI # init the SPI for the DAC spi2_0 = SPI(1, 0) spi2_0.bpw = 8 spi2_0.mode = 1 # Init the SPI for the serial to parallel spi2_1 = SPI(1, 1) spi2_1.bpw = 8 spi2_1.mode = 0 except ImportError: pass class Stepper: all_steppers = list() revision = "A4" SLEEP = 6
def __init__(self): self.__bus=SPI(3,0) self.__bus.msh=20000
yield dut.ss_select.eq(0) yield dut.rx_start.eq(0) yield dut.word_length.eq(0) trans_bits = 1 while trans_bits < 12: new_clk = (yield dut.sck) #rising edge, change data if new_clk == 1 and clk == 0 and (yield dut.ss_s[2]) == 0: yield dut.miso.eq(num & 1) num = num >> 1 trans_bits += 1 clk = new_clk yield while (yield dut.ss_s[2]) == 0: yield yield yield dut.rx_ack.eq(1) yield yield dut.rx_ack.eq(0) for i in range(50): yield if __name__ == "__main__": dut1 = SPI(clk_freq=100, operating_freq=10) run_simulation(dut1, spi_tx(dut1), vcd_name="spi_tx.vcd") dut2 = SPI(clk_freq=100, operating_freq=10) run_simulation(dut2, spi_rx(dut2), vcd_name="spi_rx.vcd")
#!/usr/bin/env python3 import serial import time import argparse from spi import SPI # get port name from arguments #parser = argparse.ArgumentParser() #parser.add_argument('--port_name', type=str, default='/dev/ttyS1', help='string of port name ex/ /dev/ttyS1') #args = parser.parse_args() # spi setup spi = SPI("/dev/spidev1.0") spi.mode = SPI.MODE_0 spi.bits_per_word = 8 spi.speed = 500000 #received = spi.transfer([0x11, 0x22, 0xFF]) #spi.write([0x12, 0x34, 0xAB, 0xCD]) def sendHandler(): while 1: time.sleep(1) try: spi.write([0x12, 0x34, 0xAB, 0xCD]) print("Sent to spi bus.") except Exception as e: print("Error writing to spi bus: {}".format(str(e)))
import gpio_setup, time import BBIO.GPIO as GPIO from spi import SPI import logging import cpickle import datetime logging.basicConfig(format='%(levelname)s:%(message)s', level = logging.WARNING) test = SPI(1,0) test.msh = 1000000 def choose_tc(num): if num > 8 or num < 1: print "invalid choice" return bits = "{0:03b}".format(num - 1) # logging.debug('bits: %s'%bits) GPIO.output("P8_12", int(bits[0])) GPIO.output("P8_14", int(bits[1])) GPIO.output("P8_16", int(bits[2])) def read_temp(num): choose_tc(num) out = test.readbytes(2) byte1 = '{0:08b}'.format(out[0]) byte2 = '{0:08b}'.format(out[1]) tempbits = byte1[1:] + byte2[:-3] return int(tempbits, 2)*0.25
class AVRInterface: SET_OUTPUT =0x10 SET_MOTOR =0x20 GET_ANALOG =0x30 GET_INPUT =0x40 SETUP =0x50 SET_PULSE =0x60 SET_MOTORAIM =0x70 def __init__(self): #setup device self.pullup = 0x00 self.spi = SPI(miso=22, mosi=23, clk=20, reset=38) self.lock= threading.Lock() def write(self,cmd, data=[]): self.spi.sendByte(cmd) for d in data: self.spi.sendByte(d) def setup(self): self.lock.acquire() self.write(self.SETUP) assert self.spi.sendByte(self.pullup)==ord('O') #no pullups actiavted (0-0x0f) self.lock.release() def set_pullup(self, ch): assert (ch>=0 and ch<4) self.lock.acquire() self.pullup |= (1<<ch) self.write(self.SETUP) assert self.spi.sendByte(self.pullup)==ord('O') #no pullups actiavted (0-0x0f) self.lock.release() def set_output(self, ch, v): assert (ch>=0 and ch<6) #if ch==2 or ch==5: return self.lock.acquire() self.write( (self.SET_OUTPUT|ch),[v]) self.lock.release() def set_pulse(self, ch, v): assert (ch>=0 and ch<6) #if ch==2 or ch==5: return self.lock.acquire() self.write( (self.SET_PULSE|ch),[(v<<1)]) self.lock.release() def set_motor(self, motor, back, speed): self.lock.acquire() self.write( (self.SET_MOTOR|motor|(back<<1)), [speed]) self.lock.release() def set_motoraim0(self, aim): self.lock.acquire() self.write( (self.SET_MOTORAIM), [(aim>>8),(aim&0xff)]) self.lock.release() def get_analog(self, ch): assert(ch<4 and ch>=0) self.lock.acquire() self.write(self.GET_ANALOG|ch) self.spi.wait(200) data1 = self.spi.readByte() data2 = self.spi.readByte() self.lock.release() return data1 + data2*255 def get_input(self): self.lock.acquire() self.write(self.GET_INPUT) data = self.spi.readByte() self.lock.release() r=[] for i in range(0,4): v = False if data&(1<<i)>0: v=True r.append( v ) return r
def led_on(self): """Turns status LED on.""" SPI.command(CMD_LEDON)
bing = BingVoice(BING_KEY) pa = pyaudio.PyAudio() stream = pa.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, start=False, # input_device_index=2, frames_per_buffer=CHUNK_SIZE) got_a_sentence = False leave = False bridge = SPI() def process_text(text): # This is pretty kludgy. Just look color name or command in the text string. # and send it to Arduino via SPI print("Matching " + text) m = re.search( '(red|orange|green|blue|yellow|purple|white|pink|turquoise|magenta|brighter|brightness\sup|brightness\sdown|on|off)', text) if m: # send the command to the Arduino via SPI command = m.group(0) # SPI bridge needs ASC command = command.encode('ascii', 'ignore') print("Sending command '%s' to Arduino" % command)
from player import Player from spi import SPI try: from creds import BING_KEY except ImportError: print( 'Get a key from https://www.microsoft.com/cognitive-services/en-us/speech-api and create creds.py with the key' ) sys.exit(-1) script_dir = os.path.dirname(os.path.realpath(__file__)) hi = os.path.join(script_dir, 'audio/hi.wav') spi = SPI() spi.write('offline\n') bing = BingVoice(BING_KEY) mission_completed = False awake = False pa = pyaudio.PyAudio() mic = Microphone(pa) player = Player(pa) def check_internet(host="8.8.8.8", port=53, timeout=6): """ Host: 8.8.8.8 (google-public-dns-a.google.com)
class Test(): def __init__(self): self.verbose = True self.u = katcp_wrapper.FpgaClient('roach2') print 'Connected...' time.sleep(1) self.u.progdev('tclk_2012_Oct_15_1635.bof') print 'Programmed...' self.s = SPI(self.u) self.tap = 0 ## Make sure that SPI interface is flushed ## and initialize self.start() def reset(self): self.s.write(0x00,0x0001) # reset def select(self, chip): self.s.select(chip) def power_cycle(self): self.s.write(0x0f,0x0200) # Powerdown self.s.write(0x0f,0x0000) # Powerup def start(self): print 'Beginning ADC power cycling' print 'Resetting ADC' self.reset() # reset print 'Reset done' print 'Power down ADC' self.power_cycle() print 'Power cycling done' def commit(self): self.power_cycle() def clear_pattern(self): self.s.write(0x45,0x0000) # Clear skew,deskew self.s.write(0x25,0x0000) # Clear ramp #self.commit() def ramp_pattern(self): self.clear_pattern() self.s.write(0x25,0x0040) # Enable ramp #self.commit() def deskew_pattern(self): self.clear_pattern() self.s.write(0x45,0x0001) #self.commit() def sync_pattern(self): self.clear_pattern() self.s.write(0x45,0x0002) #self.commit() def reset_all(self): ## Clear reg = self.u.read_int('adcleda_controller') reg = reg & 0xfffffffb self.u.write_int('adcleda_controller',reg, offset=1, blindwrite=True) reg = reg | 0x00000004 self.u.write_int('adcleda_controller',reg, offset=1, blindwrite=True) time.sleep(1) reg = reg & 0xfffffffb self.u.write_int('adcleda_controller',reg, offset=1, blindwrite=True) def get_channel(self): data = self.u.snapshot_get('fifo_data_a',man_trig=True)['data'] x = np.fromstring(data,dtype='>i4') y = x.astype('uint8') return y def get_data(self): data = [] temp = np.fromstring(self.u.snapshot_get('fifo_data',man_trig=True)['data'],dtype=np.uint8) data.append(self.process_data(temp[range(0,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(1,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(2,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(3,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(4,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(5,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(6,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(7,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(8,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(9,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(10,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(11,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(12,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(13,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(14,temp.size,16)].astype('uint8'))) data.append(self.process_data(temp[range(15,temp.size,16)].astype('uint8'))) return data def bit_slip(self, channel): ## Write to bitslip reg = self.u.read_int('adcleda_controller') reg = reg ^ 0x00000780 self.u.write_int('adcleda_controller',reg, offset=1) time.sleep(1) reg = reg ^ 0x00000780 self.u.write_int('adcleda_controller',reg, offset=1) def flip_channel(self, channel): ## Write to channel flip reg = self.u.read_int('adcleda_controller') reg = reg ^ 0x00000071 self.u.write_int('adcleda_controller',reg, offset=1) def process_data(self, data): #print 'Before:' #print ['%02x' % y for y in data[:8]] out_p = [] for num in range(0,len(data)-1): y = data[num]&0xff y = ((y&0x08)>>3)|((y&0x04)>>1)|((y&0x02)<<1)|((y&0x01)<<3)|((y&0x80)>>3)|((y&0x40)>>1)|((y&0x20)<<1)|((y&0x10)<<3) out_p.append(y) #print '\nAfter:' #print ['%02x' % y for y in out_p[:8]] return out_p def show_data(self, data): plot(data) def inc_tap(self): self.tap = self.tap + 1 y = (self.tap)&0x1f #y = (((self.tap)&0x10)>>4)|(((self.tap)&0x08)>>2)|((self.tap)&0x04)|(((self.tap)&0x02)<<2)|(((self.tap)&0x01)<<4) s = (y<<11)|(0x00000000) self.u.write_int('adcleda_controller',s,offset=1) time.sleep(1) s = (y<<11)|(0xffff0000) self.u.write_int('adcleda_controller',s,offset=1) time.sleep(1) s = (y<<11)|(0x00000000) self.u.write_int('adcleda_controller',s,offset=1) #def calibrate(self): # self.
from spi import SPI s = SPI() s.send_data([0x1A]) s.rec_data(len=4)
def create_datelist(start_date, n_months): dates = [start_date + relativedelta(months=i) for i in range(0, n_months)] return np.array(dates) if __name__ == '__main__': # Read precip data from csv crnt_path = os.path.dirname(os.path.abspath(__file__)) precip_file = os.path.join(crnt_path, '..', 'data', 'rainfall_test.csv') rainfall_data = np.genfromtxt(precip_file, delimiter=',') # Initialize SPI class spi = SPI() # Set rolling window parameters spi.set_rolling_window_params(span=1, window_type=None, center=True) # Set distribution parameters spi.set_distribution_params(dist_type='gengamma') # Calculate SPI data = spi.calculate(rainfall_data, starting_month=1) # Create date list for plotting n_dates = np.shape(data)[0] date_list = create_datelist(dt.date(2000, 1, 1), n_dates) # Plot SPI
def __init__(self, device): _spi = SPI(device)
def __init__(self, logger): Logger.log.debug('{} initializing....'.format(__name__)) self.logger = logger self.config = Config(logger=self.logger) self.support = Support(config=self.config, logger=self.logger) self.gpio = Gpio(config=self.config, logger=self.logger) self.pollperm = Pollperm(logger=self.logger) self.decoder = Decoder(config=self.config, logger=self.logger, gpio=self.gpio) self.spi = SPI(config=self.config, logger=self.logger, decoder=self.decoder, pollperm=self.pollperm) self.codegen = Codegen(config=self.config, logger=self.logger, gpio=self.gpio, spi=self.spi) self.securitylevel = SecurityLevel(logger=self.logger) self.gui = Mainwindow(self, codegen=self.codegen, config=self.config, logger=self.logger, support=self.support, securitylevel=self.securitylevel) self.switches = Switches(config=self.config, logger=self.logger, spi=self.spi, gui=self.gui) self.currentsense = CurrentSense(logger=self.logger, spi=self.spi, decoder=self.decoder, gui=self.gui, config=self.config) self.pollvalues = Pollvalues(pollperm=self.pollperm, logger=logger, config=self.config, currentsense=self.currentsense, switches=self.switches, sense_callback=self.poll_sense_callback, switch_callback=self.poll_switch_callback) self.securitywindow = SecurityWindow(logger=self.logger, securitylevel=self.securitylevel) self.window = self.gui.window self.log = self.logger.log self.knob_values = 0 self.rotary_0_pins = None self.rotary_1_pins = None self.rotary_2_pins = None self.rotary_3_pins = None self.rotary_0_pin_0_debounce = None self.rotary_0_pin_1_debounce = None self.rotary_1_pin_0_debounce = None self.rotary_1_pin_1_debounce = None self.rotary_2_pin_0_debounce = None self.rotary_2_pin_1_debounce = None self.rotary_3_pin_0_debounce = None self.rotary_3_pin_1_debounce = None self.gain0_val = 0 self.gain1_val = 0 self.gain_0_name = None self.gain_1_name = None self.gain_0_spi_channel = None self.gain_1_spi_channel = None self.gain_0_thresholds = None self.gain_1_thresholds = None self.GAIN_0_CS = None self.GAIN_1_CS = None self.speed0_val = 0 self.speed1_val = 0 self.speed_0_name = None self.speed_1_name = None self.speed_0_shape = None self.speed_1_shape = None self.speed_0_spi_channel = None self.speed_1_spi_channel = None self.speed_0_thresholds = None self.speed_1_thresholds = None self.screen_brightness_max = None self.screen_brightness_min = None self.display_brightness = None self.spi_log_pause = False self.SPEED_0_CS = None # 6 # SPEED SIMULATION TACH 1 self.SPEED_1_CS = None # 7 # SPEED SIMULATION TACH 2 self.load_from_config() self.adc_scale = None self.sense_amp_max_amps = None self.sense_ad_vin = None # LM4128CQ1MF3.3/NOPB voltage reference self.sense_ad_max_bits = 0 # AD7940 ADC self.sense_scaling_factor_mv_amp = None # 110 milivolts per amp self.sense_ad_max_scaled_value = None self.speed0 = Speedgen( pollperm=self.pollperm, logger=self.logger, config=self.config, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.speed_0_name, shape=self.speed_0_shape, spi_channel=self.speed_0_spi_channel, chip_select=self.SPEED_0_CS, pin_0=self.rotary_0_pins[0], pin_1=self.rotary_0_pins[1], pin_0_debounce=self.rotary_0_pin_0_debounce, pin_1_debounce=self.rotary_0_pin_1_debounce, thresholds=self.speed_0_thresholds, callback=self.speed_callback, commander_speed_move_callback=self.speed_move_callback) self.speed1 = Speedgen( pollperm=self.pollperm, logger=self.logger, config=self.config, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.speed_1_name, shape=self.speed_1_shape, spi_channel=self.speed_1_spi_channel, chip_select=self.SPEED_1_CS, pin_0=self.rotary_1_pins[0], pin_1=self.rotary_1_pins[1], pin_0_debounce=self.rotary_1_pin_0_debounce, pin_1_debounce=self.rotary_1_pin_1_debounce, thresholds=self.speed_1_thresholds, callback=self.speed_callback, commander_speed_move_callback=self.speed_move_callback) self.gain0 = Gains( pollperm=self.pollperm, config=self.config, logger=self.logger, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.gain_0_name, spi_channel=self.gain_0_spi_channel, chip_select=self.GAIN_0_CS, pin_0=self.rotary_2_pins[0], pin_1=self.rotary_2_pins[1], pin_0_debounce=self.rotary_2_pin_0_debounce, pin_1_debounce=self.rotary_2_pin_1_debounce, thresholds=self.gain_0_thresholds, callback=self.gains_callback, commander_gain_move_callback=self.gain_move_callback) self.gain1 = Gains( pollperm=self.pollperm, config=self.config, logger=self.logger, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.gain_1_name, spi_channel=self.gain_1_spi_channel, chip_select=self.GAIN_1_CS, pin_0=self.rotary_3_pins[0], pin_1=self.rotary_3_pins[1], pin_0_debounce=self.rotary_3_pin_0_debounce, pin_1_debounce=self.rotary_3_pin_1_debounce, thresholds=self.gain_1_thresholds, callback=self.gains_callback, commander_gain_move_callback=self.gain_move_callback) self.startup_processes()
# Send some SPI commands to test the Arduino sketch from spi import SPI import time spi = SPI() commands = ["red", "green", "blue", "off"] for command in commands: print("Sending " + command) spi.write(command + "\n") time.sleep(2)
def __init__(self, dev='/dev/spidev0.0', speed=1000000): self.__spiDev = SPI(device=dev, speed=speed) self.MFRC522_Init()
#!/usr/bin/env python from spi import SPI from time import sleep from datetime import datetime port = SPI(2,0) port.msh = 100000 #port.lsbfirst = True port.mode = 0b00 _DISPLAY_6X12 = 0x02 _DISPLAY_7X11 = 0x03 _AUTO_INCREMENT = 0x40 _FIXED_ADDRESS = 0x44 _DISPLAY_OFF = 0x80 _DISPLAY_1_16 = 0x88 _DISPLAY_2_16 = 0x89 _DISPLAY_4_16 = 0x8A _DISPLAY_10_16 = 0x8B _DISPLAY_11_16 = 0x8C _DISPLAY_12_16 = 0x8D _DISPLAY_13_16 = 0x8E _DISPLAY_14_16 = 0x8F addresses = (0xC0,0xC2,0xC4,0xC6) font = { 0: 0xFC, 1: 0x60, 2: 0xDA, 3: 0xF2,
class MFRC522: # RST Pin number,default 22 NRSTPD = 22 MAX_LEN = 16 # RC522命令字 PCD_IDLE = 0x00 PCD_AUTHENT = 0x0E PCD_RECEIVE = 0x08 PCD_TRANSMIT = 0x04 PCD_TRANSCEIVE = 0x0C PCD_RESETPHASE = 0x0F PCD_CALCCRC = 0x03 # PICC命令字 PICC_REQIDL = 0x26 PICC_REQALL = 0x52 PICC_ANTICOLL = 0x93 PICC_SElECTTAG = 0x93 PICC_AUTHENT1A = 0x60 PICC_AUTHENT1B = 0x61 PICC_READ = 0x30 PICC_WRITE = 0xA0 PICC_DECREMENT = 0xC0 PICC_INCREMENT = 0xC1 PICC_RESTORE = 0xC2 PICC_TRANSFER = 0xB0 PICC_HALT = 0x50 # 返回状态 MI_OK = 0 MI_NO_TAG_ERR = 1 MI_ERR = 2 # RC522寄存器地址 Reserved00 = 0x00 CommandReg = 0x01 CommIEnReg = 0x02 DivlEnReg = 0x03 CommIrqReg = 0x04 DivIrqReg = 0x05 ErrorReg = 0x06 Status1Reg = 0x07 Status2Reg = 0x08 FIFODataReg = 0x09 FIFOLevelReg = 0x0A WaterLevelReg = 0x0B ControlReg = 0x0C BitFramingReg = 0x0D CollReg = 0x0E Reserved01 = 0x0F Reserved10 = 0x10 ModeReg = 0x11 TxModeReg = 0x12 RxModeReg = 0x13 TxControlReg = 0x14 TxAutoReg = 0x15 TxSelReg = 0x16 RxSelReg = 0x17 RxThresholdReg = 0x18 DemodReg = 0x19 Reserved11 = 0x1A Reserved12 = 0x1B MifareReg = 0x1C Reserved13 = 0x1D Reserved14 = 0x1E SerialSpeedReg = 0x1F Reserved20 = 0x20 CRCResultRegM = 0x21 CRCResultRegL = 0x22 Reserved21 = 0x23 ModWidthReg = 0x24 Reserved22 = 0x25 RFCfgReg = 0x26 GsNReg = 0x27 CWGsPReg = 0x28 ModGsPReg = 0x29 TModeReg = 0x2A TPrescalerReg = 0x2B TReloadRegH = 0x2C TReloadRegL = 0x2D TCounterValueRegH = 0x2E TCounterValueRegL = 0x2F Reserved30 = 0x30 TestSel1Reg = 0x31 TestSel2Reg = 0x32 TestPinEnReg = 0x33 TestPinValueReg = 0x34 TestBusReg = 0x35 AutoTestReg = 0x36 VersionReg = 0x37 AnalogTestReg = 0x38 TestDAC1Reg = 0x39 TestDAC2Reg = 0x3A TestADCReg = 0x3B Reserved31 = 0x3C Reserved32 = 0x3D Reserved33 = 0x3E Reserved34 = 0x3F def __init__(self, dev='/dev/spidev0.0', speed=1000000): self.__spiDev = SPI(device=dev, speed=speed) self.MFRC522_Init() def __debug(self, s): # print (s) pass # 复位读卡器 def MFRC522_Reset(self): self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE) # 向读卡器中写数据 def Write_MFRC522(self, addr, val): self.__spiDev.transfer(((addr << 1) & 0x7E, val)) # 读取读卡器中的数据 def Read_MFRC522(self, addr): val = self.__spiDev.transfer((((addr << 1) & 0x7E) | 0x80, 0)) return val[1] # 设置位掩码 def SetBitMask(self, reg, mask): tmp = self.Read_MFRC522(reg) self.Write_MFRC522(reg, tmp | mask) # 清除位掩码 def ClearBitMask(self, reg, mask): tmp = self.Read_MFRC522(reg) self.Write_MFRC522(reg, tmp & (~mask)) # 打开天线 def AntennaOn(self): temp = self.Read_MFRC522(self.TxControlReg) if ~(temp & 0x03): self.SetBitMask(self.TxControlReg, 0x03) # 关闭天线 def AntennaOff(self): self.ClearBitMask(self.TxControlReg, 0x03) def MFRC522_ToCard(self, command, sendData): backData = [] backLen = 0 status = self.MI_ERR irqEn = 0x00 waitIRq = 0x00 n = 0 i = 0 if command == self.PCD_AUTHENT: irqEn = 0x12 waitIRq = 0x10 if command == self.PCD_TRANSCEIVE: irqEn = 0x77 waitIRq = 0x30 self.Write_MFRC522(self.CommIEnReg, irqEn | 0x80) self.ClearBitMask(self.CommIrqReg, 0x80) self.SetBitMask(self.FIFOLevelReg, 0x80) self.Write_MFRC522(self.CommandReg, self.PCD_IDLE) while i < len(sendData): self.Write_MFRC522(self.FIFODataReg, sendData[i]) i += 1 self.Write_MFRC522(self.CommandReg, command) if command == self.PCD_TRANSCEIVE: self.SetBitMask(self.BitFramingReg, 0x80) i = 2000 while True: n = self.Read_MFRC522(self.CommIrqReg) i -= 1 if ~((i != 0) and ~(n & 0x01) and ~(n & waitIRq)): break self.ClearBitMask(self.BitFramingReg, 0x80) if i != 0: if (self.Read_MFRC522(self.ErrorReg) & 0x1B) == 0x00: status = self.MI_OK if n & irqEn & 0x01: status = self.MI_NO_TAG_ERR if command == self.PCD_TRANSCEIVE: n = self.Read_MFRC522(self.FIFOLevelReg) lastBits = self.Read_MFRC522(self.ControlReg) & 0x07 if lastBits != 0: backLen = (n - 1) * 8 + lastBits else: backLen = n * 8 if n == 0: n = 1 if n > self.MAX_LEN: n = self.MAX_LEN i = 0 while i < n: backData.append(self.Read_MFRC522(self.FIFODataReg)) i += 1 else: status = self.MI_ERR return status, backData, backLen def MFRC522_Request(self, reqMode): TagType = [] self.Write_MFRC522(self.BitFramingReg, 0x07) TagType.append(reqMode) (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType) if (status != self.MI_OK) | (backBits != 0x10): status = self.MI_ERR return status, backBits def MFRC522_Anticoll(self): serNumCheck = 0 serNum = [] self.Write_MFRC522(self.BitFramingReg, 0x00) serNum.append(self.PICC_ANTICOLL) serNum.append(0x20) (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, serNum) if status == self.MI_OK: i = 0 if len(backData) == 5: while i < 4: serNumCheck = serNumCheck ^ backData[i] i += 1 if serNumCheck != backData[i]: status = self.MI_ERR else: status = self.MI_ERR return status, backData # 计算 CRC 值 def CalulateCRC(self, pIndata): self.ClearBitMask(self.DivIrqReg, 0x04) self.SetBitMask(self.FIFOLevelReg, 0x80) i = 0 while i < len(pIndata): self.Write_MFRC522(self.FIFODataReg, pIndata[i]) i += 1 self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC) i = 0xFF while True: n = self.Read_MFRC522(self.DivIrqReg) i -= 1 if not ((i != 0) and not (n & 0x04)): break pOutData = [self.Read_MFRC522(self.CRCResultRegL), self.Read_MFRC522(self.CRCResultRegM)] return pOutData # 选择标签 def MFRC522_SelectTag(self, serNum): buf = [self.PICC_SElECTTAG, 0x70] i = 0 while i < 5: buf.append(serNum[i]) i += 1 pOut = self.CalulateCRC(buf) buf.append(pOut[0]) buf.append(pOut[1]) (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf) if (status == self.MI_OK) and (backLen == 0x18): self.__debug("Size: " + str(backData[0])) return backData[0] else: return 0 def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): # First byte should be the authMode (A or B) # Second byte is the trailerBlock (usually 7) buff = [authMode, BlockAddr] # Now we need to append the authKey which usually is 6 bytes of 0xFF i = 0 while i < len(Sectorkey): buff.append(Sectorkey[i]) i += 1 i = 0 # Next we append the first 4 bytes of the UID while i < 4: buff.append(serNum[i]) i += 1 # Now we start the authentication itself (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT, buff) # 检查是否发生错误 if not (status == self.MI_OK): self.__debug("AUTH ERROR!!") if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0: self.__debug("AUTH ERROR(status2reg & 0x08) != 0") # 返回状态码 return status def MFRC522_StopCrypto1(self): self.ClearBitMask(self.Status2Reg, 0x08) # 读卡 def MFRC522_Read(self, blockAddr): recvData = [self.PICC_READ, blockAddr] pOut = self.CalulateCRC(recvData) recvData.append(pOut[0]) recvData.append(pOut[1]) status, backData, backLen = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData) return status, backData, backLen # 写卡 def MFRC522_Write(self, blockAddr, writeData): buff = [self.PICC_WRITE, blockAddr] crc = self.CalulateCRC(buff) buff.append(crc[0]) buff.append(crc[1]) status, backData, backLen = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff) if status == self.MI_OK and backLen != 4 and (backData[0] & 0x0F) != 0x0A: status = self.MI_ERR self.__debug(str(backLen) + " backdata &0x0F == 0x0A " + str(backData[0] & 0x0F)) if status == self.MI_OK: i = 0 buf = [] while i < 16: buf.append(writeData[i]) i += 1 crc = self.CalulateCRC(buf) buf.append(crc[0]) buf.append(crc[1]) status, backData, backLen = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf) if status == self.MI_OK and backLen != 4 and (backData[0] & 0x0F) != 0x0A: self.__debug("Error while writing") if status == self.MI_OK: self.__debug("Data written") # 导出1K字节, 64个扇区 def MFRC522_DumpClassic1K(self, key, uid): i = 0 while i < 64: status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid) # 检查是否认证成功 if status == self.MI_OK: self.MFRC522_Read(i) else: self.__debug("Authentication error") i += 1 def MFRC522_Init(self): 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()
#!/usr/bin/env python from spi import SPI spi2_1 = SPI(2, 1) spi2_1.bpw = 8 spi2_1.mode = 0 spi2_1.writebytes([0x30])
def __init__( self, bus, client): self.spi = SPI( bus, client, SPI.SPI_MODE_3, 550000 ) self.read_object_table()
class driveUnit(): def __init__(self): self.__bus=SPI(3,0) self.__bus.msh=20000 #def testReceive(self): # self.__bus.writebytes([0x50]) # print self.__bus.readbytes(1) def setMotorLeft(self,speed): speed = int(speed) if speed >= 0: direction = 1 else: direction = 0 self.send_startbit() #längd self.__bus.writebytes([0x03]) #kommandot self.__bus.writebytes([0x11]) self.__bus.writebytes([direction]) self.__bus.writebytes([abs(speed)]) def setMotorRight(self,speed): speed = int(speed) if speed >= 0: direction = 1 else: direction = 0 self.send_startbit() #length self.__bus.writebytes([0x03]) #kommandot self.__bus.writebytes([0x10]) self.__bus.writebytes([direction]) self.__bus.writebytes([abs(speed)]) def setArmAxis(self, id, value): self.send_startbit() #length self.__bus.writebytes([0x03]) #commando self.__bus.writebytes([16+(id+1)]) self.__bus.writebytes([value >> 8, 0x00FF & value]) def sendAxis(self,id): self.send_startbit() self.__bus.writebytes([0x01]) self.__bus.writebytes([48+(id+1)]) def sendAllAxis(self): self.send_startbit() self.__bus.writebytes([0x01]) self.__bus.writebytes([0x3E]) def sendAllMotor(self): self.send_startbit() #längd self.__bus.writebytes([0x01]) #action self.__bus.writebytes([0x3D]) def sendMotorRight(self): self.send_startbit() self.__bus.writebytes([0x01]) self.__bus.writebytes([0x30]) def sendMotorLeft(self): self.send_startbit() self.__bus.writebytes([0x01]) self.__bus.writebytes([0x31]) def send_startbit(self): self.__bus.writebytes([0xFF]) self.__bus.writebytes([0xFF])
class AT42QT1085: obj_table = {} report_id = [] #----------------------------- # Object types #----------------------------- OBJ_TYPE_MESSAGE = 5 OBJ_TYPE_COMMAND = 6 OBJ_TYPE_KEY = 13 OBJ_TYPE_GPIO = 29 OBJ_TYPE_HAPTIC = 31 #----------------------------- # Commands #----------------------------- COMMAND_RESET = 0 COMMAND_BACKUP = 1 COMMAND_CALIBRATE = 2 COMMAND_REPORT = 3 #----------------------------- # T13 : Key config #----------------------------- CONFIG_KEY_ENABLE = 0x01 CONFIG_KEY_RPTEN = 0x02 CONFIG_KEY_GUARD = 0x20 CONFIG_KEY_DISREL = 0x40 CONFIG_KEY_DISPRESS = 0x80 CONFIG_KEY_HYST_50 = 0x00 CONFIG_KEY_HYST_25 = 0x01 CONFIG_KEY_HYST_12_5 = 0x02 CONFIG_KEY_HYST_6_25 = 0x03 #----------------------------- # T29 : GPIO #----------------------------- CONFIG_GPIO_ENABLE = 0x01 CONFIG_GPIO_RPTEN = 0x02 CONFIG_GPIO_FADE = 0x04 CONFIG_GPIO_TOGGLE = 0x08 CONFIG_GPIO_DRIVELVL_PUSH = 0x10 CONFIG_GPIO_DISOFF = 0x20 CONFIG_GPIO_INVERT = 0x40 CONFIG_GPIO_OUTPUT = 0x80 GPIO_SOURCE_HOST = 0 GPIO_SOURCE_KEY = 1 GPIO_SOURCE_GPIO = 4 GPIO_DRIVELVL_PUSH = 1 GPIO_DRIVELVL_DRAIN = 0 #----------------------------- # T31 : Haptic event #----------------------------- CONFIG_HAPTIC_ENABLE = 0x01 CONFIG_HAPTIC_RPTEN = 0x02 CONFIG_HAPTIC_LOOP = 0x20 CONFIG_HAPTIC_DISFINISH = 0x40 CONFIG_HAPTIC_DISSTART = 0x80 HAPTIC_EFFECT_STRONG_CLICK = 1 HAPTIC_EFFECT_STRONG_CLICK_60 = 2 HAPTIC_EFFECT_STRONG_CLICK_30 = 3 HAPTIC_EFFECT_SHARP_CLICK = 4 HAPTIC_EFFECT_SHARP_CLICK_60 = 5 HAPTIC_EFFECT_SHARP_CLICK_30 = 6 HAPTIC_EFFECT_SOFT_BUMP = 7 HAPTIC_EFFECT_SOFT_BUMP_60 = 8 HAPTIC_EFFECT_SOFT_BUMP_30 = 9 HAPTIC_EFFECT_DOUBLE_CLICK = 10 HAPTIC_EFFECT_DOUBLE_CLICK_60 = 11 HAPTIC_EFFECT_TRIPLE_CLICK = 12 HAPTIC_EFFECT_SOFT_BUZZ = 13 HAPTIC_EFFECT_STRONG_BUZZ = 14 HAPTIC_SOURCE_HOST = 0 HAPTIC_SOURCE_KEY = 1 HAPTIC_SOURCE_GPIO = 4 #---------------------------------------------------------------------------- def __init__( self, bus, client): self.spi = SPI( bus, client, SPI.SPI_MODE_3, 550000 ) self.read_object_table() #---------------------------------------------------------------------------- def __del__( self ): pass #---------------------------------------------------------------------------- def read_object_table( self ): self.obj_table = {} self.report_id = [] info = self.read_block( 0x00, 0x00, 7 ) nobj = info[6] info = self.read_block( 0x00, 0x00, 10 + ( nobj * 6 )) crc = info[ -1 ] << 16 | info[ -2 ] << 8 | info[ -3 ] if not self.crc24( info[ :-3 ] ) == crc: raise IOError( "Invalid checksum for information block" ) for i in range( nobj ): start = 7 + ( i * 6 ) obj_type = info[ start ] ninst = info[ start + 4 ] + 1 nreports = info[ start + 5 ] self.obj_table[obj_type] = { 'lsb' : info[ start + 1 ], 'msb' : info[ start + 2 ], 'size' : info[ start + 3 ] + 1, 'ninst' : ninst, 'nreports' : nreports } for n in range( nreports * ninst ): self.report_id.append({ 'type' : obj_type, 'inst' : n }) ## Send reset command ## self.send_command( self.COMMAND_RESET ) time.sleep( 0.065 ) #---------------------------------------------------------------------------- def read_config_object( self, obj_type, instance = None ): if not obj_type in self.obj_table: raise ValueError( "Object (T%d) does not exists." % ( obj_type )) lsb = self.obj_table[ obj_type ][ 'lsb' ] msb = self.obj_table[ obj_type ][ 'msb' ] size = self.obj_table[ obj_type ][ 'size' ] ninst = self.obj_table[ obj_type ][ 'ninst' ] if instance is None: block = self.read_block( lsb, msb, size * ninst ) obj = [] for i in range( ninst ): obj.append( block[ i * size : ( i * size ) + size ] ) return obj else: if ( instance < 0 ) or ( instance > ninst - 1 ): raise ValueError( "Invalid instance ID for this type of object (T%d@%d)" % ( obj_type, instance )) lsb += ( instance * size ) msb += ( lsb & 0xFF00 ) >> 8 return self.read_block( lsb, msb, size ) #---------------------------------------------------------------------------- def write_config_object( self, obj_type, config, instance = None ): if not obj_type in self.obj_table: raise ValueError( "Object (T%d) does not exists." % ( obj_type )) lsb = self.obj_table[ obj_type ][ 'lsb' ] msb = self.obj_table[ obj_type ][ 'msb' ] size = self.obj_table[ obj_type ][ 'size' ] ninst = self.obj_table[ obj_type ][ 'ninst' ] if instance is None: if len( config ) != ninst: raise ValueError( "Invalid number of blocks for object (T%d)" % ( obj_type )) data = [] for i in range( ninst ): if len( config[ i ] ) != size: raise ValueError( "Invalid block size for object (T%d@%d)" % ( obj_type, i )) data.extend( config[ i ] ) return self.write_block( lsb, msb, data ) else: if ( instance < 0 ) or ( instance > ninst - 1 ): raise ValueError( "Invalid instance ID for this type of object (T%d@%d)" % ( obj_type, instance )) if len( config ) != size: raise ValueError( "Invalid block size for object (T%d@%d)" % ( obj_type, instance )) lsb += ( instance * size ) msb += ( lsb & 0xFF00 ) >> 8 return self.write_block( lsb, msb, config ) #---------------------------------------------------------------------------- def read_next_message( self ): msg = self.read_config_object( self.OBJ_TYPE_MESSAGE ) idx = msg[0][0] - 1 if idx == 254: return None report = self.report_id[ idx ] report['data'] = msg[0][1:-1] return report #---------------------------------------------------------------------------- def read_block( self, addr_low, addr_hi, size ): addr_hi = (( addr_low & 0x80 ) >> 7 ) + ( addr_hi << 1 ) addr_low = (( addr_low & 0x7f ) << 1 ) | 0x01 data = [ addr_low, addr_hi, size] data.extend( [0x00] * size ) received = self.spi.transfer_byte_delay( data ) time.sleep ( 0.002 ) return received[3:] #---------------------------------------------------------------------------- def write_block( self, addr_low, addr_hi, block ): addr_hi = (( addr_low & 0x80 ) >> 7 ) + ( addr_hi << 1 ) addr_low = (( addr_low & 0x7f ) << 1 ) data = [ addr_low, addr_hi, len( block ) ] data.extend( block ) received = self.spi.transfer_byte_delay( data ) time.sleep( 0.010 ) return sum( received[ 3: ] ) == ( 0xAA * len( block )) #---------------------------------------------------------------------------- def crc24( self, block ): crc = 0x00 crcpoly = 0x80001b for i in range( 0, len( block ), 2 ): if i + 1 < len( block ): data_word = ( block[ i + 1 ] << 8 ) | block[ i ] else: data_word = block[ i ] crc = (( crc << 1 ) ^ data_word ) if crc & 0x1000000: crc ^= crcpoly return crc & 0xFFFFFF #---------------------------------------------------------------------------- def send_command( self, command ): data = [ 0x00 ] * self.obj_table[ self.OBJ_TYPE_COMMAND]['size'] if command > ( len( data ) - 1 ): raise ValueError( "Invalid command: %x (T6)" % ( command )) data[ command ] = 0x55 return self.write_config_object( self.OBJ_TYPE_COMMAND, data, 0 ) #---------------------------------------------------------------------------- def gen_config_key( self, enabled = True, rpten = True, guard = False, dis_msg_rel = False, dis_msg_press = False, hyst = CONFIG_KEY_HYST_25, aks_group = 1, tchdi = 3, threshold = 0x10 ): config = [ 0x00 ] * self.obj_table[ self.OBJ_TYPE_KEY ]['size'] if enabled: config[ 0 ] |= self.CONFIG_KEY_ENABLE if rpten: config[ 0 ] |= self.CONFIG_KEY_RPTEN if dis_msg_rel: config[ 0 ] |= self.CONFIG_KEY_DISREL if dis_msg_press: config[ 0 ] |= self.CONFIG_KEY_DISPRESS if guard: config[ 0 ] |= self.CONFIG_KEY_GUARD config[ 1 ] = ( hyst & 0x03 ) | (( aks_group & 0x07 ) << 2 ) | (( tchdi & 0x07 ) << 5 ) config[ 2 ] = threshold return config #---------------------------------------------------------------------------- def gen_config_haptic( self, enabled = True, rpten = True, loop = False, dis_msg_finish = False, dis_msg_start = False, effect = HAPTIC_EFFECT_SHARP_CLICK, source = HAPTIC_SOURCE_KEY, instance = 0 ): config = [ 0x00 ] * self.obj_table[ self.OBJ_TYPE_HAPTIC ]['size'] if enabled: config[ 0 ] |= self.CONFIG_HAPTIC_ENABLE if rpten: config[ 0 ] |= self.CONFIG_HAPTIC_RPTEN if loop: config[ 0 ] |= self.CONFIG_HAPTIC_LOOP if dis_msg_finish: config[ 0 ] |= self.CONFIG_HAPTIC_DISFINISH if dis_msg_start: config[ 0 ] |= self.CONFIG_HAPTIC_DISSTART config[ 1 ] = effect & 0x7F config[ 2 ] = ( instance & 0x1F ) | (( source & 0x07 ) << 5 ) return config #---------------------------------------------------------------------------- def gen_config_gpio( self, enabled = True, rpten = True, fade = False, toggle = False, drivelvl = GPIO_DRIVELVL_PUSH, disoff = False, invert = False, output = True, pwm_on = 15, pwm_off = 0, source = GPIO_SOURCE_KEY, instance = 0): config = [ 0x00 ] * self.obj_table[ self.OBJ_TYPE_GPIO ]['size'] if enabled: config[ 0 ] |= self.CONFIG_GPIO_ENABLE if rpten: config[ 0 ] |= self.CONFIG_GPIO_RPTEN if fade: config[ 0 ] |= self.CONFIG_GPIO_FADE if toggle: config[ 0 ] |= self.CONFIG_GPIO_TOGGLE if drivelvl: config[ 0 ] |= self.CONFIG_GPIO_DRIVELVL_PUSH if disoff: config[ 0 ] |= self.CONFIG_GPIO_DISOFF if invert: config[ 0 ] |= self.CONFIG_GPIO_INVERT if output: config[ 0 ] |= self.CONFIG_GPIO_OUTPUT config[ 1 ] = ( pwm_off & 0x0F ) | (( pwm_on & 0x0F ) << 4 ) config[ 2 ] = ( instance & 0x1F ) | (( source & 0x07 ) << 5 ) return config
from microphone import Microphone from player import Player from spi import SPI try: from creds import BING_KEY except ImportError: print( 'Get a key from https://www.microsoft.com/cognitive-services/en-us/speech-api and create creds.py with the key') sys.exit(-1) script_dir = os.path.dirname(os.path.realpath(__file__)) hi = os.path.join(script_dir, 'audio/hi.wav') spi = SPI() spi.write('offline\n') bing = BingVoice(BING_KEY) mission_completed = False awake = False pa = pyaudio.PyAudio() mic = Microphone(pa) player = Player(pa) def check_internet(host="8.8.8.8", port=53, timeout=6): """ Host: 8.8.8.8 (google-public-dns-a.google.com)
def create_datelist(start_date, n_months): dates = [start_date + relativedelta(months=i) for i in range(0, n_months)] return np.array(dates) if __name__ == '__main__': # Read precip data from csv crnt_path = os.path.dirname(os.path.abspath(__file__)) precip_file = os.path.join(crnt_path, '..', 'data', 'rainfall_test.csv') rainfall_data = np.genfromtxt(precip_file, delimiter=',') # Initialize SPI class spi = SPI() # Set rolling window parameters spi.set_rolling_window_params(span=1, window_type=None, center=True) # Set distribution parameters spi.set_distribution_params(dist_type='gamma') # Calculate SPI data = spi.calculate(rainfall_data, starting_month=1) # Create date list for plotting n_dates = np.shape(data)[0] date_list = create_datelist(dt.date(2000, 1, 1), n_dates) # Plot
# interval timer from https://stackoverflow.com/questions/22498038#22498708 from threading import Event, Thread def repeat(interval, func): def loop(): while not Event().wait(interval): func() Thread(target=loop).start() # uses https://raw.githubusercontent.com/tomstokes/python-spi/master/spi.py from spi import SPI spi = SPI('/dev/spidev1.0') spi.mode = SPI.MODE_0 spi.bits_per_word = 8 spi.speed = 10 * 1000000 IODIRA = 0x00 IOCON = 0x0a GPIOA = 0x12 # write to MCP23S17 register(s), GPIOA by default def mcp23s17(address, values, register=GPIOA): global spi opcode = 0x40 | (address << 1) spi.write([opcode, register] + values)
#!/usr/bin/env python from spi import SPI # Set up the SPI dac = SPI(2, 0) dac.mode = 1 # SPI mode 1 dac.bpw = 8 # 8 bits pr word dac.lsbfirst = False # MSB transfers # Calculate the value for the DAC iChop = 2.0 # Current chopping limit (This is the value you can change) vRef = 3.3 # Voltage reference on the DAC rSense = 0.1 # Resistance for the vOut = iChop*5.0*rSense # Calculated voltage out from the DAC (See page 9 in the datasheet for the DAC) dacval = int((vOut*256.0)/vRef) # Update all channels with the value for addr in range(8): byte1 = ((dacval & 0xF0)>>4) + (addr<<4) byte2 = (dacval & 0x0F)<<4 dac.writebytes([byte1, byte2]) # Update all channels dac.writebytes([0xA0, 0xFF]) print "All channels now have vOut = "+str(vOut)+", iChop = "+str(iChop)
def reset(self): """Resets the ATmega328, MPR121 and PCA9685.""" SPI.command(CMD_RESET, delay=2)
def __init__(self, clk_freq, baud_rate, spi_operating_freq): # submodules self.submodules.uart = uart = UART(clk_freq, baud_rate) self.submodules.spi = spi = SPI(clk_freq, spi_operating_freq) self.submodules.spi_man = spi_man = ControlManager() # UART ports self.tx_port = tx_port = uart.tx_port self.rx_port = rx_port = uart.rx_port # SPI ports self.sck = sck = spi.sck self.miso = miso = spi.miso self.mosi = mosi = spi.mosi self.ss_s = ss_s = spi.ss_s # interconnect submodules # SPI manager self.comb += spi.word_length.eq(spi_man.word_length) self.comb += spi.ss_select.eq(spi_man.ss_select) self.comb += spi.lsb_first.eq(spi_man.lsb_first) self.comb += spi.rising_edge.eq(spi_man.rising_edge) # I/O self.ios = {tx_port, rx_port} | \ {sck, miso, mosi, ss_s[0], ss_s[1], ss_s[2], ss_s[3]} #Inner needed data self.uart_buffer = uart_buffer = Signal(8) self.spi_buffer = spi_buffer = Signal(16) self.num_words = num_words = Signal(6) # FSM to implementing protocol self.submodules.op_fsm = FSM(reset_state="IDLE") #IDLE, we need to receive data from UART to start. self.op_fsm.act( "IDLE", # is there new data If( uart.rx_ready, # get the new data NextValue(uart_buffer, uart.rx_data), # ack the new data NextValue(uart.rx_ack, 1), # handle the command NextState("HANDLE_COMMAND"), ).Else( NextValue(spi.tx_start, 0), NextValue(spi.rx_start, 0), NextValue(spi.rx_ack, 0), NextValue(uart.rx_ack, 0), NextValue(uart.tx_ack, 0), )) self.op_fsm.act( "HANDLE_COMMAND", # un-ack any new data NextValue(uart.rx_ack, 0), # handle if transfer message If( uart_buffer[7], # how many words in this transfer? NextValue(num_words, uart_buffer[0:6]), #recv If( uart_buffer[6], NextState("RECV_1"), #send ).Else(NextState("SEND_1"), ), # handle if control message ).Else( # send it to the control manager spi_man.instruction.eq(uart_buffer), spi_man.valid_input.eq(1), # handle the command NextState("HANDLE_CONTROL"), )) self.op_fsm.act( "HANDLE_CONTROL", # invalidate the input spi_man.valid_input.eq(0), # return to idle NextState("IDLE"), ) self.op_fsm.act( "RECV_1", # needed from RECV_4 & RECV_5 NextValue(uart.tx_ack, 0), # done? If( num_words == 0, NextState("IDLE"), ).Else( # decrease num_words NextValue(num_words, num_words - 1), # keep going NextState("RECV_2"), )) self.op_fsm.act( "RECV_2", # if spi ready If( spi.rx_ready, # start rx operation NextValue(spi.rx_start, 1), # go to next NextState("RECV_3"), )) self.op_fsm.act( "RECV_3", # set rx_start back to zero NextValue(spi.rx_start, 0), # if spi ready If( spi.rx_data_ready, # get data from spi NextValue(spi_buffer, spi.rx_data), # ack the received data NextValue(spi.rx_ack, 1), # go to next NextState("RECV_4"), )) self.op_fsm.act( "RECV_4", # set rx_ack back to zero NextValue(spi.rx_ack, 0), # if uart ready to send data, send data by UART back. If( uart.tx_ready, # send data to uart input port. NextValue(uart.tx_data, spi_buffer[0:8]), # start tx NextValue(uart.tx_ack, 1), If( spi_man.word_length > 7, # go to next NextState("RECV_5_WAIT"), ).Else( #recv next word NextState("RECV_1"), ))) self.op_fsm.act( "RECV_5_WAIT", NextValue(uart.tx_ack, 0), NextState("RECV_5"), ) self.op_fsm.act( "RECV_5", # if uart ready to send data, send data by UART back. If( uart.tx_ready, # send data to uart input port. NextValue(uart.tx_data, spi_buffer[8:16]), # start tx NextValue(uart.tx_ack, 1), #recv next word NextState("RECV_1"), )) self.op_fsm.act( "SEND_1", # needed from SEND_4 NextValue(spi.tx_start, 0), # done? If( num_words == 0, NextState("IDLE"), ).Else( # decrease num_words NextValue(num_words, num_words - 1), # keep going NextState("SEND_2"), )) self.op_fsm.act( "SEND_2", # recv from UART If( uart.rx_ready, NextValue(spi_buffer[0:8], uart.rx_data), NextValue(uart.rx_ack, 1), If( spi_man.word_length > 7, # recv spi[8:16] NextState("WAIT_SEND_3"), ).Else( # send via spi NextState("SEND_4"), ))) self.op_fsm.act( "WAIT_SEND_3", NextValue(uart.rx_ack, 0), NextState("SEND_3"), ) self.op_fsm.act( "SEND_3", # recv from UART If( uart.rx_ready, NextValue(spi_buffer[8:16], uart.rx_data), NextValue(uart.rx_ack, 1), NextState("SEND_4"), )) self.op_fsm.act( "SEND_4", NextValue(uart.rx_ack, 0), If( spi.tx_ready, NextValue(spi.tx_data, spi_buffer), NextValue(spi.tx_start, 1), NextState("SEND_1"), ))
def led_off(self): """Turns status LED off.""" SPI.command(CMD_LEDOFF)
from creds import BING_KEY except ImportError: print( 'Get a key from https://www.microsoft.com/cognitive-services/en-us/speech-api and create creds.py with the key' ) sys.exit(-1) script_dir = os.path.dirname(os.path.realpath(__file__)) hi = os.path.join(script_dir, 'audio/hi.wav') thunder = os.path.join(script_dir, 'audio/thunder-01.wav') startlearning = os.path.join(script_dir, 'audio/startlearning.wav') stoplearning = os.path.join(script_dir, 'audio/stoplearning.wav') sendir = os.path.join(script_dir, 'audio/sendir.wav') spi = SPI() spi.write('offline\n') bing = BingVoice(BING_KEY) mission_completed = False awake = False pa = pyaudio.PyAudio() mic = Microphone(pa) player = Player(pa) spi.write('online\n') def handle_int(sig, frame):
def __init__(self): #setup device self.pullup = 0x00 self.spi = SPI(miso=22, mosi=23, clk=20, reset=38) self.lock= threading.Lock()
#!/usr/bin/env python3 import struct from spi import SPI from tqdm import tqdm spi = SPI(0) print("speed:", spi.get_speed()) spi.set_speed(8000000) print("speed:", spi.get_speed()) print("delay:", spi.get_delay()) spi.put(b"\x9e" + b"\x00" * 20) allret = [] for addr in tqdm(range(0, 0x1000000, 0x1000)): ret = spi.put(b"\x03" + struct.pack(">I", addr)[1:], fSelEnd=0) ret = spi.get(0x1000, fSelEnd=1) allret.append(ret) out = b''.join(allret) with open("dump", "wb") as f: f.write(out) del spi
""" Created on Tue May 22 11:04:44 2018 @author: anind """ from spi import SPI import numpy as np import os, random from PIL import Image import time import gdal import osr from math import isnan spi = SPI() spi.set_rolling_window_params( span=1, window_type=None, center=True) # Set distribution parameters spi.set_distribution_params(dist_type='gam') def use_spi(arr: np.array) -> np.array: data = spi.calculate(arr, starting_month=1) data = data.flatten() #Calculate and return 1d array return data
FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 CHUNK_DURATION_MS = 30 # supports 10, 20 and 30 (ms) PADDING_DURATION_MS = 1000 CHUNK_SIZE = int(RATE * CHUNK_DURATION_MS / 1000) CHUNK_BYTES = CHUNK_SIZE * 2 NUM_PADDING_CHUNKS = int(PADDING_DURATION_MS / CHUNK_DURATION_MS) NUM_WINDOW_CHUNKS = int(240 / CHUNK_DURATION_MS) vad = webrtcvad.Vad(2) bing = BingVoice(BING_KEY) apiai = Apiai(APIAI_TOKEN) mqtt = Mqtt() spi = SPI() pa = pyaudio.PyAudio() stream = pa.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, start=False, frames_per_buffer=CHUNK_SIZE) got_a_sentence = False leave = False got_trigger = False def handle_int(sig, chunk): global leave, got_a_sentence
#!/usr/bin/python from spi import SPI dev = SPI(miso=22, mosi=23, clk=20, reset=38) #dev.reset() while True: print dev.sendByte(0x50)
from core import Core from port import Ports from irq import IRQTable from timer import Timer from pins import Pins from spi import SPI from usart import USART converters=[ Core(), IRQTable(), Ports(), Timer(), Pins(), SPI(), USART() ] from os import listdir # for fn in listdir("atmel-xml/"): # if (fn.find(".xml")<0 # or fn.find("ATxmega")>=0 # or fn.find("AT89")>=0 # or fn.find("AT86")>=0 # or fn.find("ATtiny10")>=0 # or fn.find("ATtiny28")>=0 # <- has weird port logic. FIXME: support this! # or fn.find("HV")>=0 # 'smart battery devices' also have some weird port logic. # or fn.find("CAN")>=0 # CAN devices are not implemented either
class sensorUnit(): def __init__(self): self.__bus=SPI(3,1) self.__bus.msh=20000 def getLeftDistance(self): self.__bus.writebytes([0x0C]) return self.__bus.readbytes(1)[0] def getRightDistance(self): self.__bus.writebytes([0x0B]) return self.__bus.readbytes(1)[0] def getLineSensor(self,temp): if temp<0 or temp>10: raise SyntaxError("Linesensor value out of bounds") self.__bus.writebytes([temp]) return self.__bus.readbytes(1)[0] def getLeftMiddleSensor(self): self.__bus.writebytes([14]) return self.__bus.readbytes(1)[0] def getRightMiddleSensor(self): self.__bus.writebytes([15]) return self.__bus.readbytes(1)[0]