Implementing a serial comms protocol

Hi guys
OK I am getting somewhere with my project now.

I have a graphics overlay PCB that I need to control from a PC

The PCB uses both SPI (for RAM data loading) and i2c (for control registers)

Having done a lot of experimentation I can now load RAM data and control the board with the arduino so that’s looking good :smiley:

Next step I have to get the PC talking to the Arduino. I’ve already played around with the serial library so basically know the ins and outs.

I also realise I need to implement some sort of protocol between the application running on the PC and the Arduino. I can inplement this however I like as I have the source code for the PC app.

My thoughts were to do it something like this

Wait for data on the serial bus.

When data arrives it will be formatted like this:

1st byte = a pre-defined command byte
2nd byte = length of command in bytes
3rd to nth byte = command parameters

So how do I go about this?

Lets assume my command bytes start 0x5n…
assume I reply on serial bus 0x90 0x00 for a good command
assume I reply on serial bus 0x99 0xnn (where nn = number of following bytes, followed by further bytes detailing the error)

In psuedo code then, I am trying to do something like this

While serial data exists
       {
       read command byte - store in array
       read length byte - store in array
       for i = 0 to length
            {
            read byte and store in array
            }

      }

Error Check 
      {
       if received bytes != length = error
       reply 0x99 0x01 nn (nn is code for wrong data length)
       wait for more data on serial port
      }

Switch:
      Case Command = 0x51
          do_something
      Case Command = 0x52
          do_something_else
       .....
       .....
      Case default
           error - unknown command
           reply 0x99 0x01 0xnn (nn is error code for unknown command)
           wait for more data on serial port

function do_something
        for i = 0; i < length byte
            {
              send bytes via SPI or i2c as required
              reply on serial bus 0x90 0x00 (command precessed OK)
              wait for more serial data
            }

So that is basically what I want to do - how best to implement it?

I am a bit uncertain how to get aspects of this psuedocode into a real program structure - especially the bit that handls serial comms and reads bytes etc

I can get my PC app to wait for a response before sending the next command on serial bus if required

Rich