Stefan Vogel
Stefan Vogel

Reputation: 25

How to write binary data to serial port in C#

I try to write some binary data to the Serial Interface with C#:

0x02 0x81 0xF4 ...

This is a command for a remote device and must be transferred exactly like this. And here starts the Problem. When I use

System.IO.Ports.SerialPort.Write(Byte[] data, int Offset, int Size)

the data gets encoded (to ASCII,UTF-8 or whatever).And that's exactly I don't can need,since my remote device doesn't understand any Encoding.

Is there a Workaround?

Upvotes: 1

Views: 9873

Answers (2)

Jeff
Jeff

Reputation: 1362

I recently solved that exact problem like this:

// Update Relay
serialPort2.Close();
serialPort2.PortName="COM3";
serialPort2.Encoding = System.Text.Encoding.GetEncoding("Windows-1252");
serialPort2.BaudRate=9600;
serialPort2.DataBits=8;
serialPort2.Parity=Parity.None;
serialPort2.StopBits= StopBits.One; 
try {serialPort2.Open();
    serialPort2.Write("\u00a0\u0001\u0001\u00a2");
} catch {
    // Open Serial Port Failed
    label1.Text=label1.Text+ " Fail";
}

Jeff

Upvotes: 0

karim
karim

Reputation: 167

you can try this :

using System.IO.Ports;

public void TestSerialPort()
{
SerialPort serialPort = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One);
serialPort.Open();
byte[] data = new byte[] { 1, 2, 3, 4, 5 };
serialPort.Write(data, 0, data.Length);
serialPort.Close();
}

Upvotes: 1

Related Questions