赞
踩
下面的方法是本人实测写的记录,感兴趣的小伙伴可以试试
通过 ls -l /dev/tty* #查看识别的串口号
- import serial
- import time
- # 这个代码也可用于多串口的测试,主要是更改/dev/ttyACM0 串口号
- ser = serial.Serial(port="/dev/ttyACM0", baudrate=9600)
- def main():
- while True:
- count = ser.inWaiting()
- if count != 0:
- print("-count = {0}".format(count))
- recv = ser.read(count)
- print("-recv = {0}".format(recv))
- # ser.write(recv)
-
- ser.flushInput()
-
- # time.sleep(0.1)
- # ser.write(b'str')
- if __name__ == '__main__':
- try:
- main()
- except KeyboardInterrupt:
- if ser != None:
- ser.close()
其实这部分就是stm32的usb的cdc配置,自行了解
- # 这部分放在main函数中
- uint32_t cur_time, pre_time = 0;
- uint32_t count = 0;
- char buf[256];
- while (1)
- {
- cur_time = HAL_GetTick();
- if ((cur_time - pre_time) >=1000 )
- {
- pre_time = cur_time;
- int length = snprintf(buf, sizeof(buf)-1, "--%d--\r\n", count++);
- CDC_Transmit_FS((uint8_t*)buf, length);
- }
- }
- # 这部分在usbd_cdc.c文件里
-
- uint8_t usbReceiveBuf[512];
- uint16_t usbReceiveLen;
-
- static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
- {
- /* USER CODE BEGIN 6 */
-
- memcpy(usbReceiveBuf, Buf, *Len); # 将接收数据转存
- usbReceiveLen = *Len;
- CDC_Transmit_FS(Buf, *Len); # 将接收到的数据发回去
- USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
- USBD_CDC_ReceivePacket(&hUsbDeviceFS);
- return (USBD_OK);
- /* USER CODE END 6 */
- }
树莓派这边发送的str字符串,stm32接收后返回,树莓接收并打印,将上述的代码发送注释打开即可
链接:百度网盘 请输入提取码 提取码:ttbo
欢迎大家指正交流^ 0 ^
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。