วันพุธที่ 28 ธันวาคม พ.ศ. 2559

qt serial non-standard baudrate example, custom speed example ตัวอย่าง

เวลาที่เราต้องการใช้ serial port และ ใช้ baudrate ไม่มาตรฐาน ( custom baudrate, custom speed, non-standard baurate, non-standard speed ) ถ้าเป็นเครื่อง pc ทั่วไป ที่มี comport ติดมากับ mainboard ก็สามารถใช้ library ที่ Qt มีมาให้ได้ทันที แต่พอเป็น usb serial ต้องใช้วิธีเขียนอีกแบบนึง จึงจะสามารถใช้งาน custom speed ได้

กว่าจะหาวิธีที่ทำให้ rpi + qt + usb serial สามารถสื่อสารโดย custom speed  ได้ ค่อนข้างลำบาก (ข้อมูลค่อนข้างน้อย ใน google) ต้องรวบรวมข้อมูลจากหลายๆที่ แล้วมาทดลองทำดู ถึงจะได้ออกมา

ผู้เขียนเลือกใช้ usb serial ยี่ห้อ z-tek เวลาไปซื้อต้องบอกเจ้าของร้านว่าเอาของจริงเท่านั้น เพราะถ้าซื้อของปลอมมา จะใช้ไม่ได้ (ของปลอมทำเลียนแบบมีเยอะมาก และ ราคาก็ถูกกว่า) หรือถ้าใครมีความสามารถผลิต usb serial เองได้ โดยใช้ chipset ftdi ก็สามารถนำมาใช้ได้เหมือนกัน

มาดูตัวอย่าง code กันดีกว่า

#include <linux/serial.h>
#include <asm/termios.h>
#include <asm/ioctls.h>
#include <asm/termbits.h>
#include <stropts.h>
#include <QThread>

#include <fcntl.h>    /* For O_RDWR */
#include <unistd.h>   /* For open(), creat() */



main(){
int fd;
fd = open("/dev/ttyUSB0",O_RDWR|O_NOCTTY);


struct termios2 tio;
ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = ความเร็วที่ต้องการ;
tio.c_ospeed = ความเร็วที่ต้องการ;
tio.c_cflag |= PARENB; // even parity
tio.c_cflag &= ~CSTOPB; // 1 stop bit
tio.c_cflag &= ~CSIZE;
tio.c_cflag |= CS8;

tio.c_cc[VTIME]=10; // wait 10 deciseconds

tio.c_cc[VMIN]=0;
ioctl(fd, TCGETS2, &tio);

========================================

พอมาทำกับ rpi4 แล้วใช้ไม่ได้ จึงเปลี่ยนเป็นแบบนี้

    struct termios2 tio;
    ioctl(fd, TCGETS2, &tio);
    tio.c_cflag &= ~CBAUD;
    tio.c_cflag |= BOTHER;
    tio.c_ispeed = 5760;
    tio.c_ospeed = 5760;
    tio.c_cflag |= PARENB; // even parity
    ioctl(fd, TCSETS2, &tio);
========================================
char ping_cmd[] = {2,1};
char ping_rec[7];
write(fd, &ping_cmd, sizeof(ping_cmd) );
QThread::msleep(1000);
read(fd, &ping_rec, sizeof(ping_rec));
write(fd, &ping_rec, sizeof(ping_rec) );
}

เมื่อ compile ผ่านแล้ว เราก็ต่อสายสัญญาณ USB232 จาก rpi เข้ากับ RS232 ของ notebook โดยไขว้ขา 2 กับ 3 สลับกันไว้
แล้วก็เปิดโปรแกรมอะไรก็ได้ที่สามารถสื่อสารผ่าน comport ได้
ในที่นี้ผู้เขียนได้ตั้งโปรแกรม comport ที่เครื่อง notebook ไว้ว่า ถ้ามี 0x01 ผ่านเข้ามา ให้ส่ง 0x61 ออกไป ก็จะได้ผลดังรูปด้านล่าง


จอบอ

ที่มา
http://stackoverflow.com/questions/12646324/how-to-set-a-custom-baud-rate-on-linux

https://blog.mbedded.ninja/programming/operating-systems/linux/linux-serial-ports-using-c-cpp/





ไม่มีความคิดเห็น: