Beispiel #1
0
    def send(self, buf, timeout=500):
        # power up
        self.reg_write(CONFIG, (self.reg_read(CONFIG) | PWR_UP) & ~PRIM_RX)
        pyb.udelay(150)

        # send the data
        self.cs.low()
        self.spi.send(W_TX_PAYLOAD)
        self.spi.send(buf)
        if len(buf) < self.payload_size:
            self.spi.send(b'\x00' * (self.payload_size - len(buf))) # pad out data
        self.cs.high()

        # enable the chip so it can send the data
        self.ce.high()
        pyb.udelay(15) # needs to be >10us
        self.ce.low()

        # blocking wait for tx complete
        start = pyb.millis()
        while pyb.millis() - start < timeout:
            status = self.reg_read_ret_status(OBSERVE_TX)
            if status & (TX_DS | MAX_RT):
                break

        # get and clear all status flags
        status = self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT)
        if not (status & TX_DS):
            raise OSError("send failed")

        # power down
        self.reg_write(CONFIG, self.reg_read(CONFIG) & ~PWR_UP)
Beispiel #2
0
    def read_register(self, address, signed=False):
        # take the chip select low to select the device
        self._cs_pin.low()

        # send the device the register you want to read
        #junk = self.spi.send_recv((address).to_bytes(1))
        self.spi.send((address).to_bytes(1))
        junk = self.spi.recv(1)

        # small delay
        pyb.udelay(50)

        # end a value of 0 to read the first byte returned
        #result = self.spi.send_recv((0x00).to_bytes(1))
        self.spi.send((0x00).to_bytes(1))
        result = self.spi.recv(1)

        # take the chip select high to de-select
        self._cs_pin.high()

        # Fix for signed or unsigned bytes
        if signed:
            result = struct.unpack('b', result)[0]
        else:
            result = struct.unpack('B', result)[0]
        return result
Beispiel #3
0
def update(t):  # Interrupt handler may not be able to acquire the lock
    global var1, var2  # if main loop has it
    if mutex.test():  # critical section start
        var1 += 1
        pyb.udelay(200)
        var2 += 1
        mutex.release()  # critical section end
Beispiel #4
0
 def get(self):
     self._trig.high()
     pyb.udelay(10)
     self._trig.low()
     d = pulseIn(self._echo, HIGH) / 29 / 2
     if d and d > D_MIN and d < D_MAX:
         return {'enable':True}
Beispiel #5
0
 def time_it(self, idx):
     sig = self.in_pin.value()
     while self.in_pin.value() == sig:
         self.buf[idx] += 1
         pyb.udelay(20)
         if  self.buf[idx] > 350:  # EOF
             raise Exception()
  def centimeters( self ) :
    start = 0
    end = 0

    self.counter = 0

    #Send 10us pulse.
    self._tpin.high()
    udelay(10)
    self._tpin.low()

    while not self._epin.value():
      start = self.counter

    j = 0

    # Wait 'till the pulse is gone.
    while self._epin.value() and j < 1000:
      j += 1
      end = self.counter

    # Calc the duration of the recieved pulse, divide the result by
    # 2 (round-trip) and divide it by 29 (the speed of sound is
    # 340 m/s and that is 29 us/cm).
    return (end - start) / 58
