Electronic – Opening serial port for reading, when data is already flowing

midiserial

I have a drummachine (Roland TR505, but all of this would be true with any other device) sending a byte 11111000 (Timing Clock MIDI message), 48 times per second, to a MIDI OUT port. It works well.

I'm reading MIDI signal on my electronic device via software with classical serial port reading techniques (at 31500 baud, etc., I totally respected the MIDI standard in my electronic schematic).

[ROLAND TR505]  =====MIDI cable=====> [MY ELECTRONIC DEVICE]

I have a tricky situation:

  1. If I power on my electronic device and I let the serial port reading software start, and then I power the TR505 on, it works : the flow of bits coming to serial port is correctly interpreted. It works perfectly.

  2. If I power the TR505 (i.e. the bits are already flowing to serial port), and then I power on my electronic device, there is a problem : probably my device starts reading serial data in the middle of a byte, i.e. data is wrongly interpreted.

Question: when you connect a device already powered on, already sending data to another device which listens serial port, how to ensure that the listening device won't start in the middle of a byte?

i.e. if the bits flow is:

...0111100001111000011110000...

how will my device know it's byte1=11110000 and not byte1=01111000 ?


Here is the software code in Python:

import serial

ser = serial.Serial('/dev/ttyAMA0', baudrate=38400) # Note: there's a well known hack in /boot/config.txt to make this work at 31500 baud, which is normally not supported on Raspberry; in short baudrate is not the problem

while True:
    data = ord(ser.read(1)) # read a byte

Best Answer

if the bits flow is:

...0111100001111000011110000...

how will my device know it's byte1=11110000 and not byte1=01111000 ?

That's not the full picture. Each Byte is 'framed' with a Start bit (0) and a Stop bit (1). The UART syncs by looking for the 1 to 0 transition when going from Stop to Start.

Most devices do not send data continuously, and any gap longer than 9 bits should be enough to get into sync. MIDI baud rate is 31250 bps, so if the timing clock is a single Byte repeated 48 times per second there should be a large gap between Bytes. The actual bit flow should look like this:-

...011110000111111111111111111111111...1111111111111111110111100001....
    ^Byte-1^                                              ^Byte-2^
Related Topic