串口二进制传输变回车

2023-11-21

上周我一直在尝试用 C 实现一个原始的串行文件传输协议,我遇到了一个非常奇怪的问题,我似乎无法在网上找到解决方案。我已经设法通过串行端口传输二进制数据并接收它,但在此过程中,所有“0D”字节都转换为“0A”。以下是我的代码。

#include <stdlib.h>
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <signal.h>
#include <sys/ioctl.h>
#include <termios.h>

//eventually plan to set up a proper communication protocol
#define ACK 0x01 
#define NAK 0x00

int setAttribs (int fd, int speed, int parity);
unsigned char* readFile(char* filename, int* file_size);

int main(void){

    //set up ports
    int fd = 0, r = 0, i = 0;
    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);//sending port
    if(fd<0){
            perror("open port ttyUSB0 failed");
            return -1;
    }
    setAttribs(fd,1500000,0);

    int rd =0, file_size=0, bytes=0;
    rd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);//receiving port
    setAttribs(rd,1500000,0);

    //create file to which the binary data will be written
    FILE *newFile;
    newFile = fopen("t.bin","wb");
    if(newFile<0){
            printf("open file failed\n");
            return -1;
    }

    //This character array will hold the file to be transferred
    unsigned char* data = '\0';
    data = readFile("t.odt", &file_size);

    ioctl(rd, TCFLSH, &bytes);//port flush which does not seem to work      
    do{

            //write data in 1024 byte chunks
            write(fd,data+i,1024);

            //wait for write to finish
            usleep(8500);

            //buffer to hold received bytes
            unsigned char buffer[1024];

            //ensure buffer is empty
            memset(buffer,0,1024);

            //read in 1024 byte chunks
            read(rd, buffer, 1024);

            //printing bytes in the buffer to check for errors
            for(r=0;r<1024;r++){
                    if(r%16==0)
                            printf("\n");
                    printf("%02X ", buffer[r]);
            }

            //write to file in 1024 byte chunks
            fwrite(buffer, 1,1024,newFile);

            //increase counter
            i+=1024;

    }while(i<8197);//its an 8088 byte file  
    printf("Done!\n");
    return 0;
}

unsigned char* readFile(char* filename, int* file_size){

    unsigned char *buffer = NULL;
    int string_size, i;
    FILE *handler = fopen(filename, "rb");

    if (handler)
    {
            // Seek the last byte of the file
            fseek(handler, 0, SEEK_END);
            // Offset from the first to the last byte, or in other words, filesize
            string_size = ftell(handler);
            printf("File length: %d\n",string_size);
            *file_size = string_size;
            // go back to the start of the file
            rewind(handler);

            // Allocate a string that can hold it all
            buffer = (unsigned char*) malloc(sizeof(unsigned char) * (string_size + 1) );

            // Read it all in one operation
            for(i=0;i<string_size;i++){
                    fread(buffer+i, sizeof(unsigned char),1, handler);
                    if(i%16==0)
                            printf("\n");
                    printf("%02X ",*(buffer+i));
            }
            // fread doesn't set it so put a \0 in the last position
            // and buffer is now officially a string
            //      buffer[string_size] = '\0';
            printf("Finished read\n");

            // Always remember to close the file
            fclose(handler);
    }
 return buffer;
}
int setAttribs (int fd, int speed, int parity)
{
    struct termios tty;
    memset (&tty, 0, sizeof tty);
    if (tcgetattr (fd, &tty) != 0)
    {
            fputs("error %d from tcgetattr", stderr);

    }
    cfsetospeed (&tty, speed);
    cfsetispeed (&tty, speed);

    tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
    // disable IGNBRK for mismatched speed tests; otherwise receive break
    // as \000 chars
    tty.c_iflag &= ~IGNBRK;         // disable break processing
    tty.c_lflag = 0;                // no signaling chars, no echo,
    // no canonical processing
    tty.c_oflag = 0;                // no remapping, no delays
    tty.c_cc[VMIN]  = 0;            // read doesn't block
    tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

    tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

    tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
    // enable reading
    tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
    tty.c_cflag |= parity;
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag &= ~CRTSCTS;

    if (tcsetattr (fd, TCSANOW, &tty) != 0)
    {
            fputs("error %d from tcsetattr", stderr);

    }
    return 1;
}
                                                                                                                                                                                                                                         

它所做的只是向一个端口中的 USB 串行转换器写入数据并在另一个端口中读取 USB 串行转换器。我只是使用 8088 字节(Hello World)的 ODT 文件对其进行测试,并尝试不同的波特率和写入块大小。经过一番尝试和错误后,我发现这种配置(1500000 bps 和 1024 字节块)既快速又相对更可靠。唯一的错误如下所示。

发送字节:70 6E 67 89 50 4E 470D0A 1A 0A 00 00 000D 49

接收字节:70 6E 67 89 50 4E 470A0A 1A 0A 00 00 000A 49

正如您所看到的,所有“0D”字节都更改为“0A”。我尝试过较低的波特率和较小的块大小,但问题仍然存在。我明白他们是回车 and 换行分别值和换行用作Linux中异步通信的控制值;但我不明白为什么这会影响回车价值观。有没有什么特殊的意义回车在串行通信中?在这种情况下有没有办法发送“0D”字节?

TL;DR:原始串行通信导致“0D”字节被“0A”替换。知道为什么吗?有什么办法解决吗?


非常感谢,它成功了!我从来不知道有 ICRNL 选项可以将换行符转换为回车符。一旦我把它和其他人分开

tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); //tty is the name of the struct termios

它是金色的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

