Ejemplo n.º 1
0
    def read_raw_data(self, result):
        """ Reads the raw (uncompensated) data from the sensor.

            Args:
                result: array of length 3 or alike where the result will be
                stored, in temperature, pressure, humidity order
            Returns:
                None
        """

        self._l1_barray[0] = self._mode
        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL_HUM,
                             self._l1_barray)
        self._l1_barray[0] = self._mode << 5 | self._mode << 2 | 1
        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                             self._l1_barray)

        sleep_time = 1250 + 2300 * (1 << self._mode)
        sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
        sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
        time.sleep_us(sleep_time)  # Wait the required time

        # burst readout from 0xF7 to 0xFE, recommended by datasheet
        self.i2c.readfrom_mem_into(self.address, 0xF7, self._l8_barray)
        readout = self._l8_barray
        # pressure(0xF7): ((msb << 16) | (lsb << 8) | xlsb) >> 4
        raw_press = ((readout[0] << 16) | (readout[1] << 8) | readout[2]) >> 4
        # temperature(0xFA): ((msb << 16) | (lsb << 8) | xlsb) >> 4
        raw_temp = ((readout[3] << 16) | (readout[4] << 8) | readout[5]) >> 4
        # humidity(0xFD): (msb << 8) | lsb
        raw_hum = (readout[6] << 8) | readout[7]

        result[0] = raw_temp
        result[1] = raw_press
        result[2] = raw_hum
Ejemplo n.º 2
0
 def awaitReset(self):
     try:
         try:
             machine.time_pulse_us(self.pin, 1)
         except:
             self.err = 'Not Connected'
             return False
         t = machine.time_pulse_us(self.pin, 0)
         if t < 480:
             self.err = 'Very short reset ' + str(t) + 'us'
             return False
     except:
         self.err = 'Very long reset'
         return False
     self.pin.init(self.pin.OUT_OD)
     self.pin.low()
     time.sleep_us(60)
     # let it float
     self.pin.init(self.pin.IN, self.pin.PULL_NONE)
     time.sleep_us(5)
     if self.pin.value() == 0:
             self.err = 'No presence response from door'
             return False
     else:
             return True
Ejemplo n.º 3
0
 def read_battery_voltage(self):
     self.set_bits_in_memory(ADCON0_ADDR, _ADCON0_GO_nDONE_MASK)
     time.sleep_us(50)
     while self.peek_memory(ADCON0_ADDR) & _ADCON0_GO_nDONE_MASK:
         time.sleep_us(100)
     adc_val = (self.peek_memory(ADRESH_ADDR) << 2) + (self.peek_memory(ADRESL_ADDR) >> 6)
     return (((adc_val * 3.3 * 280) / 1023) / 180) + 0.01    # add 10mV to compensate for the drop in the FET
Ejemplo n.º 4
0
 def _wait(self):
     count = 0
     time.sleep_us(10)
     while self.i2c.readfrom(I2C_SLAVE_ADDR, 1)[0] != 0xFF:
         time.sleep_us(100)
         count += 1
         if (count > 500):  # timeout after 50ms
             raise Exception('Pytrack board timeout')
Ejemplo n.º 5
0
 def refresh(self):
     """
     Start a new measurement.
     """
     self._cs.off()
     time.sleep_us(10)
     self._cs.on()
     self._last_measurement_start = time.ticks_ms()
Ejemplo n.º 6
0
	def __start( self, addr ):
		""" Start a SPI transaction @ addr """
		# Start new transaction
		self.ssel.value( 1 )
		#sleep_ms( 1 ) # 1 Ms between SPI transaction seems right
		sleep_us( 10 )
		self.ssel.value( 0 )
		self.spi.write( ustruct.pack( '>H', addr) ) # Convert address in MSB and LSB
Ejemplo n.º 7
0
 def freq(self, freq=None):
     if freq is None:
         return int(25000000.0 / 4096 / (self._read(0xfe) - 0.5))
     prescale = int(25000000.0 / 4096.0 / freq + 0.5)
     old_mode = self._read(0x00) # Mode 1
     self._write(0x00, (old_mode & 0x7F) | 0x10) # Mode 1, sleep
     self._write(0xfe, prescale) # Prescale
     self._write(0x00, old_mode) # Mode 1
     time.sleep_us(5)
     self._write(0x00, old_mode | 0xa1) # Mode 1, autoincrement on
Ejemplo n.º 8
0
    def createChar(self, location, charmap):
        # Write to CGRAM of new characters
        # Only 8 locations 0-7
        location &= 0x7

        self.command(HD44780LCD.LCD_SETCGRAMADDR | (location << 3))
        time.sleep_us(40)
        for i in range(8):
            self.write(charmap[i])
            time.sleep_us(40)
Ejemplo n.º 9
0
 def custom_char(self, location, charmap):
     """Write a character to one of the 8 CGRAM locations, available
     as chr(0) through chr(7).
     """
     location &= 0x7
     self.hal_write_command(self.LCD_CGRAM | (location << 3))
     time.sleep_us(40)
     for i in range(8):
         self.hal_write_data(charmap[i])
         time.sleep_us(40)
     self.move_to(self.cursor_x, self.cursor_y)
Ejemplo n.º 10
0
def getval(pin):
    """readout a dht11/22 sensor"""
    ms = [1] * 300
    pin(0)
    time.sleep_us(20000)
    pin(1)
    irqf = disable_irq()
    for i in range(len(ms)):
        ms[i] = pin()  # sample input and store value
    enable_irq(irqf)
    return ms
Ejemplo n.º 11
0
 def recvAndProcessCmd(self):
     # self.waitForRequestfake(False)
     r = self.recv()
     if r == 0x33:
         if not self.sendData(self.rom):
             return False
         return True
     else:
         print("Received: {}".format(r))
     self.err = 'Did not receive 0x33'
     time.sleep_us(1000000)
     return False
Ejemplo n.º 12
0
 def checkdist(self):
  self.trig.value(0)
  self.echo.value(0)
  self.trig.value(1)
  time.sleep_us(10)
  self.trig.value(0)
  while(self.echo.value()==0):
   pass
  t1=time.ticks_us()
  while(self.echo.value()==1):
   pass
  t2=time.ticks_us()
  return round(time.ticks_diff(t2,t1)/10000*340/2,2)
Ejemplo n.º 13
0
def rotate(RPM, angle):
    if(RPM > 20):
        print("RPM should less than 20")
        return
    delay = int(60*1000*1000/4096/RPM)
    steps = int(512*abs(angle)/360)
    if angle < 0:
        direction = -1
    else:
        direction = 1
    for i in range(steps):
        for step in seq[::direction]:
            set_step(step)
            sleep_us(delay)
Ejemplo n.º 14
0
    def sendBit(self, bit):
        try:
            machine.time_pulse_us(self.pin, 0, timeout_us=60)
        except:
            self.err = 'Write timeslot timeout'
            return

        if bit & 1:
            return
        else:
            self.pin.low()
            self.pin.init(self.pin.OUT_OD)
            time.sleep_us(60)
            self.pin.init(self.pin.IN, self.pin.PULL_NONE)
        return
Ejemplo n.º 15
0
    def distance_in_cm(self):
        # Send a 10us pulse
        self.trigger.on()
        sleep_us(10)
        self.trigger.off()

        # Wait for the pulse and calc its duration
        time_pulse = time_pulse_us(self.echo, 1, self.timeout)

        if time_pulse < 0:
            raise MeasurementTimeout(self.timeout)

        # Divide the duration of the pulse by 2 (round-trip) and then divide it
        # by 29 us/cm (speed of sound = ~340 m/s)
        return (time_pulse / 2) / 29