Beispiel #7
0
    def distance_to_obstacle_in_cm(
            self
    ):  #trigger us sensor to measure distance to the closest obstacle
        start = 0
        stop = 0
        self._pin_trigger.low()
        self._us_tmr.counter(0)

        # Send a 10us pulse - this triggers measurement sequence
        self._pin_trigger.high()
        pyb.udelay(10)
        self._pin_trigger.low()

        # Wait 'till the pulse starts.
        while self._pin_echo.value() == 0:
            start = self._us_tmr.counter()

        # Wait 'till the pulse is gone.
        while self._pin_echo.value() == 1:
            stop = self._us_tmr.counter()

        #calculate a distance in cm
        dist_in_cm = ((stop - start) /
                      2) / 29  #convert response pulse duration into distance
        return dist_in_cm
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)
def balance():
    gangle = 0.0
    start = pyb.micros()
    controlspeed = 0
    fspeed = 0
    while abs(gangle) < 45:  # give up if inclination angle >=45 degrees
        angle  = imu.pitch()
        rate   = imu.get_gy()
        gangle = compf(gangle, angle, rate, pyb.elapsed_micros(start),0.99)         
        start = pyb.micros()
        # speed control
        actualspeed = (motor1.get_speed()+motor2.get_speed())/2
        fspeed = 0.95 * fspeed + 0.05 * actualspeed
        cmd = radio.poll() # cmd[0] is turn speed, cmd[1] is fwd/rev speed
        tangle = speedcontrol(800*cmd[1],fspeed)
         # stability control
        controlspeed += stability(tangle, gangle, rate)           
        controlspeed = constrain(controlspeed,-MAX_VEL,MAX_VEL)
        # set motor speed
        motor1.set_speed(-controlspeed-int(300*cmd[0]))
        motor2.set_speed(-controlspeed+int(300*cmd[0]))
        pyb.udelay(5000-pyb.elapsed_micros(start))
    # stop and turn off motors
    motor1.set_speed(0)
    motor2.set_speed(0)
    motor1.set_off()
    motor2.set_off()
Beispiel #10
0
def init(set=True):
    global interruptOnLowClock
    cv(0)
    pyb.udelay(110)
    dv(0)
    if set:
        interruptOnLowClock = setInterrupt(ci)
Beispiel #11
0
    def get_pixel_data(self):            # TODO: send data to serPort do not print the data here
        isFirstPixel = True

        # write to frame capture register to force capture of frame
        self.write_register(ADNS3080_FRAME_CAPTURE,0x83);
        
        # wait 3 frame periods + 10 nanoseconds for frame to be captured
        pyb.udelay(1510);  # min frame speed is 2000 frames/second so 1 frame = 500 nano seconds.  so 500 x 3 + 10 = 1510

        data = "[["
        # display the pixel data
        for i in range(ADNS3080_PIXELS_Y):
            for j in range(ADNS3080_PIXELS_X):
                regValue = self.read_register(ADNS3080_FRAME_CAPTURE)

                if( isFirstPixel and (regValue & 0x40) == 0 ):
                    print("failed to find first pixel\n")

                isFirstPixel = False
                pixelValue = ( regValue << 2) & 255             # Shift to the left and cut off the last to bits
                data += str(pixelValue)                       # Used to be -> pixelValue,DEC not sure what the ,DEC did do
                if( j!= ADNS3080_PIXELS_X-1 ):
                    data += ","
                pyb.udelay(50)

            data += "\n"
        data += "]]"
        return data
    def dist(self):
        start = 0
        end = 0

        # Send a 10us pulse.
        self.trigger.high()
        pyb.udelay(10)
        self.trigger.low()

        # Wait 'till whe pulse starts.
        start_tout = pyb.micros() + 1000

        while self.echo.value() == 0:
            start = pyb.micros() 
            if start > start_tout:
                print("start_tout")
                return -1

        # Wait 'till the pulse is gone.
        end_tout = pyb.micros() + 10000 

        while self.echo.value() == 1:
            end = pyb.micros() 
            if end > end_tout:
                print("end_tout")
                return -1

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = end - start

        return dist_in_cm
