Search code examples
arduinopackethint

Sending two different informations to an Arduino


This is a question to help me get started in a program. Here is the setting : I am extracting data from a car racing game, and I would like to use this data to actuate 2 Servomotors that are plugged in to my Arduino Uno. One servo would be RPM and the other would show Speed.

The information is being sent by a program running on the PC to the Arduino via the Serial Port, and I would like to know if you would have any insights or tips on how to "separate" these two different informations so that the Arduino can recognise each one of them and use it on the correct Servomotor.

This is not so much a question on helping me on a specific bit of code, I am looking for some methods that are generally used to identify and separate different data packets.

Thanks!


Solution

  • An easy way could be to use a identier byte. So a dataframe always has a identifier byte at first. You could define the identifiers in an enum like this:

    enum DataIdentifier
    {
      Rpm,
      Speed
    };
    

    Your arduino code could be like this:

    if(Serial.available > 0)
    {
      byte Identifier = Serial.read();
      switch(Identifier)
      {
        case Rpm:
          //Read X Bytes and use the RPM Servo
          break;
        case Speed:
          //Read X Bytes and use the Speed Servo
          break;
        default:
          break;
      }
    }
    

    This solution is very modular. You can change and expand this soulution very easy.