wiolte.set_grove_power(False) time.sleep(1) wiolte.set_grove_power(True) # Initialize LTE modem m = wiolte.get_comm() m.set_supply_power(True) # Initialize barometer sensor i2c = machine.I2C(1) sensor_bmp = BMP280(i2c, 0x77) sensor_bmp.reset() sensor_bmp.configure() # Initialize humidity sensor pin_d38 = pyb.Pin('D38') # D38:SCL pin_d39 = pyb.Pin('D39') # D39:SDA i2c_d38 = machine.I2C(scl=pin_d38, sda=pin_d39) address_sht31 = i2c_d38.scan() if len(address_sht31) > 0: l.info("Found SHT31 at address %02x", address_sht31[0]) sensor_sht = SHT31(i2c_d38, address_sht31[0]) sensor_sht.stop_measurement() if not sensor_sht.reset(): l.error("Failed to reset SHT31") if not sensor_sht.set_heater(True): l.error("Failed to enable heater of SHT31") if not sensor_sht.start_measurement( repeatability=SHT31.REPEATABILITY_MEDIUM, mps=SHT31.MPS_10): l.error("Failed to start SHT31 measurement")
import pyb, json, time, re, ubinascii, machine MCU_ID = ubinascii.hexlify(machine.unique_id()).decode('utf-8', 'ignore') VERSION = '1.0.0' u4 = pyb.UART(4, 115200) u4.init(115200, bits=8, parity=None, stop=1) relay_1 = pyb.Pin('X5', pyb.Pin.OUT_PP) relay_2 = pyb.Pin('X6', pyb.Pin.OUT_PP) relay_3 = pyb.Pin('X7', pyb.Pin.OUT_PP) relay_4 = pyb.Pin('X8', pyb.Pin.OUT_PP) relay_5 = pyb.Pin('Y11', pyb.Pin.OUT_PP) relay_6 = pyb.Pin('Y12', pyb.Pin.OUT_PP) relay_7 = pyb.Pin('X17', pyb.Pin.OUT_PP) relay_8 = pyb.Pin('X18', pyb.Pin.OUT_PP) led_red = pyb.LED(1) led_green = pyb.LED(2) led_yellow = pyb.LED(3) led_blue = pyb.LED(4) led_red.on() led_green.on() led_yellow.on() led_blue.on() time.sleep(1) led_red.off() led_green.off() led_yellow.off() led_blue.off() def log(text): print_text = '[%s]:%s\r\n' % (int( pyb.millis() / 1000), text.replace('\r\n', ' ').replace('\r', ' '))
# main.py the main file of the project from time import sleep import pyb ## Pins # create a variable called led_green on the pin number LED_GREEN # by default the pin is an input to create an output use : Pin.OUT led_green = pyb.Pin('LED_GREEN', pyb.Pin.OUT) led_blue = machine.Pin('PD15') # another way to create a pin # create a timer using timer 4 with a freq of 1000 Hz timer = pyb.Timer(4, freq=1000) # t4_ch1 is the timer 4 channel 1 using as a pwm on the pin of the green led with a duty cycle initial of 50 % and because the timer 4 channel 1 is on the pin led_green t4_ch1 = timer.channel(1, mode=pyb.Timer.PWM, pin=led_green, pulse_width_percent=50) ## Functions def set_duty_cycle(timer_channel, duty_cycle): timer_channel.pulse_width_percent(duty_cycle) def toggle_led(led): if led.value() == 1: led.off() # led.value(0) # OFF else: led.on() # led.value(1) # ON
# PWM Control Example # # This example shows how to do PWM with your OpenMV Cam. # # WARNING: PWM control is... not easy with MicroPython. You have to use # the correct timer with the correct pins and channels. As for what the # correct values are - who knows. If you need to change the pins from the # example below please try out different timer/channel/pin configs. import pyb, time t2 = pyb.Timer(1, freq=1000) ch1 = t2.channel(2, pyb.Timer.PWM, pin=pyb.Pin("P0")) ch2 = t2.channel(3, pyb.Timer.PWM, pin=pyb.Pin("P1")) while (True): for i in range(100): ch1.pulse_width_percent(i) ch2.pulse_width_percent(100 - i) time.sleep(5) for i in range(100): ch1.pulse_width_percent(100 - i) ch2.pulse_width_percent(i) time.sleep(5)
def capture(SC_TOF0=False, SC_TOF1=False, SC_TOF2=False, DELAY=48, TIMEOUT_CAPTURE=50, TIMEOUT_BUTTON=500): # SC_TOF0 = False # SC_TOF1 = True # SC_TOF2 = False # write_while_capturing = False # FILL_NAME = "DATA_CUPTURED" # the csv file name. Acquiescently, the file csv will save in the folder /data_csv # TIMEOUT_CAPTURE = 50 # TIMEOUT_BUTTON = 500 # constant for distinguish the long press and short press # DELAY = 48 XSHUT_PIN_TOF_0 = "X6" XSHUT_PIN_TOF_1 = "X7" XSHUT_PIN_TOF_2 = "X8" ADDR_TOF_0 = 0x3C ADDR_TOF_1 = 0x3A ADDR_TOF_2 = 0x30 # Step I : configure the different sensors so that they will have different address # 1, configure the Xshut pins for sensors pin_for_TOF_0 = pyb.Pin(XSHUT_PIN_TOF_0, pyb.Pin.OUT) pin_for_TOF_1 = pyb.Pin(XSHUT_PIN_TOF_1, pyb.Pin.OUT) pin_for_TOF_2 = pyb.Pin(XSHUT_PIN_TOF_2, pyb.Pin.OUT) # 2, shutdown all pins handing_pin.Pin_TurnOff_C(pin_for_TOF_0) handing_pin.Pin_TurnOff_C(pin_for_TOF_1) handing_pin.Pin_TurnOff_C(pin_for_TOF_2) # 3, create a new i2c object i2c = machine.I2C(sda='X10', scl='X9', freq=400000) # 4, configure TOF1's address if SC_TOF0: handing_pin.Pin_TurnOn_C(pin_for_TOF_0) pyb.delay(10) Tof0 = VL53L0X(i2c) Tof0.set_timeout(TIMEOUT_CAPTURE) Tof0.set_address(ADDR_TOF_0) Tof0.init() # 5, configure TOF1's address if SC_TOF1: handing_pin.Pin_TurnOn_C( pin_for_TOF_1) # turn on the pin of Xshut for the sensor TOF1 pyb.delay( 10 ) # necessary delay for the response of the change of pin's level Tof1 = VL53L0X( i2c) # connect the i2c bus with the sensor and initialize Tof1.set_timeout( TIMEOUT_CAPTURE) # configure the interval of the sampling Tof1.set_address( ADDR_TOF_1) # configure the address of the sensor TOF1 Tof1.init( ) # redo the initialization of the sensor after change its address and timeout # 6, configure TOF2's address if SC_TOF2: handing_pin.Pin_TurnOn_C(pin_for_TOF_2) pyb.delay(10) Tof2 = VL53L0X(i2c) Tof2.set_timeout(TIMEOUT_CAPTURE) Tof2.set_address(ADDR_TOF_2) Tof2.init() # fin configuration of the address of the sensors # Step II : range the captured datas and send them to PC via USB while True: lighting.Light_Script_Ready() # ##*********** The script is ready now, start your show *************## # prepairing for initial information running = True start_time = utime.ticks_ms() ms_time = utime.ticks_ms() time_now = ms_time while True: sw = pyb.Switch() if sw.value(): if handing_button.button_control(TIMEOUT_BUTTON) == "L": running = False lighting.Light_FinDeEcrire() break elif handing_button.button_control(TIMEOUT_BUTTON) == "S": running = not running if running: if SC_TOF0: while (utime.ticks_diff(time_now, ms_time) < DELAY): time_now = utime.ticks_ms() pass ms_time = utime.ticks_ms() handing_file.organiser_content("TOF0", time_now, Tof0.range) if SC_TOF1: while (utime.ticks_diff(time_now, ms_time) < DELAY): time_now = utime.ticks_ms() pass ms_time = utime.ticks_ms() handing_file.organiser_content("TOF1", time_now, Tof1.range) if SC_TOF2: while (utime.ticks_diff(time_now, ms_time) < DELAY): time_now = utime.ticks_ms() pass ms_time = utime.ticks_ms() handing_file.organiser_content("TOF2", time_now, Tof2.range) lighting.Light_EnTrainDeEcrire() if running is not True: lighting.Light_Pause() lighting.Light_EnRepos()
def low_power_pins(disable_3v3=False, disable_leds=False): # from https://github.com/micropython/micropython/issues/4686 pins = [ # user IO pins 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'A11', 'A12', 'A13', 'A14', 'A15', 'B0', 'B1', 'B3', 'B4', 'B5', 'B7', 'B8', 'B9', 'B10', 'B11', 'B12', 'B13', 'C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'D0', 'D3', 'D8', 'D9', 'E0', 'E1', 'E12', 'E14', 'E15', 'F1', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F13', 'F14', 'F15', 'H2', 'H3', 'H5', 'H6', 'H7', 'H8', 'I0', 'I1', # internal pins 'D1', 'D14', 'D15', 'F0', 'F12', 'G0', 'G1', 'G2', 'G3', 'G4', 'G5', #'G6', 'H4', 'H9', 'H10', 'H11', 'H12', 'H13', 'H14', 'H15', 'I2', 'I3', ] pins_led = [ 'F3', 'F4', 'F5', ] pins_sdmmc = ['D6', 'D7', 'G9', 'G10', 'G11', 'G12'] pins_wlan = ['D2', 'D4', 'I7', 'I8', 'I9', 'I11'] pins_bt = [ 'D5', 'D10', 'E3', 'E4', 'E5', 'E6', 'G8', 'G13', 'G14', 'G15', 'I4', 'I5', 'I6', 'I10' ] pins_qspi1 = ['B2', 'B6', 'D11', 'D12', 'D13', 'E2'] pins_qspi2 = ['E7', 'E8', 'E9', 'E10', 'E11', 'E13'] for p in pins: pyb.Pin(p, pyb.Pin.IN, pyb.Pin.PULL_DOWN) if disable_3v3: pyb.Pin('EN_3V3', pyb.Pin.IN, None) if disable_leds: for p in pins_led: pyb.Pin(p, pyb.Pin.IN, pyb.Pin.PULL_UP)
def tft_init(self, controller="SSD1963", lcd_type="LB04301", orientation=LANDSCAPE, v_flip=False, h_flip=False, power_control=True): # # For convenience, define X1..X1 and Y9..Y12 as output port using thy python functions. # X1..X8 will be redefind on the fly as Input by accessing the MODER control registers # when needed. Y9 is treate seperately, since it is used for Reset, which is done at python level # since it need long delays anyhow, 5 and 15 ms vs. 10 µs. # # Set TFT general defaults self.controller = controller self.lcd_type = lcd_type self.orientation = orientation self.v_flip = v_flip # flip vertical self.h_flip = h_flip # flip horizontal self.c_flip = 0 # flip blue/red self.rc_flip = 0 # flip row/column self.setColor((255, 255, 255)) # set FG color to white as can be. self.setBGColor((0, 0, 0)) # set BG to black # self.pin_led = None # deferred init Flag self.power_control = power_control if self.power_control: # special treat for Power Pin self.pin_power = pyb.Pin("Y4", pyb.Pin.OUT_PP) self.power(True) ## switch Power on # pyb.delay(10) # this may have to be moved to the controller specific section if orientation == PORTRAIT: self.setXY = TFT_io.setXY_P self.drawPixel = TFT_io.drawPixel_P else: self.setXY = TFT_io.setXY_L self.drawPixel = TFT_io.drawPixel_L self.swapbytes = TFT_io.swapbytes self.swapcolors = TFT_io.swapcolors # ---------- for pin_name in [ "X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "Y10", "Y11", "Y12" ]: pin = pyb.Pin(pin_name, pyb.Pin.OUT_PP) # set as output pin.value(1) ## set high as default # special treat for Reset self.pin_reset = pyb.Pin("Y9", pyb.Pin.OUT_PP) # Reset the device self.pin_reset.value(1) ## do a hard reset pyb.delay(10) self.pin_reset.value(0) ## Low pyb.delay(20) self.pin_reset.value(1) ## set high again pyb.delay(20) # # Now initialiize the LCD # This is for the SSD1963 controller and two specific LCDs. More may follow. # Data taken from the SSD1963 data sheet, SSD1963 Application Note and the LCD Data sheets # if controller == "SSD1963": # 1st approach for 480 x 272 TFT_io.tft_cmd_data(0xe2, bytearray(b'\x1d\x02\x54'), 3) # PLL multiplier, set PLL clock to 100M # N=0x2D for 6.5MHz, 0x1D for 10MHz crystal # PLLClock = Crystal * (Mult + 1) / (Div + 1) # The intermediate value Crystal * (Mult + 1) must be between 250MHz and 750 MHz TFT_io.tft_cmd_data(0xe0, bytearray(b'\x01'), 1) # PLL Enable pyb.delay(10) TFT_io.tft_cmd_data(0xe0, bytearray(b'\x03'), 1) pyb.delay(10) TFT_io.tft_cmd(0x01) # software reset pyb.delay(10) # # Settings for the LCD # # The LCDC_FPR depends on PLL clock and the reccomended LCD Dot clock DCLK # # LCDC_FPR = (DCLK * 1048576 / PLLClock) - 1 # # The other settings are less obvious, since the definitions of the SSD1963 data sheet and the # LCD data sheets differ. So what' common, even if the names may differ: # HDP Horizontal Panel width (also called HDISP, Thd). The value store in the register is HDP - 1 # VDP Vertical Panel Width (also called VDISP, Tvd). The value stored in the register is VDP - 1 # HT Total Horizontal Period, also called HP, th... The exact value does not matter # VT Total Vertical Period, alco called VT, tv, .. The exact value does not matter # HPW Width of the Horizontal sync pulse, also called HS, thpw. # VPW Width of the Vertical sync pulse, also called VS, tvpw # Front Porch (HFP and VFP) Time between the end of display data and the sync pulse # Back Porch (HBP and VBP Time between the start of the sync pulse and the start of display data. # HT = FP + HDP + BP and VT = VFP + VDP + VBP (sometimes plus sync pulse width) # Unfortunately, the controller does not use these front/back porch times, instead it uses an starting time # in the front porch area and defines (see also figures in chapter 13.3 of the SSD1963 data sheet) # HPS Time from that horiz. starting point to the start of the horzontal display area # LPS Time from that horiz. starting point to the horizontal sync pulse # VPS Time from the vert. starting point to the first line # FPS Time from the vert. starting point to the vertical sync pulse # # So the following relations must be held: # # HT > HDP + HPS # HPS >= HPW + LPS # HPS = Back Porch - LPS, or HPS = Horizontal back Porch # VT > VDP + VPS # VPS >= VPW + FPS # VPS = Back Porch - FPS, or VPS = Vertical back Porch # # LPS or FPS may have a value of zero, since the length of the front porch is detemined by the # other figures # # The best is to start with the recomendations of the lCD data sheet for Back porch, grab a # sync pulse with and the determine the other, such that they meet the relations. Typically, these # values allow for some ambuigity. # if lcd_type == "LB04301": # Size 480x272, 4.3", 24 Bit, 4.3" # # Value Min Typical Max # DotClock 5 MHZ 9 MHz 12 MHz # HT (Hor. Total 490 531 612 # HDP (Hor. Disp) 480 # HBP (back porch) 8 43 # HFP (Fr. porch) 2 8 # HPW (Hor. sync) 1 # VT (Vert. Total) 275 288 335 # VDP (Vert. Disp) 272 # VBP (back porch) 2 12 # VFP (fr. porch) 1 4 # VPW (vert. sync) 1 10 # # This table in combination with the relation above leads to the settings: # HPS = 43, HPW = 8, LPS = 0, HT = 531 # VPS = 14, VPW = 10, FPS = 0, VT = 288 # self.disp_x_size = 479 self.disp_y_size = 271 TFT_io.tft_cmd_data_AS(0xe6, bytearray(b'\x01\x70\xa3'), 3) # PLL setting for PCLK # (9MHz * 1048576 / 100MHz) - 1 = 94371 = 0x170a3 TFT_io.tft_cmd_data_AS( 0xb0, bytearray( # # LCD SPECIFICATION [ 0x20, # 24 Color bits, HSync/VSync low, No Dithering 0x00, # TFT mode self.disp_x_size >> 8, self.disp_x_size & 0xff, # physical Width of TFT self.disp_y_size >> 8, self.disp_y_size & 0xff, # physical Height of TFT 0x00 ]), 7) # Last byte only required for a serial TFT TFT_io.tft_cmd_data_AS( 0xb4, bytearray(b'\x02\x13\x00\x2b\x08\x00\x00\x00'), 8) # HSYNC, Set HT 531 HPS 43 HPW=Sync pulse 8 LPS 0 TFT_io.tft_cmd_data_AS( 0xb6, bytearray(b'\x01\x20\x00\x0e\x0a\x00\x00'), 7) # VSYNC, Set VT 288 VPS 14 VPW 10 FPS 0 TFT_io.tft_cmd_data_AS( 0x36, bytearray([(orientation & 1) << 5 | (h_flip & 1) << 1 | (v_flip) & 1]), 1) # rotation/ flip, etc., t.b.d. elif lcd_type == "AT070TN92": # Size 800x480, 7", 18 Bit, lower color bits ignored # # Value Min Typical Max # DotClock 26.4 MHz 33.3 MHz 46.8 MHz # HT (Hor. Total 862 1056 1200 # HDP (Hor. Disp) 800 # HBP (back porch) 46 46 46 # HFP (Fr. porch) 16 210 254 # HPW (Hor. sync) 1 40 # VT (Vert. Total) 510 525 650 # VDP (Vert. Disp) 480 # VBP (back porch) 23 23 23 # VFP (fr. porch) 7 22 147 # VPW (vert. sync) 1 20 # # This table in combination with the relation above leads to the settings: # HPS = 46, HPW = 8, LPS = 0, HT = 1056 # VPS = 23, VPW = 10, VPS = 0, VT = 525 # self.disp_x_size = 799 self.disp_y_size = 479 TFT_io.tft_cmd_data_AS(0xe6, bytearray(b'\x05\x53\xf6'), 3) # PLL setting for PCLK # (33.3MHz * 1048576 / 100MHz) - 1 = 349174 = 0x553f6 TFT_io.tft_cmd_data_AS( 0xb0, bytearray( # # LCD SPECIFICATION [ 0x00, # 18 Color bits, HSync/VSync low, No Dithering/FRC 0x00, # TFT mode self.disp_x_size >> 8, self.disp_x_size & 0xff, # physical Width of TFT self.disp_y_size >> 8, self.disp_y_size & 0xff, # physical Height of TFT 0x00 ]), 7) # Last byte only required for a serial TFT TFT_io.tft_cmd_data_AS( 0xb4, bytearray(b'\x04\x1f\x00\x2e\x08\x00\x00\x00'), 8) # HSYNC, Set HT 1056 HPS 46 HPW 8 LPS 0 TFT_io.tft_cmd_data_AS( 0xb6, bytearray(b'\x02\x0c\x00\x17\x08\x00\x00'), 7) # VSYNC, Set VT 525 VPS 23 VPW 08 FPS 0 TFT_io.tft_cmd_data_AS( 0x36, bytearray([(orientation & 1) << 5 | (h_flip & 1) << 1 | (v_flip) & 1]), 1) # rotation/ flip, etc., t.b.d. else: print("Wrong Parameter lcd_type: ", lcd_type) return TFT_io.tft_cmd_data_AS(0xBA, bytearray(b'\x0f'), 1) # GPIO[3:0] out 1 TFT_io.tft_cmd_data_AS(0xB8, bytearray(b'\x07\x01'), 1) # GPIO3=input, GPIO[2:0]=output TFT_io.tft_cmd_data_AS(0xf0, bytearray(b'\x00'), 1) # Pixel data Interface 8 Bit TFT_io.tft_cmd(0x29) # Display on TFT_io.tft_cmd_data_AS(0xbe, bytearray(b'\x06\xf0\x01\xf0\x00\x00'), 6) # Set PWM for B/L TFT_io.tft_cmd_data_AS(0xd0, bytearray(b'\x0d'), 1) # Set DBC: enable, agressive else: print("Wrong Parameter controller: ", controller) return # # Set character printing defaults # self.text_font = None self.setTextStyle(self.color, self.BGcolor, 0, None, 0) # # Init done. clear Screen and switch BG LED on # self.text_x = self.text_y = self.text_yabs = 0 self.clrSCR() # clear the display
# # Created: 10/03/17 # - Joshua Vaughan # - [email protected] # - http://www.ucs.louisiana.edu/~jev9637 # # Modified: # * 10/23/18 - JEV - [email protected] # - Changed pin to reflect upcoming MCHE201 breakout board # - Better commenting # TODO: # * ############################################################################### import pyb # import the pyboard module import time # import the time module # Assign the output pint to variable output_pin # We set it up as an output with a pulldown resistor output_pin = pyb.Pin("X7", pyb.Pin.OUT_PP, pull=pyb.Pin.PULL_DOWN) # This for loop will run 10 times for counter in range(10): print("Turning on") output_pin.value(1) # Toggle the output_pin high/on time.sleep_ms(500) # Sleep 500 milliseconds (0.5s) print("Turning off") output_pin.value(0) # Toggle the output_pin low/off time.sleep_ms(1500) # Sleep 1500 seconds (1.5s)
def __init__(self): ''' Creates a motor driver by initializing GPIO pins and turning the motor off for safety. ''' import pyb print('Creating a motor driver') pinA10 = pyb.Pin(pyb.Pin.board.PA10, pyb.Pin.OUT_PP) #ENA -> pin10 pinA10.high() #enable motor
def pins(): for pin_name in dir(pyb.Pin.board): pin = pyb.Pin(pin_name) print('{:10s} {:s}'.format(pin_name, str(pin)))
def af(): for pin_name in dir(pyb.Pin.board): pin = pyb.Pin(pin_name) print('{:10s} {:s}'.format(pin_name, str(pin.af_list())))
'lsm9ds1_accgyr': { 'i2c_bus': 2, 'i2c_addr': 0x6A }, 'lsm9ds1_mag': { 'i2c_bus': 2, 'i2c_addr': 0x1C }, 'extPower': { 'enable': "EN_3V3" }, } sel = 0 pon = pyb.Pin(config['extPower']['enable']) pon.on() time.sleep_ms(20) tile = led36() pyb.Pin('PULL_SCL', pyb.Pin.OUT, value=1) # enable 5.6kOhm X9/SCL pull-up pyb.Pin('PULL_SDA', pyb.Pin.OUT, value=1) # enable 5.6kOhm X10/SDA pull-up i2cx = machine.I2C('X') i2cy = pyb.I2C(config['lps22hh']['i2c_bus'], pyb.I2C.MASTER, baudrate=100000) lps22 = LPS22HH(i2cy, config['lps22hh']['i2c_addr']) lsm9d1 = LSM9DS1(i2cy, config['lsm9ds1_accgyr']['i2c_addr'], config['lsm9ds1_accgyr']['i2c_addr'], config['lsm9ds1_mag']['i2c_addr']) tile.brightness(100) tile.fill_rgb(255, 255, 255)
# polarity = 0 -> clock is idle low. # phase = 0 -> sample data on rising clock edge, output data on falling clock edge. spi = pyb.SPI(2, pyb.SPI.SLAVE, polarity=0, phase=0) # NSS callback. def nss_callback(line): global spi, data try: spi.send(data, timeout=1000) except OSError as err: pass # Don't care about errors - so pass. # Note that there are 3 possible errors. A timeout error, a general purpose error, or # a busy error. The error codes are 116, 5, 16 respectively for "err.arg[0]". # Configure NSS/CS in IRQ mode to send data when requested by the master. pyb.ExtInt(pyb.Pin("P3"), pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, nss_callback) while(True): time.sleep(1000) ################################################################################################### # Arduino Code ################################################################################################### # # #include <SPI.h> # #define SS_PIN 10 # #define BAUD_RATE 19200 # #define CHAR_BUF 128 # # void setup() { # pinMode(SS_PIN, OUTPUT);
def run_mainloop(): """Standard Interface for MainLoop. Never returns.""" # Initialize the node state as always on node_state = STATE_ALWAYS_ON # Enable the NM3 power supply on the powermodule powermodule = PowerModule() powermodule.enable_nm3() # Enable power supply to 232 driver pyb.Pin.board.EN_3V3.on() pyb.Pin('Y5', pyb.Pin.OUT, value=0) # enable Y4 Pin as output max3221e = MAX3221E(pyb.Pin.board.Y5) max3221e.tx_force_on() # Enable Tx Driver # Wait for 6 seconds to let the modem start up print("6 second delay to allow the NM3 to boot up...") pyb.delay(6 * 1000) # Initialize UART and NM3 object uart = machine.UART(1, 9600, bits=8, parity=None, stop=1, timeout=1000) modem = Nm3(uart) # Generate the sensor payload object sensor_pl = sensor_payload.get_sensor_payload_instance() # Create and initialize the network protocol object net_protocol = sensor_node.NetProtocol() net_protocol.init_interfaces(modem, sensor_pl) # Start an infinite loop, listen to packets and respond first_frame_finished = False # this is for testing the sleep timing returned by the network protocol while True: # Check if a packet has been received modem.poll_receiver() modem.process_incoming_buffer() if modem.has_received_packet(): # If it has, process it and pass it on to the TDA-MAC protocol handler packet = modem.get_received_packet() payload = bytes(packet.packet_payload) # Here I assume that this packet is definitely for Networking: "UN..." # In the full main loop, we will direct "UL..." and "UN..." packets to their respective modules here. # After localisation is finished, it will be easiest to return the (Lat, Lon) here, # e.g. returned by Rahul's localisation function called in this loop. # It then can be passed to the Network Protocol object using: # net_protocol.set_location(lat, lon) # This will allow the node locations to be collected later using TDA-MAC, at the start of the data gathering stage # If the packet is "UN...", call this function handling all networking packets # It returns a flag stating whether the node can go to a sleep state until the next frame, # and the time [msec] until the next expected REQ packet from the master node (gateway or relay) if first_frame_finished and (payload[0:3] == b'UNR'): print("REQ Packet received. Time since I last went to sleep: " + \ str(utime.ticks_diff(utime.ticks_ms(), last_sleep_start_time)) + " msec") (can_go_to_sleep, time_till_next_req) = net_protocol.handle_packet(packet) if can_go_to_sleep: print("I can go to sleep. Next REQ expected after " + str(time_till_next_req) + " msec") last_sleep_start_time = utime.ticks_ms() first_frame_finished = True # If the TDA-MAC initialization has finished and the node can go to sleep, update the node state if (can_go_to_sleep): node_state = STATE_PERIODIC_SLEEP else: node_state = STATE_ALWAYS_ON # In this test, do not put the node to sleep # [TO INCORPORATE SLEEP MODE] # if (node_state == STATE_PERIODIC_SLEEP), # Put the node to sleep, but wake up (at the latest) after "time_till_next_req" msec # MINUS the time needed to power up all the modules (e.g. 6000 msec) # In this test, simply keep checking the input in 20 ms time increments pyb.delay(20)
print("Circle intersection failed #3") return None # circles are coincident and there are an infinite number of solutions a = (r1 * r1 - r2 * r2 + d * d) / (2 * d) h = sqrt(r1 * r1 - a * a) xm = x1 + a * dx / d ym = y1 + a * dy / d xs1 = xm + h * dy / d xs2 = xm - h * dy / d ys1 = ym - h * dx / d ys2 = ym + h * dx / d return (xs1, ys1), (xs2, ys2) lowerArmStep = pyb.Pin('Y9', pyb.Pin.OUT_PP) lowerArmDirn = pyb.Pin('Y10', pyb.Pin.OUT_PP) upperArmStep = pyb.Pin('Y11', pyb.Pin.OUT_PP) upperArmDirn = pyb.Pin('Y12', pyb.Pin.OUT_PP) pulseWidthUsecs = 1 betweenPulsesUsecs = 500 # Upper arm degrees per step calculation # Stepper motors move 1.8 degrees per full step # In microstepping mode so 16 microsteps per step # Motor shaft pulley has 20 teeth # Upper arm pulley has 62 teeth upperStepsPerDegree = 1 / ((1.8 / 16) * (20 / 62)) print("Upper steps per degree", upperStepsPerDegree)
def __init__(self, port): self.port = pyb.Pin(port, pyb.Pin.OUT_PP) self.port.low()
# TODO # # @author Rahul Goyal, Cameron Kao, Harry Whinnery # # @copyright License Info # # @date January 31, 2019 import controller import encoder import motor import pyb import utime ## A motor object pinENA = pyb.Pin(pyb.Pin.board.PA10, pyb.Pin.OUT_PP) pinIN1A = pyb.Pin(pyb.Pin.board.PB4, pyb.Pin.OUT_PP) pinIN2A = pyb.Pin(pyb.Pin.board.PB5, pyb.Pin.OUT_PP) motor = motor.MotorDriver([pinIN1A, pinIN2A, pinENA], 3, [1, 2]) ## An encoder object encoder = encoder.Encoder([pyb.Pin.board.PB6, pyb.Pin.board.PB7], 4, [1, 2]) ## A controller object controller = controller.Controller(K_p=0.10) # # Positioner # while(True): # motor.set_duty_cycle(controller.run(encoder.read())) # utime.sleep_ms(10) # Step repsonse while (True):
import pyb import time pin = pyb.Pin(2, pyb.Pin.OUT) for i in range(4): print('LED ON') pin.value(0) time.sleep(1) print('LED OFF') pin.value(1) time.sleep(1) print('iteration done.') print("All done.")
import cotask import task_share import print_task import controller import encoder import motor import time import utime # Allocate memory so that exceptions raised in interrupt service routines can # generate useful diagnostic printouts micropython.alloc_emergency_exception_buf (100) pinC0 = pyb.Pin (pyb.Pin.board.PC0, pyb.Pin.ANALOG) queue = task_share.Queue('f', 1000) adc = pyb.ADC(pinC0) pinC1 = pyb.Pin (pyb.Pin.board.PC1, pyb.Pin.OUT_PP) def main(): global pinC0 global queue global adc global pinC1 tim = pyb.Timer(1) tim.init(freq= 1000) tim.callback(interrupt) while True : pinC1.high ()
yellow_thresholds = [(55, 75, -15, 5, 40, 70)] #黄色ゴールのしきい値 blue_thresholds = [(30, 45, -5, 35, -60, -30)] #青色ゴールのしきい値 mirror_cx = 150 mirror_cy = 112 # You may pass up to 16 thresholds above. However, it's not really possible to segment any # scene with 16 thresholds before color thresholds start to overlap heavily. led = pyb.LED(3) sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time=2000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking clock = time.clock() spi = pyb.SPI(2, pyb.SPI.SLAVE, polarity=0, phase=0) ss = pyb.Pin('P3', pyb.Pin.IN, pull=pyb.Pin.PULL_UP) color_set_pin = pyb.Pin('P4', pyb.Pin.IN) angle = 0 distance = 0 # Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are # returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the # camera resolution. Don't set "merge=True" becuase that will merge blobs which we don't want here. while (True): clock.tick() img = sensor.snapshot() rightx = 0 leftx = 0 state = 0 x = 0 y = 0
|RES |X3 | """ import pyb # from adafruit arduino init_cmds = [0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0x0, 0x40, 0x8D, 0x14, 0x20, 0x00, 0xA1, 0xC8, 0xDA, 0x12, 0x81, 0xCF, 0xd9, 0xF1, 0xDB, 0x40, 0xA4, 0xA6, 0xAF] display_cmds = [0x21, 0, 127, 0x22, 0, 7] ## set up SPI bus rate = 8000000 spi = pyb.SPI(1, pyb.SPI.MASTER, baudrate=rate, polarity=0, phase=0) # SCK: Y6: MOSI: Y8 dc = pyb.Pin('X4', pyb.Pin.OUT_PP, pyb.Pin.PULL_DOWN) res = pyb.Pin('X3', pyb.Pin.OUT_PP, pyb.Pin.PULL_DOWN) def write_command(cmd): """ write single command byte to ssd1306 """ dc.low() spi.send(cmd) ## power on res.high() pyb.delay(1) res.low() pyb.delay(10) res.high()
def __init__(self, timer, pin, chan): """This method initializes a servo object with the specified pins and channels""" servo_pin = pyb.Pin(pin, pyb.Pin.OUT_PP) tim = pyb.Timer(timer, prescaler=79, period=19999) self.ch = tim.channel(chan, pyb.Timer.PWM, pin=servo_pin)
# i/o A15 switches boot modes from dupterm to UART6 <> UART3 pass through for screen programming. import pyb from pyb import UART import uos sp = pyb.Pin( 'A15', pyb.Pin.IN) # Activate input A15 (red led) connected to ESP8266 i/o 14 pyb.delay(10) if sp.value() == 1: uart6 = UART(6) uart6.init(9600, read_buf_len=256) uart3 = UART(3) uart3.init(9600, read_buf_len=256) # Try higher values if necessary while True: nrx = uart3.any() # Count available characters if nrx: uart6.write(uart3.read( nrx)) # Only read what's available: it should never time out nrx = uart6.any() if nrx: uart3.write(uart6.read(nrx)) else: uart6 = UART(6) uart6.init(9600) uos.dupterm(uart6) # duplicate repl on UART(6)
import pyb ## Set Pin PA10 toas open-drain output with pull up resistors #EN_Pin=pyb.Pin(pyb.Pin.board.PA10,pyb.Pin.OUT_OD, pull=pyb.Pin.PULL_UP) ## Set Pin PB4 as push-pull with the correct alternate function (timer) Pin_1=pyb.Pin(pyb.Pin.board.PC6, pyb.Pin.OUT_OD, pull=pyb.Pin.PULL_UP) ## Set Pin PB5 as push-pull with the correct alternate function (timer) Pin_2=pyb.Pin(pyb.Pin.board.PC7, pyb.Pin.OUT_OD, pull=pyb.Pin.PULL_UP) #EN_Pin.low() # Set Pins Low on startup Pin_1.low() Pin_2.low() print('We are On')
import pyb hid = pyb.USB_HID() key = pyb.Pin('X1', pyb.Pin.IN) while True: hid.send((0, 10, 0, 0)) pyb.delay(1000)
import pyb pin = pyb.Pin(14, pyb.Pin.OUT) for i in range(10): pin.value(0) pyb.delay(1000) pin.value(1) pyb.delay(1000)
def __init__(self): self.adc = pyb.ADC(pyb.Pin('PC5')) self.dac = pyb.DAC(2, bits = 12) self.myIIR = IIR(1, 1, -1022) self.timer = pyb.Timer(2, freq = 1000)
import pyb from contextlib import contextmanager import os def button(int x, str pull): pull.lower() if pull == 'none': pull = Pin.PULL_NONE elif pull == 'up': pull = Pin.PULL_UP elif pull == 'down': pull = Pin.PULL_DOWN b = pyb.Pin(x, pull) return pull def led_ob(): led = [] while i < 4: led[i] = pub.LED(i) return led # http://stackoverflow.com/a/24176022 # shameless copy paste @contextmanager def cd(newdir): prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir))
import pyb import upcd8544 from machine import SPI, Pin from pyb import UART from ubinascii import hexlify from ubinascii import * #以上为声明使用到的类库 leds = [pyb.LED(i) for i in range(1, 5)] P, L, SHUCHU = 0, 0, 0 SPI = pyb.SPI(1) #DIN=>X8-MOSI/CLK=>X6-SCK #DIN =>SPI(1).MOSI 'X8' data flow (Master out, Slave in) #CLK =>SPI(1).SCK 'X6' SPI clock RST = pyb.Pin('X20') CE = pyb.Pin('X19') DC = pyb.Pin('X18') LIGHT = pyb.Pin('X17') #以上为初始化显示屏的函数,虽然这次没有用到显示,但是备用 lcd_5110 = upcd8544.PCD8544(SPI, RST, CE, DC, LIGHT) count_ = 0 N2 = Pin('Y3', Pin.OUT_PP) N1 = Pin('Y6', Pin.OUT_PP) #定义通信系统启动引脚 N1.low() pyb.delay(2000) N1.high() pyb.delay(10000) #拉高拉低引脚,启动通信系统 u2 = UART(4, 115200) #定义串口4,设置 波特率为115200 K = 5 #设置一个选择变量K while (K == 5): #这个循环是为了设置通信区域模式为透传模式。 u2.write('AT+CIPMODE=1\r\n') pyb.delay(500) if (u2.any() > 0):
import pyb import stm # This script sets up a timer to do quadrature decoding # # It was tested using a switch similar to https://www.sparkfun.com/products/9117 # with some debounce wired up like this: https://hifiduino.files.wordpress.com/2010/10/analogdeb.jpg # Note: the debounce is only really required for mechanical switches. # # I also tested this with one of these: http://www.lynxmotion.com/p-448-quadrature-motor-encoder-wcable.aspx pin_a = pyb.Pin('X1', pyb.Pin.AF_PP, pull=pyb.Pin.PULL_NONE, af=pyb.Pin.AF1_TIM2) pin_b = pyb.Pin('X2', pyb.Pin.AF_PP, pull=pyb.Pin.PULL_NONE, af=pyb.Pin.AF1_TIM2) # The prescaler needs to be 0. When incrementing, the counter will count up-to # and including the period value, and then reset to 0. enc_timer = pyb.Timer(2, prescaler=0, period=100000) # ENC_AB will increment/decrement on the rising edge of either the A channel or the B # channel. enc_channel = enc_timer.channel(1, pyb.Timer.ENC_AB) while True: print("Counter =", enc_timer.counter()) pyb.delay(200)