Beispiel #13
0
    def update(self):
        # TODO: check for constants used
        # TODO: return x and y changes
        surface_quality = self.read_register(ADNS3080_SQUAL)
        # small delay
        pyb.udelay(50)

        # check for movement, update x,y values
        motion_reg = self.read_register(ADNS3080_MOTION)
        _overflow = ((motion_reg & 0x10) != 0)              # check if we've had an overflow # TODO: do something whit this info
        if( (motion_reg & 0x80) != 0 ):
            raw_dx = self.read_register(ADNS3080_DELTA_X, signed=True)
            # small delay
            pyb.udelay(50)
            raw_dy = self.read_register(ADNS3080_DELTA_Y, signed=True)
            self._motion = True
        else:
            raw_dx = 0
            raw_dy = 0

        last_update = pyb.millis()

        # Fix for orientation if needed
        #self.apply_orientation_matrix()

        self.dx = raw_dx
        self.dy = raw_dy

        self.x += raw_dx
        self.y += raw_dy

        return True
    def distance_in_cm(self):
        start = 0
        end = 0

        # Create a microseconds counter.
        micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
        micros.counter(0)

        # Send a 10us pulse.
        self.trigger.high()
        pyb.udelay(10)
        self.trigger.low()

        # Wait 'till whe pulse starts.
        while self.echo.value() == 0:
            start = micros.counter()

        # Wait 'till the pulse is gone.
        while self.echo.value() == 1:
            end = micros.counter()

        # Deinit the microseconds counter
        micros.deinit()

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = ((end - start) / 2) / 29

        return dist_in_cm
Beispiel #15
0
def update(t):                  # Interrupt handler may not be able to acquire the lock
    global var1, var2           # if main loop has it
    if mutex.test():            # critical section start
        var1 += 1
        pyb.udelay(200)
        var2 += 1
        mutex.release()         # critical section end
Beispiel #16
0
def init():
    global moduleInit
    cv(0)
    pyb.udelay(110)
    dv(0)
    if not moduleInit:
        moduleInit=True
        setInterrupt(ci)
Beispiel #17
0
 def step(self, num):
     for i in range(num):
         phase = self.phase.__next__()
         self.pin1.value(phase[0])
         self.pin2.value(phase[1])
         self.pin3.value(phase[2])
         self.pin4.value(phase[3])
         pyb.udelay(self.delay_time)
Beispiel #18
0
    def syncSteps(self, n):
        """Make n steps = n*/512 turn ≈ n*0.7° and return when done.
		   n > 0 turns counter clockwise (positive trigonometric angle).
		   n < 0 turns clockwise (negative trigonometric angle).
		"""
        self._setupSteps(n)
        usdelay = int(self._phasePeriod() * 1E6)
        while self._onePhase():
            pyb.udelay(usdelay)
Beispiel #19
0
 def __init__(self, sensor_table, srv):
     self.light_sensor = LightSensor()
     self.mutex = esp.mutex()
     self.sensor_table = sensor_table
     self.sensors = dict()
     self.task = esp.os_task(callback=lambda task: handler(task, srv, self))
     for sensor_name, sensor_port in sensor_table.items():
         self.sensors[sensor_name] = Sensor(sensor_name, sensor_port, 10000, task=self.task, mutex=self.mutex)
         pyb.udelay(10000)
Beispiel #20
0
 def info(self):
     self.pinCS.low()
     pyb.udelay(1000)                        # FLASH wake up delay
     self.spi.send(FLASH_RDID)
     manufacturer = self.spi.send_recv(FLASH_NOP)[0]
     id_high = self.spi.send_recv(FLASH_NOP)[0]
     id_low = self.spi.send_recv(FLASH_NOP)[0]
     self.pinCS.high()
     return manufacturer, id_high << 8 | id_low
Beispiel #21
0
 def read(self,read_addr,nr_bytes):
     buf = bytearray(1)
     buf[0]=read_addr
     self.CS.low()
     pyb.udelay(self.delay)
     self._write(buf)
     result = self._read(nr_bytes)
     self.CS.high()
     return result
Beispiel #22
0
    def reset(self):
        # return immediately if the reset pin is not defined
        if( ADNS3080_RESET == 0):
            return

        self._reset_pin.high()                  # reset sensor
        pyb.udelay(10)
        self._reset_pin.low()                   # return sensor to normal
        pyb.udelay(10)
Beispiel #23
0
 def turn(self):
     # counter incremented in timer callback, effectively changes the freq
     if self.speed != 0:
         self.count = (self.count+1)%self.rate
         if self.count == 0:
             self.step.high()
             # the stepper motor driver needs a 2us pulse
             pyb.udelay(2)
             self.step.low()