串口二进制传输变回车 的相关文章

  • 委托和接口如何互换使用?

    我可以使用接口方法代替委托吗 如何 我发现搜索接口方法比使用委托更快 我希望有一个简单的代码片段 理论上 可以通过包含单个方法的接口 例如 Java 没有委托 来完成委托完成的所有工作 然而 它使代码变得更加冗长并且没有带来什么好处 话又说
  • 以概率从列表中选择随机元素

    我有一个包含四个项目 A B C D 的列表 每个项目都有被选择的概率 例如 A 有 74 的机会被选中 B 15 C 7 D 4 我想创建一个函数 根据其概率随机选择一个项目 有什么帮助吗 为您的项目定义一个类 如下所示 class It
  • stl 集的 C# 等效项是什么?

    我想使用 C 将一些值存储在平衡二叉搜索树中 我查看了泛型命名空间中的集合 但没有找到与 stl 集合等效的集合 我可以使用什么通用集合 我不想存储键 值对 只是值 你可以使用HashSet http msdn microsoft com
  • 子进程中的变量修改

    我正在研究科比和奥哈拉伦的作品Computer Systems A Programmer s Perspective 练习 8 16 要求程序的输出如下 我更改了它 因为他们使用了一个你可以在他们的网站上下载的头文件 include
  • .NET Core 2 - 从启动中调用存储库方法[重复]

    这个问题在这里已经有答案了 我有以下存储库和类 public interface IValueService GetAll public class ValueService IValueService private DataContex
  • 这种 bash 文件名提取技术有何用途?

    我有一部分 bash 脚本正在获取不带扩展名的文件名 但我试图了解这里到底发生了什么 是做什么用的 有人可以详细说明 bash 在幕后做了什么吗 如何在一般基础上使用该技术 bin bash for src in tif do txt sr
  • C++ 为非虚方法指定初始化

    我有 a h 如下所示 class A public void doSomething 0 然后我有 b h 如下所示 include a h class b public A public void doSomething 我只是想通过尝
  • 码头无故停止

    我需要经验丰富的码头用户的建议 我在负载均衡器 亚马逊云 后面维护着 2 台 Linux 机器 使用 Jetty 9 0 3 有时我的 Jetty 容器会被 Thread 2 无故关闭 同时地 显示以下日志并且容器无故停止 没有错误 没有例
  • 如何设置cookie值?

    我正在执行以下操作来设置 cookie 值 HttpCookie mycookie new HttpCookie mycookie mycookie Value value1 Case sensitivity mycookie Expire
  • 尝试缓冲区溢出

    我正在尝试使用缓冲区溢出来更改函数的结果 以使用以下代码更改堆栈上的结果 include
  • 找出 Linux 上的默认语言

    有没有办法从C语言中找出Linux系统的默认语言 有 POSIX API 可以实现这个功能吗 例如 我想要一个人类可读格式的字符串 即德语系统上的 German 或 Deutsch 法语系统上的 French 或 Francais 等 有类
  • 从 TFS 下载工作项附件(文件已损坏)

    我正在尝试创建 C 代码 因此我可以自动从 Team Foundation Server 下载 BUGS 预定义查询的所有附件 该代码似乎工作得很好 但所有下载的文件都因意外原因而损坏 我无法查看它们 有人可以看一下代码并分享意见吗 非常感
  • 为什么 C++ 元组如此奇怪?

    我通常创建自定义structs将不同类型的值分组在一起时 这通常很好 而且我个人发现命名成员访问更容易阅读 但我想创建一个更通用的 API 在其他语言中广泛使用元组后 我想返回类型的值std tuple但发现它们在 C 中使用比在其他语言中
  • 我的 Opencv 应用程序处理速度非常慢

    我正在构建一个 OpenCV 应用程序 它从相机捕获视频 并在删除背景后将其覆盖在另一个视频上 我无法达到合理的速度 因为它以大约 1 fps 的速度播放输出 而我的背景去除以 3 fps 的速度工作 有没有办法以正常速度显示背景视频并以
  • 仅最后一个用户控件显示内容控件

    我有一个奇怪的问题 我创建了一个带有标签和画布的用户控件 画布引用资源 但画布仅显示在我的堆栈面板中的最后一个控件上 这是我的窗户
  • 将 .NET 类库(主要定义 CRUD 操作)公开为服务

    公开现有内容的最佳 有效和最快的方法是什么 类 图书馆 主要定义 CRUD 操作 作为service 周转基金服务 or WCF数据服务 以便它可以与银光 or Ajax 在那儿tools 代码生成器 RAD 工具 哪些可以支持这个 预先感
  • 使用 System.Json 迭代 JSON

    我正在探索 NET 4 5 的功能System Json库 但没有太多文档 而且由于流行的 JSON NET 库 搜索起来相当棘手 我基本上想知道 我如何循环一些 JSON 例如 People Simon Age 25 Steve Age
  • Lambda 按值捕获和“mutable”关键字

    关键词的必要性mutable在 lambda 中 是造成极大混乱的根源 考虑代码 int x 10 function
  • 定义一个断言,即使定义了 NDEBUG,该断言也有效

    我想定义一个assert与标准相同的宏assert 3 http man7 org linux man pages man3 assert 3 html调用 但它不会被预处理器删除NDEBUG被定义为 这样的呼唤 让我们称之为assert2
  • “while(true) { Thread.Sleep }”的原因是什么?

    我有时会遇到以下形式的代码 while true do something Thread Sleep 1000 我想知道这是否被认为是好的做法还是坏的做法以及是否有任何替代方案 通常我在服务的主函数中 找到 这样的代码 我最近在 Windo

随机推荐