寫了個串口通信的小例子,點擊右側連接查看 https://github.com/PuGongYing1/SerialPortgit
不多看到有資料寫如何以中斷的方式發送一幀數據,若是以等待的發送數據幀,對高速運行的單片機來講是很浪費時間的,下面就介紹一種使用中斷方式發送數據幀,操做平臺採用51 mcugithub
首先定義一個數據幀的結構體,該結構體能夠作爲一個全局變量,全部的發送都要通過這個結構體:數組
//結構體
struct {
char busy_falg;//忙標誌,若在發送數據時置位1,即在開始發送置位1,發送結束置位0
int index;//索引,指向須要發送數組的位置
int length;//整個數據幀的長度
char *buf;//指向須要發送的數據幀,建議爲全局變量,不然一旦開始發送,必須等到發送結束,即判斷busy_falg爲0
} send_buf;發送數據的函數,這裏有個缺點,就是仍是要使用while來檢測串口是否忙碌,不過這樣比佔用系統時間來發送要好的多了:函數
//發送一幀
void SendBuf(char *buf,int length)
{
while(busy_falg);//查詢發送是否忙,不然循環等待
send_buf.length = length;
send_buf.index = 0;
send_buf.buf = buf;
send_buf.busy_falg = 1;
SBUF = send_buf.buf[0];//寫入SBUF,開始發送,後面就自動進入中斷髮送
}串口中斷髮送函數,注意設置空閒標誌位,避免多任務時多個發送幀調用了同一個結構體:url
void SerialInt() interrupt 4 //串口中斷
{
if(RI == 1) //串口接收
{
RI = 0;
}
else if(TI == 1)//串口發送
{
TI = 0;
send_buf.index++;
if(send_buf.index == send_buf.length)
{
send_buf.busy_falg = 0;//發送結束
return;
}
SBUF = send_buf.buf[send_buf.index];//繼續發送下一個
}
}
串口中斷髮送就是這樣簡單,注意busy_falg和index的使用。
.net
From <http://m.blog.csdn.net/liucheng5037/article/details/48831993>blog