Linux C 语言串口发送 BIN 文件:128 位数据块传输
Linux C 语言串口发送 BIN 文件:128 位数据块传输
本文将演示如何在 Linux 系统中使用 C 语言编写程序,通过串口发送 BIN 文件,并每次发送 128 位数据块。
代码示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#define BUFFER_SIZE 128
int send_data(int fd, const char *data, int len) {
int bytes_written = 0;
while (bytes_written < len) {
int n = write(fd, data + bytes_written, len - bytes_written);
if (n < 0) {
return -1;
}
bytes_written += n;
}
return bytes_written;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <filename>
", argv[0]);
return 0;
}
int fd = open("/dev/ttyUSB0", O_WRONLY | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening serial port
");
return -1;
}
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CRTSCTS;
tcsetattr(fd, TCSANOW, &options);
char buffer[BUFFER_SIZE];
int bytes_read = 0;
int total_bytes = 0;
int file_fd = open(argv[1], O_RDONLY);
if (file_fd < 0) {
printf("Error opening file
");
return -1;
}
do {
bytes_read = read(file_fd, buffer, BUFFER_SIZE);
if (bytes_read > 0) {
int bytes_sent = send_data(fd, buffer, bytes_read);
if (bytes_sent < 0) {
printf("Error sending data
");
return -1;
}
total_bytes += bytes_sent;
}
} while (bytes_read > 0);
close(file_fd);
close(fd);
printf("Sent %d bytes
", total_bytes);
return 0;
}
程序解析
- 打开串口设备文件:使用
open()函数打开串口设备文件(例如/dev/ttyUSB0)。 - 设置串口参数:使用
tcgetattr()函数获取当前串口参数,并使用cfsetispeed()和cfsetospeed()函数设置波特率,以及其他参数。 - 打开要发送的文件:使用
open()函数打开要发送的 BIN 文件。 - 循环读取文件并发送数据:使用
read()函数读取文件数据,每次读取 128 字节。如果读取成功,则使用send_data()函数将数据发送到串口。 - 数据发送函数
send_data():该函数确保所有数据都完整发送。如果数据没有完全发送,则会一直重试发送。
注意事项
- 请根据您的硬件设备修改串口设备文件路径和串口参数。
- 请确保串口连接到接收设备,并确保接收设备可以接收数据。
send_data()函数会阻塞等待数据发送完成,这可能会影响程序性能。
总结
本示例代码演示了如何使用 C 语言编写 Linux 程序,通过串口发送 BIN 文件,并每次发送 128 位数据块。您可以根据自己的需求修改代码,例如调整发送数据块大小或添加错误处理机制。
原文地址: https://www.cveoy.top/t/topic/oWXc 著作权归作者所有。请勿转载和采集!