Example #1
0
def	ultrasound():
	
	Trigger = Pin('X3', Pin.OUT_PP)
	Echo = Pin('X4',Pin.IN)
	
	# Create a microseconds counter.
	micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
	micros.counter(0)
	start = 0
	end = 0
	
	# Send a 20usec pulse every 10ms
	while True:
		Trigger.high()
		pyb.udelay(20)
		Trigger.low()
		
		# Wait until pulse starts
		while Echo.value() == 0:   # do nothing
			start = micros.counter()	# mark time at rising edge
		
		# Wait until pulse goes low
		while Echo.value() == 1:   # do nothing
			end = micros.counter()		# mark time at falling edge
		
		# Duration echo pulse = end - start
		# Divide this by 2 to take account of round-trip
		# Speed of sound in air is 340 m/s or 29 us/cm
		# Distance in cm = (pulse_width)*0.5/29
		distance = int(((end - start) / 2) / 29)
		print('Distance: ', distance, ' cm')
		pyb.delay(500)
Example #2
0
def init(timer_id=2, nc_pin='Y3', gnd_pin='Y4', vcc_pin='Y1', data_pin='Y2'):
    global nc
    global gnd
    global vcc
    global data
    global micros
    global timer
    # Leave the pin unconnected
    if nc_pin is not None:
        nc = Pin(nc_pin)
        nc.init(Pin.OUT_OD)
        nc.high()
    # Make the pin work as GND
    if gnd_pin is not None:
        gnd = Pin(gnd_pin)
        gnd.init(Pin.OUT_PP)
        gnd.low()
    # Make the pin work as power supply
    if vcc_pin is not None:
        vcc = Pin(vcc_pin)
        vcc.init(Pin.OUT_PP)
        vcc.high()
    # Configure the pid for data communication
    data = Pin(data_pin)
    # Save the ID of the timer we are going to use
    timer = timer_id
    # setup the 1uS timer
    micros = pyb.Timer(timer, prescaler=83, period=0x3fffffff)  # 1MHz ~ 1uS
    # Prepare interrupt handler
    ExtInt(data, ExtInt.IRQ_FALLING, Pin.PULL_UP, None)
    ExtInt(data, ExtInt.IRQ_FALLING, Pin.PULL_UP, edge)
Example #3
0
    def start(self, speed, direction):
        """ method to start a motor
        Arguments:
          speed : speed of the motor 0-100 (as percentage of max)
          direction : CW or CCW, for clockwise or counterclockwise
        """

        PWMpin = Pin(self.PWMpin)
        DIRpin = Pin(self.DIRpin, Pin.OUT_PP)
        # DIR1 and DIR2 have to be opposite to move, toggle to change direction
        if direction in ('cw','CW','clockwise'):
            DIRpin.high()

        elif direction in ('ccw','CCW','counterclockwise'):
            DIRpin.low()

        else:
            raise ValueError('Please enter CW or CCW for direction.')

        # Start the motor
        if 0 <= speed <= 100:
            # self.PWMpin = Pin('X4')
            tim = Timer(self.timer_id, freq=1000)
            ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin)
            ch.pulse_width_percent(speed)
            # PWM.start(self.PWMpin, speed)
        else:
            raise ValueError("Please enter speed between 0 and 100")

        # set the status attributes
        self.isRunning = True
        self.currentDirection = direction
        self.currentSpeed = speed
Example #4
0
    def start(self, speed, direction):
        PWM_py_pin = Pin(self.PWMpin)
        DIR_py_pin = Pin(self.DIRpin, Pin.OUT_PP)

        tim = Timer(self.timer_id, freq=1000)
        ch = tim.channel(self.channel_id, Timer.PWM, pin=PWM_py_pin)

        if direction in ('cw', 'CW', 'clockwise'):
            DIR_py_pin.high()

        elif direction in ('ccw', 'CCW', 'counterclockwise'):
            DIR_py_pin.low()

        else:
            raise ValueError('Please enter CW or CCW')

        if 0 <= speed <= 100:
            ch.pulse_width_percent(speed)

        else:
            raise ValueError("Please enter a speed between 0 and 100")

        self.isRunning = True
        self.currentDirection = direction
        self.currentSpeed = speed
Example #5
0
    def start(self, speed, direction):
        PWM_py_pin = Pin(self.PWMpin)
        DIR_py_pin = Pin(self.DIRpin, Pin.OUT_PP)

        tim = Timer(self.timer_id, freq=1000)
        ch = tim.channel(self.channel_id, Timer.PWM, pin=PWM_py_pin)

        if direction in ('cw', 'CW', 'clockwise'):
            DIR_py_pin.high()

        elif direction in ('ccw', 'CCW', 'counterclockwise'):
            DIR_py_pin.low()

        else:
            raise ValueError('Please enter CW or CCW')

        if 0 <= speed <= 100:
            ch.pulse_width_percent(speed)

        else:
            raise ValueError("Please enter a speed between 0 and 100")

        self.isRunning        = True
        self.currentDirection = direction
        self.currentSpeed     = speed
class Relay(object):
  """Control a relay board with an output pin.  Set on to True to drive the relay pin low
     which turns the relay on."""

  def __init__( self, pin ) :
    """Pin may be a pin name or pyb.Pin object set for output."""

    if type(pin) == str:
      self._pin = Pin(pin, Pin.OUT_PP, Pin.PULL_DOWN)
    elif type(pin) == Pin:
      self._pin = pin
    else:
      raise Exception("pin must be pin name or pyb.Pin")

    self.on = False

  @property
  def on( self ) : return self._pin.value()

  @on.setter
  def on( self, value ) :
    if value:
      self._pin.low()
    else:
      self._pin.high()
class rs485_tmcl_interface(uart_tmcl_interface):
    def __init__(self,
                 port=4,
                 data_rate=115200,
                 host_id=2,
                 module_id=1,
                 debug=False):
        super().__init__(port, data_rate, host_id, module_id, debug)

        self.__dir = Pin(Pin.cpu.B1, Pin.OUT_PP)

    def _send(self, hostID, moduleID, data):
        buf = self.__dir.value()
        self.__dir.high()
        super()._send(hostID, moduleID, data)
        self.__dir.value(buf)

    def _recv(self, hostID, moduleID):
        buf = self.__dir.value()
        self.__dir.low()
        read = super()._recv(hostID, moduleID)
        self.__dir.value(buf)

        return read

    @staticmethod
    def available_ports():
        return set([4])
class Relay(object):
    """Control a relay board with an output pin.  Set on to True to drive the relay pin low
     which turns the relay on."""
    def __init__(self, pin):
        """Pin may be a pin name or pyb.Pin object set for output."""

        if type(pin) == str:
            self._pin = Pin(pin, Pin.OUT_PP, Pin.PULL_DOWN)
        elif type(pin) == Pin:
            self._pin = pin
        else:
            raise Exception("pin must be pin name or pyb.Pin")

        self.on = False

    @property
    def on(self):
        return self._pin.value()

    @on.setter
    def on(self, value):
        if value:
            self._pin.low()
        else:
            self._pin.high()
Example #9
0
 def _send_pulse(self):
     pin = Pin(self._pin, mode=Pin.OUT)
     pin.low()
     udelay(2)
     pin.high()
     udelay(10)
     pin.low()
     pin = Pin(self._pin, mode=Pin.IN)
 def read_temps(self):  #读取温度
     data = []
     j = 0
     N1 = Pin(self.PinName, Pin.OUT_PP)  #设置输出模式
     #N1=self.N1
     N1.low()  #拉低引脚
     time.sleep_ms(20)  #保持20ms(最少18ms)
     N1.high()  #拉高引脚
     time.sleep_us(30)  #保持30us(20~40us)
     #wait to response
     N1 = Pin(self.PinName, Pin.IN)  #设置输入模式
     while N1.value() == 1:  #等待温度传感器响应
         continue
     while N1.value() == 0:
         continue
     while N1.value() == 1:
         continue
     #get data
     while j < 40:  #通过引脚接收数据
         k = 0
         while N1.value() == 0:
             continue
         while N1.value() == 1:
             k += 1
             if k > 100: break
         if k < 3:
             data.append(0)
         else:
             data.append(1)
         j = j + 1
     print('Sensor is working')
     #print(k)
     j = 0
     #get temperature
     #利用接收的电平信号算出温湿度数值
     humidity_bit = data[0:7]  #0-7位湿度信息
     humidity_point_bit = data[8:15]  #8-15位湿度小数信息
     temperature_bit = data[16:23]  #16-23位温度信息
     temperature_point_bit = data[24:31]  #24-31位温度小数信息
     check_bit = data[32:39]  #32-39位校验信息
     humidity = 0
     humidity_point = 0
     temperature = 0
     temperature_point = 0
     check = 0
     for i in range(7):  #计算温湿度
         humidity += humidity_bit[i] * 2**(7 - i)
         humidity_point += humidity_point_bit[i] * 2**(7 - i)
         temperature += temperature_bit[i] * 2**(7 - i)
         temperature_point += temperature_point_bit[i] * 2**(7 - i)
         check += check_bit[i] * 2**(7 - i)
     tmp = humidity + humidity_point + temperature + temperature_point
     if check == tmp:  #检验正确,输出结果
         print('temperature is', temperature, 'wet is', humidity, '%')
     else:  #检验错误,输出数据结果
         print('SHUJUCUOWU', humidity, humidity_point, temperature,
               temperature_point, check)
     return str(temperature) + ',' + str(humidity)
