Send data from Processing to Arduino

Hi everyone,

I am trying to send 70 values from Processing to Arduino (as fast as possible), in order for Arduino to feed with these values a servo driver shield. What I tried to do in my code is to send the data one by one and each time a value is received Arduino confirms that to Processing in order to move to the next one. However my code doesn't works properly. Please have a look below to see what mistakes do I have, or if you have a better solution for the procedure please share it! Thank you for you time!

-----------------------------------------

Arduino Code

-----------------------------------------

 

int val[70];

void setup()   {

  Serial.begin(9600);

}

void loop() {

 Serial.write(0);

   for (int i=0;i<70;i++){       

     if(Serial.available()>0)

     val[i]=Serial.read();

     Serial.write(i);     

     Serial.flush();        

   }

    }

if (val[0]==1 & val[1]==2)

{

    Serial.println("done");

} else {

    Serial.println("error");

  }

  delay(500);

}

 

 

 

----------------------------------------- 

Processing Code

-----------------------------------------

 

import processing.serial.*;

Serial myPort;

int last;

byte a[] = { 111, 112, 113, 99, 99, 99, 99, 99, 99, 99,

             99, 99, 99, 99, 99, 99, 99, 99, 99, 99,

             99, 99, 99, 99, 99, 99, 99, 99, 99, 99,

             99, 99, 99, 99, 99, 99, 99, 99, 99, 99,

             99, 99, 99, 99, 99, 99, 99, 99, 99, 99,

             99, 99, 99, 99, 99, 99, 99, 99, 99, 99,

             99, 99, 99, 99, 99, 99, 99, 114, 115, 116 };

void setup()

{

  size (200, 200);

  String portName = Serial.list()[6];

  myPort = new Serial (this, portName, 9600);

   delay(2000);

}

void draw()

{

  while (myPort.available()>=0)

  {

    for (int i=0; i<70; i++)

    {

      last = myPort.read();

      if (int(last) == i-1)

      { 

        myPort.clear();

        myPort.write(a[i]);

      }

    }

  }

}

 

 

 

 

 

 

I just wanted to add onto

I just wanted to add onto bdk6’s comments. 

As he says, your code assumes that the complete message has arrived, when chances are, it hasn’t arrived yet.  You need to assume that you are in the middle of the message at any time.  The reason your code works fine with a 2 second delay, is that the receiver has plenty of time to queue up the serial message, and your code is never caught in the middle of an incoming message.  Try this snippet:

// this will make a global so value won’t change between calls

int index = 0 ;

void loop () // you had draw() - I assume that was a typo??

{

 

while (serial.available( ) == 0)

{

val[index] = serial.read();

index ++ ;

}

if ( index > 70 )

{

index = 0;

// send confirmation back to the other arduino

}

} // end of loop()

This plus bdk6’s should point you in the right direction.  FYI, there are a number of free libraries out there that already deal with this for you.

Regards,

 

Bill