Ejemplo n.º 16
0
def measure():
    Trig.low()
    sleep_us(15)
    Trig.high()
    sleep_us(15)
    Trig.low()
    while(Echo.value() == 0):
        start = ticks_us()
    while(Echo.value() == 1):
        end = ticks_us()
    duration = end - start
    dist = 0.03435 * 0.5 * duration
    print("duration: " + str(duration) + ", " + \
          "distance: " + str(dist))
    return dist
Ejemplo n.º 17
0
 def wait_response(self):
     start = time.ticks_ms()
     while 1:
         try:
             self.i2c.readfrom_into(self.addr, self.buf1)
             n = self.buf1[0]
             break
         except OSError as er:
             time.sleep_us(500)
         if time.ticks_diff(time.ticks_ms(), start) > 5000:
             raise Exception('timeout')
     if n >= 129:
         raise Exception(n)
     if n == 0:
         return b''
     else:
         return self.i2c.readfrom(self.addr, n)
Ejemplo n.º 18
0
    def send_command(self, ins, p1, p2, data=None, expected=None):

        # These command variables are always sent
        cmd = struct.pack('3B', ins, p1, p2)

        # Looks like data is only sent with the length (Lc)
        if data:
            assert len(data) <= 251 # Thus speaks the datasheet
            cmd += struct.pack('B', len(data))
            cmd += data

        # Expected data is either not present at all, 0 for null-terminated, or a number for fixed
        if expected is not None:
            cmd += struct.pack('B', expected)

        if self.debug:
            print("Sending: " + hexlify(cmd).decode())

        self.spi.write(cmd)

        # Wait for a little while
        time.sleep_us(15) # This should take at most 14.5us
        while self.tc_busy_bar() == 0:
            machine.idle()

        # Request a response
        if expected is not None:
            if expected > 0:
                result_bytes = self.spi.read(2 + expected)
            else:
                result_bytes = self.spi.read(EPD.MAX_READ)
                strlen = result_bytes.find(b'\x00')
                result_bytes = result_bytes[:strlen] + result_bytes[strlen+1:strlen+3]
        else:
            result_bytes = self.spi.read(2)

        if self.debug:
            print("Received: " + hexlify(result_bytes).decode())

        (result,) = struct.unpack_from('>H', result_bytes[-2:])

        if result != EPD.SW_NORMAL_PROCESSING:
            raise ValueError("Bad result code: 0x%x" % result)

        return result_bytes[:-2]
Ejemplo n.º 19
0
 def _send_pulse_and_wait(self):
     """
     Send the pulse to trigger and listen on echo pin.
     We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
     """
     self.trigger.value(0) # Stabilize the sensor
     time.sleep_us(5)
     self.trigger.value(1)
     # Send a 10us pulse.
     time.sleep_us(10)
     self.trigger.value(0)
     try:
         pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
         return pulse_time
     except OSError as ex:
         if ex.args[0] == 110: # 110 = ETIMEDOUT
             raise OSError('Out of range')
         raise ex
Ejemplo n.º 20
0
 def write8(self, value, char_mode=False):
     """Write 8-bit value in character or data mode.  Value should be an int
     value from 0-255, and char_mode is True if character data or False if
     non-character data (default).
     """
     # One millisecond delay to prevent writing too quickly.
     time.sleep_us(1000)
     # Set character / data bit.
     self._rs(char_mode)
     # Write upper 4 bits.
     self._d4((value >> 4) & 1)
     self._d5((value >> 5) & 1)
     self._d6((value >> 6) & 1)
     self._d7((value >> 7) & 1)
     self._pulse_enable()
     # Write lower 4 bits.
     self._d4(value        & 1)
     self._d5((value >> 1) & 1)
     self._d6((value >> 2) & 1)
     self._d7((value >> 3) & 1)
     self._pulse_enable()
Ejemplo n.º 21
0
def breath():
    Brightness = 90
    Inhale = 800
    Pulse = Inhale*1000/Brightness
    for i in range(Brightness):
        p.low()
        sleep_us(i*10)
        p.high()
        sleep_us(int(Pulse) - i*10)
    for i in range(Brightness, 0, -1):
        p.low()
        sleep_us(i*10)
        p.high()
        sleep_us(int(Pulse) - i*10)
Ejemplo n.º 22
0
 def _pulse_enable(self):
     # Pulse the clock enable line off, on, off to send command.
     self._en(0)
     time.sleep_us(5)
     self._en(1)
     time.sleep_us(5)
     self._en(0)
     time.sleep_us(50)
Ejemplo n.º 23
0
    def read(self):
        """
        Reads last measurement and starts a new one. If new measurement is not ready yet, returns last value.
        Note: The last measurement can be quite old (e.g. since last call to `read`).
        To refresh measurement, call `refresh` and wait for `ready` to become True before reading.
        :return: Measured temperature
        """
        # Check if new reading is available
        if self.ready():
            # Bring CS pin low to start protocol for reading result of
            # the conversion process. Forcing the pin down outputs
            # first (dummy) sign bit 15.
            self._cs.off()
            time.sleep_us(10)

            # Read temperature bits 14-3 from MAX6675.
            value = 0
            for i in range(12):
                # SCK should resemble clock signal and new SO value
                # is presented at falling edge
                self._cycle_sck()
                value += self._so.value() << (11 - i)

            # Read the TC Input pin to check if the input is open
            self._cycle_sck()
            self._error = self._so.value()

            # Read the last two bits to complete protocol
            for i in range(2):
                self._cycle_sck()

            # Finish protocol and start new measurement
            self._cs.on()
            self._last_measurement_start = time.ticks_ms()

            self._last_read_temp = value * 0.25

        return self._last_read_temp
Ejemplo n.º 24
0
	def shiftOut(self, data, latch=True):
		# print(data)
		for bit in range(8):
			print(bit)
			
			if 0 == (data & (1<<bit)):
				self._dataPin.value(0)
				print("low")
			else:
				self._dataPin.value(1)
				print("high")
			self._clockPin.value(0)
			time.sleep_us(1)
			self._clockPin.value(1)
			time.sleep_us(10)
		if(latch):
			self._latchPin.value(0)
			time.sleep_us(1)
			self._latchPin.value(1)
			time.sleep_us(1)
Ejemplo n.º 25
0
 def sleep_us(self, useconds):
     try:
         time.sleep_us(useconds)
     except AttributeError:
         machine.udelay(useconds)
Ejemplo n.º 26
0
 def _wake(self):
     self._cmd(_RDP)
     time.sleep_us(100)
Ejemplo n.º 27
0
 def _write_byte(self, b):
     for i in range(8):
         self.dio.write_digital((b >> i) & 1)
         time.sleep_us(TM1637_DELAY)
         self.clk.write_digital(1)
         time.sleep_us(TM1637_DELAY)
         self.clk.write_digital(0)
         time.sleep_us(TM1637_DELAY)
     self.clk.write_digital(0)
     time.sleep_us(TM1637_DELAY)
     self.clk.write_digital(1)
     time.sleep_us(TM1637_DELAY)
     self.clk.write_digital(0)
     time.sleep_us(TM1637_DELAY)
Ejemplo n.º 28
0
 def __init__(self, clk, dio):
     self.clk = clk
     self.dio = dio
     time.sleep_us(TM1637_DELAY)
     self._write_data_cmd()
     self._write_dsp_ctrl()
Ejemplo n.º 29
0
def send_id(out_signal, pin_name):

    L2 = Pin(pin_name, mode=Pin.AF_PP, af=Pin.AF1_TIM2)
    timer = Timer(2, freq=38000)
    ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5)
    sleep_us(9000)
    ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0)
    sleep_us(4500)

    for i in out_signal:
        if i == "0":
            ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5)
            sleep_us(560)
            ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0)
            sleep_us(565)
        else:
            ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5)
            sleep_us(560)
            ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0)
            sleep_us(1690)

        ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5)
        sleep_us(560)
        ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0)