Example #11
0
class ScopePin:
    def __init__(self, pin_name):
        self.pin = Pin(pin_name, Pin.OUT_PP)
        self.pin.low()

    def pulse(self, n=1):
        for i in range(n):
            self.pin.high()
            self.pin.low()
def tuuletus():
    p_tuuletin = Pin('Y8', Pin.OUT_PP)
    p_tuuletin.high()

    p_tuuletin1 = Pin('Y7', Pin.OUT_PP)
    p_tuuletin1.high()

    p_tuuletin2 = Pin('Y6', Pin.OUT_PP)
    p_tuuletin2.low()
Example #13
0
 def read_temps(self):
     data = []
     j = 0
     N1 = Pin(self.PinName, Pin.OUT_PP)
     N1.low()
     time.sleep(0.03)
     N1.high()
     #wait to response
     N1 = Pin(self.PinName, Pin.IN)
     while N1.value() == 1:
         continue
     while N1.value() == 0:
         continue
     while N1.value() == 1:
         continue
     #get data
     while j < 40:
         k = 0
         while N1.value() == 0:
             continue
         while N1.value() == 1:
             k += 1
             if k > 100:
                 break
         if k < 3:
             data.append(0)
         else:
             data.append(1)
         j = j + 1
     #print('Sensor is working')
     j = 0
     #get temperature
     humidity_bit = data[0:8]
     humidity_point_bit = data[8:16]
     temperature_bit = data[16:24]
     temperature_point_bit = data[24:32]
     check_bit = data[32:40]
     humidity = 0
     humidity_point = 0
     temperature = 0
     temperature_point = 0
     check = 0
     for i in range(8):
         humidity += humidity_bit[i] * 2**(7 - i)
         humidity_point += humidity_point_bit[i] * 2**(7 - i)
         temperature += temperature_bit[i] * 2**(7 - i)
         temperature_point += temperature_point_bit[i] * 2**(7 - i)
         check += check_bit[i] * 2**(7 - i)
     tmp = humidity + humidity_point + temperature + temperature_point
     if check == tmp:
         pass
         #print('temperature is',temperature,'wet is',humidity,'%')
     else:
         pass
         #print('SHUJUCUOWU',humidity,humidity_point,temperature,temperature_point,check)
     #return str(temperature)+','+str(humidity)
     return temperature, humidity
Example #14
0
    def read_temps(self):#读取温度
        data=[]
        j=0
        N1 = Pin(self.PinName, Pin.OUT_PP)#设置输出模式
        #N1=self.N1
        N1.low()#拉低引脚
        time.sleep_ms(20)#保持20ms(最少18ms)
        N1.high()#拉高引脚
		time.sleep_us(30)#保持30us(20~40us)
Example #15
0
def  drive_motor():
	A1 = Pin('Y9',Pin.OUT_PP)
	A2 = Pin('Y10',Pin.OUT_PP)
	A1.high()
	A2.low()
	motor = Pin('X1')
	tim = Timer(2, freq = 1000)
	ch = tim.channel(1, Timer.PWM, pin = motor)
	while True:
		ch.pulse_width_percent(50)
Example #16
0
class Button:

    def __init__(self, power_supply_pin, control_pin):
        self.pin = control_pin
        self.power_supply_pin = power_supply_pin
        self.operation = Pin(control_pin, Pin.IN, Pin.PULL_UP)
        self.power = Pin(power_supply_pin, Pin.OUT_PP)
        self.power.high()

    def value(self):
        return self.operation.value()
Example #17
0
class vactrolControl:
    """simple class providing on/off functionality of a vactrol
    controlled by a pyboard bin.
    """
    def __init__(self, vactrolPin):
        self.vactrol = Pin(vactrolPin, Pin.OUT_PP)
        self.vactrol.low()

    def on(self):
        self.vactrol.high()

    def off(self):
        self.vactrol.low()
Example #18
0
def PCA8574_tests():

    try:
        # Initialize I2C 1
        i2c = I2C(I2C_BUS1, I2C.MASTER, baudrate=100000)
        # returns list of slave addresses
        I2C_List = i2c.scan()

        if I2C_List:
            print("I2C Slaves Present =", I2C_List)
        else:
            print("There are no I2C devices present! Exiting application.")
            sys.exit(0)
    except Exception as e:
        print(e)

    p_out = Pin('PD14', Pin.OUT_PP)
    p_out.high()

    # Test that we can initialize the object
    try:
        PCA8574_Object = PCA8574_IO(i2c, I2C_List[0])
        print("PCA8574, Object Creation, Passed")
    except:
        print("PCA8574, Object Creation, Failed")

    try:
        PCA8574_Object1 = PCA8574_IO(i2c, 256)
        print("PCA8574, I2C Address Out-of-Bounds, Failed")
    except:
        print("PCA8574, I2C Address Out-of-Bounds, Passed")

    #######
    # Test reading the switch
    #######

    # Set the switch to not pressed
    p_out.high()
    Result = PCA8574_Object.Read()
    if Result is 0xFF:
        print("PCA8574, LSB I/O - High, Passed")
    else:
        print("PCA8574, LSB I/O - High, Failed,", Result)

    # Set the switch to pressed
    p_out.low()
    Result = PCA8574_Object.Read()
    if Result is 0xFE:
        print("PCA8574, LSB I/O - Low, Passed")
    else:
        print("PCA8574, LSB I/O - Low, Failed,", Result)
Example #19
0
def motor_control():
	# define various I/O pins for ADC
	adc_1 = ADC(Pin('X19'))
	adc_2 = ADC(Pin('X20'))

	# set up motor with PWM and timer control
	A1 = Pin('Y9',Pin.OUT_PP)
	A2 = Pin('Y10',Pin.OUT_PP)
	pwm_out = Pin('X1')
	tim = Timer(2, freq = 1000)
	motor = tim.channel(1, Timer.PWM, pin = pwm_out)
	
	A1.high()	# motor in brake position
	A2.high()

	# Calibrate the neutral position for joysticks
	MID = adc_1.read()		# read the ADC 1 value now to calibrate
	DEADZONE = 10	# middle position when not moving
	
	# Use joystick to control forward/backward and speed
	while True:				# loop forever until CTRL-C
		speed = int(100*(adc_1.read()-MID)/MID)
		if (speed >= DEADZONE):		# forward
			A1.high()
			A2.low()
			motor.pulse_width_percent(speed)
		elif (speed <= -DEADZONE):
			A1.low()		# backward
			A2.high()
			motor.pulse_width_percent(-speed)
		else:
			A1.low()		# stop
			A2.low()		
Example #20
0
def	flash_LEDs():

	rLED = Pin('Y9', Pin.OUT_PP)
	bLED = Pin('Y10',Pin.OUT_PP)

	while True:
		rLED.high()
		pyb.delay(250)
		bLED.high()
		pyb.delay(250)
		rLED.low()
		pyb.delay(250)
		bLED.low()
		pyb.delay(250)
Example #21
0
class Outctl():
    def __init__(self):
        self.relay = Pin('Y7', Pin.OUT_PP)
        self.alarm = Pin('Y8', Pin.OUT_PP)
        self.led1 = Pin('Y3', Pin.OUT_PP)
        self.led2 = Pin('Y4', Pin.OUT_PP)

    def high(self, str):
        if str == 'relay':
            self.relay.high()
        elif str == 'alarm':
            self.alarm.high()
        elif str == 'led1':
            self.led1.high()
        elif str == 'led2':
            self.led2.high()
        else:
            pass

    def low(self, str):
        if str == 'relay':
            self.relay.low()
        elif str == 'alarm':
            self.alarm.low()
        elif str == 'led1':
            self.led1.low()
        elif str == 'led2':
            self.led2.low()
        else:
            pass
