近來因爲項目需要,第一次接觸Linux系統的硬件,心裏有點小激動。。。我使用的Microwrt是OPENWRT的微型版本,系統一樣,但更加小巧,方便使用。
不過由於是第一次使用,光Helloworld就測試了很長時間。現在更卡在了串口問題上,在網上也沒找到OPENWRT串口方面的資料(可能是我比較笨吧)。在高人的指導下,我更改了詢問度孃的方式,開始搜索Linux串口方面的資料。雖然找到了一些,但是感覺講解的都不是很清晰。後來找到了shanzhizhi的博客,上面講解的很清晰,在他的指導下,我也就寫了這個簡單的串口程序,因爲很簡單,而且是初試,不足之處,請大家見諒。
Microwrt串口使用過程:
1、通過ssh的方式進入Microwrt系統之中,然後進入/etc/目錄,修改inittab,打開文件並將如下代碼的最後一行註釋掉。
::sysinit:/etc/init.d/rcS S boot
::shutdown:/etc/init.d/rcS K stop
ttyS0::askfirst:/bin/login
#ttyS1::askfirst:/bin/login
2.編輯serial.c文件,代碼如下:/*
*按照教程學習串口的編程
*網址:http://blog.csdn.net/shanzhizi/article/details/9241393
*/
//頭文件
#include <stdio.h> //標準輸入輸出定義
#include <stdlib.h> //標準函數庫定義
#include <unistd.h> //Unix標準函數定義
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> //文件控制定義
#include <termios.h> //POSIX中斷控制定義
#include <errno.h> //錯誤號定義
//定義波特率數組
int speed_arr[] = {B115200, B38400, B19200, B9600, B4800, B2400, B1200, B300};
int name_arr[] = {115200,38400, 19200, 9600, 4800, 2400, 1200, 300};
//打開串口
int open_port(void)
{
int fd; //串口的標識符
//O_NOCTTY用來告訴Linux這個程序不會成爲“控制終端”
//O_NDELAY用來告訴Linux這個程序不關心DCD信號
fd=open("/dev/ttyS1",O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1)
{
//不能打開串口
perror("open_port: Unable to open /dev/ttyS1 -");
return(fd);
}
else
{
fcntl(fd, F_SETFL, 0);
printf("open ttys1 .....\n");
return(fd);
}
}
//設置波特率
void set_speed_and_parity(int fd, int speed)
{
int i=0; //設置循環標誌——注意不要在for內設置,否則會出錯
struct termios Opt; //定義termios結構
if(tcgetattr(fd,&Opt)!=0)
{
perror("tcgetattr fd");
return;
}
for(i = 0; i < 8 ; i++)
{
if(speed == name_arr[i])
{
tcflush(fd, TCIOFLUSH);
cfsetispeed(&Opt, speed_arr[i]);
cfsetospeed(&Opt, speed_arr[i]);
/*tcsetattr函數標誌:
TCSANOW:立即執行而不等待數據發送或者接受完成。
TCSADRAIN:等待所有數據傳遞完成後執行。
TCSAFLUSH:Flush input and output buffers and make the change
*/
if(tcsetattr(fd, TCSANOW, &Opt) != 0)
{
perror("tcsetattr fd");
return;
}
tcflush(fd, TCIOFLUSH);
}
}
//設置奇偶校驗——默認8個數據位、沒有校驗位
Opt.c_cflag &= ~PARENB;
Opt.c_cflag &= ~CSTOPB;
Opt.c_cflag &= ~CSIZE;
Opt.c_cflag |= CS8;
}
/*
//設置奇偶校驗——默認8個數據位、沒有校驗位
int set_parity()
{
Opt.c_options.c_cflag &= ~PARENB
options.c_cflag &= ~CSTOPB
options.c_cflag &= ~CSIZE;
Opt.c_cflag |= CS8;
}
*/
int main(void)
{
int fd;
int nread,i;
char buff[]="Hello\n";
//打開串口
if((fd=open_port())<0)
{
perror("open_port error");
return 0;
}
//設置波特率和校驗位
set_speed_and_parity(fd,115200);
//設置校驗位
//set_parity();
printf("fd=%d\n",fd);
//嘗試先寫內容
for(int i=0;i<100;i++)
{
nread=write(fd,buff,8);
//nread=read(fd,buff,8);
printf("nread=%d,%s\n",nread,buff);
}
//關閉串口
close(fd);
return 0;
}
3.進行編譯。在這裏就不詳細寫它的Makefile和它的Make過程了,可以參照openwrt刷機教程。
4.將生成的bin文件通過winscp(win7)或scp指令(Linux和Mac)的方式發送到Microwrt的/usr/bin目錄下
5.直接運行./serial。就可以看到它的運行結果了。。。
關於Microwrt的串口連接,使用UPIN54轉UPIN27模塊就可以了,然後將FT232模塊直接插在它的上面,用數據線連接它和電腦,就可以檢測串口數據連接了。