Serial Port Complete - Latest Microcontroller projects

(lily) #1

Chapter 9


 // Write a Char.


Char valueToWrite;

valueToWrite = 'A';
binaryWriter1.Write( valueToWrite );

// Read a Char.

int receivedData;

receivedData = binaryReader1.Read();
Console.WriteLine( Strings.ChrW( receivedData ) );

// Write an array of Chars.

Char[] valueToWrite = new Char[2];

valueToWrite[0] = 'O';
valueToWrite[1] = 'K';
binaryWriter1.Write( valueToWrite,0,2 );

// Read Chars into an array.

Char[] receivedData = new Char[2];

binaryReader1.Read(receivedData,0,2);

Console.WriteLine(receivedData);
BinaryWriter and BinaryReader can also send and receive strings. Each string is
prefixed with a length value. Before transmitting a string, a BinaryWriter object
encodes a 32-bit length value using the Write7BitEncodedInt method. The
method encodes the length value as one or more bytes depending on the value
being encoded.
You don’t have to understand the encoding method to use it in an application.
BinaryReader and BinaryWriter create and extract the length values automati-
cally. With that said, this is how the encoding works:
The encoding divides the value to transmit into units of 7 bits each. Each unit
is stored in bits 0–6 of a prefix byte to be transmitted. In the byte that contains
the most significant bits of the length value, bit 7 is zero. For all of the other
bytes, bit 7 is set to 1.
Free download pdf