Example #22
0
class MAX14914:
    def __init__(self,
                 do_set_pin=Pin.cpu.A5,
                 do_pp_pin=Pin.cpu.A6,
                 di_ena_pin=Pin.cpu.A7,
                 dido_lvl_pin=Pin.cpu.C0,
                 fault_pin=Pin.cpu.C1,
                 ov_vdd_pin=Pin.cpu.A4):
        self.DO_SET = Pin(do_set_pin, Pin.OUT_PP)
        self.DO_PP = Pin(do_pp_pin, Pin.OUT_PP)
        self.DI_ENA = Pin(di_ena_pin, Pin.OUT_PP)

        self.DIDO_LVL = Pin(dido_lvl_pin, Pin.IN)
        self.FAULT = Pin(fault_pin, Pin.IN)
        self.OV_VDD = Pin(ov_vdd_pin, Pin.IN)

    def setIOMode(self, mode):
        ''' set input mode D0 = 0 or DI = 1'''
        if (mode == "0"):
            self.DI_ENA.low()
        elif (mode == "1"):
            self.DI_ENA.high()

    def setPPMode(self, mode):
        ''' set PP mode.
            In DO mode, set PP high (1) to
            enable push-pull mode operation of the DO driver. In DI mode, set
            PP low(0) for IEC Type 1/3 input characteristics and set high for
            Type 2 input characteristics.
            '''
        if (mode == 0):
            self.DO_PP.low()
        elif (mode == 1):
            self.DO_PP.high()

    def setDO(self, state):
        '''set Digital Out'''
        self.DO_SET.value(state)

    def getDIDO_LVL(self):
        '''get level of DOI-PIN'''
        return self.DIDO_LVL.value()

    def getFault(self):
        '''getFault'''
        return not self.FAULT.value()

    def getOV_VDD(self):
        '''reports an overvoltage detection'''
        return self.OV_VDD.value()
class SpiMaster:
    def __init__(self, bus=1, baudrate=328125, polarity=0, phase=0, ss='A4'):
        self.ss = Pin(ss, Pin.OUT)
        self.ss.high()
        self.spi = SPI(bus, SPI.MASTER, baudrate=baudrate, polarity=polarity,
                       phase=phase)
        self.msgbuf = bytearray(32)
        self.status = bytearray(4)

    def write_status(self, status):
        self.ss.low()
        self.spi.send(0x01)
        self.spi.send(status & 0xFF)
        self.spi.send((status >> 8) & 0xFF)
        self.spi.send((status >> 16) & 0xFF)
        self.spi.send((status >> 24) & 0xFF)
        self.ss.high()

    def read_status(self):
        self.ss.low()
        self.spi.send(0x04)
        self.spi.recv(self.status)
        self.ss.high()
        return (
            self.status[0] |
            (self.status[1] << 8) |
            (self.status[2] << 16) |
            (self.status[3] << 24)
        )

    def read_data(self):
        self.ss.low()
        self.spi.send(0x03)
        self.spi.send(0x00)
        self.spi.recv(self.msgbuf)
        self.ss.high()
        return self.msgbuf

    def read_msg(self, encoding='utf-8'):
        return bytes(self.read_data()).strip('\0').decode(encoding)

    def write_data(self, data):
        self.msgbuf[:] = data[:32] + b'\0' * (32 - len(data[:32]))
        self.ss.low()
        self.spi.send(0x02)
        self.spi.send(0x00)
        self.spi.send(self.msgbuf)
        self.ss.high()
class spi_ic_interface(object):
    def __init__(self,
                 spi=SPI(1, SPI.MASTER, baudrate=10000, polarity=1, phase=1),
                 cs=Pin.cpu.A4):
        self.__spi = spi
        self.__cs = Pin(cs, Pin.OUT_PP)

    def send(self, buf):
        self.__cs.low()
        self.__spi.send(buf)
        self.__cs.high()

    def send_recv(self, buf_send, buf_recv):
        self.__cs.low()
        self.__spi.send_recv(buf_send, buf_recv)
        self.__cs.high()
Example #25
0
class SpiMaster:
    def __init__(self, bus=1, baudrate=328125, polarity=0, phase=0, ss='A4'):
        self.ss = Pin(ss, Pin.OUT)
        self.ss.high()
        self.spi = SPI(bus,
                       SPI.MASTER,
                       baudrate=baudrate,
                       polarity=polarity,
                       phase=phase)
        self.msgbuf = bytearray(32)
        self.status = bytearray(4)

    def write_status(self, status):
        self.ss.low()
        self.spi.send(0x01)
        self.spi.send(status & 0xFF)
        self.spi.send((status >> 8) & 0xFF)
        self.spi.send((status >> 16) & 0xFF)
        self.spi.send((status >> 24) & 0xFF)
        self.ss.high()

    def read_status(self):
        self.ss.low()
        self.spi.send(0x04)
        self.spi.recv(self.status)
        self.ss.high()
        return (self.status[0] | (self.status[1] << 8) | (self.status[2] << 16)
                | (self.status[3] << 24))

    def read_data(self):
        self.ss.low()
        self.spi.send(0x03)
        self.spi.send(0x00)
        self.spi.recv(self.msgbuf)
        self.ss.high()
        return self.msgbuf

    def read_msg(self, encoding='utf-8'):
        return bytes(self.read_data()).strip('\0').decode(encoding)

    def write_data(self, data):
        self.msgbuf[:] = data[:32] + b'\0' * (32 - len(data[:32]))
        self.ss.low()
        self.spi.send(0x02)
        self.spi.send(0x00)
        self.spi.send(self.msgbuf)
        self.ss.high()
Example #26
0
class UltraSonicMeter(object):

    def __init__(self):
        self.tmp = self.time = 0
        self.cnt = 0
        self.fr = 0
        self.trig = Pin('X12', Pin.OUT_PP, Pin.PULL_NONE)
        echoR = Pin('X1', Pin.IN, Pin.PULL_NONE)
        echoF = Pin('X2', Pin.IN, Pin.PULL_NONE)
        self.micros = pyb.Timer(5, prescaler=83, period=0x3fffffff)
        self.timer = Timer(2, freq=1000)
        self.timer.period(3600)
        self.timer.prescaler(1375)
        self.timer.callback(lambda e: self.run_trig())
        extR = ExtInt(echoR, ExtInt.IRQ_RISING, Pin.PULL_NONE, self.start_count)
        extF = ExtInt(echoF, ExtInt.IRQ_FALLING, Pin.PULL_NONE, self.read_dist)

    def run_trig(self):
        self.trig.high()
        pyb.udelay(1)
        self.trig.low()

    def start_count(self, line):
        self.micros.counter(0)
        self.time = self.micros.counter()
        self.timer.counter(0)

    def read_dist(self, line):
        end = self.micros.counter()
        micros = end-self.time
        distP1 = micros//5
        distP2 = micros//6
        distP3 = (distP1-distP2)//10*2
        dist = distP2+distP3

        if dist != 0:
            self.cnt += 1
            self.fr += dist

        if self.cnt == 15:
            tmp = self.tmp
            dist = self.fr//self.cnt
            if tmp != dist:
                print(dist, 'mm')
                self.tmp = dist
            self.cnt = 0
            self.fr  = 0
Example #27
0
class MAX14914:
    def __init__(self,
                 do_set_pin=Pin.cpu.A5,
                 do_pp_pin=Pin.cpu.A6,
                 di_ena_pin=Pin.cpu.A7,
                 dido_lvl_pin=Pin.cpu.C0,
                 fault_pin=Pin.cpu.C1,
                 ov_vdd_pin=Pin.cpu.A4):
        self.DO_SET = Pin(do_set_pin, Pin.OUT_PP)
        self.DO_PP = Pin(do_pp_pin, Pin.OUT_PP)
        self.DI_ENA = Pin(di_ena_pin, Pin.OUT_PP)

        self.DIDO_LVL = Pin(dido_lvl_pin, Pin.IN)
        self.FAULT = Pin(fault_pin, Pin.IN)
        self.OV_VDD = Pin(ov_vdd_pin, Pin.IN)

    def setIOMode(self, mode):
        ''' set input mode D0 = 0 or DI = 1'''
        if (mode == "0"):
            self.DI_ENA.low()
        elif (mode == "1"):
            self.DI_ENA.high()

    #DI_ENA = HIGH
    def setPPMode(self, mode):
        ''' set input mode D0 or DI'''
        if (mode == 0):
            self.DO_PP.low()
        elif (mode == 1):
            self.DO_PP.high()

    def setDO(self, state):
        '''set Digital Out'''
        self.DO_SET.value(state)

    def getDIDO_LVL(self):
        '''get level of DOI-PIN'''
        return self.DIDO_LVL.value()

    def getFault(self):
        '''getFault'''
        return not self.FAULT.value()

    def getOV_VDD(self):
        '''reports an overvoltage detection'''
        return self.OV_VDD.value()
