Pablo Software Solutions
Part 2. Reading the NXT Battery and Beep
1. Add a second button and label to Form1
2.  Double click on Button2 and the code window will open.  Enter the code to read the NXT battery voltage below.
     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
       
Dim byteOut(5) As Byte
        Dim byteIn(6) As Byte
        Dim Voltage, i As Integer
        Try
            byteOut(0) = &H2  '2 bytes in output message
            byteOut(1) = &H0  'should be 0 for NXT
            byteOut(2) = &H0  '&H0 = reply expected &H80 = no reply expected
            byteOut(3) = &HB  '$HB = read battery command
            SerialPort1.Write(byteOut, 0, 4) '0 = offset into byteOut and 4 = number of bytes
            'now read the reply
            byteIn(0) = SerialPort1.ReadByte ' number of bytes in message
            byteIn(1) = SerialPort1.ReadByte ' should be 0 for NXT
            For i = 2 To 1 + byteIn(0) ' read rest of message
                byteIn(i) = SerialPort1.ReadByte()
           
Next
            Voltage = byteIn(5) + byteIn(6) * 256 ' the voltage has low byte in 5 and high in 6
            Label2.Text = Voltage 'display voltage
        Catch ex As Exception
            MsgBox(ex.ToString)
       
End Try
    End Sub
3.  Now run the program.  First press Button1 to establish the connection.  After Label1 changes to Connected, press Button2.  Label2 will change to the NXT battery voltage in mV.
4.  Add a third button and a NumericUpDown control to Form1.
5.  In the properties window of NumericUpDown1 you need to set the max, min and value for the control
6.  Double click on Button3 and enter the code below
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
       
Dim byteOut(8) As Byte
        Dim freq As Int16
       
Try
            byteOut(0) = &H6  '6 bytes in output message
            byteOut(1) = &H0  'should be 0 for NXT
            byteOut(2) = &H80 '&H0 = reply expected &H80 = no reply expected
            byteOut(3) = &H3  'PLAYTONE
            freq = NumericUpDown1.Value
            byteOut(4) = freq - (freq / 256) * 256
'low byte of freq
            byteOut(5) = freq / 256 'high byte of freq
            byteOut(6) = &H64 'low byte of duration = 100 ms
            byteOut(7) = &H0  'high byte of duration
            SerialPort1.Write(byteOut, 0, 8)
       
Catch ex As Exception
            MsgBox(ex.ToString)
       
End Try
    End Sub
7.  Now run the program.  Click Button1 to make the connection then click Button3.  The NXT should make a 1000Hz beep.  You can either enter a new frequency or just increment and decrement the value then click Button3 again to make the beep.
8.  Continue to Part 3 to learn how to send messages to Bluetooth mailboxes