quarta-feira, 10 de julho de 2013

Protocols [Part deux]

Hello again...

Let's carry on with the protocols.

As I mentioned before, you can either have an ASCII or binary protocol... or with both.
You see, for simplicity when reading the code, it's nice to have an ASCII character to define the command/status, and for simplicity (in case numbers are being transmitted) sending the data in binary form.

The main advantage of sending data in binary form is space and processing overhead.
For example, say that you have a system where your Arduino sends some information to the computer in this format (in ASCII):


! signifies the message start
C - signifies the variable that is being sent, lets assume the number of pulses from the electricity counter.
30000 is the number of pulses at the moment.
\n is the end of the message. In C, '\n' is a single character.

This message would take 8 bytes to send in ASCII format. Not only that, you would have to take your pulse count variable, convert it to ASCII (Serial.print does this "automatically") and send it. Your computer, to calculate the actual power used, would then have to take the string with 30000 and convert it to integer format in order to use it in Power calculations and data logging.

This is quite a lot of effort isn't it?

Another possibility would be to mix the encoding of the message like this:


BB is two bytes in binary format. So what used to take 8 bytes can now take 5.

Not only that... in ASCII you either send data with variable length (which causes a bit more overhead in the processing of data) or you have to stuff it with 0's to the defined length. Say if you wanted to send 15, you would send 00015.

With this mixed format, this is not a problem. Not only that there is no need to convert these bytes from and to ASCII. These can be used "directly".

And by directly I mean

unsigned int variable = 0;

variable = Serial.read() << 8; //shift the first byte to the left

variable = variable + Serial.read(); //write the second byte in it's place.

Although, as I said, this is something that you'd use if your microcontroller project will interface with a program of some sort on the other end. If it's you on a Serial Port or Arduino IDE, then the best option would really be to use an ASCII format.

Next we'll talk about message formats.

Sem comentários:

Enviar um comentário