Example #28
0
	def __init__(self):
		self.dbg = Pin("X9", Pin.OUT_PP)
		self.dbg.low()
		self.spi = SPI(2, SPI.MASTER, baudrate=5250000)
		ss = Pin(self.CS_TFT, Pin.OUT_PP)
		ss.low()
		self.dc = Pin(self.DC, Pin.OUT_PP)
		self.dc.low()
		self.DC_flag = False
		cs_sd = Pin(self.CS_SD, Pin.OUT_PP)
		cs_sd.high()
		self.lite = Pin(self.LITE, Pin.OUT_PP)
		self.lite.high()
		reset = Pin(self.RST, Pin.OUT_PP)
		reset.low()
		delay(2)
		reset.high()
		delay(200)
class EngineWheel:
    def __init__(self, pin1, pin2):
        self.pin1 = Pin(pin1, Pin.OUT_PP)
        self.pin2 = Pin(pin2, Pin.OUT_PP)

    def move(self):
        self.pin1.high()
        self.pin2.low()

    def stop(self):
        # self.pin1.high()
        # self.pin2.high()

        self.pin1.low()
        self.pin2.low()

    def back(self):
        self.pin1.low()
        self.pin2.high()
Example #30
0
class Motor:
    def __init__(self, pinA, pinB):
        self._a = Pin(pinA, Pin.OUT_PP) #todo: check motor driver pins for internal pull resistors. or use pyboard pin pulling and open drain?
        self._b = Pin(pinB, Pin.OUT_PP)
        self.stop()

    # defaults to connect both terminals to GND, but can override to VCC
    def stop(self, val = False):
        self._a.value(val)
        self._b.value(val)

    def drive(self, direction):
        if direction > 0:
            self._a.high()
            self._b.low()
        elif direction == 0:
            self.stop()
        elif direction < 0:
            self._a.low()
            self._b.high()
Example #31
0
    def __init__(self,
                 pin_cs=Pin.cpu.C0,
                 spi=1,
                 pin_fltr=Pin.cpu.A13,
                 pin_cmd=Pin.cpu.C1):
        FLTR = Pin(pin_fltr, Pin.OUT_PP)
        CMND = Pin(pin_cmd, Pin.OUT_PP)
        FLTR.high()
        CMND.high()
        self.__SPI = spi_ic_interface(spi=SPI(spi,
                                              SPI.MASTER,
                                              baudrate=5000,
                                              polarity=0,
                                              phase=0),
                                      cs=pin_cs)

        self.outputs = 0x00
        buf = self.build_byte_array(self.MAX14912_SET_OUT_STATE_CMD,
                                    "00000000")
        self.__SPI.send_recv(buf, buf)
def init(timer_id=2, data_pin='Y2', the_dhttype='DHT22'):
    global _dataDHT
    global micros
    global timer
    global dhttype
    
    if (the_dhttype == 'DHT11'):
        dhttype = 0
    else:
        dhttype = 1
    # Configure the pid for data communication
    _dataDHT = Pin(data_pin)
    # Save the ID of the timer we are going to use
    _dataDHT = timer_id
    # setup the 1uS timer
    micros = pyb.Timer(timer, prescaler=83, period=0x3fffffff)  # 1MHz ~ 1uS
    # Prepare interrupt handler
    ExtInt(_dataDHT, ExtInt.IRQ_FALLING, Pin.PULL_UP, None)
    ExtInt(_dataDHT, ExtInt.IRQ_FALLING, Pin.PULL_UP, _interuptHandler)
    _dataDHT.high()
    pyb.delay(250)
Example #33
0
def pins_test():
    i2c = I2C(1, I2C.MASTER)
    spi = SPI(2, SPI.MASTER)
    uart = UART(3, 9600)
    servo = Servo(1)
    adc = ADC(Pin.board.X3)
    dac = DAC(1)
    pin = Pin('X4', mode=Pin.AF_PP, af=Pin.AF3_TIM9)
    pin = Pin('Y1', mode=Pin.AF_OD, af=3)
    pin = Pin('Y2', mode=Pin.OUT_PP)
    pin = Pin('Y3', mode=Pin.OUT_OD, pull=Pin.PULL_UP)
    pin.high()
    pin = Pin('Y4', mode=Pin.OUT_OD, pull=Pin.PULL_DOWN)
    pin.high()
    pin = Pin('X18', mode=Pin.IN, pull=Pin.PULL_NONE)
    pin = Pin('X19', mode=Pin.IN, pull=Pin.PULL_UP)
    pin = Pin('X20', mode=Pin.IN, pull=Pin.PULL_DOWN)
    print('===== output of pins() =====')
    pins()
    print('===== output of af() =====')
    af()
Example #34
0
def pins_test():
    i2c = I2C(1, I2C.MASTER)
    spi = SPI(2, SPI.MASTER)
    uart = UART(3, 9600)
    servo = Servo(1)
    adc = ADC(Pin.board.X3)
    dac = DAC(1)
    pin = Pin('X4', mode=Pin.AF_PP, af=Pin.AF3_TIM9)
    pin = Pin('Y1', mode=Pin.AF_OD, af=3)
    pin = Pin('Y2', mode=Pin.OUT_PP)
    pin = Pin('Y3', mode=Pin.OUT_OD, pull=Pin.PULL_UP)
    pin.high()
    pin = Pin('Y4', mode=Pin.OUT_OD, pull=Pin.PULL_DOWN)
    pin.high()
    pin = Pin('X18', mode=Pin.IN, pull=Pin.PULL_NONE)
    pin = Pin('X19', mode=Pin.IN, pull=Pin.PULL_UP)
    pin = Pin('X20', mode=Pin.IN, pull=Pin.PULL_DOWN)
    print('===== output of pins() =====')
    pins()
    print('===== output of af() =====')
    af()
Example #35
0
class MotorDriver:
    def __init__(self, a, b, p, c, d, q, e):
        self._left = MotorPWM(a, b, p)
        self._right = MotorPWM(c, d, q)
        self._standby = Pin(e, Pin.OUT_PP)
        self._standby.high()

    # Automatically enables driver when setting speed
    def drive(self, left, right, enable = True):
        pass

    def driveL(self, speed, enable = True):
        pass

    def driveR(self, speed, enable = True):
        pass

    def stop(self):
        pass

    def stopL(self):
        pass

    def stopR(self):
        pass

    def freewheel(self):
        pass

    def freewheelL(self):
        pass

    def freewheelR(self):
        pass

    def enable(self):
        self._standby.low()

    def disable(self):
        self._standby.high()
Example #36
0
class Motor:
    def __init__(self, out1, out2, pwm, chan):
        self.o1 = Pin(out1, Pin.OUT_PP)
        self.o2 = Pin(out2, Pin.OUT_PP)
        self.pwm = Pin(pwm)
        self.ch = tim.channel(chan, Timer.PWM, pin=self.pwm)
        self.speed = 50

    def forward(self):
        self.o1.high()
        self.o2.low()
        self.ch.pulse_width_percent(self.speed)

    def stop(self):
        self.o1.low()
        self.o2.low()
        self.ch.pulse_width_percent(0)

    def backward(self):
        self.o1.low()
        self.o2.high()
        self.ch.pulse_width_percent(self.speed)
Example #37
0
class LIS302DL:
    def __init__(self):
        self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE)
        self.cs_pin.high()
        self.spi = SPI(1,
                       SPI.MASTER,
                       baudrate=328125,
                       polarity=0,
                       phase=1,
                       bits=8)

    def rd(self, addr, nbytes):
        if nbytes > 1:
            addr |= READWRITE_CMD | MULTIPLEBYTE_CMD
        else:
            addr |= READWRITE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        buf = self.spi.send_recv(bytearray(nbytes *
                                           [0]))  # read data, MSB first
        self.cs_pin.high()
        return buf

    def wr(self, addr, buf):
        if len(buf) > 1:
            addr |= MULTIPLEBYTE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        for b in buf:
            self.spi.send(b)
        self.cs_pin.high()

    def read_id(self):
        return self.rd(LIS302DL_WHO_AM_I_ADDR, 1)

    def init(self, init_param=0x47, filter_param=0x2D):
        self.wr(LIS302DL_CTRL_REG1_ADDR, bytearray([init_param]))
        self.wr(LIS302DL_CTRL_REG2_ADDR, bytearray([filter_param]))

    def getx(self):
        buf = (self.rd(0x29, 1)[0]) - 1
        if buf > 127:
            return ((256 - buf) * (-1)) / 5.81
        else:
            return buf / 5.81

    def gety(self):
        buf = (self.rd(0x2B, 1)[0]) - 4
        if buf > 127:
            return ((256 - buf) * (-1)) / 5.81
        else:
            return buf / 5.81

    def getz(self):
        buf = (self.rd(0x2D, 1)[0]) + 8
        if buf > 127:
            return ((256 - buf) * (-1)) / 5.81
        else:
            return buf / 5.81
