2013-07-12 42 views
1

我有unsigned int DataBAR並想發送char到串口!write()返回errno 14爲什麼?

我的代碼是:

unsigned char Printer_buffer[PRN_BUFFER_SIZE]; 
unsigned int DataBAR, DataD, DataT; 

for (i = 0; i < 8; i++) { 
    SumaN = SumaN + (Printer_buffer[i] & 0x0F); 
    DataBAR = (Printer_buffer[i] & 0x0F) + 0x30; 
    nbytes = write(fd,DataBAR ,1); //want to send to the serial port 
    printf("write error code is %d !!!!!!!!!\n", errno); 
    if (nbytes != 1) { 
    printf("error writing on serial port!!!\n"); 
    } 
    sleep(1); 
    SumaP = SumaP + ((Printer_buffer[i] >> 4) & 0x0F); 
    DataBAR = ((Printer_buffer[i] >> 4) & 0x0F) + 0x30; 
    nbytes = write(fd, DataBAR, 1); 
    printf("write error code is %d !!!!!!!!!\n", errno); 
    if (nbytes != 1) { 
    printf("error writing on serial port!!!\n"); 
    } 
    sleep(1); 
} 

write回到errno=14如何解決這個問題呢?

在C PIC18F我用這個代碼,它是工作:

for (i=0;i<8;i++){ 
    SumaN=SumaN+(Printer_buffer[i] & 0x0F); 
    DataBAR=(Printer_buffer[i] & 0x0F) + 0x30; 
    while(BusyUART1()); 
    putcUART1(DataBAR);    
    SumaP=SumaP+((Printer_buffer[i]>>4) & 0x0F); 
    DataBAR=((Printer_buffer[i]>>4) & 0x0F) + 0x30; 
    while(BusyUART1()); 
    putcUART1(DataBAR);    
} 

我真的現在在這,感謝您的幫助!

+1

errno 14 =錯誤的地址,您如何打開'fd'? –

+0

fd = open(「/ dev/ttyS0」,O_RDWR | O_NOCTTY | O_NDELAY); (「open_port:Unable to open/dev/ttyS0 \ n」);如果(fd == -1){ \t \t perror \t \t exit(1); \t} –

+0

串口配置:tcgetattr(fd,&termAttr); \t // baudRate = B115200;/*不需要*/ \t cfsetispeed(&termAttr,B57600); \t cfsetospeed(&termAttr,B57600); \t termAttr.c_cflag&=〜PARENB; \t termAttr.c_cflag&=〜CSTOPB; \t termAttr.c_cflag&=〜CSIZE; \t termAttr.c_cflag | = CS8; \t termAttr.c_cflag | =(CLOCAL | CREAD); \t termAttr.c_lflag&=〜(ICANON | ECHO | ECHOE | ISIG); \t termAttr.c_iflag&=〜(IXON | IXOFF | IXANY); \t termAttr.c_oflag&=〜OPOST; \t termAttr.c_cc [VMIN] = 3; \t termAttr.c_cc [VTIME] = 5; \t tcsetattr(fd,TCSANOW,&termAttr); –

回答

3

write()int write(int fd, void *buf, int n)所以你不能傳遞一個整數作爲第二個參數。我想你沒有包含unistd.h,否則你的代碼甚至不應該編譯。而是指the man page,並呼籲

write(fd, &DataBAR, 1) 

但要知道,這取決於你的系統的字節序不管你寫的最多的還是通過這樣做,最不顯著字節。更好地將DataBAR定義爲char(或將值複製到char c中並使用&c,write()

+1

好吧,OP要發一個'char',所以'n'只會是1(儘管你可能會認爲endianness可能會引發一個問題)。 –

+0

@抽出你是對的,我會編輯 –

相關問題