# How exactly Matlab sent bits in a serial communication?

7 views (last 30 days)
Pablo Medina on 17 Dec 2016
Commented: Walter Roberson on 19 Dec 2016
I am using serial communication in orden to send an specific binary secuence. For example: DataBits = [0 0 0 0 0 0 0 1], which represent the number 1 (decimal). But Matlab send data to the channel like this [0(StartBit) (0 0 0 0 0 0 1 0) DataBits 1(StopBit)]. I realized this using an Oscilloscope.
Commands Used:
s = serial('COM3','BaudRate',9600,'DataBits',8,'StopBits',1,'InputBufferSize',500);
fopen(s)
fwrite(s,1,'async')
So, Matlab is adding a 0 at the 8th position of the DataBits [0 0 0 0 0 0 1 0] = 2 (decimal). My questions is if there is a way to send exactly a binary sequence using fwrite() function.

Walter Roberson on 18 Dec 2016
You should fwrite uint8(1) to avoid questions about what happens when you fwrite double values.
If your oscilloscope showed you the order you indicated and you were using an rs232 port then one of three things was happening:
• you were not writing the value you thought you were; or
• your oscilloscope is wrong; or
• you have a hardware error in your rs232
I say this because rs232 requires that the least significant bit be sent first, so the 1 bit would have had to be sent immediately after the start bit.
##### 3 CommentsShow 1 older commentHide 1 older comment
Walter Roberson on 19 Dec 2016
The default for fwrite() is to uint8() the values before writing, so fwrite(s,1) and fwrite(s,uint8(1)) are the same, but the explicit cast makes it easier for the reader to be sure they know what is happening.
If you want to send something outside the range 0 to 255, you should use the precision argument, and the byte order argument is a good idea too, such as fwrite(s, value, 'int16', 'ieee-be')
Walter Roberson on 19 Dec 2016
Correction, the byte order cannot be specified for serial.