Example #38
0
class DriveMotor:

    def __init__(self, pwmPin, dirPin1, dirPin2,timer, timerCh):
        self.pin = Pin(pwmPin)
        self.dirPin1 = Pin(dirPin1, Pin.OUT_PP)
        self.dirPin2 = Pin(dirPin2, Pin.OUT_PP)
        self.tim = Timer(timer, freq = 25000)
        self.ch = self.tim.channel(timerCh, Timer.PWM, pin = self.pin)
      
        
    def drive(self, dutyCycle, direction):
        if direction == 'forward':
            self.dirPin1.high()
            self.dirPin2.low()
        elif direction == 'reverse':
            self.dirPin1.low()
            self.dirPin2.high()
        elif direction == 'stop':
            self.dirPin1.low()
            self.dirPin2.low()
        self.ch.pulse_width_percent(dutyCycle)
        
Example #39
0
class STAccel:
    def __init__(self):
        self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE)
        self.cs_pin.high()
        self.spi = SPI(1, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8)

        self.who_am_i = self.read_id()

        if self.who_am_i == LIS302DL_WHO_AM_I_VAL:
            self.write_bytes(LIS302DL_CTRL_REG1_ADDR, bytearray([LIS302DL_CONF]))
            self.sensitivity = 18
        elif self.who_am_i == LIS3DSH_WHO_AM_I_VAL:
            self.write_bytes(LIS3DSH_CTRL_REG4_ADDR, bytearray([LIS3DSH_CTRL_REG4_CONF]))
            self.write_bytes(LIS3DSH_CTRL_REG5_ADDR, bytearray([LIS3DSH_CTRL_REG5_CONF]))
            self.sensitivity = 0.06 * 256
        else:
            raise Exception('LIS302DL or LIS3DSH accelerometer not present')

    def convert_raw_to_g(self, x):
        if x & 0x80:
            x = x - 256
        return x * self.sensitivity / 1000

    def read_bytes(self, addr, nbytes):
        if nbytes > 1:
            addr |= READWRITE_CMD | MULTIPLEBYTE_CMD
        else:
            addr |= READWRITE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        #buf = self.spi.send_recv(bytearray(nbytes * [0])) # read data, MSB first
        buf = self.spi.recv(nbytes)
        self.cs_pin.high()
        return buf

    def write_bytes(self, addr, buf):
        if len(buf) > 1:
            addr |= MULTIPLEBYTE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        for b in buf:
            self.spi.send(b)
        self.cs_pin.high()

    def read_id(self):
        return self.read_bytes(WHO_AM_I_ADDR, 1)[0]

    def x(self):
        return self.convert_raw_to_g(self.read_bytes(OUT_X_ADDR, 1)[0])

    def y(self):
        return self.convert_raw_to_g(self.read_bytes(OUT_Y_ADDR, 1)[0])

    def z(self):
        return self.convert_raw_to_g(self.read_bytes(OUT_Z_ADDR, 1)[0])

    def xyz(self):
        return (self.x(), self.y(), self.z())
Example #40
0
class IgnitionModule(object):
    ignited = False
    ign_point = 0

    def __init__(self, pin="X5", ignition_length=500):
        self.pin = Pin(pin, Pin.OUT_PP)
        self.ignition_length = ignition_length
        self.pin.low()

    def ignite(self, ign_point=0):
        self.ignited = False
        self.ign_point = ign_point

    def update(self, round_start):
        if not self.ignited:
            while elapsed_micros(round_start) < self.ign_point:
                self.pin.low()
            self.pin.high()
            udelay(self.ignition_length)
            self.pin.low()
            self.ignited = True
        else:
            self.pin.low()
def  remote():

	#initialise UART communication
	uart = UART(6)
	uart.init(9600, bits=8, parity = None, stop = 2)

	# define various I/O pins for ADC
	adc_1 = ADC(Pin('X19'))
	adc_2 = ADC(Pin('X20'))

	# set up motor with PWM and timer control
	A1 = Pin('Y9',Pin.OUT_PP)
	A2 = Pin('Y10',Pin.OUT_PP)
	pwm_out = Pin('X1')
	tim = Timer(2, freq = 1000)
	motor = tim.channel(1, Timer.PWM, pin = pwm_out)

	# Motor in idle state
	A1.high()	
	A2.high()	
	speed = 0
	DEADZONE = 5

	# Use keypad U and D keys to control speed
	while True:				# loop forever until CTRL-C
		while (uart.any()!=10):    #wait we get 10 chars
			n = uart.any()
		command = uart.read(10)
		if command[2]==ord('5'):
			if speed < 96:
				speed = speed + 5
				print(speed)
		elif command[2]==ord('6'):
			if speed > - 96:
				speed = speed - 5
				print(speed)
		if (speed >= DEADZONE):		# forward
			A1.high()
			A2.low()
			motor.pulse_width_percent(speed)
		elif (speed <= -DEADZONE):
			A1.low()		# backward
			A2.high()
			motor.pulse_width_percent(-speed)
		else:
			A1.low()		# idle
			A2.low()		
Example #42
0
    def start(self, speed, direction):
        """ method to start a motor
        Arguments:
          speed : speed of the motor 0-100 (as percentage of max)
          direction : CW or CCW, for clockwise or counterclockwise
        """

        PWMpin = Pin(self.PWMpin)
        DIRpin = Pin(self.DIRpin, Pin.OUT_PP)
        # DIR1 and DIR2 have to be opposite to move, toggle to change direction
        if direction in ('cw','CW','clockwise'):
            DIRpin.high()

        elif direction in ('ccw','CCW','counterclockwise'):
            DIRpin.low()

        else:
            raise ValueError('Please enter CW or CCW for direction.')

        # Start the motor
        if 0 <= speed <= 100:
            # self.PWMpin = Pin('X4')
            tim = Timer(self.timer_id, freq=1000)
            ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin)
            ch.pulse_width_percent(speed)
            # PWM.start(self.PWMpin, speed)
        else:
            raise ValueError("Please enter speed between 0 and 100")

        # set the status attributes
        self.isRunning = True
        self.currentDirection = direction
        self.currentSpeed = speed
        while self.isRunning:
            print("\nMotorA =", enc_timer.counter())
            print("\nMotorB =", enc_timer_1.counter())
Example #43
0
def port_init():
	""" Setup and Init Pins used in scan_keys; GPIOC used. """

	# Rows (Pull-ups inverted logic)
	pin0 = Pin("C0", Pin.IN, Pin.PULL_UP)       # C0–C3 inputs for reading 4 rows from keypad (inverted logic)
	pin1 = Pin("C1", Pin.IN, Pin.PULL_UP)
	pin2 = Pin("C2", Pin.IN, Pin.PULL_UP)
	pin3 = Pin("C3", Pin.IN, Pin.PULL_UP)

	# Columns (One column active (low) at the time) Open drain allows threading (OR-function without diodes)
	pin4 = Pin("C4", Pin.OUT_OD, Pin.PULL_UP)   # C4–C6 outputs for driving columns low one at the time
	pin5 = Pin("C5", Pin.OUT_OD, Pin.PULL_UP)
	pin6 = Pin("C6", Pin.OUT_OD, Pin.PULL_UP)
	pin7 = Pin("C7", Pin.OUT_PP)                # C7 used for timimg/debug: set low while scanning

	pin4.high()
	pin5.high()
	pin6.high()
	pin7.high()
class Motor(  ):
  """Control a motor connected to the L298N Dual motor controller."""

  def __init__( self, forward, backward, speed ) :
    """forward pin name, backward pin name, speed = (pin name, timer#)
       Need to make sure the given timer # is associated with the speed
       pin or an exception will be raised.  The speed pin must support
       PWM."""
    self._forward = Pin(forward, Pin.OUT_PP)
    self._backward = Pin(backward, Pin.OUT_PP)
    self._speedControl = PWM(speed[0], speed[1])
    self._speed = 0

  @property
  def speed( self ) : return self._speed

  @speed.setter
  def speed( self, value ) :
    self._speed = value
    if (value == 0):
      self._forward.low()
      self._backward.low()
    elif (value < 0):
      self._forward.low()
      self._backward.high()
    else:
      self._forward.high()
      self._backward.low()

    self._speedControl.pulse_width_percent = min(100, abs(value))

  def brake( self ) :
    """ Brake the motor by sending power both directions. """
    self._forward.high()
    self._backward.high()
    self._speedControl.pulse_width_percent = 100
    delay(1000)
    self.speed = 0
