I'm attached a Sensor IR-Array Sensor. With the following code I'm reading every byte it sends.
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(11500); // opens serial port for console
Serial.print("Output active");
Serial1.begin(19200); // opens serial port to sensor
Serial.print("Sensor active");
}
void loop() {
if (Serial1.available() > 0) {
Serial1.read();
Serial.println(incomingByte , HEX);
}
}
now the sensor has a output format of total 17bytes. (please take look at the Picture ).
How can I read this 17bytes correctly from the beginning, so I don't grabing the data from the middle?
How can I read this 17bytes correctly from the beginning, so I don't grabing the data from the middle?
Read two bytes. See if the first one is 0x00 and if the second one is 0xDF. If not, move byte to to byte 1, and read another byte. Repeat until the two bytes are 0x00 and 0xDF.
Then, read the next 15 bytes, as they become available.
Of course, as you read a value, you need to assign it to a variable. Discarding it (as you are doing) doesn't make sense.
while(Serial.available() > 0) // Don't read unless
{
for(index = 0; index == 16; index++) //0 to 16 is 17
{
SensorData = Serial.read();
SerialData[index] = SensorData;
}
}
If there is at least one byte available, read all 17 of them. Hardly seems useful to store 16 -1s in the array.
That won't read a complete packet, anyway. It will simply, assuming that there are 17 or more bytes available, grab 17 bytes. Not necessarily the correct 17 to make a packet.
How often does the device send data? Is is a continuous stream, or is there a long (relatively) gap between the spaced parts that make up a packet?
So, you could read and discard serial data until the buffer is empty. Record that happens. When there is serial data again, record when that happens. If the time between events is greater than 360 milliseconds, you are at the start of a new packet.
superkato:
its sending continuously with a gap of 388msec.
I will try the Serial.readBytes class.
( Damn I wish I had more knowledge Im just a beginner and I wanted to do this for my dads project.)
As PaulS says to wait for the 388ms delay, record 17 bytes then confirm by re-calculating the 16 byte checksum and comparing to be sure you have read valid data.
It appears with your sensor the end of transmission marker is basically the 388msec. delay. Below is a simple setup that uses a small delay to allow the input buffer to be filled until the sensor delay occurrs.
// zoomkat 7-30-11 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later
String readString;
void setup() {
Serial.begin(9600);
Serial.println("serial test 0021"); // so I can keep track of what is loaded
}
void loop() {
while (Serial.available()) {
delay(2); //delay to allow byte to arrive in input buffer
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
Serial.println(readString);
readString="";
}
}