c - 使用 VxWorks C 将二进制数据发送到串行端口

标签 c serial-port vxworks

您好,我正在尝试对 UEIPAC 600-1G 立方体进行编程以接收来自温度传感器的数据。为了激活传感器,我必须向其发送二进制数据。我正在尝试发送设置为十六进制值的字符,但出现了问题。我通过将数据转储到文本文件中进行了测试,得到了空格,后面跟着一些乱码。如何通过串口发送二进制数据?

struct timespec tim, tim2;
unsigned char access_code[] ="       ";
int bytes=256; /*num of bytes to read at a time*/
char re[bytes]; 
int re_len = 0;
int n_access = 0;   /* store number of bytes written from access code */
int n_read =0;
int i=0;
int baud=0;
int bytes_written=0;
/* hold the file descriptor */ 
int fd = 0;  
access_code[0]=0x01; /*fill access code with correct hex data */
access_code[1]=0x00;
access_code[2]=0x00;
access_code[3]=0x00;
access_code[4]=0x08;
access_code[5]=0x02;
access_code[6]=0x03;
re_len = bytes;
memset(re, 0, sizeof(char)*bytes);
//nanopause initialization data
tim.tv_sec = 0;
tim.tv_nsec = 95000000;
/* open the device for writing and reading later. */ 
fd = open( "/tyCo/0", O_RDWR, 0);
//fd = open("TEST.txt", O_RDWR, 0);
//baud = ioctl(fd, FIOBAUDRATE, 19200); /*note test length maybe 576000 b/c terminal*/

for (i=0;i<7;i++){
    n_access = n_access+write( fd, &access_code[i], 1); /* write */ 
}
logfile=fopen ("LOGFILE.txt","a"); /* open log file*/
outputfile=fopen ("SENSORDATA.txt","a"); /* open output file*/
if(fd<0)  /* check for open error */
    fprintf(logfile,"%s","\nerror opening file\n");
fprintf(logfile,"%s" "%d" "%c","number of access code bytes written: ",n_access,'\n'); /* display bytes written*/
//step 1 call completed now pause with nano pause
if(nanosleep(&tim,&tim2)<0){
    fprintf(logfile,"%s","Nano sleep system call failed \n");
}
//step 2 complete now read with read code
n_read = read( fd, re, re_len); /* read */
if(n_read<0)
    fprintf(logfile,"%s","error reading serial data from sensor\n");
bytes_written=fprintf(outputfile,"%s",re);
fprintf(logfile,"%s" "%d" "%c","call and response executed number of bytes written: ",bytes_written,'\n');

//baud = ioctl(fd, FIOBAUDRATE, 57600);
close( fd ); /* close */ 
fclose(logfile);
fclose(outputfile);

最佳答案

它将向/tyCo/0 写入“001\0\0\0\b 002 003”,这是预期的。 为什么需要一次写入一个字节?

在写入之前,请确保 TEST.txt 文件中的 7 个字节之后没有任何内容,因为您只写入了 7 个字节。您还可以删除 TEST.txt 文件,触摸该文件以使其存在,然后它就只有您写入的 7 个字节。

关于c - 使用 VxWorks C 将二进制数据发送到串行端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862445/

相关文章:

c++ - 修复 Arduino 和 C++ Mac OS X 之间的通信

vxworks - 如何在 shell 解释器中重复 vxworks 6.9 shell 命令

symAdd 可以用来覆盖 sysSymTbl 中的现有符号吗?

c - VxWorks 堆栈帧异常大

signed 和 unsigned char 之间的比较

c - 为什么二进制数据文件比数据大?

c - printf() 的异常行为?

c - 如何在 posix_openpt() 中定义名称

python - 以编程方式与 OS X 或 Linux 中的串行端口通信

bash - grep 从 shell 脚本内的串行端口输入 5 秒