Example #45
0
class STAccel:
    def __init__(self):
        self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE)
        self.cs_pin.high()
        self.spi = SPI(1, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8)
        self.write_bytes(LIS302DL_CTRL_REG1_ADDR, bytearray([LIS302DL_CONF]))
        if self.read_id() != LIS302DL_WHO_AM_I_VAL:
            raise Exception('LIS302DL accelerometer not present')

    def read_bytes(self, addr, nbytes):
        if nbytes > 1:
            addr |= READWRITE_CMD | MULTIPLEBYTE_CMD
        else:
            addr |= READWRITE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        #buf = self.spi.send_recv(bytearray(nbytes * [0])) # read data, MSB first
        buf = self.spi.recv(nbytes)
        self.cs_pin.high()
        return buf

    def write_bytes(self, addr, buf):
        if len(buf) > 1:
            addr |= MULTIPLEBYTE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        for b in buf:
            self.spi.send(b)
        self.cs_pin.high()

    def read_id(self):
        return self.read_bytes(LIS302DL_WHO_AM_I_ADDR, 1)[0]

    def x(self):
        return convert_raw_to_g(self.read_bytes(LIS302DL_OUT_X, 1)[0])

    def y(self):
        return convert_raw_to_g(self.read_bytes(LIS302DL_OUT_Y, 1)[0])

    def z(self):
        return convert_raw_to_g(self.read_bytes(LIS302DL_OUT_Z, 1)[0])

    def xyz(self):
        val = self.read_bytes(LIS302DL_OUT_X, 5)
        return [convert_raw_to_g(val[0]),
                convert_raw_to_g(val[2]),
                convert_raw_to_g(val[4])]
Example #46
0
class STAccel:
    def __init__(self):
        self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE)
        self.cs_pin.high()
        self.spi = SPI(1, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8)
        self.wr(LIS302DL_CTRL_REG1_ADDR, bytearray([LIS302DL_CONF]))

    def rd(self, addr, nbytes):
        if nbytes > 1:
            addr |= READWRITE_CMD | MULTIPLEBYTE_CMD
        else:
            addr |= READWRITE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        buf = self.spi.send_recv(bytearray(nbytes * [0])) # read data, MSB first
        self.cs_pin.high()
        return buf

    def wr(self, addr, buf):
        if len(buf) > 1:
            addr |= MULTIPLEBYTE_CMD
        self.cs_pin.low()
        self.spi.send(addr)
        for b in buf:
            self.spi.send(b)
        self.cs_pin.high()

    def read_id(self):
        return self.rd(LIS302DL_WHO_AM_I_ADDR, 1)

    def get_xyz(self):
        val = self.rd(LIS302DL_OUT_X, 5)
        x = signed8(val[0]) * 18.0 / 1000
        y = signed8(val[2]) * 18.0 / 1000
        z = signed8(val[4]) * 18.0 / 1000
        return [x, y, z]
Example #47
0
class SPIMgr():
    """
    This class provides an interface to the hardware level SPI object which
    it encapsulates as a member. 
    When creating an instance you must provide the pyboard side and 
    the latch pin's name, eg.
    >>> from spiMgr import SPIMgr
    >>> from state import State
    >>> s = SPIMgr(State.spiOnX,State.spiLatchPinName)
    >>> print(s)
    SPIMgr:
    SPI:
	BoardSide:	1
	MasterOrSlave:	Master
    STCP:
    Pin:
	LatchPin:	X5
	PinOut:	OUT_PP
	Value:	0
    ++
    The class only provides one method: update(bitArray).
    This method is called with an array of ints representing the 
    bits to be set to one via an SPI call. The process is
    1. set the latch pin LOW
    2. send the bits, int by int
    3. set the latch pin to high
    Note that when doing Off-board tests, the 'send' message will 
    appear twice.
    usage:
    >>> s.update([0,1,2,4,8,16])
    Pin:
	LatchPin:	X5
	PinOut:	OUT_PP
	Value:	0
	set: LOW
    Simulated: send:	0b0
    send:	0b0
    Simulated: send:	0b1
    send:	0b1
    Simulated: send:	0b10
    send:	0b10
    Simulated: send:	0b100
    send:	0b100
    Simulated: send:	0b1000
    send:	0b1000
    Simulated: send:	0b10000
    send:	0b10000
    Pin:
	LatchPin:	X5
	PinOut:	OUT_PP
	Value:	1
	set: HIGH
    """
    def __init__(self,spiOnX,latchPin):
        # create an SPI.MASTER instance on the 'X' side of the board, 
        # first arg=1 means 'X side' of the board
        boardSide = 1
        if not spiOnX:
            boardSide = 2
        self.spi = SPI(boardSide,SPI.MASTER)
        # create the stcp pin on the "latch" pin
        self.stcp = Pin(latchPin, Pin.OUT_PP)

    def update(self,bitArray):
        # send the data bits to the shift register
        # unset the latch
        self.stcp.low()
        # send the bits
        i=0 # remove for production
        for r in bitArray:
            self.spi.send(r)
            #### COMMENT NEXT LINE FOR Off-Board TESTS!
            #State.printT('send reg:\t' + str(i)+ '\t{0:08b}'.format(r))
            i += 1  # remove for production
        # turn on the latch
        self.stcp.high()

    def __repr__(self):
        return 'SPIMgr:' + \
            '\n' + str(self.spi) + \
            '\nSTCP:\n' + str(self.stcp)
import pyb
from pyb import Pin, Timer


Trigger = Pin('X3', Pin.OUT_PP)
Echo = Pin('X4',Pin.IN)

# Create a microseconds counter.
micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
micros.counter(0)
start = 0				# timestamp at rising edge of echo
end = 0					# timestamp at falling edge of echo

while True:
	# Send a 20usec pulse every 10ms
	Trigger.high()
	pyb.udelay(20) #udelay uses argument in microseconds
	Trigger.low()

	# Wait until echo pulse goes from low to high
	while Echo.value() == 0:
		start = micros.counter()	# record start time of pulse

	# Wait until echo pulse goes from high to low
	while Echo.value() == 1:   # do nothing
		end = micros.counter()		# record end time of pulse

	# Calculate distance from delay duration
	distance = int(((end - start) / 2) / 29)
	print('Distance: ', distance, ' cm')
	pyb.delay(500)
Example #49
0
class STAccel:
    def __init__(self, cs='PE3', spi=1, debug=False):
        self._debug = debug
        self.cs_pin = Pin(cs, Pin.OUT_PP, Pin.PULL_NONE)
        self.cs_pin.high()
        self.spi = SPI(spi, SPI.MASTER, baudrate=328125, polarity=0, phase=1,
                       bits=8)

        self.read_id()
        # First SPI read always returns 255 --> discard and read ID again
        self.who_am_i = self.read_id()
        self.debug("Accel-ID: %s" % self.who_am_i)

        if self.who_am_i == LIS302DL_WHO_AM_I_VAL:
            self.write_bytes(LIS302DL_CTRL_REG1_ADDR, LIS302DL_CONF)
            self.sensitivity = 18
        elif self.who_am_i == LIS3DSH_WHO_AM_I_VAL:
            self.write_bytes(LIS3DSH_CTRL_REG4_ADDR, LIS3DSH_CTRL_REG4_CONF)
            self.write_bytes(LIS3DSH_CTRL_REG5_ADDR, LIS3DSH_CTRL_REG5_CONF)
            self.sensitivity = 0.06 * 256
        else:
            msg = 'LIS302DL or LIS3DSH accelerometer not present'

            if self._debug:
                self.debug(msg)
            else:
                raise IOError(msg)

    def debug(self, *msg):
        if self._debug:
            print(" ".join(str(m) for m in msg))

    def _convert_raw_to_g(self, x):
        if x & 0x80:
            x -= 256

        return x * self.sensitivity / 1000

    def read_bytes(self, addr, nbytes):
        self.cs_pin.low()

        if nbytes > 1:
            self.spi.send(addr | READWRITE_CMD | MULTIPLEBYTE_CMD)
        else:
            self.spi.send(addr | READWRITE_CMD)

        # read data, MSB first
        buf = self.spi.recv(nbytes)
        self.cs_pin.high()
        return buf

    def write_bytes(self, addr, buf):
        if not isinstance(buf, (int, bytes, bytearray)):
            buf = bytes(buf)

        if not isinstance(buf, int) and len(buf) > 1:
            addr |= MULTIPLEBYTE_CMD

        self.cs_pin.low()
        self.spi.send(addr)
        self.spi.send(buf)
        self.cs_pin.high()

    def read_id(self):
        return self.read_bytes(WHO_AM_I_ADDR, 1)[0]

    def x(self):
        return self._convert_raw_to_g(self.read_bytes(OUT_X_ADDR, 1)[0])

    def y(self):
        return self._convert_raw_to_g(self.read_bytes(OUT_Y_ADDR, 1)[0])

    def z(self):
        return self._convert_raw_to_g(self.read_bytes(OUT_Z_ADDR, 1)[0])

    def xyz(self):
        return (self.x(), self.y(), self.z())
