matlab, python串口10ms毫秒 连续发送16进制数组

matlab, python串口10ms毫秒 连续发送16进制数组

ref:

sscom上位机

首先用上位机sscom的定时10ms发送
在这里插入图片描述

但实测周期确是16ms左右, 数字填更小也没有用了, 可能和cpu性能有关

matlab

clear
delete(instrfindall);   %关闭串口
global c;               %全局变量
c = serial('COM4');   %以默认方式打开串口
c.BaudRate = 115200;     %设置波特率为110
set(c, 'TimeOut', 1);   % 设置串口数据最大读写时间,如果超过这个时间,仍读取不到数据,那么则终止读写
fopen(c);                %打开串口

while 1
%     fprintf(c,hex2dec(FF)); 
    fwrite(c,[255 2 144 0 36 189 201 220 59 105 39 101 59 28 217 86 63 192 194 16 186 192 74 184 55 181 111 225 185 241 49 24 61 110 134 130 189 108 101 29 193 0 0 3]);
%     pause(0.01);
%     tic;
    for t = 0.001:0.001:0.01
        while toc < t
        end
    end
end
fclose(c);  

最后一段代码可以实现10ms左右的延时, 本身程序执行也要耗费一些时间, 不会完全精确到10ms, 如果用pause(0.01)函数做延时的话, 周期降到16ms左右就不能再降了

python

import serial#导入串口通信库
import time
from time import sleep

ser = serial.Serial()

def port_open_recv():#对串口的参数进行配置
    ser.port='com4'
    ser.baudrate=115200
    ser.bytesize=8
    ser.stopbits=1
    ser.parity="E"#奇偶校验位
    ser.open()
    if(ser.isOpen()):
        print("串口打开成功!")
    else:
        print("串口打开失败!")
#isOpen()函数来查看串口的开闭状态

def port_close():
    ser.close()
    if(ser.isOpen()):
        print("串口关闭失败!")
    else:
        print("串口关闭成功!")

if __name__ == '__main__':
    port_open_recv()
    while True:
        a = "FF 02 90 00 24 bd c9 dc 3b 69 27 65 3B 1C D9 56 3F C0 C2 10 BA C0 4A B8 37 B5 6F E1 B9 F1 31 18 3D 6E 86 82 BD 6C 65 1D C1 00 00 03"
        # a = "aacc"
        # send(a)
        ser.write(bytes.fromhex(a))#编码
        # sleep(0.005)#起到一个延时的效果,这里如果不加上一个while True,程序执行一次就自动跳出了
            # 毫秒延时
        delay_mark = time.time()    
        while True:
            offset = time.time() - delay_mark
            if offset > 0.0095:
                break

最后一段代码可以实现10ms的延时, 本身程序执行也要耗费一些时间, 不会完全精确到10ms, 如果用sleep(0.01)函数做延时的话, 周期降到16ms左右就不能再降了

猜你喜欢

转载自blog.csdn.net/weixin_46143152/article/details/126192199#comments_22740485