def __init__(self, pins_dict, timer=6, reverse_pols=False): self.__enable = pwm.PWM(pins_dict['enable']) self.__control0 = pins_dict['control0'] if not reverse_pols else pins_dict['control1'] self.__control0.init(pyb.Pin.OUT_PP) self.__control0.low() self.__control1 = pins_dict['control1'] if not reverse_pols else pins_dict['control0'] self.__control1.init(pyb.Pin.OUT_PP) self.__control1.low() self.__led = pins_dict['led'] self.__led.init(pyb.Pin.OUT_PP) self.__tack0 = pins_dict['tack0'] if not reverse_pols else pins_dict['tack1'] self.__tack1 = pins_dict['tack1'] if not reverse_pols else pins_dict['tack0'] self.__tack1.init(pyb.Pin.IN) #pyb.millis doesn't have enough resolution #start timer at TIMER_FREQ, with max possible period if timer in [1,8,9,10,11]: self.__ucounter = pyb.Timer(timer, prescaler=int(pyb.freq()[3]/TIMER_FREQ), period=0x7fffffff) elif timer in [2,3,4,5,6,7,12,13,14]: self.__ucounter = pyb.Timer(timer, prescaler=int(pyb.freq()[2]/TIMER_FREQ), period=0x7fffffff) self.__tim_rollover = False #set a callback on the timer which sets __tim_rollover true if it overflows #i.e. it counts past it's period, without a tack occuring. #if so we assume speed is zero as we can no longer measure it self.__ucounter.callback(self.__ISR_TIMER_SPEED) self.__pulsetime = 0 #this is measured speed ... we are at rest self.__pulsedir = 0 #at init doesn't matter what direction this indicates #register interrupt on tack0 self.__extint = pyb.ExtInt(self.__tack0, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, self.__ISR_TACK_SPEED)
def run_tests(freqs, fb): print("Starting tests...") pyb.freq(freqs[0], freqs[1], freqs[2], freqs[3]) dt = [] for i in range(0, 10): dt.append(compute_time(fb)) avg_dt = average(dt) return avg_dt
def run_tests(): results_str = "Decoder;Format;CPU;AHB;APB1;APB2;Average time in ms\n" freqs_test = [[56000000, 56000000, 14000000, 28000000], [84000000, 84000000, 42000000, 84000000]] # Switch on LEDs to show start for led in [LED(i) for i in range(1, 3)]: led.on() for freqs in freqs_test: fr_cols = ';'.join(str(int(f / 1000000)) for f in freqs) pyb.freq(freqs[0], freqs[1], freqs[2], freqs[3]) avg_dt_jpg = display_jpeg("images/test3.jpg") results_str += "{};{};{};{}\n".format("jpeg", "RGB565", fr_cols, avg_dt_jpg) avg_dt_bmp24 = display_bmp("images/test24.bmp") results_str += "{};{};{};{}\n".format("bmp", "RGB565", fr_cols, avg_dt_bmp24) #avg_dt_bmp256 = display_bmp("images/test256.bmp") #results_str += "{};{};{};{}\n".format("bmp", "PAL256", fr_cols, avg_dt_bmp256) #avg_dt_bmp16 = display_bmp("images/test16.bmp") #results_str += "{};{};{};{}\n".format("bmp", "PAL16", fr_cols, avg_dt_bmp16) #avg_dt_gif = display_gif("images/test256.gif") #results_str += "{};{};{};{}\n".format("gif", "RGB565", fr_cols, avg_dt_gif) avg_dt_p16 = display_p16("images/test.p16") results_str += "{};{};{};{}\n".format("p16", "PAL16", fr_cols, avg_dt_p16) avg_dt_p16_py = display_p16_py("images/test.p16") results_str += "{};{};{};{}\n".format("p16_py", "PAL16", fr_cols, avg_dt_p16_py) avg_dt_p256 = display_p256("images/test.p256") results_str += "{};{};{};{}\n".format("p256", "PAL256", fr_cols, avg_dt_p256) avg_dt_p256_py = display_p256_py("images/test.p256") results_str += "{};{};{};{}\n".format("p256_py", "PAL256", fr_cols, avg_dt_p256_py) print(results_str) with open("fileread.csv", "w") as text_file: print("{}".format(results_str), file=text_file) # Switch off LEDs to show end for led in [LED(i) for i in range(1, 3)]: led.off()
def __get_can_settings(bit_rate, sampling_point): clk = 48000000 if omv.board_type() == "H7" else pyb.freq()[2] for prescaler in range(8): for bs1 in range(16): for bs2 in range(8): if bit_rate == ((clk >> prescaler) // (1 + bs1 + bs2)) and (sampling_point * 10) == (((1 + bs1) * 1000) // (1 + bs1 + bs2)): return (1 << prescaler, bs1, bs2) raise ValueError("Invalid bit_rate and/or sampling_point!")
def __init__(self, pins_dict, timer=6, reverse_pols=False): self.__enable = pwm.PWM(pins_dict['enable']) self.__control0 = pins_dict[ 'control0'] if not reverse_pols else pins_dict['control1'] self.__control0.init(pyb.Pin.OUT_PP) self.__control0.low() self.__control1 = pins_dict[ 'control1'] if not reverse_pols else pins_dict['control0'] self.__control1.init(pyb.Pin.OUT_PP) self.__control1.low() self.__led = pins_dict['led'] self.__led.init(pyb.Pin.OUT_PP) self.__tack0 = pins_dict['tack0'] if not reverse_pols else pins_dict[ 'tack1'] self.__tack1 = pins_dict['tack1'] if not reverse_pols else pins_dict[ 'tack0'] self.__tack1.init(pyb.Pin.IN) #pyb.millis doesn't have enough resolution #start timer at TIMER_FREQ, with max possible period if timer in [1, 8, 9, 10, 11]: self.__ucounter = pyb.Timer(timer, prescaler=int(pyb.freq()[3] / TIMER_FREQ), period=0x7fffffff) elif timer in [2, 3, 4, 5, 6, 7, 12, 13, 14]: self.__ucounter = pyb.Timer(timer, prescaler=int(pyb.freq()[2] / TIMER_FREQ), period=0x7fffffff) self.__tim_rollover = False #set a callback on the timer which sets __tim_rollover true if it overflows #i.e. it counts past it's period, without a tack occuring. #if so we assume speed is zero as we can no longer measure it self.__ucounter.callback(self.__ISR_TIMER_SPEED) self.__pulsetime = 0 #this is measured speed ... we are at rest self.__pulsedir = 0 #at init doesn't matter what direction this indicates #register interrupt on tack0 self.__extint = pyb.ExtInt(self.__tack0, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, self.__ISR_TACK_SPEED)
import pyb import time # Setup timing to achieve target baud-rate baud = 250000 # 25k pclk1 = pyb.freq()[2] (bs1, bs2) = (5, 8) prescaler = int(pclk1 / (baud * (1 + bs1 + bs2))) # Initialize CAN controller extframe = False can1 = pyb.CAN(1, pyb.CAN.NORMAL, extframe=extframe, prescaler=prescaler, bs1=bs1, bs2=bs2) #can2 = pyb.CAN(2, pyb.CAN.NORMAL, extframe=extframe, prescaler=prescaler, bs1=bs1, bs2=bs2) def can2rx_cb(bus, reason): print('cb2', bus, reason) #can1.setfilter(0, pyb.CAN.LIST32, 0, (0x211, 0x212)) can1.setfilter(0, pyb.CAN.LIST16, 0, (0x211, 0x212, 0x213, 0x214)) #while not can1.any(0): # time.sleep(0.01) # #print(can1.recv(0))
# test pyb module on F411 MCUs import os, pyb if not 'STM32F411' in os.uname().machine: print('SKIP') import sys sys.exit() print(pyb.freq())
stm.mem32[stm.RTC + stm.RTC_BKP17R] = stm.mem32[stm.RTC + stm.RTC_BKP16R] stm.mem32[stm.RTC + stm.RTC_BKP16R] = (stm.mem32[stm.RTC] << 8) | ( stm.mem32[stm.RTC + stm.RTC_SSR] & 0xff) stm.mem32[stm.RTC + stm.RTC_BKP19R] += 1 import mymain dt = rtc.datetime() info1 = rtc.info() ts1 = pyb.micros() print('\n%d us 0x%x %d us 0x%x %d us LSx_dt: %d us' % (stupt, info0, ts0 - stupt, info1, ts1 - stupt, ts1 - ts0)) print('%d-%02d-%02d %02d:%02d:%02d.%06d' % (res[0], res[1], res[2], res[4], res[5], res[6], res[7])) try: adc = pyb.ADCAll(12, 0) except: adc = pyb.ADCAll(12) try: vref = adc.read_vref() except: vref = 3.3 print('Tcore: %.1f C Vcore_ref: %.3f V Vbat: %.3f V Vref: %.3f V' % (adc.read_core_temp(), adc.read_core_vref(), adc.read_core_vbat(), vref)) print('freq: ', pyb.freq()) print('LTE:') hexd(stm.RCC + 0x70, 0x10) led.off()
# test pyb module on F411 MCUs import os, pyb if not "STM32F411" in os.uname().machine: print("SKIP") raise SystemExit print(pyb.freq())
# Note that timer clocks are doubled if bus prescaler factor != 1 # as per section 7.2 ("Clocks") of RM0090 Reference Manual if apb1_div == 1: tmr_apb1_clk = apb1_freq else: tmr_apb1_clk = apb1_freq * 2 if apb2_div == 1: tmr_apb2_clk = apb2_freq else: tmr_apb2_clk = apb2_freq * 2 # Compare with system reported values calc_clocks = (int(sysclk_freq), int(ahb_freq), int(apb1_freq), int(apb2_freq)) sys_clocks = pyb.freq() print("Calculated values: ", calc_clocks) print("System reported values:", sys_clocks) if calc_clocks == sys_clocks: print("Values match!") else: print("Values DON'T match") print() print("APB1 timer clock =", int(tmr_apb1_clk)) print("APB2 timer clock =", int(tmr_apb2_clk))
import pyb pyb.freq(36 * 1000000) pyb.main('main.py')
# boot.py -- run on boot-up import machine import pyb pyb.freq(84000000) pyb.main('pintest.py')
#hardware platform: pyboard V1.1 import pyb from pyb import LED led = LED(1) led.off() pyb.freq(168000000) #set CPU frequency in hertz. a = 0 def blink(): global a if a > 8400 and a < 16800: led.toggle() elif a >= 16800: a = 0 a += 1 while True: blink() pyb.wfi( ) #pyb.wfi() is used to reduce power consumption while waiting for an event such as an interrupt.
min_ticks = 0 max_ticks = 0 avg_ticks = 0 std_dev_ticks = 0 n = 0 timer = Timer(2) logger = logging.getLogger(__name__) logger.info("Latency test RS232") logger.info("Initializing interface.") interface = rs232_tmcl_interface(data_rate=DATA_RATE) logger.info("Performing test.") ticks = (WORST_CASE_LATENCY * PAYLOAD * pyb.freq()[2] * 2) / 1000 prescaler = int(ticks / 0x3fffffff) period = int((WORST_CASE_LATENCY * PAYLOAD * pyb.freq()[2] * 2) / (1000 * (prescaler + 1))) while (n < N_SAMPLES): timer.counter(0) timer.init(prescaler=prescaler, period=period, callback=timeout) for i in range(0, PAYLOAD): interface.send_request_only(TMCL_Request(MODULE_ID, 1, 2, 3, 4, 5), host_id=HOST_ID, module_id=MODULE_ID) try: for i in range(0, PAYLOAD): interface.receive_reply(module_id=MODULE_ID, host_id=HOST_ID) except: pass
else: pass def runLedStartNoBlock(flag=True, tim_num=14, tim_freq=0.3, led_num=4): """ """ if flag: tim = Timer(tim_num, freq=tim_freq) tim.callback(lambda cb_fun: LED(led_num).toggle()) else: pass if __name__ == "__main__": deDug(str(pyb.freq())) deDug('CODE START -->\n') # runLedStartNoBlock(flag=True) # uart = UART(6, 115200) uart.write('--> CODE START -->\n') # adc = [ADC(Pin('X8'))] * 4 adc[0] = ADC(Pin('X8')) adc[1] = ADC(Pin('X7')) adc[2] = ADC(Pin('X6')) adc[3] = ADC(Pin('X5')) # f_win_n = 10
# boot.py # MIT license; Copyright (c) 2020 Andrea Corbo import os import pyb pyb.freq(84000000) # Sets main clock to reduce power consumption. pyb.usb_mode( "VCP+MSC") # Sets usb device to act only as virtual com port, needed # to map pyboard to static dev on linux systems. try: os.mount(pyb.SDCard(), "/sd") # Mounts SD card. except: print("UNABLE TO MOUNT SD")
# boot.py -- run on boot-up # can run arbitrary Python, but best to keep it minimal import machine import pyb #pyb.main('main.py') # main script to run after this one pyb.usb_mode('CDC+MSC') # act as a serial and a storage device #pyb.usb_mode('CDC+HID') # act as a serial device and a mouse pyb.freq(4000000) #Set frequency as the lowest possible card while SD card writing.
# Uses the thermopile shield as crude object location detector. Relative position is # transmitted over the UART pins (UART 3) # import sensor, image, time, fir, pyb # If connected by USB, enable diagnostics # TODO: this detection doesn't work! #usb = pyb.USB_VCP() #debug = usb.isconnected() debug = True # Display the system clock rate if debug: print(repr(pyb.freq())) # Setup the UART uart_bus = 1 uart_baud = 115200 uart = pyb.UART(uart_bus, baudrate=uart_baud, flow=0, bits=8, parity=None, stop=1, timeout_char=10) # LEDs led_ir = pyb.LED(4) led_ir.on()
def show(self): buf = self.buf pyb.freq(168000000) pyb.disable_irq() bb = _bitbang(_buf_addr(self.buf), self.length * 3 * 8) pyb.enable_irq()
# Created on a Pyboard (PYB) v1.1 (with STM32F405RGT6 microcontroller) # but should be readily adaptable to other Micropython systems # # External hardware requirement: "Loop-back" connection from X1 (PA0) # to X2 (PA1) via series resistor (e.g. 1k) or jumper wire # # See README.md for further information from micropython import const import utime import pyb import iol # Get APB1 clock frequency in Hz apb1_clk = pyb.freq()[2] # Get pclk1 value from tuple # Port bit definitions PA_TXD = const(0) # External pin X1 PA_RXD = const(1) # External pin X2 # Register definitions pa_enr = iol.Reg("RCC.AHB1ENR") ua_enr = iol.Reg("RCC.APB1ENR") pa_moder = iol.RegArr("GPIOA.MODER", 16, 2) pa_afr = iol.RegArr("GPIOA.AFR0,AFR1", 8, 4) pa_pupdr = iol.RegArr("GPIOA.PUPDR", 16, 2) pa_odr = iol.Reg("GPIOA.ODR")
import machine import micropython micropython.alloc_emergency_exception_buf(100) baud = 1250000 # 125000 # 125000 bittime = 1/baud # bs1, bs2 should total 10-1 TqCt = 10 BS1 = int(0.875*TqCt) BS2 = TqCt - 1 - BS1 # bittime = (1+ bs1 + bs2) * tq tq = bittime / (1+BS1+BS2) PCLK1 = pyb.freq()[2] # 30,000,000 # tq = prescaler/PCLK1 (it seems that only integer prescaler values work) prescaler = PCLK1 * tq print('tq {} BS1 {} BS2 {} prescaler {}'.format(tq, BS1, BS2, prescaler)) can = pyb.CAN(1, pyb.CAN.NORMAL, auto_restart=True, extframe=False, prescaler=int(prescaler), bs1=BS1, bs2=BS2) can.setfilter(0, pyb.CAN.LIST16, 0, (123, 124, 125, 126)) message = b'message' print('sending ', message) can.send(message, 123) buf = ''
# boot.py -- run on boot-up # can run arbitrary Python, but best to keep it minimal import machine import pyb pyb.freq(168000000) #pyb.main('main.py') # main script to run after this one #pyb.usb_mode('VCP+MSC') # act as a serial and a storage device #pyb.usb_mode('VCP+HID') # act as a serial device and a mouse
# boot.py -- run on boot-up # can run arbitrary Python, but best to keep it minimal import machine import pyb pyb.freq(96000000) pyb.main('hv_pulser.py') # main script to run after this one # pyb.usb_mode('CDC+MSC') # act as a serial and a storage device # pyb.usb_mode('CDC+HID') # act as a serial device and a mouse
# BMP180.py -- controlling barometer BMP180 import struct import pyb, micropython from pyb import I2C, Switch pyb.freq(64000000) micropython.alloc_emergency_exception_buf(100) i2c = I2C(2, I2C.MASTER, baudrate=4500000) sw = Switch() # oversampling setting (short 0..3) oss = 3 # slave (device) address that scanned by I2C.scan(): sladdr = 0x77 # standard sea level at Zero point in hPa #hPaZero = 1013.25 def get_I2C_calib(msb, lsb, unsigned=False): # 'H' = unsigned short, 'h' = signed short tp = '<H' if unsigned else '<h' MSB = struct.unpack(tp, i2c.mem_read(1, sladdr, msb))[0] LSB = struct.unpack(tp, i2c.mem_read(1, sladdr, lsb))[0] data = struct.unpack(tp, struct.pack(tp, (MSB<<8 | LSB)))[0] return data
# https://github.com/hmaerki/micropython/tree/master/canbus_example import uos print('This is a %s v%s. %s.' % (uos.uname().sysname, uos.uname().release, uos.uname().machine)) import pyb # Get clock frequency: # https://docs.micropython.org/en/latest/pyboard/library/pyb.html#pyb.freq freq = pyb.freq() pclk1 = freq[3] # [s-1]. For the Pyboard v3: 48'000'000 (48MHz) # Don't know if these values are correct for all baudrates. # However, there sum must be 20! BS1 = 14 BS2 = 6 for prescaler in range(4, 500): tq = float(prescaler)/pclk1 # [s] nominal_bittime = tq * (1 + BS1 + BS2) baud = 1.0/nominal_bittime if abs(((baud+500.0) % 1000.0) - 500.0) < 1.0: # Print only the baudrates with a even value. # (There may be a better way to write the test above...) print('%0.2f kBaud: can = CAN(1, CAN.NORMAL, prescaler=%d, bs1=%d, bs2=%d)' % (baud/1000.0, prescaler, BS1, BS2))
# Created on a Pyboard (PYB) v1.1 (with STM32F405RGT6 microcontroller) # but should be readily adaptable to other Micropython systems # # External hardware requirement: 50k potentiometer (10k or 100k also # okay) from +3.3V supply to ground, with wiper connected to X7 (PA6) # via series resistor (e.g. 330 ohm) or jumper wire # # See README.md for further information from micropython import const import pyb import iol # Get bus clock frequency in Hz apb2_clk = pyb.freq()[3] # Get pclk2 value from tuple # Port bit definitions PA_GRN = const(14) # Internal LED PA_AIN = const(6) # External pin X7 # Other ADC settings ADC_BITS = const(12) # Resolution in bits ADC_CONVS = const(1) # Number of conversions ADC_SAMP_CYCS = const(84) # Number of ADC sampling cycles # Calculate derived ADC values
import pyb from pyb import UART from pyb import Pin from pyb import ExtInt from pyb import Timer from pyb import ADC from pyb import I2C import time import _thread pyb.freq(30000000) log = open('log.txt', 'r') pack = [] for line in log.readlines(): data_pack = line.strip().split(',') pack.append(float(data_pack[1])) log.close() ''' SONIC_RX:X4 ACCEL:X9--SCL,X10--SDA a = 'FEFE00000058250400092F0800000A0D' hex_a = bytes.fromhex(a) a = hex_a.hex() ''' class CONFIG(): def __init__(self): self.btn = Pin("Y8", Pin.IN, Pin.PULL_UP) self.accel = pyb.Accel()
if (n == 0): min_ticks = value max_ticks = value avg_ticks = value std_dev_ticks = 0 else: min_ticks = min(min_ticks, value) max_ticks = max(max_ticks, value) avg_ticks_new = avg_ticks + ((value - avg_ticks) / (n + 1)) std_dev_ticks = (((n - 1) * std_dev_ticks) + ((value - avg_ticks_new) * (value - avg_ticks))) / n avg_ticks = avg_ticks_new n += 1 tout = False logger.info("Calculating statistical values.") std_dev_ticks = math.sqrt(std_dev_ticks) min_real = real(min_ticks, timer.prescaler(), pyb.freq()[2] * 2) * 1000 # ms max_real = real(max_ticks, timer.prescaler(), pyb.freq()[2] * 2) * 1000 # ms avg_real = real(avg_ticks, timer.prescaler(), pyb.freq()[2] * 2) * 1000 # ms std_dev_real = real(std_dev_ticks, timer.prescaler(), pyb.freq()[2] * 2) * 1000 # ms logger.info( "Minimum: {} ticks, Maximum: {} ticks, Mean: {} ticks, Standard deviation: {} ticks" .format(min_ticks, max_ticks, avg_ticks, std_dev_ticks)) logger.info( "Minimum: {} ms, Maximum: {} ms, Mean: {} ms, Standard deviation: {} ms". format(min_real, max_real, avg_real, std_dev_real))
''' MicroPython Documentation @date: 2017.11.20 ''' ''' 1.1 General board control ''' import pyb pyb.repl_uart(pyb.UART(1, 9600)) pyb.wfi() pyb.freq() pyb.freq(60000000) pyb.stop() ''' 1.2 Delay and timing ''' import time time.sleep(1) # sleep for 1 second time.sleep_ms(500) time.sleep_us(10) start = time.ticks_ms() delta = time.ticks_diff(time.ticks_ms() - start) ''' 1.3 LED ''' from pyb import LED
# https://docs.micropython.org/en/latest/pyboard/quickref.html import utime as time buf = bytes() import pyb pyb.repl_uart(pyb.UART(1, 9600)) # duplicate REPL on UART(1) pyb.wfi() # pause CPU, waiting for interrupt pyb.freq() # get CPU and bus frequencies pyb.freq(60000000) # set CPU freq to 60MHz pyb.stop() # stop CPU, waiting for external interrupt # Internal LEDs¶ # See pyb.LED. from pyb import LED led = LED(1) # 1=red, 2=green, 3=yellow, 4=blue led.toggle() led.on() led.off() # LEDs 3 and 4 support PWM intensity (0-255) LED(4).intensity() # get intensity LED(4).intensity(128) # set intensity to half # Internal switch # See pyb.Switch. from pyb import Switch