Ejemplo n.º 30
0
    def initg(self):
        '''Initialize a green tab version.'''
        self._reset()

        self._writecommand(TFT.SWRESET)  #Software reset.
        time.sleep_us(150)
        self._writecommand(TFT.SLPOUT)  #out of sleep mode.
        time.sleep_us(255)

        data3 = bytearray([0x01, 0x2C, 0x2D
                           ])  #fastest refresh, 6 lines front, 3 lines back.
        self._writecommand(TFT.FRMCTR1)  #Frame rate control.
        self._writedata(data3)

        self._writecommand(TFT.FRMCTR2)  #Frame rate control.
        self._writedata(data3)

        data6 = bytearray([0x01, 0x2c, 0x2d, 0x01, 0x2c, 0x2d])
        self._writecommand(TFT.FRMCTR3)  #Frame rate control.
        self._writedata(data6)
        time.sleep_us(10)

        self._writecommand(TFT.INVCTR)  #Display inversion control
        self._writedata(bytearray([0x07]))
        self._writecommand(TFT.PWCTR1)  #Power control
        data3[0] = 0xA2
        data3[1] = 0x02
        data3[2] = 0x84
        self._writedata(data3)

        self._writecommand(TFT.PWCTR2)  #Power control
        self._writedata(bytearray([0xC5]))

        data2 = bytearray(2)
        self._writecommand(TFT.PWCTR3)  #Power control
        data2[0] = 0x0A  #Opamp current small
        data2[1] = 0x00  #Boost frequency
        self._writedata(data2)

        self._writecommand(TFT.PWCTR4)  #Power control
        data2[0] = 0x8A  #Opamp current small
        data2[1] = 0x2A  #Boost frequency
        self._writedata(data2)

        self._writecommand(TFT.PWCTR5)  #Power control
        data2[0] = 0x8A  #Opamp current small
        data2[1] = 0xEE  #Boost frequency
        self._writedata(data2)

        self._writecommand(TFT.VMCTR1)  #Power control
        self._writedata(bytearray([0x0E]))

        self._writecommand(TFT.INVOFF)

        self._setMADCTL()

        self._writecommand(TFT.COLMOD)
        self._writedata(bytearray([0x05]))

        self._writecommand(TFT.CASET)  #Column address set.
        self.windowLocData[0] = 0x00
        self.windowLocData[1] = 0x01  #Start at row/column 1.
        self.windowLocData[2] = 0x00
        self.windowLocData[3] = self._size[0] - 1
        self._writedata(self.windowLocData)

        self._writecommand(TFT.RASET)  #Row address set.
        self.windowLocData[3] = self._size[1] - 1
        self._writedata(self.windowLocData)

        dataGMCTRP = bytearray([
            0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2b,
            0x39, 0x00, 0x01, 0x03, 0x10
        ])
        self._writecommand(TFT.GMCTRP1)
        self._writedata(dataGMCTRP)

        dataGMCTRN = bytearray([
            0x03, 0x1d, 0x07, 0x06, 0x2e, 0x2c, 0x29, 0x2d, 0x2e, 0x2e, 0x37,
            0x3f, 0x00, 0x00, 0x02, 0x10
        ])
        self._writecommand(TFT.GMCTRN1)
        self._writedata(dataGMCTRN)

        self._writecommand(TFT.NORON)  #Normal display on.
        time.sleep_us(10)

        self._writecommand(TFT.DISPON)
        time.sleep_us(100)

        self.cs(1)
Ejemplo n.º 31
0
 def _cycle_sck(self):
     self._sck.on()
     time.sleep_us(1)
     self._sck.off()
     time.sleep_us(1)
Ejemplo n.º 32
0
 def _pulse(self):
     """Trigger ultrasonic module with 10us pulse."""
     self._trig.value(1)
     sleep_us(10)
     self._trig.value(0)
Ejemplo n.º 33
0
 def _cycle_sck(self):
     self._sck(1)
     time.sleep_us(1)
     self._sck(0)
     time.sleep_us(1)
Ejemplo n.º 34
0
from machine import Pin
from neopixel import NeoPixel

pin = Pin(15, Pin.OUT)   # set GPIO0 to output to drive NeoPixels
np = NeoPixel(pin, 8)   # create NeoPixel driver on GPIO0 for 8 pixels
np[0] = (255, 255, 255) # set the first pixel to white
np.write()              # write data to all pixels
r, g, b = np[0]         # get first pixel colour
for i in range(8):
np[i] = (255, 255, 255) 
np.write()
import time

time.sleep(1)           # sleep for 1 second
time.sleep_ms(500)      # sleep for 500 milliseconds
time.sleep_us(10)       # sleep for 10 microseconds

def fita(r,g,b):
for i in range(8):
np[i] = (r,g,b)
np.write()

def yellow():
for i in range(255):
fita(i,i,0)
time.sleep_ms(100)


