3

I'm trying to convert a number from a textbox into 2 bytes which can then be sent over serial. The numbers range from 500 to -500. I already have a setup so I can simply send a string which is then converted to a byte. Here's a example:

send_serial("137", "1", "244", "128", "0")

The textbox number will go in the 2nd and 3rd bytes

This will make my Roomba (The robot that all this code is for) drive forward at a velocity of 500 mm/s. The 1st number sent tells the roomba to drive, 2nd and 3rd numbers are the velocity and the 4th and 5th numbers are the radius of the turn (between 2000 and -2000, also has a special case where 32768 is straight).

dsolimano
  • 8,870
  • 3
  • 48
  • 63
LAK132
  • 193
  • 1
  • 10

2 Answers2

2
var value = "321";
var shortNumber = Convert.ToInt16(value);
var bytes = BitConverter.GetBytes(shortNumber);

Alternatively, if you require Big-Endian ordering:

var bigEndianBytes = new[]
{
    (byte) (shortNumber >> 8), 
    (byte) (shortNumber & byte.MaxValue)
};
e_ne
  • 8,340
  • 32
  • 43
0

Assume you are using System.IO.Ports.SerialPort, you will write using SerialPort.Write(byte[], int, int) to send the data.

In case if your input is like this: 99,255, you will do this to extract two bytes:

// Split the string into two parts
string[] strings = textBox1.text.Split(',');
byte byte1, byte2;
// Make sure it has only two parts,
// and parse the string into a byte, safely
if (strings.Length == 2
    && byte.TryParse(strings[0], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out byte1)
    && byte.TryParse(strings[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out byte2))
{
    // Form the bytes to send
    byte[] bytes_to_send = new byte[] { 137, byte1, byte2, 128, 0 };
    // Writes the data to the serial port.
    serialPort1.Write(bytes_to_send, 0, bytes_to_send.Length);
}
else
{
    // Show some kind of error message?
}

Here I assume your "byte" is from 0 to 255, which is the same as C#'s byte type. I used byte.TryParse to parse the string into a byte.

Alvin Wong
  • 12,210
  • 5
  • 51
  • 77
  • I've probably misunderstood some part of the OP, so I am rewriting the answer – Alvin Wong Dec 23 '12 at 04:04
  • I have already made some code where I simply have to parse strings which are then converted to numbers that can be sent over serial – LAK132 Dec 23 '12 at 04:11
  • I have to parse a string containing a number between 0 and 255, so yes you are correct in assuming that. – LAK132 Dec 23 '12 at 04:13