Sending packets to Arduino

I'm working on a project where I will be controlling a robot powered by an Arduino UNO through a bluetooth shield. The objective is to send 16-bit packets over serial and I have no idea where to begin. I need to get a better understanding of how to create a packet and send it to the Arduino. Are there any basic examples to help me get started?

This sketch here can receive a packet of data in this format, <Aaa,Bbb,Cccc...Z>

int buffer[8]; // adjust to the size of data you are receiving, this example is receiving no more then 8 ints
int counter = 0;

void setup(){
  Serial.begin(115200);
}

void loop() 
{
  if(Serial.available() > 0)
  {
    char temp = Serial.read(); // example incomming data <1,23,456,7890>
    if( temp == '<' ) // is incoming char equal to <, if so gather the rest
    { 
      counter = 0; // make sure counter is set to zero
      while(1)
      {
        if(Serial.available() > 0)
        {
          char temp = Serial.read(); // read in incoming char
          
          if(temp != ',' && temp != '>') 
          {
            buffer[counter] = (buffer[counter]*10) + (temp - '0');// converts temp into an int then stores it
          }

          if(temp == ',') // split data from the comma
          {
            counter++; // increment buffer index
          }

          if(temp == '>') // if incoming char is >, then break out of loop
          {  
            break; // breaks out of the while loop
          }
        }
      }
    }
    for(int NUM = 0; NUM <= counter; NUM++) //will output "1,23,456,7890"
     {
     Serial.print(buffer[NUM]);
     if(NUM != counter) Serial.print(",");
     }
     Serial.println();
  }

  while(counter != -1) 
  {
    buffer[counter] = 0; 
    --counter;
  }
}

You can use sprintf() to structure the packet to be sent, like so:
int Output[10]; // create an array large enough to hold the newly formed string.
sprintf(Output, "<%d, %d, %d, %d>", data1, data2, data3, data4);

send Output either serially or whatever.

1 Like