VB.Net send decimal udp - vb.net

I am trying to send a single byte to a PIC from a computer (Note: the pic only accepts a single byte else it will only accept the first byte of the data send)
This shouldn't be much of a problem because I only want to manage a total of 8 LEDS so I only need it to go from 0 to 255 but I am having issues achieving this.
If I try to send the value 1 to the pic my program sends 31 if I try to send 5 it sends 35 If I try to send 255 it sends 3*2*3*5*3*5* so for every single digit I try to send it adds a 3 in front of it. I am using the following code to determine the value and to send it:
Dim t As Integer = 0
Dim result As Integer = 0
For Each chk As CheckBox In GroupBox1.Controls
If chk.Checked = True Then
result = result + 2 ^ t
End If
t = t + 1
Next
publisher.Connect(IPTo, PortTo)
Dim sendbytes() As Byte = ASCII.GetBytes(result)
publisher.Send(sendbytes, sendbytes.Length)
I think the issue is with the convert to ASCII.
I also try to receive the inputs from the PIC to my pc for this I have the following script inside a timer:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
Dim ep As IPEndPoint = New IPEndPoint(IPAddress.Any, 0)
Dim rcvbytes() As Byte = subscriber.Receive(ep)
Dim translate As String
translate = System.BitConverter.ToInt32(rcvbytes, 0)
TBRcv.Text = translate
Catch ex As Exception
End Try
End Sub

ASCII.GetBytes expects a string (encoded in ASCII). Giving it an Int32 doesn't make sense.
Check out System.BitConverter.GetBytes() and System.BitConverter.ToInt32() (for the receiving end)
So the only change you'd need to make is:
Dim sendbytes() As Byte = BitConverter.GetBytes(result)
Further discussion:
What has happened is that your result (let's say 5), is first converted to string (now it's "5"), then ASCII.GetBytes will now return a byte array with a single value 0x35, because Asc("5") is 0x35.

The ASCII value of the character 1 is 0x31, etc. For reference :

Related

The code gives leading zeros in hex to binary output

The code gives additional 4 zeros, where the output should be without leading zeros. But I can't just trim it because with a different hex output it seems to produce different results. where did that four zeros come from? optionstrict on
The wrong output from the code (notice the additional leading 0000 in the wrong output in the front)
0000101001110011101011000110110111000000100000010010000001100000111111101101111101001010111110101011101001001100100101110111010011010110101101101100110000110110110000111001100100000111010011001011110110110010111111110000101011110010111010001000010100000101
The correct and expected binary should be (converted with an online hex to binary tool)
101001110011101011000110110111000000100000010010000001100000111111101101111101001010111110101011101001001100100101110111010011010110101101101100110000110110110000111001100100000111010011001011110110110010111111110000101011110010111010001000010100000101
The VB.net code I used
Private Function HexStringToByteArray(ByVal shex As String) As Byte()
Dim B As Byte() = Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
Return Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim hex As String = "0a73ac6dc0812060fedf4afaba4c9774d6b6cc36c399074cbdb2ff0af2e88505"
Dim bytes As Byte() = HexStringToByteArray(hex)
If BitConverter.IsLittleEndian Then
Array.Reverse(bytes)
End If
Dim myBA3 As New BitArray(bytes)
Dim myba3_reversed As New BitArray(myBA3.Length)
Dim count As Integer = (myBA3.Count - 1)
Dim myba3BITS As String = Nothing
For i = 0 To myBA3.Count - 1
If myBA3(i) = True Then
myba3BITS &= "1"
End If
If myBA3(i) = False Then
myba3BITS &= "0"
End If
count = (myBA3.Count - 1) - i
myba3_reversed(i) = myBA3(count)
Next i
Dim reversedBITS As String = Nothing
For i = 0 To myba3_reversed.Count - 1
If myba3_reversed(i) = True Then
reversedBITS &= "1"
End If
If myba3_reversed(i) = False Then
reversedBITS &= "0"
End If
Next i
Dim bits As String = reversedBITS
End Sub
Your input starts with "0a". If I use the Windows Calculator app in Programmer mode and enter that in HEX, the BIN output is "1010". Your code is taking each pair of hexadecimal digits and outputting eight binary digits, a buye for a byte. If you wanted to express the binary value 1010 in eight digits, what would it look like? You'd pad the value with four leading zeroes, wouldn't you? Where have you see that before? If your input doesn't have aleading zero then you need to add one. If your output does have leading zeroes and you don't want them, take them off. This is why you need to actually understand what your code is doing.

