Go Down

Topic: send serial selectively (only when active)? (Read 771 times) previous topic - next topic

brendanmccloskey

Nov 27, 2012, 01:27 pm Last Edit: Nov 27, 2012, 01:30 pm by brendanmccloskey Reason: 1
Hi

I am using serial.write to send data from 12 diy FSR's - to MaxMSP - and I recently learned from a more experienced colleague that it is common practice to send data only when it changes. This sounds attractive. Would it simply be a matter of writing the following:

Code: [Select]

int var=analogRead(myPin);

if (var > 0){
Serial.write (var);
}
else
{
//do nothing
}


Will this 'mute' or clear the serial buffer when my sensors are inactive? I guess my question is, how do I send my data only when the sensors are sending values > 0?

Apologies for poor wording;
and thanks

PaulS

Quote
Would it simply be a matter of writing the following:

No. The value might be 45 27 times in a row. You want to send the value again only when it isn't the same as the value last sent.

Code: [Select]
int currVal;
int prevVal = 0;

void loop()
{
   currVal = analogRead(myPin);
   if(currVal != prevVal)
   {
      Serial.write(currVal);
      prevVal = currVal;
   }
}

brendanmccloskey

Yes, I tried my own example and my 'sent' data is unreliable. As my FSRs are homemade, the raw values fluctuate from c.120 (+/-5) to c. 800 (+/-5) so I was using [map] and [constrain] quite heavily to force the inactive value down to zero. Could I ask for further help in applying a delta function; this way I can send data only when the delta exceeds a set threshold.

thank you

PaulS

Quote
Could I ask for further help in applying a delta function; this way I can send data only when the delta exceeds a set threshold.

Sure.

Code: [Select]
int currVal;
int prevVal = 0;

void loop()
{
   currVal = analogRead(myPin);
   if(abs(currVal - prevVal) > 5)
   {
      Serial.write(currVal);
      prevVal = currVal;
   }
}

This will send a value only when the difference between the current value and the previous value is greater than 5, positive or negative.

You might want to divide the fsr reading by some amount, say 5, and then send each (different) value without worrying about a range. Either one will work.

brendanmccloskey

yep, you beat me to it:

Code: [Select]

int currVal;
int prevVal;
int delta;

void loop(){
currVal=analogRead(0);
delta=currVal-prevVal;
prevVal=currVal;
}


thanks for all your help

Brendan

Go Up