Exemple #1
0
def tmp_wfi():
    sw = Switch()
    sw.callback(f)
    global i
    while True:
        if (i == 1):
            read_tmp()
            i = 0
        else:
            pyb.wfi()
Exemple #2
0
from pyb import Switch, Pin

led = Pin('LED_BLUE', Pin.OUT_PP)
btn = Switch()


def cb():
    state = btn.value()
    led.value(not led.value())
    print('ON' if led.value() else 'OFF')


btn.callback(cb)
led.on()
Exemple #3
0
from pyb import Switch

sw = Switch()
print(sw())
sw.callback(print)
sw.callback(None)
'''
实验名称:按键
版本:v1.0
日期:2020.12
作者:01Studio
'''

from pyb import LED, Switch


def fun1():
    LED(4).toggle()


sw = Switch()  #定义按键对象名字为sw
sw.callback(fun1)  #当按键被按下时,执行函数fun1(),即LED(4)状态反转
Exemple #5
0
vol = 80  #音量初始化,80

######################
# 播放 USR按键
######################
play_flag = 0


def music_play():
    global play_flag
    play_flag = 1


sw = Switch()
sw.callback(music_play)

######################
# 音量加 A0按键
######################
VOL_U = Pin('A0', Pin.IN, Pin.PULL_UP)  #构建按键A0

vol_up_flag = 0


def vol_up(VOL_U):

    global vol

    #消除按键抖动
    if VOL_U.value() == 0:
orange = LED(3)
orange.on()

#########################
#      Sub Programs     #
#########################


def start():
    hc12.write('1')
    orange.off()


#create switch object
big_red_button = Switch()
big_red_button.callback(start)

finished = False

#########################
#       Main Loop       #
#########################

while finished == False:  #While loop that loops forever

    if hc12.any():
        data = hc12.readline()
        data = data.decode('utf-8')

        dataArray = data.split(',')  #Split it into an array called dataArray
'''
实验名称:按键
版本:v2.0
日期:2020.12
作者:01Studio
'''

from pyb import LED, Switch

sw = Switch()  #定义按键对象名字为sw
sw.callback(lambda: LED(4).toggle())  #当按键被按下时,LED(4)状态反转
#定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

#LCD初始化
d = LCD43M(portrait=1)
d.fill(WHITE)  #填充白色

#电容触摸屏初始化,方向和LCD一致
t = GT1151(portrait=1)

#USR按键初始化
sw = Switch()  #定义按键对象名字为sw
sw.callback(lambda: d.fill(WHITE))  #当按键被按下时,LCD清屏白色

