Home > Uncategorized > Serial comunication protocol with arduino

Serial comunication protocol with arduino

A serial comunication example with a medium complex protocol:
I promise to expan it using crcs ;)

#define ledPin 13
#define waitForByte 200 //Time waiting for the next check of available data
#define maxItertionWaiting 20 //Maximun iteration before timeout

// Return values in checkResponse
#define errorTimeout -1
#define errorProtocol -2
#define responseOK 0

// first data to send
byte tSend1[]={0x15, 0x39, 0xF2, 0x78, 0x22, 0x11};
// first data to receive
byte tResp1[]={0x20, 0x1B, 0xF2, 0x79, 0x24, 0x11};
// second data to send
byte tSend2[]={0x25, 0x45, 0xF2, 0x7a, 0x09, 0x11};
// second data to receive
byte tResp2[]={0x30, 0xa0, 0xF2, 0x7b, 0x59, 0x11};

//buffer to put the response in
byte *LastResponse=NULL;

// Initialize everything
void setup()
{
Serial.begin(9600);

// wait a bit
delay(100);

// we will light on when the protocol finnalice ok
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}

// Read the response (in LastResponse
int checkResponse(byte response[],int iResponseSize)
{
int iReceivedCounter=0; // How many byte we have receive
int iReceivedValue=0;
int iIteration=0; // How many iterations we have wait for the last data
int iResult=responseOK;

if(LastResponse!=NULL) //Free memory
free(LastResponse);

LastResponse=(byte *)calloc(iResponseSize,1); //Alloc memory for new data

while(iReceivedCounter
{
if(Serial.available()>0)
{
iIteration=0;
iReceivedValue=Serial.read();
if(iReceivedValue!=response[iReceivedCounter]) // is it the waited byte?
{
iResult=errorProtocol;
break;
}
else
LastResponse[iReceivedCounter++]=(byte)iReceivedValue;
}
else
{
if(iIteration
{
delay(waitForByte); // One more try
iIteration++;
}
else
{
iResult=errorTimeout;
break;
}
}
}
return iResult;
}

void sendData(byte dataToSend[],int iSize)
{
for(int i=0;i
{
Serial.print(dataToSend[i],BYTE);
}
}

void loop()
{
int iImportantValue=0;

sendData(tSend1,6);
delay(200); // allow some time for the Serial data to be sent
if(checkResponse(tResp1,6)==responseOK)
{
sendData(tSend2,6);
delay(200); // allow some time for the Serial data to be sent
if(checkResponse(tResp2,6)==responseOK)
{
iImportantValue=LastResponse[3]*256+LastResponse[2];
digitalWrite(ledPin, HIGH);
}
}
}

  1. cableman
    February 19th, 2009 at 23:53 | #1

    I need my Arduino communicates with 25000000 inverters, but I’ve a problem with a special kind of CRC…could you tell me something about? is it possible to program an Arduino with the famous “onetopperchild” ;) ))

  2. February 20th, 2009 at 17:36 | #2

    Thanks for your coment cableman.
    At the moment we can handle only 25 inverters more o less, but we are working very hard on it at this precise moment.

    Ask to hexadeciman about the improvement in a near future.

  1. No trackbacks yet.