Reading a serial buffer for an item

I would appreciate the community's help as I am not a C programmer. I have read numerous tutorials on serial programming but could not find what I am looking for. Namely, reading the value of each item in the serial buffer.

I am reading from a serial sensor using:

int len;
char buf[60];

len = Serial1.readBytes((char *)buf,50);

if(len > 0)
{
for (int i=0; i <= len; i++)
{
if (buf[i] == 170)
.....
......

I need to loop over the entire buffer and look for an entry = 170. (Hex = AA).

How can I print the value of each item in the buffer so I can see the stream? I tried sending the buffer items by using String(buf[0]) but I am getting gibberish.

Thanks in advance.

@Jimmie

String(buf[0])

This will convert the index 0 of the char array to a C String object. If you print a non-printable character value you will get gibberish!

Serial.printlnf("Buffer value [%i] = %i", i, buf[i]);

Should output Buffer value [10] = 170

What you want to do is format the char value as a hex or integer string. Also, char is really an ascii character value (7 bits) and you want to read values of >127 - so better to use uint8_t or byte.

In terms of looking for 170 value you could try using the Stream class findUntil() - examples in the firmware reference.

Thank you @armor for your time but I did not understand. If my code is

int len;
char buf[60];
len = Serial1.readBytes((char *)buf,50);
if(len > 0)
{
   for (int i=0; i <= len; i++)
   {
       if (buf[i] == 170)             

What should this statement be?

int len;
char buf[60];
len = Serial1.readBytes((char *)buf,sizeOf(buf));
if(len > 0)
{
   for (int i=0; i <= len; i++)
   {
       if (buf[i] == 170)
       {
           Serial.printlnf("Buffer value [%i] = 170", i);
           //do something else that you want to ??
       }
       else
       {
           Serial.printlnf("Buffer value [%i] = %i", i, buf[i]);
       }
   }
}

I do not know what you want to do when you find char = 170?

Thank you @armor. I am seeing the stream using Particle Dev on my PC.

I have been trying to print the buf[i] value to the cloud to see what I am getting. If I may bother you with one request, how does one print the value to the cloud?

In setup() you could declare a cloud variable - these must be of type String, integer, or double.

If you want to output a char then you could convert it to a String or an integer - integer would be;

int cloudVarInt = 0;
void setup()
{
...your code
Particle.variable("name", cloudVarInt);
}
void loop()
{
...your code
cloudVarInt = (int) buf[i];  //type cast char to int
}
1 Like

Thank you very much @armor. I think I got it now.

I appreciate it.