while True:

    data = t.read()  #获取触摸屏坐标
    print(data)  #REPL打印

    #当产生触摸时
    if data[0] != 2:  #0:按下; 1:移动; 2:松开

        #触摸坐标画圆
        d.drawCircle(data[1], data[2], 10, BLACK, fillcolor=BLACK)
        d.printStr('(X:' + str(data[1]) + ' Y:' + str(data[2]) + ')',
                   10,
                   10,
                   RED,
Exemple #9
0
def main():
    print('Traffic lights running ...')

    class Events:
        RED_TIMEOUT = 1
        AMBER_TIMEOUT = 2
        GREEN_TIMEOUT = 3
        ERROR = 4
        START = 5

    start = State(
        ident='start'
    )  # Special start state to allow for initialization before operation.

    timer0 = 10

    class FlashingRed(State):  # Special fault state that should never exit.
        def __init__(self):
            super().__init__(ident='error')
            self.timer = Timer(timer0 + 4)
            self.led = LED(1)

            # noinspection PyUnusedLocal
            def toggle_with_arg(
                not_used
            ):  # Toggle func that accepts an arg, because ``schedule`` *needs* an arg.
                self.led.toggle()

            self.led_tog_ref = toggle_with_arg  # Store the function reference locally to avoid allocation in interrupt.

        def __enter__(self):
            self.timer.init(
                freq=2, callback=lambda _: schedule(self.led_tog_ref, None))
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.led.off()
            self.timer.deinit()

    flashing_red = FlashingRed()

    traffic_lights = Machine(initial_state=start)  # The traffic light machine.
    traffic_lights.actions[
        Events.RED_TIMEOUT] = flashing_red.action  # Catch anything unexpected.
    traffic_lights.actions[Events.AMBER_TIMEOUT] = flashing_red.action
    traffic_lights.actions[Events.GREEN_TIMEOUT] = flashing_red.action
    traffic_lights.actions[Events.ERROR] = flashing_red.action
    traffic_lights.actions[Events.START] = flashing_red.action

    tl_fire_ref = traffic_lights.fire  # Store the function reference locally to avoid allocation in interrupt.
    error = Switch()
    error.callback(lambda: schedule(tl_fire_ref, Events.ERROR))

    class LEDState(
            State
    ):  # Output is determined by ``__enter__`` and ``__exit__`` (common in embedded machines).
        def __init__(self, led_num, time_on, event):
            super().__init__(ident=led_num)  # Use the LED num as the ident.
            self.led = LED(self.ident)  # The LED to use.
            self.timer = Timer(timer0 + self.ident)  # The timer to use.
            self.timeout = time_on  # Time to wait before firing event.
            self.event = event  # Event to fire at end of time_on.

        def __enter__(self):
            self.led.on()
            self.timer.init(
                freq=1 / self.timeout,
                callback=lambda _: schedule(tl_fire_ref, self.event))
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            self.led.off()
            self.timer.deinit()
            return False

    red = LEDState(led_num=1, time_on=3, event=Events.RED_TIMEOUT)
    green = LEDState(led_num=2, time_on=3, event=Events.GREEN_TIMEOUT)
    amber = LEDState(led_num=3, time_on=0.5, event=Events.AMBER_TIMEOUT)

    red.actions[Events.RED_TIMEOUT] = green.action
    green.actions[Events.GREEN_TIMEOUT] = amber.action
    amber.actions[Events.AMBER_TIMEOUT] = red.action
    start.actions[Events.START] = red.action

    with traffic_lights:
        _ = traffic_lights.fire(
            event=Events.START
        )  # Start the machine once all the setup is complete.
        while True:  # Keep running timers (and other peripherals), but otherwise do nothing.
            wfi()
Exemple #10
0
       uart.write(clearcmd)
#-------LCD5110Init-----------#
SPI    = pyb.SPI(1) #DIN=>X8-MOSI/CLK=>X6-SCK
RST    = pyb.Pin('Y12')
CE     = pyb.Pin('Y11')
DC     = pyb.Pin('Y10')
LIGHT  = pyb.Pin('Y9')
lcd_5110 =upcd8544.PCD8544(SPI, RST, CE, DC, LIGHT)
lcd_5110.lcd_write_bmp()
#------------------------------#      
print('wait......')
pyb.delay(2800)
print('initstart.......')
uart.write(initcmd)
sw=Switch()
sw.callback(test)
while True:
   if uart.any()>0:
       data=uart.read()
       print('revdata:',data)
       if isFlag==0:
           #说明接收的是复位后的信息
           if data==b'Init end\r\n':
               #复位完毕
               print('init ok.......')
               pyb.delay(2000)
               isFlag=1
               pyb.LED(2).on()
               lcd_5110.lcd_write_bmp(0)
       else:
           if len(data)>=5:
Exemple #11
0
cam.reset()
cam.set_framesize(sensor.VGA)  #640*480分辨率
cam.display()  #LCD显示

num = 0  #用于命名图片
cam_flag = 0  #拍照标志位


##############################
#      USR按键  拍照并保存
##############################
def fun():
    global cam_flag
    cam_flag = 1


#USR按键初始化
sw = Switch()
sw.callback(fun)

while True:

    #收到拍照命令
    if cam_flag == 1:

        #拍照并保存图片
        cam.snapshot("/flash/" + str(num) + ".jpg")

        num = num + 1  #照片名称
        cam_flag = 0  #清空标志位
Exemple #12
0
import pyb
#import Pin so we can use it in the project
from pyb import Pin
from pyb import Switch

#set p_out to Pin X1
p_out = Pin('X1', Pin.OUT_PP)

#just a variable so the loop never stops
x = 0
#while loop to continually blink the led in Pin X1

sw = Switch()
#when user switch is pressed the LED toggles on or off
sw.callback(lambda: pyb.LED(3).toggle())

#loop to blink led in pin x1
while x == 0:
    p_out.high()
    pyb.delay(500)
    p_out.low()
    pyb.delay(500)
Exemple #13
0
vol = 80  #音量初始默认80,范围:0-100

######################
# 播放 USR按键
######################
play_flag = 0  #播放标志位


def video_play():
    global play_flag
    play_flag = 1


sw = Switch()
sw.callback(video_play)

######################
# 音量加 A0按键
######################
VOL_U = Pin('A0', Pin.IN, Pin.PULL_UP)  #构建按键A0


def vol_up(VOL_U):

    global vol

    #消除按键抖动
    if VOL_U.value() == 0:
        time.sleep_ms(10)
        if VOL_U.value() == 0:
#hardware platform: pyboard V1.1

from pyb import Switch
from pyb import LED


def mycallback():
    led.toggle()  #Toggle the LED between on and off.


led = LED(1)
led.off()
userButton = Switch()  #Create and return a switch object.

#userButton.callback(lambda:led.toggle())
userButton.callback(mycallback)

while True:
    pass
orange = LED(3)
orange.on()


#########################
#      Sub Programs     #
#########################


def start():
	hc12.write('1')
	orange.off()

#create switch object
big_red_button = Switch()
big_red_button.callback(start)

finished = False
 

#########################
#       Main Loop       #
#########################
 
while finished == False: #While loop that loops forever

	if hc12.any(): 
		data = hc12.readline()
		data = data.decode('utf-8')

		dataArray = data.split(',')   #Split it into an array called dataArray
Exemple #16
0
from pyb import Switch

sw = Switch()
print(sw())
sw.callback(print)
sw.callback(None)
Exemple #17
0
	#print("Frequency Right =",freq_R)
	pyb.LED(2).toggle()

def stop():
	global motor_L_brake, motor_R_brake, tim, freq_L, freq_R
	tim.callback(None)
	motor_L_brake.low()
	motor_R_brake.low()
	pidL.setPoint(0)
	pidR.setPoint(0)
	freq_L = 0
	freq_R = 0

sw = Switch()
#sw.callback(lambda: print("Frequency L =",freq_L,"rpm and Frequency R =",freq_R,"rpm"))
sw.callback(lambda: forward(2000))
tim.callback(speedCorrection)
#tim1.callback(freq)

#forward(4000)

#hall sensors as inperrupts
hall_R = ExtInt('Y1',ExtInt.IRQ_RISING_FALLING,Pin.PULL_NONE,cfreq_R)
hall_L = ExtInt('Y2',ExtInt.IRQ_RISING_FALLING,Pin.PULL_NONE,cfreq_L)	

tim = pyb.Timer(10,freq=10)
#f.write("A AND B VARYING SPEED")
#f.write("Speed-A"+"\t"+"DAC-A"+"\t"+"Speed-B"+"\t"+"DAC-B"+"\n")

'''  the two relays are connected to Y4 and Y5 for electronic brake control of both the bldc motor '''
Exemple #18
0
send_flag = 0


def send():
    global send_flag

    #消除抖动,sw按下返回1,松开返回0。
    if sw.value() == 1:
        delay(10)
        if sw.value() == 1:

            send_flag = 1


sw = Switch()  #定义按键对象名字为sw
sw.callback(send)  #当按键被按下时,执行函数send()

can = CAN(1, CAN.NORMAL)  #设置CAN1为普通模式(RX-->PB8,TX-->PB9)
#设置接收相关配置 id=123, 124, 125 和 126
can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126))

