Reputation:
I wish to write to the serialport com1
01 00 00 02 37 30 04
That's the command for initialization..
When i write a char array or byte array
c[0] = (char)01;//
c[1] = (char)00;
c[2] = (char)00;
c[3] = (char)02;
c[4] = (char)37;
c[5] = (char)30;
c[6] = (char)04;
serialPort 1.Write(c, 0, c.Length);
byte[] bb1 = System.Text.Encoding.Default.GetBytes(c);
I can see in the serial port monitor: 01 00 00 02 25 1E 04 obviously 37 is converted to 25 and 30 to 1E... How do i pass 37 and 30 and not hex values... i tried various ways...
Upvotes: 2
Views: 8742
Reputation: 700322
The serial port monitor is showing the values in hexadecimal, so they match the values that you send in exactly. There is no conversion going on, the decimal value 37 is 25 in hexadecimal, and the decimal value 30 is 1E in hexadecimal.
Use hexadecimal notation (0x) for the literal values when you create the array, then you see that the values come out as expected in the serial port monitor:
byte[] c = new byte[] {
0x01,
0x00,
0x00,
0x02,
0x37,
0x30,
0x04
};
serialPort 1.Write(c, 0, c.Length);
Upvotes: 7
Reputation: 391336
The problem here is that you've specified the values to send in decimal, and viewing them in hexadecimal. Obviously there will be differences.
To fix this, change your code to specify the values in hexadecimal instead by prefixing each value with 0x, like this:
c[0] = (char)0x01;//
c[1] = (char)0x00;
c[2] = (char)0x00;
c[3] = (char)0x02;
c[4] = (char)0x37;
c[5] = (char)0x30;
c[6] = (char)0x04;
serialPort1.Write(c, 0, c.Length);
Then you will see the same values in the output as those you expect.
Also see @Guffas answer which shows a better way to initialize an array, at least if you're using C# 3.5.
Upvotes: 2
Reputation: 58637
You are passing 37 and 30, not hex values.
Are you talking about viewing hex values?
If that's the case, what are you using to view the serial port output? If its not something you wrote, that might just be the way the program behaves.
Upvotes: 1