def yellow():
for i in range(255):
fita(i,i,0)
Ejemplo n.º 35
0
def octopus_demo():
    print()
    #global notInitServo
    notInitServo = True
    global oled
    global fet
    ###beep(pwm0,500,100) # start beep
    #tim.init(period=1000, mode=Timer.ONE_SHOT, callback=lambda t:print("test timer - thread delay"))
    #tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(2))
    printOctopus()
    print("Hello, this is basic octopusLAB example")
    print(" (Press Ctrl+C to abort | CTRL+D to soft reboot)")
    print()

    time.sleep_us(10)  # sleep for 10 microseconds
    led.blink(500)
    time.sleep_ms(300)  # 1s
    start = time.ticks_ms()

    run = True
    while run:
        sel = mainMenu()
        piezzo.beep(1000, 50)

        if sel == "a":
            print("analog input test: ")
            pin_an = Pin(pinout.ANALOG_PIN, Pin.IN)
            adc = machine.ADC(pin_an)
            an = adc.read()
            print("RAW: " + str(an))
            # TODO improve mapping formula, doc: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/adc.html
            print("volts: {0:.2f} V".format(an / 4096 * 10.74), 20, 50)

        if sel == "b":
            count = 5
            for _ in range(count):
                piezzo.beep(500, 100)
                led.blink(500)

        if sel == "bt":
            butt1 = Pin(pinout.BUTT1_PIN, Pin.IN, Pin.PULL_UP)
            butt2 = Pin(pinout.BUTT2_PIN, Pin.IN, Pin.PULL_UP)
            butt3 = Pin(pinout.BUTT3_PIN, Pin.IN, Pin.PULL_UP)
            count = 10
            for _ in range(count):
                print("b1-" + str(butt1.value())),
                print("b2-" + str(butt2.value())),
                print("b3-" + str(butt3.value()))
                piezzo.beep(500, 100)
                led.blink(500)

        if sel == "c":
            clt()
            printOctopus()

        if sel == "f":
            print("file info /dir/ls:")  #
            print(os.listdir())
            print("> lib: " + str(os.listdir("lib")))
            print("> util: " + str(os.listdir("util")))
            print("> pinouts: " + str(os.listdir("pinouts")))

            i2c_scann()

        if sel == "i":
            print("System info:")
            print("> octopus() ver: " + ver)
            from util.sys_info import sys_info
            sys_info()

        if sel == "m":
            time.sleep_ms(500)
            from util.buzzer.melody import mario
            piezzo.play_melody(mario)
            piezzo.nosound()

        if sel == "r1": RGBtest()
        if sel == "r8":
            np = rgb_init(8)
            Rainbow()

        if sel == "r80":
            NUMBER_LED = 8
            np = rgb_init(NUMBER_LED)
            for i in range(NUMBER_LED):
                np[i] = (1, 0, 0)
                time.sleep_ms(1)  # REVIEW:
            np.write()

        if sel == "s":
            from util.setup import setup
            setup()

        if sel == "t":
            print("temperature >")
            from lib.temperature import TemperatureSensor
            ts = TemperatureSensor(pinout.ONE_WIRE_PIN)
            temp = ts.read_temp()
            # print to console
            print(temp)

        if sel == "w":
            w_connect()

        if sel == "wr1":
            w_connect()
            np = rgb_init(1)
            import urequests
            import json
            url1 = "http://octopuslab.cz/api/ws.json"
            print(url1)
            r1 = urequests.post(url1)
            j = json.loads(r1.text)
            time.sleep_ms(2000)
            print(j["r"])
            np[0] = (j["r"], j["g"], j["b"])  #R
            np.write()

        if sel == "q":
            print("machine.reset() and Exit")
            time.sleep_ms(1000)
            machine.reset()
            run = False

        if sel == "d":
            printOctopus()
            print(">>> Display test submenu")
            print('=' * 30)
            print("--- [od] --- oled display test")
            print("--- [os] --- oled 3segment")
            print("--- [oi] --- oled display image")
            print("--- [m7] --- max display 8x7-segm")
            print("--- [m8] --- max display 8x8-matrix")
            print("--- [sd] --- serial display")
            print("-+- [nd] -+- Nextion display")
            print("-+- [id] -+- ink display")
            print('=' * 30)
            sel_d = input("select: ")

            if sel_d == "od":
                print("oled display test >")
                oled_intit()

                oled.fill(1)
                oled.show()
                time.sleep_ms(300)
                oled.fill(0)  # reset display
                oled.show()

                # write text on x, y
                oled.text('OLED test', 25, 10)
                oled.text(get_hhmm(":", rtc), 45, 29)  #time HH:MM
                oled.hline(0, 50, 128, 1)
                oled.text("octopusLAB 2018", 5, 55)  #time HH:MM
                oled.show()
                time.sleep_ms(1000)

            if sel_d == "os":
                print("oled segment test >")
                oled_intit()
                #from util.display_segment import * #???
                for num in range(10):
                    threeDigits(oled, 20 + num, True, True)
                    time.sleep_ms(50)

            if sel_d == "oi":
                print("oled image test >")
                oled_intit()
                import framebuf

                IMAGE_WIDTH = 63
                IMAGE_HEIGHT = 63

                with open('assets/octopus_image.pbm', 'rb') as f:
                    f.readline()  # Magic number
                    f.readline()  # Creator comment
                    f.readline()  # Dimensions
                    data = bytearray(f.read())
                    fbuf = framebuf.FrameBuffer(data, IMAGE_WIDTH,
                                                IMAGE_HEIGHT,
                                                framebuf.MONO_HLSB)
                    # To display just blit it to the display's framebuffer (note you need to invert, since ON pixels are dark on a normal screen, light on OLED).
                    oled.invert(1)
                    oled.blit(fbuf, 0, 0)

                oled.text("Octopus", 66, 6)
                oled.text("Lab", 82, 16)
                oled.text("Micro", 74, 35)
                oled.text("Python", 70, 45)
                oled.show()

            if sel_d == "m7":
                from lib.max7219_8digit import Display
                #spi = SPI(-1, baudrate=100000, polarity=1, phase=0, sck=Pin(14), mosi=Pin(13), miso=Pin(2))
                #ss = Pin(15, Pin.OUT)
                d7 = Display(spi, ss)
                d7.write_to_buffer('12345678')
                d7.display()

            if sel_d == "m8":
                from lib.max7219 import Matrix8x8
                d8 = Matrix8x8(spi, ss, 1)  #1/4
                #print("SPI device already in use")

                count = 6
                for i in range(count):
                    d8.fill(0)
                    d8.text(str(i), 0, 0, 1)
                    d8.show()
                    print(i)
                    time.sleep_ms(500)

                d8.fill(0)
                d8.show()

            if sel_d == "sd":
                from machine import UART
                uart = UART(2, 9600)  #UART2 > #U2TXD(SERVO1/PWM1_PIN)
                uart.write('C')  #test quick clear display

                uart.write('W7')  #change color
                uart.write('h30')  #horizontal line
                uart.write('h230')  #horizontal line

                uart.write('R0')
                uart.write('W2')  #color
                uart.write('QoctopusLAB - UART2 test*')
                time.sleep_ms(100)
                uart.write('R2')
                uart.write('W1')  #color
                uart.write('QESP32 & ROBOTboard*')
                time.sleep_ms(100)

                uart.write('R5')
                uart.write('W2')  #color

                num = 9
                for i in range(num):
                    uart.write('Q')
                    uart.write(str(num - i - 1))
                    uart.write('*')
                    time.sleep_ms(500)

        if sel == "r":
            printOctopus()
            print()
            print('=' * 30)
            print(">>> Boards special test")
            print('.' * 30)
            print("    Robot board")
            print("--- [dc] --- dc motor test")
            print("--- [se] --- servo")
            print("--- [sm] --- step motor")
            print('.' * 30)
            print("    IoT board")
            print("--- [re] --- relay test")
            print("--- [fa] --- pwm fan test")
            print("--- [li] --- led fade in")
            print("--- [lo] --- led fade out")
            print("--- [lp] --- led pulse")
            print('=' * 30)

            sel_r = input("select: ")
            if sel_r == "dc":
                print("dc motor test >")
                a1 = Pin(pinout.MOTOR_1A, Pin.OUT)
                a2 = Pin(pinout.MOTOR_2A, Pin.OUT)
                a12 = Pin(pinout.MOTOR_12EN, Pin.OUT)
                a3 = Pin(pinout.MOTOR_3A, Pin.OUT)
                a4 = Pin(pinout.MOTOR_4A, Pin.OUT)
                a34 = Pin(pinout.MOTOR_34EN, Pin.OUT)

                a34.value(0)
                a12.value(1)

                print("a12:10")
                a1.value(1)
                a2.value(0)
                time.sleep_ms(3000)
                print("a12:01")
                a1.value(0)
                a2.value(1)
                time.sleep_ms(3000)

                a12.value(0)
                a34.value(1)

                print("a34:01")
                a3.value(0)
                a4.value(1)
                time.sleep_ms(3000)
                print("a12:10")
                a3.value(1)
                a4.value(0)
                time.sleep_ms(3000)
                a34.value(0)

            if sel_r == "se":
                print("servo1 test >")
                #pwm_center = int(pinout.SERVO_MIN + (pinout.SERVO_MAX-pinout.SERVO_MIN)/2)
                pwm_center = 60

                #if notInitServo:
                print("init-servo:")
                pin_servo1 = Pin(pinout.PWM1_PIN, Pin.OUT)
                servo1 = PWM(pin_servo1, freq=50, duty=pwm_center)
                print("OK")
                time.sleep_ms(1500)
                #notInitServo = False

                time.sleep_ms(1500)
                servo1.duty(SERVO_MAX)
                time.sleep_ms(1500)
                servo1.duty(SERVO_MIN)
                time.sleep_ms(1500)

                print("degree45")
                set_degree(servo1, 45)

            if sel_r == "sm":
                from lib.sm28byj48 import SM28BYJ48
                #PCF address = 35 #33-0x21/35-0x23
                ADDRESS = 0x23
                # motor id 1 or 2
                MOTOR_ID1 = 1
                #MOTOR_ID2 = 2

                i2c_sda = Pin(pinout.I2C_SDA_PIN, Pin.IN, Pin.PULL_UP)
                i2c_scl = Pin(pinout.I2C_SCL_PIN, Pin.OUT, Pin.PULL_UP)

                i2c = machine.I2C(scl=i2c_scl, sda=i2c_sda,
                                  freq=100000)  # 100kHz as Expander is slow :(
                motor1 = SM28BYJ48(i2c, ADDRESS, MOTOR_ID1)

                # turn right 90 deg
                motor1.turn_degree(90)
                # turn left 90 deg
                motor1.turn_degree(90, 1)

            if sel_r == "re":
                print("relay test >")
                rel = Pin(pinout.RELAY_PIN, Pin.OUT)
                rel.value(1)
                time.sleep_ms(3000)
                rel.value(0)

            if sel_r == "li":
                if not fet:
                    fet = Pin(pinout.MFET_PIN, Pin.OUT)

                print("led - pwm fade in - test >")
                #lf = PWM(Pin(pinout.MFET_PIN))
                #lf.duty(0)
                #lf.freq(5000)
                #time.sleep_ms(1000)
                #for i in range(100):
                #     lf.duty(i*10)
                #     time.sleep_ms(20)
                fade_in(fet, 500, 5)

            if sel_r == "lo":
                if not fet:
                    fet = Pin(pinout.MFET_PIN, Pin.OUT)

                print("led - pwm fade out - test >")
                #lf = PWM(Pin(pinout.MFET_PIN))
                #lf.duty(1000)
                #lf.freq(5000)
                #time.sleep_ms(1000)
                #for i in range(100):
                #      lf.duty(1000-i*10)
                #      time.sleep_ms(20)
                fade_out(fet, 500, 5)

            if sel_r == "lp":
                lf = PWM(Pin(pinout.MFET_PIN))
                for i in range(5):
                    pulse(lf, 200)

        if sel == "p":
            printOctopus()
            print()
            print(">>> Projects submenu")
            print('=' * 30)
            print("--- [1] --- temporary")
            print("--- [2] --- todo")
            print("--- [3] --- ")
            print('=' * 30)

            sel_p = input("select: ")
            if sel_p == "1":
                print("project 1 >")

    delta = time.ticks_diff(time.ticks_ms(), start)  # compute time difference
    print("> delta time: " + str(delta))
    piezzo.beep(2000, 50)
    print("all OK, press CTRL+D to soft reboot")
    led.blink(50)
