以下是一个简单的例子代码:

#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>\n", argv[0]);
        return 0;
    }

    int fd = open("/dev/ttyUSB0", O_WRONLY | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening serial port\n");
        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\n");
        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\n");
                return -1;
            }
            total_bytes += bytes_sent;
        }
    } while (bytes_read > 0);

    close(file_fd);
    close(fd);

    printf("Sent %d bytes\n", total_bytes);

    return 0;
}

这个程序的主要思路是打开串口设备文件,设置串口参数,然后打开要发送的文件,每次读取128字节,通过串口发送。如果读取到的字节数小于128,说明已经读取到文件末尾,程序退出。发送数据的函数send_data会保证数据发送完整,如果数据没有完整发送,会一直重试发送

linux系统C语言写一个函数读取一个BIN文件通过串口发送每次发送128位

原文地址: https://www.cveoy.top/t/topic/hua7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录