tags:

views:

1260

answers:

4

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...

A: 

If you want to pass 37 in hex use 0x37 instead of 37.

maciejkow
"How do i pass 37 and 30 and *not* hex values"
samoz
Yes, I noticed it. However, I thought that it just may be possible, that the desired input is given in hex and Kal didn't notice that.
maciejkow
Basically the same as most other answers, why the downvotes?
Henk Holterman
A: 

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.

samoz
+1  A: 

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.

Lasse V. Karlsen
Initialising an array works already in C# 2, in C# 3 you can omit the "new byte[]" part.
Guffa
+4  A: 

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);
Guffa