Ejemplo n.º 36
0
 def delay_read(self):
     time.sleep_us(self.CTRL_BYTE_DELAY)
Ejemplo n.º 37
0
 def _wait(self):
     time.sleep_us(100)
     while self.i2c.readfrom(I2C_SLAVE_ADDR, 1)[0] != 0xFF:
         time.sleep_us(100)
Ejemplo n.º 38
0
import time

# put to sleep = wait
#time.sleep(1)           # sleep for 1 second
#time.sleep_ms(500)      # sleep for 500 milliseconds
#time.sleep_us(10)       # sleep for 10 microseconds

# compute delta time
start = time.ticks_ms()  # get millisecond counter
time.sleep_us(100)
delta = time.ticks_diff(time.ticks_ms(), start)  # compute time difference
print(delta)  # must be about 100
Ejemplo n.º 39
0
    def initr(self):
        '''Initialize a red tab version.'''
        self._reset()

        self._writecommand(TFT.SWRESET)  #Software reset.
        time.sleep_us(150)
        self._writecommand(TFT.SLPOUT)  #out of sleep mode.
        time.sleep_us(500)

        data3 = bytearray([0x01, 0x2C, 0x2D
                           ])  #fastest refresh, 6 lines front, 3 lines back.
        self._writecommand(TFT.FRMCTR1)  #Frame rate control.
        self._writedata(data3)

        self._writecommand(TFT.FRMCTR2)  #Frame rate control.
        self._writedata(data3)

        data6 = bytearray([0x01, 0x2c, 0x2d, 0x01, 0x2c, 0x2d])
        self._writecommand(TFT.FRMCTR3)  #Frame rate control.
        self._writedata(data6)
        time.sleep_us(10)

        data1 = bytearray(1)
        self._writecommand(TFT.INVCTR)  #Display inversion control
        data1[0] = 0x07  #Line inversion.
        self._writedata(data1)

        self._writecommand(TFT.PWCTR1)  #Power control
        data3[0] = 0xA2
        data3[1] = 0x02
        data3[2] = 0x84
        self._writedata(data3)

        self._writecommand(TFT.PWCTR2)  #Power control
        data1[0] = 0xC5  #VGH = 14.7V, VGL = -7.35V
        self._writedata(data1)

        data2 = bytearray(2)
        self._writecommand(TFT.PWCTR3)  #Power control
        data2[0] = 0x0A  #Opamp current small
        data2[1] = 0x00  #Boost frequency
        self._writedata(data2)

        self._writecommand(TFT.PWCTR4)  #Power control
        data2[0] = 0x8A  #Opamp current small
        data2[1] = 0x2A  #Boost frequency
        self._writedata(data2)

        self._writecommand(TFT.PWCTR5)  #Power control
        data2[0] = 0x8A  #Opamp current small
        data2[1] = 0xEE  #Boost frequency
        self._writedata(data2)

        self._writecommand(TFT.VMCTR1)  #Power control
        data1[0] = 0x0E
        self._writedata(data1)

        self._writecommand(TFT.INVOFF)

        self._writecommand(TFT.MADCTL)  #Power control
        data1[0] = 0xC8
        self._writedata(data1)

        self._writecommand(TFT.COLMOD)
        data1[0] = 0x05
        self._writedata(data1)

        self._writecommand(TFT.CASET)  #Column address set.
        self.windowLocData[0] = 0x00
        self.windowLocData[1] = 0x00
        self.windowLocData[2] = 0x00
        self.windowLocData[3] = self._size[0] - 1
        self._writedata(self.windowLocData)

        self._writecommand(TFT.RASET)  #Row address set.
        self.windowLocData[3] = self._size[1] - 1
        self._writedata(self.windowLocData)

        dataGMCTRP = bytearray([
            0x0f, 0x1a, 0x0f, 0x18, 0x2f, 0x28, 0x20, 0x22, 0x1f, 0x1b, 0x23,
            0x37, 0x00, 0x07, 0x02, 0x10
        ])
        self._writecommand(TFT.GMCTRP1)
        self._writedata(dataGMCTRP)

        dataGMCTRN = bytearray([
            0x0f, 0x1b, 0x0f, 0x17, 0x33, 0x2c, 0x29, 0x2e, 0x30, 0x30, 0x39,
            0x3f, 0x00, 0x07, 0x03, 0x10
        ])
        self._writecommand(TFT.GMCTRN1)
        self._writedata(dataGMCTRN)
        time.sleep_us(10)

        self._writecommand(TFT.DISPON)
        time.sleep_us(100)

        self._writecommand(TFT.NORON)  #Normal display on.
        time.sleep_us(10)

        self.cs(1)
Ejemplo n.º 40
0
 def sleep_us(self, useconds):
     try:
         time.sleep_us(useconds)
     except AttributeError:
         machine.udelay(useconds)