Example #50
0
class Robot:
    def __init__(self):
        # Timer for motor PWM
        self.tim2 = Timer(2, freq=10000)
        
        # Timer to dim lights
        self.tim4 = Timer(4, freq=1000)
        
        # Variables
        self.step_R = 0          #counter for (micro) step
        self.step_L = 0          #counter for (micro) step
        self.n_steps = 16        #number of steps
        self.dir_R = 0           #direction 1=positive, -1=negative, 0=none
        self.dir_L = 0           #direction 1=positive, -1=negative, 0=none
        self.speed_R = 0         #speed counter. If >255 step will be executed
        self.speed_L = 0         #speed counter. If >255 step will be executed
        self.max_speed_R = 256   #maximum speed
        self.max_speed_L = 256   #maximum speed
        self.sspeed_R = 0        #set speed
        self.sspeed_L = 0        #set speed
        self.dist_R = 0          #distance counter
        self.dist_L = 0          #distance counter
        self.power_R = 0         #PWM power setting 0 - 100%
        self.power_L = 0         #PWM power setting 0 - 100%
        self.low_light = 20      #PWM setting for tail light
        self.target_R = 0        #motion control position target
        self.target_L = 0        #motion control position target
        self.acc = 0.5           #motion control acceleration
        self.dts_R = 0           #motion distance to stop
        self.dts_L = 0           #motion distance to stop
           
        # Lights:
        self.LH = Pin('PD12', pyb.Pin.OUT_PP)
        self.RH = Pin('PD13', pyb.Pin.OUT_PP)
        self.TL = self.tim4.channel(3, Timer.PWM, pin=Pin.cpu.D14)
        self.HL = Pin('PD15', pyb.Pin.OUT_PP)
        
        # RH Motor
        self.RH_STBY = Pin('PE6', pyb.Pin.OUT_PP)
        self.RH_PWMA = self.tim2.channel(1, Timer.PWM, pin=Pin.cpu.A15)
        self.RH_AIN1 = Pin('PE8', pyb.Pin.OUT_PP)
        self.RH_AIN2 = Pin('PE9', pyb.Pin.OUT_PP)
        self.RH_PWMB = self.tim2.channel(2, Timer.PWM, pin=Pin.cpu.A1)
        self.RH_BIN1 = Pin('PE10', pyb.Pin.OUT_PP)
        self.RH_BIN2 = Pin('PE11', pyb.Pin.OUT_PP)
        
        # LH Motor
        self.LH_STBY = Pin('PE7', pyb.Pin.OUT_PP)
        self.LH_PWMA = self.tim2.channel(3, Timer.PWM, pin=Pin.cpu.A2)
        self.LH_AIN1 = Pin('PE12', pyb.Pin.OUT_PP)
        self.LH_AIN2 = Pin('PE13', pyb.Pin.OUT_PP)
        self.LH_PWMB = self.tim2.channel(4, Timer.PWM, pin=Pin.cpu.A3)
        self.LH_BIN1 = Pin('PE14', pyb.Pin.OUT_PP)
        self.LH_BIN2 = Pin('PE15', pyb.Pin.OUT_PP)
        
        # Switch lights off
        self.LH.low()
        self.RH.low()
        self.TL.pulse_width_percent(0)
        self.HL.low()
        
        # Switch motor drivers off and PWM to low
        self.RH_PWMA.pulse_width_percent(self.power_R)
        self.RH_PWMB.pulse_width_percent(self.power_R)
        self.LH_PWMA.pulse_width_percent(self.power_L)
        self.LH_PWMB.pulse_width_percent(self.power_L)
        self.RH_STBY.low()
        self.LH_STBY.low()
        
        # Set all other motor pins low
        self.RH_AIN1.low()
        self.RH_AIN2.low()
        self.RH_BIN1.low()
        self.RH_BIN2.low()
        self.LH_AIN1.low()
        self.LH_AIN2.low()
        self.LH_BIN1.low()
        self.LH_BIN2.low()
        
    def Lights(self, status):
        if status == 1:
            self.HL.high()
            self.TL.pulse_width_percent(self.low_light)
        else:
            self.HL.low()
            self.TL.pulse_width_percent(0)
            
    def Brakes(self, status):
        if status == 1:
            self.TL.pulse_width_percent(100)
        elif status == 0:
            if self.HL.value() == 0:
                self.TL.pulse_width_percent(0)
            else:
                self.TL.pulse_width_percent(self.low_light)

    def Blink(self, side):
        if side == -1:
            self.RH.low()
            if self.LH.value() == 0:
                self.LH.high()
            else:
                self.LH.low()
                
        if side == 1:
            self.LH.low()
            if self.RH.value() == 0:
                self.RH.high()
            else:
                self.RH.low()
                
        if side == 2:
            if self.RH.value() == 0:
                self.RH.high()
                self.LH.high()
            else:
                self.RH.low()
                self.LH.low()
                
        if side == 0:
            self.RH.low()
            self.LH.low()

    def MotorStatus(self, left, right):
        if left == 1:
            self.LH_STBY.high()
        elif left != 1:
            self.LH_STBY.low()
        if right == 1:
            self.RH_STBY.high()
        elif right != 1:
            self.RH_STBY.low()
            
    def DoStep(self, dir_L, dir_R):
        if self.step_L == 0:
            self.LH_AIN1.high()
            self.LH_AIN2.low()
            self.LH_PWMA.pulse_width_percent(self.power_L)
            self.LH_PWMB.pulse_width_percent(0)
        elif self.step_L == 1:
            self.LH_AIN1.high()
            self.LH_AIN2.low()
            self.LH_PWMA.pulse_width_percent(self.power_L)
            self.LH_BIN1.high()
            self.LH_BIN2.low()
            self.LH_PWMB.pulse_width_percent(self.power_L)
        elif self.step_L == 2:
            self.LH_PWMA.pulse_width_percent(0)
            self.LH_BIN1.high()
            self.LH_BIN2.low()
            self.LH_PWMB.pulse_width_percent(self.power_L)
        elif self.step_L == 3:
            self.LH_AIN1.low()
            self.LH_AIN2.high()
            self.LH_PWMA.pulse_width_percent(self.power_L)
            self.LH_BIN1.high()
            self.LH_BIN2.low()
            self.LH_PWMB.pulse_width_percent(self.power_L)
        elif self.step_L == 4:
            self.LH_AIN1.low()
            self.LH_AIN2.high()
            self.LH_PWMA.pulse_width_percent(self.power_L)
            self.LH_PWMB.pulse_width_percent(0)
        elif self.step_L == 5:
            self.LH_AIN1.low()
            self.LH_AIN2.high()
            self.LH_PWMA.pulse_width_percent(self.power_L)
            self.LH_BIN1.low()
            self.LH_BIN2.high()
            self.LH_PWMB.pulse_width_percent(self.power_L)
        elif self.step_L == 6:
            self.LH_PWMA.pulse_width_percent(0)
            self.LH_BIN1.low()
            self.LH_BIN2.high()
            self.LH_PWMB.pulse_width_percent(self.power_L)
        elif self.step_L == 7:
            self.LH_AIN1.high()
            self.LH_AIN2.low()
            self.LH_PWMA.pulse_width_percent(self.power_L)
            self.LH_BIN1.low()
            self.LH_BIN2.high()
            self.LH_PWMB.pulse_width_percent(self.power_L)
            
        self.step_L += dir_L
        if self.step_L < 0:
            self.step_L = self.n_steps + dir_L
        if self.step_L >= self.n_steps:
            self.step_L = -1 + dir_L
            
        if self.step_R == 0:
            self.RH_AIN1.high()
            self.RH_AIN2.low()
            self.RH_PWMA.pulse_width_percent(self.power_R)
            self.RH_PWMB.pulse_width_percent(0)
        elif self.step_R == 1:
            self.RH_AIN1.high()
            self.RH_AIN2.low()
            self.RH_PWMA.pulse_width_percent(self.power_R)
            self.RH_BIN1.high()
            self.RH_BIN2.low()
            self.RH_PWMB.pulse_width_percent(self.power_R)
        elif self.step_R == 2:
            self.RH_PWMA.pulse_width_percent(0)
            self.RH_BIN1.high()
            self.RH_BIN2.low()
            self.RH_PWMB.pulse_width_percent(self.power_R)
        elif self.step_R == 3:
            self.RH_AIN1.low()
            self.RH_AIN2.high()
            self.RH_PWMA.pulse_width_percent(self.power_R)
            self.RH_BIN1.high()
            self.RH_BIN2.low()
            self.RH_PWMB.pulse_width_percent(self.power_R)
        elif self.step_R == 4:
            self.RH_AIN1.low()
            self.RH_AIN2.high()
            self.RH_PWMA.pulse_width_percent(self.power_R)
            self.RH_PWMB.pulse_width_percent(0)
        elif self.step_R == 5:
            self.RH_AIN1.low()
            self.RH_AIN2.high()
            self.RH_PWMA.pulse_width_percent(self.power_R)
            self.RH_BIN1.low()
            self.RH_BIN2.high()
            self.RH_PWMB.pulse_width_percent(self.power_R)
        elif self.step_R == 6:
            self.RH_PWMA.pulse_width_percent(0)
            self.RH_BIN1.low()
            self.RH_BIN2.high()
            self.RH_PWMB.pulse_width_percent(self.power_R)
        elif self.step_R == 7:
            self.RH_AIN1.high()
            self.RH_AIN2.low()
            self.RH_PWMA.pulse_width_percent(self.power_R)
            self.RH_BIN1.low()
            self.RH_BIN2.high()
            self.RH_PWMB.pulse_width_percent(self.power_R)
            
        self.step_R += dir_R
        if self.step_R < 0:
            self.step_R = self.n_steps + dir_R
        if self.step_R >= self.n_steps:
            self.step_R = -1 + dir_R
            
    def MoveStep(self, n):
        if self.sspeed_L < 0:
            ldir = -n
        else:
            ldir = n
        
        self.speed_L += (self.sspeed_L * ldir)
        if self.speed_L > 255:
            self.dir_L = ldir
            self.dist_L += ldir
            self.speed_L -= 256 * n
        else:
            self.dir_L = 0
            
        if self.sspeed_R < 0:
            rdir = -n
        else:
            rdir = n
               
        self.speed_R += (self.sspeed_R * rdir)
        if self.speed_R > 255:
            self.dir_R = rdir
            self.dist_R += rdir
            self.speed_R -= 256 * n
        else:
            self.dir_R = 0
        
        self.DoStep(self.dir_L, self.dir_R)
            
    def SetPower(self, left, right):
        self.power_R = right
        self.power_L = left
        self.DoStep(0,0)

    def GetDist(self):
        return (self.dist_L, self.dist_R)
        
    def SetDist(self, dl, dr):
        self.dist_L = dl
        self.dist_R = dr
        
    def SetTarget(self, t_L, t_R):
        self.target_L = t_L
        self.target_R = t_R
        
    def GetTarget(self):
        return(self.target_L, self.target_R)
        
    def SetMaxSpeed(self, s_L, s_R):
        self.max_speed_L = s_L
        self.max_speed_R = s_R   
        
    def Stop(self):
        self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512
        self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512
        
        if self.sspeed_L < 0:
            self.dts_L *= -1
            
        if self.sspeed_R < 0:
            self.dts_R *= -1
        
        self.target_L = self.dist_L +  self.dts_L
        self.target_R = self.dist_R +  self.dts_R

    def Motion(self, n):
        self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512
        self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512

        if self.sspeed_L < 0:
            self.dts_L *= -1
            
        if self.sspeed_R < 0:
            self.dts_R *= -1
        
        if self.target_L > (self.dist_L + self.dts_L) and self.sspeed_L < self.max_speed_L:
            self.sspeed_L += self.acc
        elif self.target_L < (self.dist_L + self.dts_L) and self.sspeed_L > -self.max_speed_L:
            self.sspeed_L -= self.acc
        elif self.target_L == self.dist_L and abs(self.sspeed_L) < 50:
            self.sspeed_L = 0

        if self.target_R > (self.dist_R + self.dts_R) and self.sspeed_R < self.max_speed_R:
            self.sspeed_R += self.acc
        elif self.target_R < (self.dist_R + self.dts_R) and self.sspeed_R > -self.max_speed_R:
            self.sspeed_R -= self.acc
        elif self.target_R == self.dist_R and abs(self.sspeed_R) < 50:
            self.sspeed_R = 0
        
        self.MoveStep(n)
        
