本帖最后由 xiehuahere 于 2012-7-20 12:12 编辑
搞定了!
基于这个UDF,我给自己封装了用于串口收发的两个函数SendLine和WaitFor,这样用起来就方便啦 ^_^Local $buff, $dbgSwitch = False
;============================================================================
; Name: SendLine
; Description: Send one command line
; Return value: 0 - Success
; -1 - Failure
;============================================================================
Func SendLine($string)
_CommClearInputBuffer()
_CommClearOutputBuffer()
_CommSendstring($string & @CR, 1) ; Wait till string sent
If @error <> 0 Then
Logger("! Error occured while sending string '" & $string & "', ErrCode: " & @error, 2)
Return -1
EndIf
Logger("T -> " & $string, 6)
Return 0
EndFunc
;============================================================================
; Name: WaitFor
; Description: Wait for desired output. Use it after each SendLine() to make buff always hold the latest content
; Return value: 0 - Success
; -1 - Failure
;============================================================================
Func WaitFor($string, $timeout=2000)
$buff = "" ; Clear buff before each receiving
If $string <> "" Then
Local $timer = TimerInit()
Do
$buff &= _CommGetString()
If @error <> 0 Then
Logger("! Error occured while receiving string '" & $string & "', ErrCode: " & @error, 2)
Return -1
EndIf
If $buff = '' Then
Sleep(20)
Else
mgdebugCW($buff & @CRLF)
EndIf
If TimerDiff($timer) > $timeout Then
Logger("! Timeout when waiting for '" & $string & "'", 2)
Return -1
EndIf
Until StringInStr($buff, $string) > 0
EndIf
Logger("R <- " & $buff & @LF, 6) ; @LF is for Unix->DOS convertion
Return 0
EndFunc
Func Logger($msg, $logLevel = 8)
Switch $logLevel
Case 1
$levelInfo = "Level(1,User)"
Case 2
$levelInfo = "Level(2,Warning)"
Case 4
$levelInfo = "Level(4,Error)"
Case 6
If Not $dbgSwitch Then Return ; Default: No debug info
$levelInfo = "Level(6,Debug)"
Case 8
$levelInfo = "Level(8,Information)"
Case Else
$levelInfo = "Level(?,None)"
EndSwitch
Local $logfile = $logFolder & "\log" & '_' & @YEAR & @MON & @MDAY & '.txt'
_FileWriteLog($logfile, $levelInfo & ", " & $msg)
EndFunc
|