linux读取ttyusb0分区表,读取的/ dev/ttyUSB0与LINUX

博主试图通过C程序读取连接到/Linux系统的/dev/ttyUSB0设备上GPS发送的XBee协议数据。遇到的问题是在使用read()函数时出现接收错误,导致无法正确显示数据,接收到的字符是乱码。尝试了不同格式的字符串输出,但未成功。其他用户建议提供更详细的错误信息,并检查串口配置是否适合二进制传输。
摘要由CSDN通过智能技术生成

C程序我想读由GPS的XBee协议发送的数据帧。 XStick收到以下数据的USB:读取的/ dev/ttyUSB0与LINUX

CHARS : 15931 SENTENCES = 0 CHECKSUM : 58

Heading : 55 Tilt: -46 Roll:2

CHARS : ....

等等...我可以通过终端控制输入阅读:

$ screen /dev/ttyUSB0

我想以同样的方式看到这些细节,但与C语言编写的程序下面是我做的:

#include

#include

#include

#include

#include

#include "serial_port.h"

void read_Serial_Port(const char* DEVICE_PORT)

{

int file;

struct termios options;

char message[100];

unsigned int nCountMax = 60;

bool b;

file = open(DEVICE_PORT, O_RDONLY | O_NOCTTY | O_NDELAY);

if(file == -1){perror("Unable to open the serial port\n");}

printf("Serial port open successful\n");

tcgetattr(file, &options);

cfsetispeed(&options, B9600);

可以通过以下步骤将/dev/ttyUSB0的数据放到共享内存中: 1. 打开/dev/ttyUSB0设备,并设置其属性,例如波特率、数据位、停止位等等。 2. 创建共享内存,通过shmget函数可以创建共享内存,指定共享内存的大小。 3. 通过shmat函数将共享内存映射到进程的地址空间中。 4. 通过read函数从/dev/ttyUSB0设备中读取数据,并将数据写入共享内存中。 5. 通过shmdt函数将共享内存与进程的地址空间分离。 下面是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <termios.h> #define SHM_SIZE 4096 int main() { int fd = -1; int shmid = -1; char *shmaddr = NULL; struct termios options; // 打开/dev/ttyUSB0设备,并设置属性 fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { perror("open ttyUSB0 error"); exit(EXIT_FAILURE); } tcgetattr(fd, &options); // 获取当前设置 options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_cflag &= ~PARENB; options.c_iflag &= ~(IXON | IXOFF | IXANY); options.c_oflag &= ~OPOST; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); options.c_cc[VTIME] = 0; options.c_cc[VMIN] = 1; cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); tcsetattr(fd, TCSANOW, &options); // 设置属性 // 创建共享内存 shmid = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT | 0666); if (shmid < 0) { perror("shmget error"); exit(EXIT_FAILURE); } // 映射共享内存到进程地址空间 shmaddr = shmat(shmid, NULL, 0); if (shmaddr == (void *)-1) { perror("shmat error"); exit(EXIT_FAILURE); } while (1) { char buf[256] = {0}; int ret = read(fd, buf, sizeof(buf)); if (ret < 0) { perror("read error"); exit(EXIT_FAILURE); } if (ret == 0) { continue; } // 将读取的数据写入共享内存 strncpy(shmaddr, buf, SHM_SIZE); } // 分离共享内存 if (shmdt(shmaddr) < 0) { perror("shmdt error"); exit(EXIT_FAILURE); } // 删除共享内存 if (shmctl(shmid, IPC_RMID, NULL) < 0) { perror("shmctl error"); exit(EXIT_FAILURE); } // 关闭设备 close(fd); return 0; } ``` 上述代码只是一个简单的示例,实际应用中需要根据具体需求进行修改。同时需要注意的是,共享内存需要在多个进程之间进行共享,需要考虑进程间同步和互斥问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值