最近在學習linux 串口操作,計劃是把從串口讀到的資料 寫到一個 .TXT 檔案,發現下寫完定義的char title[] = "time data\n"; 字符后,第二行總會多出來一下^@ 內容,這個對應的是\0 字符,可代碼里面沒有寫過這個字符,不知道這個字符是怎么出來的,請教各位是否有遇到過的,指點一下,謝謝! 如下是代碼和測驗的結果。
//串口配置函式
int serial_test(void)
{
char testdata[]={0xfe,0x19,0x26,0x34};
char dataread[10];
bzero(dataread,sizeof(dataread));
fd0 = open("/dev/ttyS2",O_RDWR);
if(fd0 <0)
{
printf("open serial fail\n");
return 1;
}
tcgetattr(fd0, &oldtio); /* Save fd1 setting */
tcgetattr(fd0, &newtio);
newtio.c_cflag = B115200 | CS8 | CREAD | CLOCAL;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VMIN] = 1;
newtio.c_cc[VTIME] = 0;
tcflush(fd0, TCIFLUSH);
tcsetattr(fd0, TCSANOW, &newtio); /* Configuration fd1 *///使設定的終端屬性立即生效
printf("serial ok\n");
sleep(1);
}
/// 串口執行緒函式
void *serial_read_data(void * arg)
{
fd_set fdR;
//char buff[30] = {0};
int fd1;
struct timeval timeout= {0,0};
int rselect;
time_t timer;
char timebuff[40];
char buff[256];
int len,len1,len2;
char kongge[] = " ";
char title[] = "time data\n";
char huanghang[] = "\n";
char rdatabuff[100] = {0};
fd0 = open("/dev/ttyS2",O_RDWR);
tcflush(fd0,TCIFLUSH);
sleep(4);
fd1 = open("/umsd/stest.txt",O_RDWR|O_CREAT|O_TRUNC);
lseek(fd1,0,SEEK_END);
write(fd1,title,sizeof(title));
timeout.tv_sec = 10;
bzero(buff,sizeof(buff));
bzero(timebuff,sizeof(timebuff));
if(fd0< 0)
{
printf("open fuji serial fild\n");
}
while (1)
{
FD_ZERO(&fdR);
FD_SET(fd0,&fdR );
rselect = select(fd0+1,&fdR,NULL,NULL,&timeout);
switch (rselect)
{
case -1:
printf("serial error\n");
break;
case 0:
// printf("serial no read data\n");
break;
default:
if(FD_ISSET(fd0,&fdR))
{
len1 = read(fd0,rdatabuff,sizeof(rdatabuff));
timer = time(NULL);
ctime_r(&timer,timebuff);
len= strlen(timebuff);
strncpy(buff,timebuff,len-1);
strcat(buff,kongge);
strcat(buff,rdatabuff);
strcat(buff,huanghang);
len2 = strlen(buff);
write(fd1,buff,len2);
printf("read data ok %s\n",buff);
bzero(buff,sizeof(buff));
bzero(rdatabuff,sizeof(rdatabuff));
}
}
}
/// 測驗結果
/mnt/home # cd /umsd
/umsd # vi stest.txt
time data
^@Wed Feb 7 09:09:50 2018 123456789
Wed Feb 7 09:10:00 2018 serial ok
Wed Feb 7 09:10:02 2018 123456789
uj5u.com熱心網友回復:
既有可能是不可見的\r\n 等字符,可以從16進制工具od 命令查看下。uj5u.com熱心網友回復:
你好,這個問題您解決了嗎?轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/242501.html
標籤:非技術區
上一篇:openssh如何禁用scp?
下一篇:bash -c 問題