Ejemplo n.º 41
0
    def initb(self):
        '''Initialize blue tab version.'''
        self._size = (ScreenSize[0] + 2, ScreenSize[1] + 1)
        self._reset()
        self._writecommand(TFT.SWRESET)  #Software reset.
        time.sleep_us(50)
        self._writecommand(TFT.SLPOUT)  #out of sleep mode.
        time.sleep_us(500)

        data1 = bytearray(1)
        self._writecommand(TFT.COLMOD)  #Set color mode.
        data1[0] = 0x05  #16 bit color.
        self._writedata(data1)
        time.sleep_us(10)

        data3 = bytearray([0x00, 0x06, 0x03
                           ])  #fastest refresh, 6 lines front, 3 lines back.
        self._writecommand(TFT.FRMCTR1)  #Frame rate control.
        self._writedata(data3)
        time.sleep_us(10)

        self._writecommand(TFT.MADCTL)
        data1[0] = 0x08  #row address/col address, bottom to top refresh
        self._writedata(data1)

        data2 = bytearray(2)
        self._writecommand(TFT.DISSET5)  #Display settings
        data2[
            0] = 0x15  #1 clock cycle nonoverlap, 2 cycle gate rise, 3 cycle oscil, equalize
        data2[1] = 0x02  #fix on VTL
        self._writedata(data2)

        self._writecommand(TFT.INVCTR)  #Display inversion control
        data1[0] = 0x00  #Line inversion.
        self._writedata(data1)

        self._writecommand(TFT.PWCTR1)  #Power control
        data2[0] = 0x02  #GVDD = 4.7V
        data2[1] = 0x70  #1.0uA
        self._writedata(data2)
        time.sleep_us(10)

        self._writecommand(TFT.PWCTR2)  #Power control
        data1[0] = 0x05  #VGH = 14.7V, VGL = -7.35V
        self._writedata(data1)

        self._writecommand(TFT.PWCTR3)  #Power control
        data2[0] = 0x01  #Opamp current small
        data2[1] = 0x02  #Boost frequency
        self._writedata(data2)

        self._writecommand(TFT.VMCTR1)  #Power control
        data2[0] = 0x3C  #VCOMH = 4V
        data2[1] = 0x38  #VCOML = -1.1V
        self._writedata(data2)
        time.sleep_us(10)

        self._writecommand(TFT.PWCTR6)  #Power control
        data2[0] = 0x11
        data2[1] = 0x15
        self._writedata(data2)

        #These different values don't seem to make a difference.
        #     dataGMCTRP = bytearray([0x0f, 0x1a, 0x0f, 0x18, 0x2f, 0x28, 0x20, 0x22, 0x1f,
        #                             0x1b, 0x23, 0x37, 0x00, 0x07, 0x02, 0x10])
        dataGMCTRP = bytearray([
            0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2b,
            0x39, 0x00, 0x01, 0x03, 0x10
        ])
        self._writecommand(TFT.GMCTRP1)
        self._writedata(dataGMCTRP)

        #     dataGMCTRN = bytearray([0x0f, 0x1b, 0x0f, 0x17, 0x33, 0x2c, 0x29, 0x2e, 0x30,
        #                             0x30, 0x39, 0x3f, 0x00, 0x07, 0x03, 0x10])
        dataGMCTRN = bytearray([
            0x03, 0x1d, 0x07, 0x06, 0x2e, 0x2c, 0x29, 0x2d, 0x2e, 0x2e, 0x37,
            0x3f, 0x00, 0x00, 0x02, 0x10
        ])
        self._writecommand(TFT.GMCTRN1)
        self._writedata(dataGMCTRN)
        time.sleep_us(10)

        self._writecommand(TFT.CASET)  #Column address set.
        self.windowLocData[0] = 0x00
        self.windowLocData[1] = 2  #Start at column 2
        self.windowLocData[2] = 0x00
        self.windowLocData[3] = self._size[0] - 1
        self._writedata(self.windowLocData)

        self._writecommand(TFT.RASET)  #Row address set.
        self.windowLocData[1] = 1  #Start at row 2.
        self.windowLocData[3] = self._size[1] - 1
        self._writedata(self.windowLocData)

        self._writecommand(TFT.NORON)  #Normal display on.
        time.sleep_us(10)

        self._writecommand(TFT.RAMWR)
        time.sleep_us(500)

        self._writecommand(TFT.DISPON)
        self.cs(1)
        time.sleep_us(500)
def main(): # main function 
    BUZZER.value(1) # set Buzzer Pin to HIGH 
    time.sleep_us(half_cycle) # first half of the time period   
    BUZZER.value(0) # set Buzzer Pin to LOW
    time.sleep_us(half_cycle) # second half of the time period
Ejemplo n.º 43
0
    def initb2(self):
        '''Initialize another blue tab version.'''
        self._size = (ScreenSize[0] + 2, ScreenSize[1] + 1)
        self._offset[0] = 2
        self._offset[1] = 1
        self._reset()
        self._writecommand(TFT.SWRESET)  #Software reset.
        time.sleep_us(50)
        self._writecommand(TFT.SLPOUT)  #out of sleep mode.
        time.sleep_us(500)

        data3 = bytearray([0x01, 0x2C, 0x2D])  #
        self._writecommand(TFT.FRMCTR1)  #Frame rate control.
        self._writedata(data3)
        time.sleep_us(10)

        self._writecommand(TFT.FRMCTR2)  #Frame rate control.
        self._writedata(data3)
        time.sleep_us(10)

        self._writecommand(TFT.FRMCTR3)  #Frame rate control.
        self._writedata(data3)
        time.sleep_us(10)

        self._writecommand(TFT.INVCTR)  #Display inversion control
        data1 = bytearray(1)  #
        data1[0] = 0x07
        self._writedata(data1)

        self._writecommand(TFT.PWCTR1)  #Power control
        data3[0] = 0xA2  #
        data3[1] = 0x02  #
        data3[2] = 0x84  #
        self._writedata(data3)
        time.sleep_us(10)

        self._writecommand(TFT.PWCTR2)  #Power control
        data1[0] = 0xC5  #
        self._writedata(data1)

        self._writecommand(TFT.PWCTR3)  #Power control
        data2 = bytearray(2)
        data2[0] = 0x0A  #
        data2[1] = 0x00  #
        self._writedata(data2)

        self._writecommand(TFT.PWCTR4)  #Power control
        data2[0] = 0x8A  #
        data2[1] = 0x2A  #
        self._writedata(data2)

        self._writecommand(TFT.PWCTR5)  #Power control
        data2[0] = 0x8A  #
        data2[1] = 0xEE  #
        self._writedata(data2)

        self._writecommand(TFT.VMCTR1)  #Power control
        data1[0] = 0x0E  #
        self._writedata(data1)
        time.sleep_us(10)

        self._writecommand(TFT.MADCTL)
        data1[0] = 0xC8  #row address/col address, bottom to top refresh
        self._writedata(data1)

        #These different values don't seem to make a difference.
        #     dataGMCTRP = bytearray([0x0f, 0x1a, 0x0f, 0x18, 0x2f, 0x28, 0x20, 0x22, 0x1f,
        #                             0x1b, 0x23, 0x37, 0x00, 0x07, 0x02, 0x10])
        dataGMCTRP = bytearray([
            0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2b,
            0x39, 0x00, 0x01, 0x03, 0x10
        ])
        self._writecommand(TFT.GMCTRP1)
        self._writedata(dataGMCTRP)

        #     dataGMCTRN = bytearray([0x0f, 0x1b, 0x0f, 0x17, 0x33, 0x2c, 0x29, 0x2e, 0x30,
        #                             0x30, 0x39, 0x3f, 0x00, 0x07, 0x03, 0x10])
        dataGMCTRN = bytearray([
            0x03, 0x1d, 0x07, 0x06, 0x2e, 0x2c, 0x29, 0x2d, 0x2e, 0x2e, 0x37,
            0x3f, 0x00, 0x00, 0x02, 0x10
        ])
        self._writecommand(TFT.GMCTRN1)
        self._writedata(dataGMCTRN)
        time.sleep_us(10)

        self._writecommand(TFT.CASET)  #Column address set.
        self.windowLocData[0] = 0x00
        self.windowLocData[1] = 0x02  #Start at column 2
        self.windowLocData[2] = 0x00
        self.windowLocData[3] = self._size[0] - 1
        self._writedata(self.windowLocData)

        self._writecommand(TFT.RASET)  #Row address set.
        self.windowLocData[1] = 0x01  #Start at row 2.
        self.windowLocData[3] = self._size[1] - 1
        self._writedata(self.windowLocData)

        data1 = bytearray(1)
        self._writecommand(TFT.COLMOD)  #Set color mode.
        data1[0] = 0x05  #16 bit color.
        self._writedata(data1)
        time.sleep_us(10)

        self._writecommand(TFT.NORON)  #Normal display on.
        time.sleep_us(10)

        self._writecommand(TFT.RAMWR)
        time.sleep_us(500)

        self._writecommand(TFT.DISPON)
        self.cs(1)
        time.sleep_us(500)
