linux 串口测试指令和测试程序
    		       		warning:
    		            这篇文章距离上次修改已过447天,其中的内容可能已经有所变动。
    		        
        		                
                在Linux环境下,可以使用screen和minicom等串口调试工具进行串口测试。以下是使用screen进行串口通信的基本命令和步骤:
首先,安装screen:
sudo apt-update
sudo apt-get install screen然后,使用screen连接到串口设备:
screen /dev/ttyS0 115200这里/dev/ttyS0是串口设备文件,115200是波特率。
在screen会话中,你可以输入任何你想发送的数据,并且可以看到接收到的数据。
退出screen会话的快捷键是Ctrl-A然后按k,确认后退出。
如果你想要一个简单的串口测试程序,可以使用以下示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
 
int main() {
    int fd;
    struct termios options;
    char buffer[255];
    int bytes_read;
 
    fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1) {
        perror("open_port: Unable to open serial port - ");
        return(-1);
    }
 
    // 获取并配置串口选项
    tcgetattr(fd, &options);
    cfsetispeed(&options, B115200); // 输入波特率
    cfsetospeed(&options, B115200); // 输出波特率
    options.c_cflag |= (CLOCAL | CREAD); // 开启接收
    options.c_cflag &= ~CSIZE; // 清除当前数据位设置
    options.c_cflag |= CS8;    // 8位数据位
    options.c_cflag &= ~PARENB; // 关闭校验位
    options.c_cflag &= ~CSTOPB; // 1位停止位
    options.c_cc[VMIN] = 1; // 读取最小字符数
    options.c_cc[VTIME] = 0; // 读取最小字符时间
    tcflush(fd, TCIFLUSH); // 清空输入缓冲区
 
    // 写入数据到串口
    write(fd, "Hello Serial!\n", 14);
 
    // 从串口读取数据
    bytes_read = read(fd, buffer, sizeof(buffer));
    if (bytes_read > 0) {
        buffer[bytes_read] = '\0';
        printf("Received: %s", buffer);
    }
 
    close(fd); // 关闭串口
    return 0;
}这个程序会在打开的串口设备中写入"Hello Serial!",然后读取任何传入的数据并打印出来。
请确保你有适当的权限来访问串口设备,并且根据你的实际情况调整串口设备文件和波特率。
评论已关闭