AT89C52單片機(jī)與VB串行通信的實(shí)現(xiàn)
數(shù)據(jù)發(fā)送程序:
Private Sub Command1_Click()
Dim outbuf(1 To 6) As Byte
Dim lstr1 As String
Dim hstr2 As String
Dim len1 As Integer
Command1.Enabled = False
len1 = Len(Hex(Val(Text2.Text)))
………
If LR(1) = 1 Then
outbuf(1) = 69 ;對(duì)應(yīng)字符“E”
Else
outbuf(1) = 68 ;對(duì)應(yīng)字符“D”
End If
outbuf(2) = 84 ;對(duì)應(yīng)字符“T”
outbuf(3) = LR(1)
outbuf(4) = stoby(hstr2)
outbuf(5) = stoby(lstr1)
outbuf(6) = 13
MScomm1.RThreshold = 5 * Val(Text2.Text)
MScomm1.Output = outbuf
End Sub
數(shù)據(jù)接受程序:
Private Sub MScomm1_OnComm()
Select Case MScomm1.CommEvent
Case comEvReceive
Dim inbuf() As Byte, i%, buf$
buf =
inbuf = MScomm1.Input
Rev_num = UBound(inbuf)
ReDim lnum(0 To Rev_num) As Integer
For i = 0 To Rev_num
lnum(i) = inbuf(i)
buf = buf + Str(inbuf(i)) +
Next i
Case comEvSend
End Select
End Sub
由于MSComm控件數(shù)據(jù)接受設(shè)計(jì)為按字節(jié)方式,可接發(fā)的數(shù)值范圍為0~255。當(dāng)上位機(jī)讀取數(shù)據(jù)個(gè)數(shù)超過(guò)255(1字節(jié))時(shí),為了能讓下位機(jī)正確接受,解決方法是通過(guò)編制的函數(shù)stoby將文本框Text2輸入的記錄個(gè)數(shù)(字符型)轉(zhuǎn)化成字節(jié)型,并分成兩個(gè)字節(jié)送給下位機(jī)。另外,系統(tǒng)中有關(guān)數(shù)據(jù)保存、數(shù)據(jù)圖表處理、打印等功能的實(shí)現(xiàn)在此不再贅述。
5.結(jié)論
2C總線器件的采用簡(jiǎn)化了硬件電路設(shè)計(jì),提高了可靠性。本系統(tǒng)已投入使用,經(jīng)過(guò)實(shí)際應(yīng)用表明,通信系統(tǒng)工作穩(wěn)定、可靠。滿足系統(tǒng)要求,每到一分鐘就向 ATC256中寫入1條記錄(5個(gè)數(shù)據(jù)),ATC256可保存12小時(shí)的記錄,下位機(jī)需要讀取數(shù)據(jù)時(shí),可根據(jù)下位機(jī)的讀取指令讀取任意條記錄。
[參考文獻(xiàn)]
[1]ATMEL 2-wires Serial EEPROMs AT24C128/256[DK].
[2]何立民,單片機(jī)高級(jí)教程[M],北京:北京航空航天大學(xué)出版社,1999年.
[3]范逸之 陳立元,Visual Basic 與RS-232串行通信控制[M],北京:中國(guó)青年出版社,2002年.
評(píng)論