歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下的串口編程

Linux下的串口編程

日期:2017/3/1 10:04:44   编辑:Linux編程

一:串口發送端程序

/***************************************************************************************************
**文件:w_uart.c
**編寫者:huangminqiang
**編寫日期:2012年10月15號
**簡要描述:串口發送程序,在PC機上發送。
**修改者:
**修改日期:2012年11月12號
**注:
****************************************************************************************************/
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#define COM "/dev/ttyS0"

typedef enum
{
NON, //無校驗
ODD, //偶校驗
EVEN,//奇校驗
}cal_t;

/****** 設置串口***************************************************************************************/
static int set_com(int fd, int speed, int bits, cal_t cal, int stop )
{
struct termios curtio;

memset(&curtio, 0, sizeof(curtio));

//取得串口已有的屬性
if (0 != tcgetattr(fd, &curtio))
{
perror("Failed to tcgetattr");
return -1;
}

//設置輸入輸出波特率
cfsetispeed(&curtio, speed);
cfsetospeed(&curtio, speed);

//設置為原始模式
curtio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG | ECHOE | ECHOK | ECHONL);
curtio.c_iflag &= ~(BRKINT | IUCLC | ICRNL | INLCR | IGNCR);

//激活相應選項
curtio.c_cflag |= CLOCAL | CREAD;

//設置數據位
curtio.c_cflag &= ~CSIZE;
curtio.c_cflag |= bits;

//設置校驗位
if (ODD == cal)
{
curtio.c_iflag |= (INPCK | ISTRIP);
curtio.c_cflag |= PARENB;
curtio.c_cflag |= PARODD;
}
else if(EVEN == cal)
{
curtio.c_iflag |= (INPCK | ISTRIP);
curtio.c_cflag |= PARENB;
curtio.c_cflag &= ~PARODD;
}
else
{
curtio.c_cflag &= ~PARENB;
}

//設置停止位
if (2 == stop)
{
curtio.c_cflag |= CSTOPB;
}
else
{
curtio.c_cflag &= ~CSTOPB;
}

//設置最少字符等待時間
curtio.c_cc[VTIME] = 0;
curtio.c_cc[VMIN] = 0;

//清空緩沖
tcflush(fd, TCIOFLUSH);

//設置新串口屬性
if (0 != tcsetattr(fd, TCSANOW, &curtio))
{
perror("Failed to tcgetattr");
return -1;
}

printf("set done!\n");

return 0;
}


/****** 寫入串口信息 **********************************************************************************/
int WriteUartInfo(void)
{
int fd;
int cnt = 0;
int w_cnt = 0;
unsigned char w_buf[128];

//打開串口
fd = open(COM, O_RDWR);
if(0 > fd)
{
perror("uart open err:");
return -1;
}

#if 0
//設置串口參數
if (0 != set_com(fd, B115200, CS8, NON, 1))
{
printf("set_com failed!\n");
goto _out;
}
#endif

//發送信息
while(1)
{
printf("plese input a buffer : ");
memset(w_buf, 0, sizeof(w_buf));
fgets(w_buf, sizeof(w_buf), stdin);
w_cnt = write(fd, w_buf, sizeof(w_buf));
if(0 > w_cnt)
{
perror("write error : ");
goto _out;
}
printf("sent out ! \n");

//結束判斷
if( !strncmp(w_buf, "quit", 4) )
{
break;
}
}

//關閉串口
close(fd);
return 0;
_out:
close(fd);
return -1;
}


/****** 主函數 ****************************************************************************************/
int main(void)
{
if( WriteUartInfo() )
{
printf("write uart data failed!\n");
return -1;
}

return 0;
}

Copyright © Linux教程網 All Rights Reserved