Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Serial Port Problems


  • Please log in to reply
11 replies to this topic

#1 tknman0700

tknman0700

    Member

  • Members
  • PipPip
  • 26 posts

Posted 29 May 2012 - 08:31 PM

I am trying to get my head around serial ports using VB and having problems here. I am interfacing with SeeedStudio GSM board.

Here is my code....

Dim awatingResponseString As String = ""
Dim awaitingResponse As Boolean = False
Dim sp As SerialPort

Public Sub Main()
        Dim sp As New SerialPort(SerialPorts.COM1, 19200, Parity.Odd, 8, StopBits.One)
        SendSMS("18005551212", "test")
    End Sub

Public Sub PrintLine(ByVal line As String, Optional ByVal awaitResponse As Boolean = False, Optional ByVal awaitResponseString As String = "")
        If Not awaitResponseString.Equals("") Then
            awatingResponseString = awaitResponseString
            While Not awatingResponseString.Equals("")
                Thread.Sleep(1000)
            End While
        End If
        Print(line)
        If awaitResponse Then
            awaitingResponse = True
            While awaitingResponse
                Thread.Sleep(100)

            End While
        End If
    End Sub

    Private Sub Print(ByVal line As String)
        Dim encoder As New System.Text.UTF8Encoding()
        Dim bytesToSend As Byte() = encoder.GetBytes(line)
        sp.Write(bytesToSend, 0, bytesToSend.Length)
    End Sub

    Public Sub SendSMS(ByVal msisdn As String, ByVal message As String)
        'PrintLine("");
        PrintLine("AT+CMGF=1", True)
        PrintLine("AT+CMGS=""" & msisdn & """", False)
        PrintLine(message)
        Thread.Sleep(100)
        PrintEnd()
        Thread.Sleep(500)
        'Debug.Print("SMS Sent!");
    End Sub

    Private Sub PrintEnd()
        Dim bytesToSend As Byte() = New Byte(0) {}
        bytesToSend(0) = 26
        sp.Write(bytesToSend, 0, 1)
        Thread.Sleep(200)
    End Sub

In the Print() function I get this error:

An unhandled exception of type 'System.NullReferenceException' occurred in Netduino Power Control.exe

And I get this error when I issue the sp.write.
I am trying understand how to test and debug with serial port but keep bumping my head here.
Can anyone offer help?

Thanks

#2 CW2

CW2

    Advanced Member

  • Members
  • PipPipPip
  • 1592 posts
  • LocationCzech Republic

Posted 29 May 2012 - 08:43 PM

IMHO the sp variable in Print method is null (nothing), because you have aliased hidden it with a new local variable declaration in Main. Move "Dim sp as new SerialPort(...)" outside Main or replace "Dim sp" there with an assignment and it should work.

Edit: The correct term is name hiding (or shadowing)

#3 tknman0700

tknman0700

    Member

  • Members
  • PipPip
  • 26 posts

Posted 29 May 2012 - 08:48 PM

ClrInfo.targetFrameworkVersion: 4.2.0.0 SolutionReleaseInfo.solutionVersion: 4.2.0.0 SolutionReleaseInfo.solutionVendorInfo: Netduino Plus (v4.2.0.0 RC4) by Secret Labs LLC SoftwareVersion.BuildDate: Feb 2 2012 SoftwareVersion.CompilerVersion: 410713 FloatingPoint: True SourceLevelDebugging: True ThreadCreateEx: True LCD.Width: 0 LCD.Height: 0 LCD.BitsPerPixel: 0 AppDomains: True ExceptionFilters: True IncrementalDeployment: True SoftReboot: False Profiling: False ProfilingAllocations: False ProfilingCalls: False IsUnknown: False

#4 CW2

CW2

    Advanced Member

  • Members
  • PipPipPip
  • 1592 posts
  • LocationCzech Republic

Posted 29 May 2012 - 09:02 PM

...
Dim sp As SerialPort

Public Sub Main()
  ' The following statement declares a local variable sp,
  ' which hides the class member sp from above. Thus, sp in Print is not set.
  Dim sp As New SerialPort(SerialPorts.COM1, 19200, Parity.Odd, 8, StopBits.One)
  SendSMS("18005551212", "test")
End Sub
Fix:

...
 Dim sp As New SerialPort(SerialPorts.COM1, 19200, Parity.Odd, 8, StopBits.One)

Public Sub Main()
  SendSMS("18005551212", "test")
End Sub
or

...
Dim sp As SerialPort

Public Sub Main()
  ' No Dim here
  sp = New SerialPort(SerialPorts.COM1, 19200, Parity.Odd, 8, StopBits.One)
  SendSMS("18005551212", "test")
End Sub


#5 tknman0700

tknman0700

    Member

  • Members
  • PipPip
  • 26 posts

Posted 29 May 2012 - 09:08 PM

That for sure fixed my error... now on the next problem and probably my bigger problem. I dont know how to debug serial port communication on this thing. Are there any samples you can point me to for help on getting data back from a serial port? In other words once I print to the serial port how do I see what came back? This may seem stupid but I am very new to hardware interfacing - not .net development but I need some pointers. Thanks

#6 tknman0700

tknman0700

    Member

  • Members
  • PipPip
  • 26 posts

Posted 29 May 2012 - 09:37 PM

I am interfacing with this GPRS board and on their wiki the reference setting the serial port mode to be swserial but when I set it like that I cannot seem to read any data from teh serial port. I have jumpers set to xduino and I get data but it is just echo data of what I send to the port. Sorry there may be something very obvious here but I am not sure what I am doing wrong.

#7 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 29 May 2012 - 10:33 PM

This is probably totally unrelated, but are you opening up the serial port after creating the sp object?

sp.Open();

Chris

#8 JerseyTechGuy

JerseyTechGuy

    Advanced Member

  • Members
  • PipPipPip
  • 870 posts

Posted 30 May 2012 - 01:29 AM

I agree with Chris... don't see an sp.Open() Statement.

Personally I would do it something like this:

Dim sp as SerialPort

Public Sub Main()
	sp = New SerialPort(SerialPorts.COM1, 19200, Parity.Odd, 8, StopBits.One)

	Thread.Sleep(10)
   
	SendSMS("18005551212", "test")

End Sub

Public Sub SendSMS(ByVal msisdn As String, ByVal message As String)

	If Not(sp.Open()) then
   	     sp.Open()
	End if

	PrintLine("");
	PrintLine("AT+CMGF=1", True)
	PrintLine("AT+CMGS=""" & msisdn & """", False)
	PrintLine(message)

	Thread.Sleep(100)

	PrintEnd()

	Thread.Sleep(500)

	Debug.Print("SMS Sent!")

	sp.Close()

End Sub


#9 tknman0700

tknman0700

    Member

  • Members
  • PipPip
  • 26 posts

Posted 30 May 2012 - 04:27 PM

Ok thank you for your advice... I left out that line. I have it working now but I am trying to better understand how to write and read from serial ports generally speaking. How to know when the data is done being "read" on the serial port etc. Thank you

#10 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 30 May 2012 - 07:46 PM

Hi tknman0700,

Ok thank you for your advice... I left out that line. I have it working now but I am trying to better understand how to write and read from serial ports generally speaking. How to know when the data is done being "read" on the serial port etc.

You can grab the values from SerialPort.BytesToRead and SerialPort.BytesToWrite to determine how much data is left to be read/written... The Flush() function also lets you make sure that all outgoing data has been written, including any background buffers.

Chris

#11 tknman0700

tknman0700

    Member

  • Members
  • PipPip
  • 26 posts

Posted 31 May 2012 - 02:04 AM

Ok I am still a bit confused.. I am doing this.

Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
        ' Check if Chars are received

        Dim ReadBuffer As Byte() = New Byte(sp.BytesToRead - 1) {}
        If e.EventType = SerialData.Chars Then
            ' Create new buffer

            sp.Read(ReadBuffer, 0, ReadBuffer.Length)

            If ReadBuffer.Length > 0 And (ReadBuffer(ReadBuffer.Length - 1) = 10 OrElse ReadBuffer(ReadBuffer.Length - 1) = 0) Then
                ' New line or terminated string.
                output.Append(GetUTF8StringFrombytes(ReadBuffer))
                Debug.Print("Recieved : " & output.ToString())
                output.Clear()
              Else
                Try
                    output.Append(GetUTF8StringFrombytes(ReadBuffer))
                Catch ecx As Exception
                    Debug.Print("Cannot parse : " & ecx.StackTrace)
                End Try
            End If
        End If

    End Sub

The problem is that when I "read" from the bus I also see what I just sent to the bus.

I have added the above as a handler....

AddHandler sp.DataReceived, New SerialDataReceivedEventHandler(AddressOf serialPort_DataReceived)

But I am not sure why I see the stuff I just sent to the serial bus in addition to the data that the device placed on the bus. Like i said I am new to hardware interfacing but not .net development. I think I am just missing a few connections here to really taking good advantage of this prototyping kit.

Any direction for handling serial data is appreciated...

This is code I have adapted from a few sources online as starters...

Thanks

#12 tknman0700

tknman0700

    Member

  • Members
  • PipPip
  • 26 posts

Posted 31 May 2012 - 04:09 AM

not sure I follow the .flush() reference. Would you do this before you read from the port?




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.