Linux應用層對串口的使用操作

在Linux中串口作爲字符設備,設備節點在/dev/目錄下,使用普通的open,close,write和read等系統調用即可使用。這其中會涉及到一些串口的基本屬性的設置,如:波特率,奇偶校驗,停止位,數據位以及有無流控等。一些特殊的系統調用和數據結構會被使用。

參考:

https://blog.csdn.net/u013485792/article/details/51006790

 

下面是一個簡單的示例: 

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>

int uart_init(int fd)
{
	struct termios newtio, oldtio;
	fcntl(fd,F_SETFL,0);/*恢復串口爲阻塞狀態*/
    if ( tcgetattr(fd, &oldtio ) != 0) {  
        perror("tcgetattr error");
        return -1;
    }
	bzero( &newtio, sizeof(newtio) );
    newtio.c_cflag  |= B115200 | CLOCAL | CREAD; // 設置波特率,本地連接,接收使能
    newtio.c_cflag &= ~CSIZE;
	newtio.c_cflag  |= CS8; // 數據位爲 8 ,CS7 for 7 
	newtio.c_cflag &= ~CSTOPB; // 一位停止位, 兩位停止爲 |= CSTOPB
	newtio.c_cflag &= ~PARENB; // 無校驗
	//newtio.c_cflag |= PARENB; //有校驗
	//newtio.c_cflag &= ~PARODD // 偶校驗
	//newtio.c_cflag |=  PARODD    // 奇校驗
	//newtio.c_cc[VTIME] = 0; // 等待時間,單位百毫秒 (讀)。後有詳細說明
	//newtio.c_cc[VMIN] = 0; // 最小字節數 (讀)。後有詳細說明
	tcflush(fd, TCIOFLUSH); // TCIFLUSH刷清輸入隊列。
                                       //TCOFLUSH刷清輸出隊列。 
                                       //TCIOFLUSH刷清輸入、輸出隊列。
	tcsetattr(fd, TCSANOW, &newtio); // TCSANOW立即生效;
                                                        //TCSADRAIN:Wait until everything has been transmitted;
                                                        //TCSAFLUSH:Flush input and output buffers and make the change	
	
	return 0;
}

int main(int argc, char *argv[])
{
	char buff[50] = {0};
	//char w_buff[] = {0xaa, 0x55, 0x00, 0x30, 0x00, 0x08, 0x00, 0x00, 0xff, 0x07, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x00, 0x00, 0x0d, 0x0a };
	char w_buff[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa};
	int read_size = 0, i = 0, write_size = 0;
	//int fd = open("/dev/ttyAMA0", O_RDWR|O_NOCTTY|O_NDELAY);
	int fd = open("/dev/ttyAMA0", O_RDWR|O_NOCTTY);
	if(-1 == fd){
		perror("can't open serialport");
		return -1;
	}
	
	uart_init(fd);

	while(1)
	{
		write_size = write(fd, w_buff, sizeof(w_buff));
		if(write_size < 0){
			perror("serial port write is error");
		}
		
		read_size = read(fd, buff, sizeof(buff));
		printf("write_size = %d .receive length:%d data:", write_size, read_size);
		for(i = 0; i < read_size; i++){
			printf("%02x ", buff[i]);
		}
		printf("\n");
		usleep(300000);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章