logo

如何在定时器中断函数里面接收串口的数据

2023-07-30 02:27
8
_4gde

我尝试令stm32f1的板子和openmv通信

下面是我的代码

# Hello World Example
#
# Welcome to the OpenMV IDE! Click on the green run arrow button below to run the script!

import sensor, image, time, pyb, struct

sensor.reset()                      # Reset and initialize the sensor.
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA)   # Set frame size to QVGA (320x240)
sensor.skip_frames(time = 2000)     # Wait for settings take effect.
clock = time.clock()                # Create a clock object to track the FPS.


##初始化串口
uart = pyb.UART(1, 115200, timeout_char=1000)                         # i使用给定波特率初始化
uart.init(115200, bits=8, parity=None, stop=1, timeout_char=1000) # 使用给定参数初始化

res=1

def uart_call_back_(t):
    global uart
    if uart.any():
        res=uart.read()
        res = struct.unpack('B', res)
        res = hex(res)
        res = int(res)
        if res == 0xaf:
            pyb.LED(1).toggle()
            print('succes')
    return

tim = pyb.Timer(4)              # create a timer object using timer 4  使用定时器4创建一个定时器对象
tim.init(freq=1000)                # trigger at 2Hz 以2Hz触发
tim.callback(uart_call_back_)

def snshot():
    #clock.tick()                    # Update the FPS clock.
    img = sensor.snapshot()         # Take a picture and return the image.
    
    #print(clock.fps())              # Note: OpenMV Cam runs about half as fast when connected
                                    # to the IDE. The FPS should increase once disconnected.

while(True):
    snshot()

我得到了这样的错误:

uncaught exception in Timer(4) interrupt handler

MemoryError:

我尝试在while的主循环里面调用这个uart_call_back_这个函数而不是把它当成定时器的中断函数,可以运行,但是缺点就是,主循环里每一次循环都要拍照以及后续还要做图像的处理,这意味着可能不能及时的处理串口发来的信息。我想知道有什么方法可以解决这个error。

2023-07-31 17:12
I
网红小智智 星瞳科技

不要使用中断接收串口数据。

串口有缓冲的,只要缓冲不满,就不会丢。只需要在主循环里读取就行了。

2023-07-31 20:03
8
_4gde

了解了,谢谢大佬:smiling_face_with_open_mouth_smiling_eyes: :smiling_face_with_open_mouth_smiling_eyes: