Write a serial communication protocol


Thread Starter


I have to write a sw under Unity Pro to communicate with a device via serial (rs485) character link. This device has his own communication protocol, so I have to implement a custom driver on the PLC side. The communication is half-duplex Master(plc) Slave(device). I think to use a ascii communication channel with the function OUT_IN_CHAR to send requests and receive responses, and I will want to send packet in byte array format (like: 0x40 0x33 0x1A 0xF4... and so on). My problem is that all the functions to read/write on the serial port accept only parameters in STRING type. How can I convert an array of byte in string? Is the correct choice useing this kind of function (OUT_IN_CHAR) or you think i could try something else?
Thank you in advance for your help.. :-D


Luca Gallina

dear Federico,

I never used Unity Pro, the following is a basic method:

You need a further array to store the output string, size will be double of the source byte array. Write a for-next loop, pick each nibble (values 0x0..0xF) of the byte-array and add a proper offset to transform it into an ASCII character: add 0x30 to nibble values within 0x0...0x9 interval, 0x37 to nibble values within 0xA...0xF interval. Example: - byte array = 0x123A - char array = 0x31323341 (that means a '123A' string)

A look at any ASCII character conversion table would help.

You may have to declare also the string length or add a terminator (again, I never used Unity Pro): your string could be just a fixed-length char array, a null-terminated string or a string with a length indicator stored in the first byte.

Luca Gallina