如何为在macOS Mojave中读取串行数据的C程序设置自定义波特率

我正在使用一种以250,000波特率发送数据的设备。该设备已连接到Silicon Labs CP2012 UART到USB控制器。我正在尝试从设备读取串行数据,以便可以在其他C程序中使用它。我尝试使用stty -f /dev/cu.SLAB_USBtoUART 250000 & screen /dev/cu.SLAB_USBtoUART 250000,但是输出乱码/错误(就像您会看到波特率定义不正确)。我可以使用应用程序Serial来获取正确的数据,并且编写了一个简单的Python脚本,该脚本成功读取并打印了数据。但是,我似乎无法找到如何使C实现正常工作的方法。是否有人对在macOS(Mojave)中如何执行此操作有任何想法?我看过几篇关于在Linux中设置自定义波特率的文章,但似乎找不到关于macOS的任何东西。

这是我正在使用的示例代码。显然,波特率设置错误,但仅将其更改为250000是行不通的(按预期,据我的理解,termios.h仅支持最高230400的波特率)。

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

int main(int argc,char** argv)
{
        struct termios tio;
        struct termios stdio;
        struct termios old_stdio;
        int tty_fd;

        unsigned char c='D';
        tcgetattr(STDOUT_FILENO,&old_stdio);

        printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]);
        memset(&stdio,sizeof(stdio));
        stdio.c_iflag=0;
        stdio.c_oflag=0;
        stdio.c_cflag=0;
        stdio.c_lflag=0;
        stdio.c_cc[VMIN]=1;
        stdio.c_cc[VTIME]=0;
        tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
        tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
        fcntl(STDIN_FILENO,F_setfL,O_NONBLOCK);       // make the reads non-blocking

        memset(&tio,sizeof(tio));
        tio.c_iflag=0;
        tio.c_oflag=0;
        tio.c_cflag=CS8|CREAD|CLOCAL;           // 8n1,see termios.h for more information
        tio.c_lflag=0;
        tio.c_cc[VMIN]=1;
        tio.c_cc[VTIME]=10;

        tty_fd=open(argv[1],O_RDWR | O_NONBLOCK);      
        cfsetospeed(&tio,B115200);            // 115200 baud
        cfsetispeed(&tio,B115200);            // 115200 baud

        tcsetattr(tty_fd,&tio);
        while (c!='q')
        {
                if (read(tty_fd,&c,1)>0)        write(STDOUT_FILENO,1);              // if new data is available on the serial port,print it out
                //if (read(STDIN_FILENO,1)>0)  write(tty_fd,1);                     // if new data is available on the console,send it to the serial port
        }

        close(tty_fd);
        tcsetattr(STDOUT_FILENO,&old_stdio);

        return EXIT_SUCCESS;
} ```
lele537 回答:如何为在macOS Mojave中读取串行数据的C程序设置自定义波特率

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3047694.html

大家都在问