Ejemplo n.º 44
0
    def measure(self,
                printflag=False,
                n=12,
                on1=0,
                off1=0,
                on2=0,
                off2=0):  #take a reading
        """
        Performs a measurement of conductivity across a four-pole probe.
        
        Parameters
        ----------
        saveflag: boolean, optional
            Flag to determine if output is saved for calibration, default false
        n: int, optional
            Number of adc readings to take for the measurement, default = 12
        on1: int, optional
            time in microseconds that power pin 1 is on before taking a reading, default = 0
        off1: int, optional
            time in microseconds that power pin 1 is turned off before turning on power pin, default = 0
        on2: int, optional
            time in microseconds that power pin 2 is on before taking a reading, default = 0
        off2: int,optional
            time in microseconds that power pin 2 is turned off before turning on power pin, default = 0
            
        Returns
        -------
        resistance1 : float
            Apparent resistance computed using normal polarity.
        resistance2 : float
            Apparent resistance computed using reverse polarity.
        temperature : float
            Temperature (degrees C)
        conductivity : float
            Conductivity.
                            
        Note
        ----
        Also sets the value for temperature, conductivity, counts, and resistances
        """

        #pre-allocate arrays for counts to be read into
        imeas1 = arr.array('l', [0] * n)
        imeas2 = arr.array('l', [0] * n)
        p3meas1 = arr.array('l', [0] * n)
        p3meas2 = arr.array('l', [0] * n)
        p4meas1 = arr.array('l', [0] * n)
        p4meas2 = arr.array('l', [0] * n)

        starttime = time.ticks_us()
        for i in range(n):
            self.gpio1.high()
            time.sleep_us(on1)
            imeas1[i] = (self.adc3_current.read_u16() >> 4)
            p3meas1[i] = (self.adc1.read_u16() >> 4)
            p4meas1[i] = (self.adc2.read_u16() >> 4)
            self.gpio1.low()
            time.sleep_us(off1)

            self.gpio2.high()
            time.sleep_us(on2)
            imeas2[i] = (self.adc3_current.read_u16() >> 4)
            p3meas2[i] = (self.adc1.read_u16() >> 4)
            p4meas2[i] = (self.adc2.read_u16() >> 4)
            self.gpio2.low()
            time.sleep_us(off2)

        endtime = time.ticks_us()
        elapsed_time = endtime - starttime

        #pre-allocate arrays for current, voltage drop across poles, and resistance, for flow each direction
        i1 = arr.array('f', [0] * n)
        i2 = arr.array('f', [0] * n)
        V1 = arr.array('f', [0] * n)
        V2 = arr.array('f', [0] * n)
        R1 = arr.array('f', [0] * n)
        R2 = arr.array('f', [0] * n)

        #compute current, voltage, and resistance for each sample (do outside sampling loop to maintain sampling timing)
        for i in range(n):
            try:
                i1[i] = imeas1[i] / 4095 * 3.3 / self.con_resistance
                i2[i] = (3.3 - imeas2[i] / 4095 * 3.3) / self.con_resistance
                V1[i] = (p3meas1[i] - p4meas1[i]) / 4095 * 3.3
                V2[i] = (p4meas2[i] - p3meas2[i]) / 4095 * 3.3
                R1[i] = V1[i] / i1[i]
                R2[i] = V2[i] / i2[i]
            except:
                R1[i] = -999999
                R2[i] = -999999
                print('Error in resistance computation')

        #clean data by sampling middle two quartiles
        upper_index = math.ceil(3 * n / 4)
        lower_index = math.floor(n / 4)
        sampled_length = (upper_index - lower_index)
        self.resistance1 = sum(
            sorted(R1)[lower_index:upper_index]) / sampled_length
        self.resistance2 = sum(
            sorted(R2)[lower_index:upper_index]) / sampled_length

        icount1 = sum(sorted(imeas1)[lower_index:upper_index]) / sampled_length
        probe3count1 = sum(
            sorted(p3meas1)[lower_index:upper_index]) / sampled_length
        probe4count1 = sum(
            sorted(p4meas1)[lower_index:upper_index]) / sampled_length
        icount2 = sum(sorted(imeas2)[lower_index:upper_index]) / sampled_length
        probe3count2 = sum(
            sorted(p3meas2)[lower_index:upper_index]) / sampled_length
        probe4count2 = sum(
            sorted(p4meas2)[lower_index:upper_index]) / sampled_length

        #call thermistor reading, with 400 adc readings per measurement
        #self.T = thermistor_ac.temperature(self.adc_therm, self.therm_power, self.therm_ground, self.therm_resistance, 400)
        #self.k = self.conductivity(self.resistance2,self.A,self.B,self.C)
        #self.S = self.salinity(self.T, self.k)
        #self.k25 = self.k25(self.k,self.T)

        if printflag:
            for i in range(n):
                print(
                    'R1 = %s, R2 = %s, V1 = %s, V2 = %s, i1 = %s, i2 = %s, p3count1 = %s, p3count2 = %s, p4count1 = %s, p4count2 = %s'
                    % (R1[i], R2[i], V1[i], V2[i], i1[i], i2[i], p3meas1[i],
                       p3meas2[i], p4meas1[i], p4meas2[i]))
            print('elapsed time = %s micro seconds' % (elapsed_time))
            print('speed = %s Hz' % (n / elapsed_time * 1000000))

        return (self.resistance1, self.resistance2, icount1, probe3count1,
                probe4count1, icount2, probe3count2, probe4count2)
Ejemplo n.º 45
0
 def _write_byte(self, dat):
     self.cs.value(1)
     time.sleep_us(DELAY_US)
     self._buf1[0] = dat
     self.spi.write(self._buf1)
     self.cs.value(0)
Ejemplo n.º 46
0
    def spin_ms(self, dur_ms=0, period_ms=-1, callback=None):
        """ If not using a Timer to call `update()` regularly, calling `spin()`
        once per main loop and everywhere else instead of `time.sleep_ms()`
        is an alternative to keep the robotling board updated.
        e.g. "spin(period_ms=50, callback=myfunction)"" is setting it up,
             "spin(100)"" (~sleep for 100 ms) or "spin()" keeps it running.
    """
        #print("spin_ms(", dur_ms, period_ms, ");", self._spin_t_last_ms)

        if self._spin_period_ms > 0:
            p_ms = self._spin_period_ms
            p_us = p_ms * 1000
            d_us = dur_ms * 1000

            if dur_ms > 0 and dur_ms < (p_ms - APPROX_UPDATE_DUR_MS):
                time.sleep_ms(int(dur_ms))

            elif dur_ms >= (p_ms - APPROX_UPDATE_DUR_MS):
                # Sleep for given time while updating the board regularily; start by
                # sleeping for the remainder of the time to the next update ...
                t_us = time.ticks_us()
                dt_ms = time.ticks_diff(time.ticks_ms(), self._spin_t_last_ms)
                if dt_ms > 0 and dt_ms < p_ms:
                    time.sleep_ms(dt_ms)

                # Update
                self.update()
                self._spin_t_last_ms = time.ticks_ms()

                # Check if sleep time is left ...
                d_us = d_us - int(time.ticks_diff(time.ticks_us(), t_us))
                if d_us <= 0:
                    return

                # ... and if so, pass the remaining time by updating at regular
                # intervals
                while time.ticks_diff(time.ticks_us(), t_us) < (d_us - p_us):
                    time.sleep_us(p_us)
                    self.update()

                # Remember time of last update
                self._spin_t_last_ms = time.ticks_ms()

            else:
                # No sleep duration given, thus just check if time is up and if so,
                # call update and remember time
                d_ms = time.ticks_diff(time.ticks_ms(), self._spin_t_last_ms)
                if d_ms > self._spin_period_ms:
                    self.update()
                    self._spin_t_last_ms = time.ticks_ms()

        elif period_ms > 0:
            # Set up spin parameters and return
            self._spin_period_ms = period_ms
            self._spin_callback = callback
            self._spinTracker.reset(period_ms)
            self._spin_t_last_ms = time.ticks_ms()

        else:
            # Spin parameters not setup, therefore just sleep
            time.sleep_ms(dur_ms)
