Hi Robert,
I have been trying your code... but am still getting stuck somewhere... probably because of my experience with VB. I was assuming that I should put the code snippet in between the #Region area (like I had before) and then call the different subs/functions when I activate the boolean toggle. So, the code looked like this when I put it into Grasshopper (see below). The problem is that I'm getting a lot of error messages saying that OpenPort, GetValue, ...etc. are not declared... so the script wont even run. I also had a question about the Class comment you added... saying that I would need to "work it into the grasshopper class". How exactly do I do that? I know it's not an easy question since you are unfamiliar with the program... but I do appreciate your help with all of this.
Sub RunScript(ByVal activate As Boolean)
If activate Then
Call OpenPort()
Call GetValue()
Call CPort_DataReceived()
Call HandleComPort()
print(StoredValue)
Else
Call ClosePort()
print("not receiving data")
End If
End Sub
#Region "Additional methods and Type declarations"
Public Class port
' I wrapped this in a class, but you would need to work it into the grasshopper class
Private WithEvents CPort As IO.Ports.SerialPort 'port with events
Private TempBuffer As String = String.Empty 'holds the input between events until we get a new line
Private Delegate Sub HandleComPortDelegate() 'allows com port to run in a background thread without blocking
Private StoredValue As String = String.Empty 'holds value from port until you call for it
Sub OpenPort() 'called early in the app, before the port is ever needed. This attaches the port, and opens it to listen.
CPort = New IO.Ports.SerialPort
Try
CPort = My.Computer.Ports.OpenSerialPort("COM3", 9600)
Catch ex As Exception
MessageBox.Show("no port")
End Try
End Sub
'this would be better as a property, but I don't know how Grasshopper handles properties
Function GetValue() As String
Return StoredValue
End Function
'this is fired by the port when it has data
Private Sub CPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles CPort.DataReceived
Dim HndlComPort As New HandleComPortDelegate(AddressOf HandleComPort) 'declare thread
HndlComPort.Invoke() ' invoke a new delegate to digest the events
End Sub
Private Sub HandleComPort() 'background handler for com port
TempBuffer &= CPort.ReadExisting 'append into tempbuffer
If (Strings.Right(TempBuffer, 2) = vbCrLf) Then 'if end of item 'this may need to be changed, since Arduino's println may use cr or lf only. I can't remember at this point.
StoredValue = TempBuffer 'offload
TempBuffer = String.Empty 'reset
End If
End Sub
'should be called when the port is no longer needed.
Private Sub ClosePort()
If CPort.IsOpen = True Then
CPort.Close()
End If
CPort.Dispose()
End Sub
End Class
#End Region
End Class