def playSlurred(note, Hz, length):
#    print(note, Hz, int(Hz * length))
    for duration in range(0, int(Hz * length), 2):
#        print('Running note:', note + ':', 1/Hz, duration, '/', int(Hz * length))
        phone.high()
        udelay(int(1e6/Hz))
        phone.low()
        udelay(int(1e6/Hz))
    print('Done')
Beispiel #25
0
def tone(f,t,b=0):
    global bz
    p = int(1000000/f)
    t1 = pyb.millis()+t
    while pyb.millis() < t1:
        bz.high()
        pyb.udelay(p)
        bz.low()
        pyb.udelay(p)
    if b!=0: pyb.delay(b)
 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()
Beispiel #27
0
 def main(self):
     while True:
         if not self.in_pin.value():
             self.scan()
             print()
             print(self.buf)
             print("".join(["X" if _ > 29 else " " for _ in self.buf]))
             print()
             pyb.delay(90)
         pyb.udelay(50)
Beispiel #28
0
 def read_raw_pressure(self):
     """Reads the raw (uncompensated) pressure level from the sensor."""
     conversion_time = [5000, 8000, 14000, 26000]
     self._write_byte(BMP180_CONTROL, BMP180_READPRESSUREDCMD+(self._mode<<6))
     pyb.udelay(conversion_time[self._mode])
     raw = self._read_u24(BMP180_PRESSUREDATA)>>(8-self._mode)
     #MSB = self._read_byte(BMP180_PRESSUREDATA)
     #LSB = self._read_byte(BMP180_PRESSUREDATA+1)
     #XLSB = self._read_byte(BMP180_PRESSUREDATA+2)
     #raw = ((MSB << 16) + (LSB << 8) + XLSB) >> (8 - self._mode)
     return raw
def handleSplitCharSet(listset, key, baseOctave, bpm, timesig):
    print(listset)
    prefix, note, suffix = listset[0], listset[1], listset[2]
    style, octave = handlePrefix(prefix, baseOctave)
    note, length = handleSuffix(note, key, suffix, bpm, timesig)
    print(note, octave, length, style)
    if note == 'Rz':
        udelay(int(length * 1e6))
    else:
        playNote(note, octave, length, style)
    print('Terminating...')
Beispiel #30
0
    def start_listening(self):
        self.reg_write(CONFIG, self.reg_read(CONFIG) | PWR_UP | PRIM_RX)
        self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT)

        if self.pipe0_read_addr is not None:
            self.reg_write(RX_ADDR_P0, self.pipe0_read_addr)

        self.flush_rx()
        self.flush_tx()
        self.ce.high()
        pyb.udelay(130)
Beispiel #31
0
 def getTempHum(self, buzz=True):
     id_bit = 0 # identificador del bit que estamos tratando
     vbit = 0  # valor de la palabra de 40 bits que se lee, incluye checksum
     self.oneWire.init(pyb.Pin.OUT_PP)
     self.oneWire.high()
     retardo=250
     if buzz:
         #suena buzzer
         self.ch2.pulse_width(12000)
         pyb.delay(80) #in msecs
         self.ch2.pulse_width(0)
         retardo=170
     #pull the pin high and wait 250 milliseconds (ya esta en high, esperamos 250ms de todos modos)
     pyb.delay(retardo)
     #Host pulls low 1.5 ms
     start = pyb.micros()
     self.oneWire.low()
     pyb.udelay(1500)
     #Host pulls up 30us
     self.oneWire.high()
     pyb.udelay(30)
     #Paso a INPUT
     self.oneWire.init(pyb.Pin.IN)
     #sensor pulls low 80us
     while self.oneWire.value() != 0:
         pass
     #sensor pulls up 80us
     while self.oneWire.value() != 1:
         pass
     #sensor pulls low 50us // start bit
     while self.oneWire.value() != 0:
         pass
     while(True):
         #bit starts
         while self.oneWire.value() != 1:
             pass
         start = pyb.micros()
         #bit ends
         while self.oneWire.value() != 0:
             pass
         if (pyb.micros()-start) > 50:
             vbit = (vbit << 1) | 0x1 
         else:
             vbit = (vbit << 1)
         id_bit = id_bit + 1
         if id_bit >= 40:
             check_rec = vbit & 0xff   # checksum recibido
             vbit = vbit >> 8  #aqui "vbit" contiene el valor medido (32 bits)
             check_cal = (vbit & 0xff) + ((vbit >> 8) & 0xff) + ((vbit >> 16) & 0xff) + ((vbit >> 24) & 0xff) # checksum calculado 
             if check_cal != check_rec:
                 self.frt.setAlarmBit(2)
             break
     return vbit
