以下是一个可能的实现,使用了Linux系统的文件操作和串口通信库:

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

#define BAUDRATE B9600
#define SERIAL_PORT "/dev/ttyS0"
#define MAX_BUF_SIZE 4096

void send_file(const char* filename)
{
    // 打开串口
    int serial_fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
    if (serial_fd < 0) {
        perror("open serial port");
        exit(1);
    }

    // 配置串口
    struct termios options;
    tcgetattr(serial_fd, &options);
    cfsetispeed(&options, BAUDRATE);
    cfsetospeed(&options, BAUDRATE);
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CRTSCTS;
    tcsetattr(serial_fd, TCSANOW, &options);

    // 打开文件
    FILE* fp = fopen(filename, "rb");
    if (fp == NULL) {
        perror("open file");
        exit(1);
    }

    // 读取文件内容并发送
    char buf[MAX_BUF_SIZE];
    size_t n;
    while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
        int ret = write(serial_fd, buf, n);
        if (ret < 0) {
            perror("write serial port");
            exit(1);
        }
    }

    // 关闭文件和串口
    fclose(fp);
    close(serial_fd);
}

int main()
{
    // 读取当前目录下的所有bin文件并发送
    system("ls *.bin > temp.txt");
    FILE* fp = fopen("temp.txt", "r");
    if (fp == NULL) {
        perror("open temp file");
        exit(1);
    }
    char filename[256];
    while (fgets(filename, sizeof(filename), fp) != NULL) {
        send_file(filename);
    }
    fclose(fp);
    system("rm temp.txt");
    return 0;
}

注意:该实现仅供参考,具体实现可能需要根据实际情况进行修改和调整

linux系统下使用C语言编写一个函数读取当前目录下的bin文件并通过串口发送出来

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

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