can.send('message!', 123)  #发送id=123的信息

num = 0
while True:

    #判断有无收到信息
    if can.any(0):
        text = can.recv(0)  #读取数据
        print(text)  #通过REPL打印串口3接收的数据
Exemple #19
0
sw = Switch()


def setup_next_pin():
    global sw
    sw.callback(None)
    global __idx
    if __idx + 1 >= len(PINS):
        __idx = 0
    else:
        __idx += 1
    sleep(0.5)
    sw.callback(setup_next_pin)


sw.callback(setup_next_pin)

print("Press the A switch (USR button) to select next PIN")
__pin = None
__current_idx = __idx
while True:
    # Do we change the Pin ?
    if __idx != __current_idx:
        # reconfigure as input (High impedance)
        if __pin:
            __pin.release()

        __pin = pwm(PINS[__idx])
        __pin.percent = 33  # 33% duty cycle
        __current_idx = __idx
        print("Setting PWM on pin %s" % PIN_NAMES[__idx])
Exemple #20
0
#定义5组角度:-90、-45、0、45、90
angle = [-90, -45, 0, 45, 90]

key_node = 0  #按键标志位
i = 0  #用于选择角度


##############################################
#  按键和其回调函数
##############################################
def key():
    global key_node
    key_node = 1


sw.callback(key)  #当按键被按下时,执行函数key()