Example #51
0
class BLE:
    BLE_NONE=0
    BLE_SHIELD=1

    def command(self, cmd):
        if self.type==self.BLE_SHIELD:
            self.uart.write(cmd)
            self.uart.write("\r\n")
            r=self.uart.read(9)
            if r[0]!=82: raise OSError("Response corrupted!")
            if r[1]==49: raise OSError("Command failed!")
            if r[1]==50: raise OSError("Parse error!")
            if r[1]==51: raise OSError("Unknown command!")
            if r[1]==52: raise OSError("Too few args!")
            if r[1]==53: raise OSError("Too many args!")
            if r[1]==54: raise OSError("Unknown variable or option!")
            if r[1]==55: raise OSError("Invalid argument!")
            if r[1]==56: raise OSError("Timeout!")
            if r[1]==57: raise OSError("Security mismatch!")
            if r[1]!=48: raise OSError("Response corrupted!")
            for i in range(2,6):
                if r[i]<48 or 57<r[i]: raise OSError("Response corrupted!")
            if r[7]!=13 or r[8]!=10: raise OSError("Response corrupted!")
            l=((r[2]-48)*10000)+\
              ((r[3]-48)*1000)+\
              ((r[4]-48)*100)+\
              ((r[5]-48)*10)+\
              ((r[6]-48)*1)
            if not l: return None
            if l==1 or l==2: raise OSError("Response corrupted!")
            response=self.uart.read(l-2)
            if self.uart.readchar()!=13: raise OSError("Response corrupted!")
            if self.uart.readchar()!=10: raise OSError("Response corrupted!")
            return response

    def deinit(self):
        if self.type==self.BLE_SHIELD:
            self.uart.deinit()
            self.rst=None
            self.uart=None
            self.type=self.BLE_NONE

    def init(self, type=BLE_SHIELD):
        self.deinit()
        if type==self.BLE_SHIELD:
            self.rst=Pin("P7",Pin.OUT_OD,Pin.PULL_NONE)
            self.uart=UART(3,115200,timeout_char=1000)
            self.type=self.BLE_SHIELD
            self.rst.low()
            sleep(100)
            self.rst.high()
            sleep(100)
            self.uart.write("set sy c m machine\r\nsave\r\nreboot\r\n")
            sleep(1000)
            self.uart.readall() # clear

    def uart(self):
        if self.type==self.BLE_SHIELD: return self.uart

    def type(self):
        if self.type==self.BLE_SHIELD: return self.BLE_SHIELD

    def __init__(self):
        self.rst=None
        self.uart=None
        self.type=self.BLE_NONE
Example #52
0
                  # imposto allarme A con ora spegnimento e setto flag relay_a=1.
                  # set alarm A at switch off time and set relay_a=1 
                  allarm_a.timeset(hour=int(pkl['hre_a']),minute=int(pkl['mine_a']),second=0)
                  uart.write("Set Stop Time A at : "+pkl['hre_a']+":"+pkl['mine_a']+"\n")

                  # aggiorno dati salvati in memoria per riflettere nuovo valore relay_a
                  # update data to reflect relay_a status. 
                  pkl['relay_a']="1"
                  z = pickle.dumps(pkl).encode('utf8')
                  bkram[0] = len(z)
                  ba[4: 4+len(z)] = z

                  # genero impulso per cambio stato FF.
                  # pulse to change state on FF
                  pin_relay_a.high()
                  pyb.delay(10)
                  pin_relay_a.low()
                  uart.write("Attiva Relay A - con sonda - "+"\n")
                  uart.write("relay_a_on"+"\n")
                  uart.write("Sleep A - con sonda -"+"\n")
                  reason=""
                  upower.wkup.enable()
                  pyb.standby()

       if active_day_a==True and pkl['relay_a']=='0' and enable_sonda_a==False:
              uart.write('Alarm A --> active_day_a=True, relay_a=0, enable_sonda_a=False. '+'\n') 
              uart.write("Set Stop Time A at : "+str(hre_a)+":"+str(mine_a)+"\n")

                # imposto allarme A con ora spegnimento e setto flag relay_a=1
                # set alarm A at switch off time and set relay_a=1              
# Task 4: Joystick Controlling the Motor
# Author: BSG
# Version 1.0
# 26 May 2016

print ('This is Test 4: Joystick Controlling the Motor')
from pyb import Pin, Timer, ADC



while True:
    pyb.delay(1)
    A1 = Pin('Y9',Pin.OUT_PP)
    A2 = Pin('Y10',Pin.OUT_PP)
    A1.high()
    A2.low()
    motor = Pin('X1')
    tim = Timer(2, freq = 1000)
    ch = tim.channel(1, Timer.PWM, pin = motor)



    adc_1 = ADC(Pin('X19')) #vertical
    adc_2 = ADC(Pin('X20')) #horizontal
    J_sw = Pin('Y11', Pin.IN) #switch

    vertical = (int(adc_2.read()) / 1700)*100
    ch.pulse_width_percent(vertical)