4

我正在开发一个新项目,我想与连接到我的 debian 机器的 FTDI 建立连接。我打算用 C 而不是 C++ 编写代码。这就是我的问题。我发现的所有示例都不完整,或者是为 c++ 编译器而不是 GCC 编译器制作的。

目标是与连接到 FTDI 的微控制器交谈。对于调试,我想开始构建一个能够:

  • 使用 ttyUSB1 在启动时初始化串行连接
  • 发送一个字符串
  • pc接收到字符串时显示字符串
  • 将通信保存到 .txt 文件

是否有任何示例代码或教程可以做到这一点?

如果我成功了,我会明确地将代码放在这里,以便新观众可以使用它!

编辑:

就像我说的那样,如果我有代码,我会发布它,这对我有用:

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

#define MODEM "/dev/ttyUSB0"
#define BAUDRATE B115200    

int main(int argc,char** argv)
{   
    struct termios tio;
    struct termios stdio;
    struct termios old_stdio;
    int tty_fd, flags;
    unsigned char c='D';
    tcgetattr(STDOUT_FILENO,&old_stdio);
    printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]);
    memset(&stdio,0,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,0,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]=5;
    if((tty_fd = open(MODEM , O_RDWR | O_NONBLOCK)) == -1){
        printf("Error while opening\n"); // Just if you want user interface error control
        return -1;
    }
    cfsetospeed(&tio,BAUDRATE);    
    cfsetispeed(&tio,BAUDRATE);            // baudrate is declarated above
    tcsetattr(tty_fd,TCSANOW,&tio);
    while (c!='q'){
        if (read(tty_fd,&c,1)>0){
            write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out
            printf("\n");
        }
        if (read(STDIN_FILENO,&c,1)>0){
            write(tty_fd,&c,1);//if new data is available on the console, send it to serial port
            printf("\n");
        }
    }
    close(tty_fd);
    tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
    return EXIT_SUCCESS;
}

大部分代码来自http://en.wikibooks.org/wiki/Serial_Programming/Serial_Linux但我也使用了下面发布的代码中的一些代码。

4

2 回答 2

3

处理串行端口(对于 linux 操作系统):
- 要打开通信,您需要一个描述符,该描述符将是您的串行端口的句柄。
- 设置标志来控制通信的方式。
- 将命令写入此句柄(确保正确格式化输入)。
- 得到答案。(确保您要阅读所需的信息量)
- 关闭手柄。它看起来像这样:

int fd; // file descriptor
int flags; // communication flags
int rsl_len; // result size
char message[128]; // message to send, you can even dinamically alocate.
char result[128]; // result to read, same from above, thanks to @Lu

flags = O_RDWR | O_NOCTTY; // Read and write, and make the job control for portability
if ((fd = open("/dev/ttyUSB1", flags)) == -1 ) {
  printf("Error while opening\n"); // Just if you want user interface error control
  return -1;
}
// In this point your communication is already estabilished, lets send out something
strcpy(message, "Hello");
if (rsl_len = write(fd, message, strlen(message)) < 0 ) {
  printf("Error while sending message\n"); // Again just in case
  return -2;
}
if (rsl_len = read(fd, &result, sizeof(result)) < 0 ) {
  printf("Error while reading return\n");
  return -3;
}
close(fd);

请注意,您必须关心写什么和读什么。在奇偶校验控制、停止位、波特率等情况下可以使用更多标志。

于 2013-10-17T14:12:31.647 回答
0

由于 gcc 是 C/C++ 编译器,因此您无需将自己限制为纯 C。

如果您喜欢编写大量样板代码,并且您真的知道自己在做什么,那么坚持使用纯 C 是可以的。许多人错误地使用了 Unix API,并且很多示例代码都过于简单化了。至少可以说,编写正确的 Unix C 代码有点烦人。

就个人而言,我建议不仅使用 C++,还建议使用 Qt 等更高级别的应用程序开发框架。Qt 5 捆绑了一个QtSerialPort模块,可以轻松枚举串行端口、配置它们以及将数据输入和输出。Qt 不会强迫您使用 gui 模块,它可以是命令行应用程序,也可以是非交互式服务器/守护程序。

QtSerialPort 也可以从 Qt 4 中使用,但它没有与 Qt 4 捆绑在一起,您必须将它添加到您的项目中。我建议从 Qt 5 开始,使用它的 C++11 支持会更好。

使用 Qt 的代码可以非常简单,不会比您的纯英文描述长多少。下面是一个使用 Qt 5 和 C++11 的 Qt 控制台应用程序。它使用coreserialport模块。它还处理SIGINT信号,以便在进程因^C. 我正在使用QLocalSocket原始 Unix API 来与 Unix 信号处理程序进行通信,功能是相同的。

只有里面的代码main是严格要求的,其余的只是在你点击时让它正确包装^C

#include <QCoreApplication>
#include <QSerialPort>
#include <QFile>
#include <QTextStream>
#include <QLocalServer>
#include <QLocalSocket>
#include <cstdio>
#include <csignal>

QLocalSocket * xmit;

static void signalHandler(int)
{
    xmit->write(" ");
    xmit->flush();
}

static bool setupSignalHandler()
{
    QLocalServer srv;
    srv.listen("foobarbaz");
    xmit = new QLocalSocket(qApp);
    xmit->connectToServer(srv.serverName(), QIODevice::WriteOnly);
    srv.waitForNewConnection();
    QLocalSocket * receive = srv.nextPendingConnection();
    receive->setParent(qApp);
    qApp->connect(receive, &QLocalSocket::readyRead, &QCoreApplication::quit);
    struct sigaction sig;
    sig.sa_handler = signalHandler;
    sigemptyset(&sig.sa_mask);
    sig.sa_flags = SA_RESTART;
    return ! sigaction(SIGINT, &sig, NULL);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    setupSignalHandler();

    QSerialPort port("ttyUSB1");
    QFile file("file.txt");
    QTextStream err(stderr, QIODevice::WriteOnly);
    QTextStream out(stdout, QIODevice::WriteOnly);
    if (!file.open(QIODevice::WriteOnly)) {
        err << "Couldn't open the output file" << endl;
        return 1;
    }
    if (!port.open(QIODevice::ReadWrite)) {
        err << "Couldn't open the port" << endl;
        return 2;
    }
    port.setBaudRate(9600);
    QObject::connect(&port, &QSerialPort::readyRead, [&](){
        QByteArray data = port.readAll();
        out << data;
        file.write(data);
    });
    out << "Use ^C to quit" << endl;
    return a.exec();
}
于 2013-10-17T21:29:48.307 回答