##############################################
#  OLED初始显示
##############################################
oled.fill(0)  # 清屏显示黑色背景
oled.text('01Studio', 0, 0)  # 首行显示01Studio
oled.text('Servo-180', 0, 15)  # 次行显示实验名称
oled.text(str(angle[i]), 0, 35)  # 显示当前角度
oled.text('Pls Press USER', 0, 55)  #提示按按键
oled.show()

#X1指定角度,启动时i=0,默认-90°
s1.angle(angle[i])

while True:
Exemple #21
0
#构建语音模块对象
wm = audio.WM8978()

record_flag = 0  #录音标志位


######################
# 开始录音 USR按键
######################
def rec_begin():
    global record_flag
    record_flag = 1


sw = Switch()
sw.callback(rec_begin)

######################
# 停止录音 A0按键
######################
KEY_A = Pin('A0', Pin.IN, Pin.PULL_UP)  #构建按键A0


def rec_stop(KEY_A):
    global record_flag
    #消除按键抖动
    if KEY_A.value() == 0:
        time.sleep_ms(5)
        if KEY_A.value() == 0:

            record_flag = 2
Exemple #22
0
def run_uav_test(i2c_bus=2):
    global SIGNALS
    global SIGNAL_USR

    SIGNALS[0] = 0
    serial_port = USB_VCP()
    nmea_line = None
    # serial_port.setinterrupt(-1)
    disp = display.create_spi_display(SSD1322, 256, 64)
    i2c = I2C(i2c_bus, freq=400000)
    devices = i2c.scan()
    lsm303 = LSM303D(i2c)
    switch = Switch()
    speed_pid = PID(target=500, kp=.4, ki=.2, kd=.1)
    uav['pid'] = speed_pid
    timestamp = None
    w = 0

    screen_renderers = [
        render_gps_screen, render_hud_screen, render_imu_screen
    ]
    renderer_idx = 0
    render_screen = screen_renderers[renderer_idx]

    switch.callback(switch_cb)

    while True:
        # retrieving data
        accel, mag = lsm303.read()

        if serial_port.any():
            nmea_line = str(serial_port.readline(), 'utf-8')

        # processing data
        x, y, z = accel
        x, z, y = mag
        uav['imu']['north'] = atan2(y, x) * 180.0 / pi

        if nmea_line:
            update_gps_data(nmea_line)
            nmea_line = None

        # sending orders
        if renderer_idx % 2:
            if timestamp:
                pid_value = speed_pid.update(
                    uav['speed'],
                    elapsed_millis(timestamp) / 1000.0)
                adjust_throttle(serial_port, pid_value)

            timestamp = millis()

        if SIGNALS[0] & SIGNAL_USR:
            renderer_idx = renderer_idx + 1
            render_screen = screen_renderers[renderer_idx %
                                             len(screen_renderers)]
            SIGNALS[0] = SIGNALS[0] & ~SIGNAL_USR

        render_screen(disp.framebuf, uav)

        disp.send_buffer()
        delay(50)