Thursday, November 5, 2015

Serial Port - PuTTY - VBScript - Werma LED Beacon Multicolour

On this session, I would like to give a documentation of my mini project. There are few ways to communicate with serial port. you may use HyperTerminal, PuTTY, or other applications.

At the moment, I focus on PuTTY to communicate with Serial Port (WERMA LED). Instead of running PuTTY and trigger commands manually to LED, I create a script in VBScript to trigger it.

This sample script will turn on BLUE colour of LED for one second and will turn off the LED afterward. I also add a function how to get the correct port dynamically regardless any port you have plug the LED in your PC.

Option Explicit
On Error Resume next 

Dim oshell
Dim PortNum

Set oshell = createobject("Wscript.Shell") 
oshell.run "cmd.exe"
Wscript.sleep 200

PortNum = GetPortNumber
Wscript.sleep 200

If PortNum = "INVALID" Then
  Wscript.sleep 200
  oshell.sendkeys "exit"+ ("{Enter}")
Else
  oshell.Run("putty.exe -serial" + " " + PortNum + " " + "-sercfg 9600,8,n,1,N") 
  Wscript.sleep 200
  oshell.sendkeys "WR 00 01 01 64" + ("{Enter}")     ' WR 00 RR GG BB <CR>
  Wscript.sleep 1000
  oshell.sendkeys "WR 00 01 01 01" + ("{Enter}")
  Wscript.sleep 200
  oshell.sendkeys "%" + ("{F4}")
  Wscript.sleep 200
  oshell.sendkeys ("{Enter}")
  Wscript.sleep 200
  oshell.sendkeys "exit"+ ("{Enter}")  
End If

Set oshell = nothing

Function GetPortNumber()
  Dim objShell
  Dim I
  Dim WermaPortFound
  Dim skey
  Dim skey2
  Dim InstanceID
  Dim PortName
  Dim WERMAPVID

  WERMAPVID = "VID_04B4&PID_E00A"
  
  Set objShell = WScript.CreateObject("WScript.Shell") 
  I = 0
  with CreateObject("WScript.Shell")
    Do Until WermaPortFound OR (I = 15)
      
      InstanceID = " "
      PortName = " "
      WermaPortFound = FALSE
  
      skey = "HKLM\SYSTEM\CurrentControlSet\Services\usbser\Enum\" + Cstr(I) 
      On Error Resume Next       
      InstanceID = .regread(sKey)     
      
      If (InstanceID <> " ") AND (InStr(UCase(InstanceID),UCase(WERMAPVID)) > 0) Then
        skey2 = "HKLM\SYSTEM\CurrentControlSet\Enum\" + InstanceID + "\Device Parameters\PortName"   
        On Error Resume Next 
        PortName = .regread(sKey2)
        
        If (PortName <> " ")  AND (InStr(UCase(PortName),"COM") > 0)Then 
          WermaPortFound = (Err.number = 0)
        End If

      End If

      I = I + 1
    Loop
  End with


  If WermaPortFound Then
     GetPortNumber = PortName
  Else
     GetPortNumber = "INVALID" 
  End If
  
  Err.Clear
  Set objShell = nothing

End Function

No comments:

Post a Comment