Beispiel #32
0
def read_BMP180_temp():
    UT = 0
    for i in range(3):
        # writing read temp register 0x2E
        i2c.mem_write(0x2E, sladdr, 0xF4)
        pyb.udelay(4500)

        MSB = struct.unpack("<h", i2c.mem_read(1, sladdr, 0xF6))[0]
        LSB = struct.unpack("<h", i2c.mem_read(1, sladdr, 0xF7))[0]

        UT += (MSB<<8) | LSB

    return int(UT/3)
Beispiel #33
0
def mouseInit():
    global clockDelay,dataDelay,stopDelay,shortDelay,oneHundredMicroSeconds,dataPin,clockPin

    """
    the dialogue should be (in decimal!)

    Sending reset to mouse
    250
    170
    0
    Sending remote mode code
    250

    Sending reset to mouse
    251
    36
    36
    Sending remote mode code
    243
    >>> psmouse.setup()
    Sending reset to mouse
    228
    228
    228
    Sending remote mode code
    251
    >>> psmouse.setup()
    Sending reset to mouse
    251
    36
    36
    Sending remote mode code
    251

    """

    
    goHi(clockPin)
    goHi(dataPin)
    print('Sending reset to mouse')
    mouseWrite(0xff)
    print(mouseRead())  # ack byte */
    #  Serial.print("Read ack byte1\n");
    print(mouseRead()) # blank */
    print(mouseRead()) # blank */
    print('Sending remote mode code')
    mouseWrite(0xf0)  # remote mode */
    print(mouseRead() ) # mouseRead()  # ack */
    #  Serial.print("Read ack byte2\n");
    pyb.udelay(oneHundredMicroSeconds);
Beispiel #34
0
def _read(gpio:int) -> int:
    read = ptr32(gpio + stm.GPIO_IDR)
    set_hi = ptr16(gpio + stm.GPIO_BSRRL)
    set_lo = ptr16(gpio + stm.GPIO_BSRRH)

    bit = 0X01
    res = 0

    # release the clock and data
    set_hi[0] = 1 << 0 # write X1=PA0 clock
    set_hi[0] = 1 << 1 # write X2=PA1 data
    
    udelay(50)  # I don't know why we wait for 1/2 clock cycle?

    # wait for the clock to go LOW
    while read[0] & (1 << 0): # read X1=PA0 clock
        pass

    # ignore start bit
    while not read[0] & (1 << 0): # read X1=PA0 clock
        pass

    # now read in the 8 data bits
    for i in range(8):
        # wait for the clock to go LOW
        while read[0] & (1 << 0): # read X1=PA0 clock
            pass
        #read the bit on the data pin
        if read[0] & (1 << 1): # read X2=PA1 data
            res |= bit 
        while not read[0] & (1 << 0): # read X1=PA0 clock
            pass
        bit <<= 1
        
    #ignore parity bit, wait a full clock cycle
    while read[0] & (1 << 0): # read X1=PA0 clock
        pass
    while not read[0] & (1 << 0): # read X1=PA0 clock
        pass

    #ignore stop bit, wait a full clock cycle
    while read[0] & (1 << 0): # read X1=PA0 clock
        pass
    while not read[0] & (1 << 0): # read X1=PA0 clock
        pass

    #hold incoming data, lock the clock
    set_lo[0] = 1 << 0 # write X1=PA0 clock
    return res