Using the serial port

For some time I've been working on learning how to program VB.NET. With the help of this page and the internet, I managed to create a program that sends some hex values to an interface box and get a routine response from it.
The problem here is that the communication was TCP/IP. But now I have a new box with a USB interface and now I do not have the slightest idea of how to send and receive those same hex values using the Serial port.
Below is the code. I don't know if someone could help me set it up for a serial port named COM13 or at least explain to me what to do.
This is what the program does.
Push scan
Connects to the TCP/IP of the BOX (10.2.12.65)
Sends the activation protocol E1 33
Sends the get date command 05 6c 29 f1 3c 81
Box responds back date with bytes
When the program reads the byte corresponding to 81(hex) it starts converting them into characters and adding them to a string to be displayed on the textbox on the bottom.
That's basically it. The problem is that until now I have been able to send only text strings but the box does not recognize it and it responds garbage and not the date.
Here is the code:
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
Dim client As New TcpClient
Dim transmit As NetworkStream
Dim protocol As Byte()
Dim data As Byte()
Dim ByteArrayToHexStr As String = String.Empty
Dim message As String
Dim datos_byte As Byte()
Dim respuesta As [String] = [String].Empty
Dim transision As [String] = [String].Empty
Dim Date_full As [String] = [String].Empty
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Clear()
client = New TcpClient("10.2.12.65", 10001)
transmit = client.GetStream()
protocol = {225, 51} ' E1 33 in hex value
transmit.Write(protocol, 0, protocol.Length)
Thread.Sleep(45)
data = {5, 108, 41, 241, 60, 129} ' 05 6c 29 f1 3c 81 in hex value
transmit.Write(data, 0, data.Length)
data = New Byte(66) {}
Thread.Sleep(45)
Dim bytes As Int32 = transmit.Read(data, 0, data.Length)
Dim Date1 As String = String.Empty
Dim Date2 As String = String.Empty
Dim Date_temp As Integer = 0
For i As Integer = 0 To UBound(data)
Date1 = data(i)
If Date1 = "129" Then
Date_temp = i + 1
i = 1000
For k As Integer = 0 To 5
If k = 0 Then
Date1 = data(Date_temp + k)
Date_full = Chr(Date1)
Else
Date1 = data(Date_temp + k)
Date2 = Chr(Date1)
Date_full = Date_full & Date2
End If
Next
Else
End If
Next
Thread.Sleep(45)
transmit.Close()
client.Close()
TextBox1.Text = TextBox1.Text & Date_full
End Sub
End Class
Please have a look at Microsoft's example of the SerialPort class: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
If you get garbage back that might indicate the baudrate is configured incorrectly. I'm not sure what you mean by 'box' but this device should have a specified baudrate which you should be able to find in its datasheet or product information.

Loop through contents in the text file

New TechGuy on this site. Thought i'd make this resourceful since im getting ready to graduate and want more programming practice. I have a question:
I tried looping through a text file I created and I wanted to replace each multiple of 3 with the word "changed". I created a text file and entered numbers 1-15 on each line. My code is below but for some reason it would only change the number 3 and 13. I tried using this link as a resource (Loop through the lines of a text file in VB.NET) but that wasnt to helpful. Anyway here is my code, can someone help with what i'm doing wrong?
Public Class numbers
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim OpenFilePrompt As New OpenFileDialog
openFilePrompt.ShowDialog()
Dim currentReader As New System.IO.StreamReader(OpenFilePrompt.FileName)
txtInput.Text = currentReader.ReadToEnd
Dim a As String
Dim numbers As New List(Of String)
a = txtInput.Text
numbers.Add(a)
Dim b As Integer
For i = 0 To numbers.Count Step 3
b = b + 3
TextBox2.Text = (numbers.Item(i).Replace(b.ToString, "Changed"))
Next
End Sub
End Class
You are setting numbers (the first item) to a, which is txtInput.Text.
Then you have a one size list which is completely useless!
You should use Mod instead.
Divides two numbers and returns only the remainder.
So just check if Integer Mod 3 equals 0.
Also consider using File.ReadAllLines(String), Val(String), String.Join(String, String()) and File.WriteAllLines(String, String()).
Dim Content() As String = File.ReadAllLines(OpenFilePrompt.FileName)
For Index As Integer = 0 To Content.Length - 1
Dim Number As Integer = Val(Content(Index))
If Number Mod 3 = 0 Then
Content(Index) = "changed"
End If
Next
txtInput.Text = String.Join(vbCrLf, Content)
File.WriteAllLines(OpenFilePrompt.FileName, Content)