Ejemplo n.º 47
0
def uart1_handler(uart_o):
    global uart1_irq
    global uart1_int_count
    if uart1_irq.flags() & UART.RX_ANY:
        uart1_int_count += 1


uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler)
uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler)

uart0.write(b"123")
# wait for the characters to be received
while not uart1.any():
    pass

time.sleep_us(100)
print(uart1.any() == 3)
print(uart1_int_count > 0)
print(uart1_irq.flags() == 0)
print(uart0_irq.flags() == 0)
print(uart1.read() == b"123")

uart1.write(b"12345")
# wait for the characters to be received
while not uart0.any():
    pass

time.sleep_us(100)
print(uart0.any() == 5)
print(uart0_int_count > 0)
print(uart0_irq.flags() == 0)
Ejemplo n.º 48
0
 def _start(self):
     self.dio(0)
     sleep_us(TM1637_DELAY)
     self.clk(0)
     sleep_us(TM1637_DELAY)
Ejemplo n.º 49
0
 def _stop(self):
     self.dio.write_digital(0)
     time.sleep_us(TM1637_DELAY)
     self.clk.write_digital(1)
     time.sleep_us(TM1637_DELAY)
     self.dio.write_digital(1)
Ejemplo n.º 50
0
 def _stop(self):
     self.dio(0)
     sleep_us(TM1637_DELAY)
     self.clk(1)
     sleep_us(TM1637_DELAY)
     self.dio(1)
Ejemplo n.º 51
0
    def send_recv(self,
                  opcode=None,
                  p1=0,
                  p2=0,
                  body=b'',
                  resp_len=1,
                  delay=None):
        #
        # Send a command block and read response. Sometimes a delay is needed.
        #
        # use a special setup packet to WRITE a command/value to device under test
        # see ../ae.h for struct aeCmdResponse_t

        assert len(body) <= 77
        assert 1 <= resp_len <= 65, resp_len
        assert opcode

        # organize packet:
        #  flag, len, op, p1, p2, (body), crc1, crc2
        pkt = ustruct.pack('BBBBH', IOFLAG_CMD, 1 + 1 + 1 + 2 + len(body) + 2,
                           opcode, p1, p2)
        pkt += body
        pkt += crc16w(pkt[1:])

        pkt = self.serialize(pkt)

        ow = self.ow
        ow.write(b'\x00')  # WAKEUP token
        ow.read()  # thow out old garbage
        sleep_us(2500)  # tWHI: 2.5ms min
        ow.write(pkt)
        sleep_us(40)  # tTURNAROUND (80)

        if delay is None:
            # delay is required, but complete table is annoying
            if opcode in (OP.DeriveKey, OP.ECDH, OP.PrivWrite, OP.Sign):
                delay = 60
            elif opcode in (OP.GenKey, ):
                delay = 120
            else:
                delay = 20

        # delay for chip to do its maths
        sleep_ms(delay)

        while 1:
            # read back response
            ow.write(b'\x00')  # WAKEUP token
            while ow.any():
                ow.read(1)  # thow out old garbage
            sleep_us(2500)  # tWHI: 2.5ms min
            ow.write(self.x88)

            # expect back
            # - the TX token (echo)
            # - length byte
            # - 1+ body
            # - 2 bytes CRC
            #
            resp = ow.read(8 * (1 + 1 + resp_len + 2))

            if not resp:
                # chip wasn't ready yet: retry
                continue

            resp = self.deserialize(resp, 1)
            #print("resp: %r" % resp)

            if len(resp) < 4:
                # chip wasn't ready? Noise?
                raise WrongResponseLength(len(resp))

            if resp_len != resp[0] - 3:
                if (resp[0] == 4) and (crc16w(resp[:-2]) == resp[-2:]):
                    # probably an error response
                    raise ChipErrorResponse(hex(resp[1]))

                #print("wr len: %r" % resp)
                raise WrongResponseLength(len(resp))

            # check CRC, over all but last two bytes.
            expect = crc16w(resp[:-2])

            if expect != resp[-2:]:
                raise CRCError()

            return resp[1:-2]
Ejemplo n.º 52
0
 def _write_byte(self, b):
     for i in range(8):
         self.dio((b >> i) & 1)
         sleep_us(TM1637_DELAY)
         self.clk(1)
         sleep_us(TM1637_DELAY)
         self.clk(0)
         sleep_us(TM1637_DELAY)
     self.clk(0)
     sleep_us(TM1637_DELAY)
     self.clk(1)
     sleep_us(TM1637_DELAY)
     self.clk(0)
     sleep_us(TM1637_DELAY)
Ejemplo n.º 53
0
def send_byte(byte):
    sda=Pin(14,mode=Pin.OUT)
    scl=Pin(2,mode=Pin.OUT)
    scl.off()
    for i in range(8):
        if byte&0X80:
            sda.on()
            #print(1)
        else:
            sda.off()
            #print(0)
        byte<<=1
        time.sleep_us(1)
        scl.on()
        time.sleep_us(2)
        scl.off()
        time.sleep_us(1)
    sda.on()
    sda=Pin(14,mode=Pin.IN)
    time.sleep_us(1)
    scl.on()
    ack=sda.value()
    time.sleep_us(2)
    scl.off()
    time.sleep_us(1)
    if ack:
        print('device no response!')
    #print ('ack=',ack)
    return ack
Ejemplo n.º 54
0
def btnPressed(pin):
    led.toggle()
    time.sleep_us(100)
print(temp_dht22, " ºC")

print(hum_dht22, " %")

#####----- Water flow HC-SR04 -----#####

trig = Pin(4, Pin.OUT)
echo = Pin(2, Pin.IN)

timeout_us = 25000  # no need to wait more then sensor's range limit (4,00 m)

sensor_hight = 150  # cm

trig.value(1)
sleep_us(10)
trig.value(0)

duration = time_pulse_us(echo, 1, timeout_us)

if duration < 0:
    print("Out of range")
else:
    # To calculate the distance we get the pulse_time and divide it by 2
    # (the pulse walk the distance twice)
    # the sound speed on air (343.2 m/s), that It's equivalent to
    # 0.034320 cm/us that is 1cm each 29.1us
    # Calculate the Speed of Sound in M/S
    sound_comp = 331.4 + (0.606 * temp_dht22) + (0.0124 * hum_dht22)
    #    print(sound_comp, " sound_comp")
Ejemplo n.º 56
0
 def _cycle_sck(self):
     self._sck.on()
     time.sleep_us(1)
     self._sck.off()
     time.sleep_us(1)
Ejemplo n.º 57
0
def sad():

    print("Sad!")

    csPin.value(0)
    time.sleep_us(500)

    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x01)
    spi.write(0x01)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)

    time.sleep_us(500)
    csPin.value(1)
Ejemplo n.º 58
0
def happy():

    print("Happy!")

    csPin.value(0)
    time.sleep_us(500)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x02)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x01)
    spi.write(0x01)
    spi.write(0x01)
    spi.write(0x01)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)
    spi.write(0x00)

    time.sleep_us(500)
    csPin.value(1)
Ejemplo n.º 59
0
def sleep_us(time_us):
    return time.sleep_us(time_us)
Ejemplo n.º 60
0
def pulse(X=0):
    outPin.value(1)
    time.sleep_us(1)
    outPin.value(0)