|
實現(xiàn)單片機(jī)和計算機(jī)之間的數(shù)據(jù)交換, Windows 環(huán)境下的Visual Basic 6.0 作為可視化的編程工具, 具有完整的基于組件設(shè)計的可視化集成開發(fā)環(huán)境、操作簡單、界面友好的特點(diǎn)。 上位機(jī)通信程序是用VB6.0 使用MAX232 來進(jìn)行數(shù)據(jù)通信的協(xié)議, 既可 以使用查詢方式又可以使用事件驅(qū)動方式來完成串行通信。
1 上位機(jī)程序
Private Sub Form- Load( )
MSComm1.CommPort=1‘選擇通信端口1’
MSComm1.InputLen=0‘串行數(shù)據(jù)接收緩沖區(qū)初始化’
MSComm1.Settings=“9600, n, 8, 1”
設(shè)置端口參數(shù): 波特率為9 600 b/s, 無奇偶校驗位, 8 位數(shù)據(jù), 1 位停
止位。
MSComm1.PortOpen=True ‘打開串口’
MSComm1.RThreshold=1 ‘有一個字符就接收’
ENDSub
Private Sub MSComm1_OnComm( )
Select Case MSComm1.CommEvent
Case comEvReceive
DimBuffer As Variant, i
MSComm1.InputMode=comInputModeBinary
MSComm1.InputLen=0
Do’該循環(huán)判斷輸入緩沖區(qū)是否有數(shù)據(jù)
DoEvents
Loop Until MSComm1.InBufferCount>=1
Buffer=MSComm1.Input
For i = LBound( Buffer) To UBound( Buffer)
List1.AddItemBuffer( i) ‘把接收到的數(shù)據(jù)顯示在列表框中’
Next i
Case Else
End Select
End Sub
Private Sub CommandClose- Click( )
IfMSComm1.PortOpen=True Then
MSComm1.PortOpen=False
‘關(guān)閉串行端口’
x=MsgBox(“關(guān)閉通信! ”, 16)
End If
ENDSub
2 下位機(jī)程序
#include <reg51.h>
#include <intrins.h>
#include <stdio.h>
#include <string.h>
#include <absacc.h>
#define uint unsigned int
#define uchar unsigned char
sbit P1_5=P1^5; //RS485 的控制位
uchar flag; //結(jié)果為負(fù)和正的標(biāo)志位
void delay( unsigned int count) //延時子程序
{
unsigned int i;
while( count)
{
i=200;
while( i>0) i- - ;
count- - ;
}
}
void main( void)
{
SCON=0X50;
TMOD=0X21; //定時器1, 工作在方式2
TL1=0XFD; //所用晶振為11.0592, 波特率設(shè)定為9 600 b/s
TH1=0XFD;
TR1=1; //啟動定時器1
EA=1;
ES=1;
??
do{ P1_5=1; //串行發(fā)控制位
tmpchange( ) ; //數(shù)據(jù)采集函數(shù)調(diào)用
??
SBUF=TEMP; //把數(shù)據(jù)送入串行口緩沖寄存器
if( TI==0)
TI=0; }
while( 1) ;
}
|
|