Binary Search or Insertion Sort with list view [Visual Basic .net]

Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
Dim midpoint As Integer
If lowindex > highindex Then
MsgBox("Search Failed")
Else
midpoint = (highindex + lowindex) / 2
If temp(midpoint) = Key Then
MsgBox("found at location " & midpoint)
ElseIf Key < temp(midpoint) Then
Call BinarySearch(Key, lowindex, midpoint, temp)
ElseIf Key > temp(midpoint) Then
Call BinarySearch(Key, midpoint, highindex, temp)
End If
End If
End Sub
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim Key As String = txtSearch.Text
Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
Dim lowindex As Integer = 0
Dim highindex As Integer = lstOutput.Items.Count - 1
'Somehow all of the items in Target column must be placed in temp array
Dim temp(Me.lstOutput.Items.Count - 1) As String
' BinarySearch(Key, lowindex, highindex, temp)
End Sub
For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub
Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language
Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myArray(Me.ListView1.Items.Count - 1) As String
Dim i As Integer
' load array
For i = 0 To Me.ListView1.Items.Count - 1
myArray(i) = Me.ListView1.Items(i).Text
Next
' show the results
Dim s As String = ""
For i = 0 To UBound(myArray)
s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
Next
MsgBox(s, MsgBoxStyle.Information, "myArray Contents")
' now go ahead and manipulate the array as needed
' ...
End Sub

How to send a data array from an Arduino to vb

I am trying to send data bytes from an Arduino to my visual basic app, but it does not work. I've already tried several solutions but I don't get the values back, I've send to the arduino.
The code I'm using for the visual basic app:
Private Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)
Dim bytes As Integer = 6
Dim comBuffer As Byte() = New Byte(bytes - 1) {}
'read the data and store it
SerialPort1.Read(comBuffer, 0, bytes)
Dim aryReceived(10) As Integer
For i As Integer = 1 To (bytes - 1)
aryReceived(i) = comBuffer(i)
Y(i) = aryReceived(i)
Next
a = comBuffer(1)
b = comBuffer(2)
End Sub
Private Sub Verzenden()
Dim waardes() As Byte
waardes = {X(1), X(2), X(3), X(4), X(5), X(6)}
If SerialPort1.IsOpen = True Then
SerialPort1.Write(waardes, 0, waardes.Length)
End If
End Sub
Private Sub VerzendButton_Click(sender As Object, e As EventArgs) Handles VerzendButton.Click
X(1) = 10
X(2) = 11
X(3) = 12
X(4) = 13
X(5) = 14
X(6) = 15
Verzenden()
End Sub
and the arduino code:
int x[9];
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available() >= 6){
for(int i = 1; i < 7; i++){
x[i] = Serial.read();
}
for(int i = 1; i < 7; i++){
Serial.println(x[i]);
}
}
}
I send 6 bytes to the arduino with the following values: 10, 11, 12, 13, 14 & 15, but sometimes I have to send the bytes twice before the debugger breaks. The values that return in a & b are not the same as I send. The code for sending the bytes works fine.
Can someone help me?
The breakpoint I've set is at the 'end sub' command of the receive event. I often get for a 51 and for b 56, but they're random at other times.
X, Y and a & b are all defined in the public.
Public Class Form1
Dim indata As Integer
Dim Setting As New My.MySettings()
Dim Opstartmodus As Byte
Dim OpstartCOMpoort As String
Dim myPort As Array
Delegate Sub SetTextCallBack(ByVal [text] As String)
Dim a As Byte, b As Byte, c As Byte, d As Byte, f As Byte, g As Byte
Dim WaardeVerzenden As Byte, X(9) As Byte, Y(9) As Byte
Edit: I've added a delay of 500 microseconds in the arduino code between the receive action and the sens action. Now, After one click on the send button, the debugger breaks immediately. Thats one problem solved! But now, I get always the following patter back: 49,48,13,10,49,49. That totaly doesn't match with the pattern I send to the Arduino:(
I found the solution;) I have Serial.println replaced by Serial.write(x,6). In the Visual Basic app I replaced the reveive event with:
Private Sub SerialPort1_DataReceived(sender As Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
For i As Integer = 0 To (Bytes - 1)
Y(i) = SerialPort1.ReadByte()
Next
End Sub
The Visual Basic app does now receive the data I send from the arduino:)