1

This question may be a duplicate of this question or this question

I am using C and trying to communicate with a device which works on serial communication. I am reading a single byte and storing it in an array and then checking the array element to '\0' (0x00). If it's '\0' then that means the data is now not available.

volatile int rxFlag = 0;
volatile int index = 0;

void function()             //event based function, whenever a byte is received
{
  Rx[index] = ReadUSART();     //reading a byte
  if(Rx[index] == '\0' )       //checking if its null 
  {
    rxFlag = 1;                //raise a flag

  }
  index++;                       //increment index
}

Below is the screenshot of the Rx:

enter image description here

In the image you can see the from Rx[0]-Rx[24] it contains data but Rx[25] is a null terminator (0x00) and the rxFlag should be set to 1. But it is not set.

What is the another way of checking if the array element is '\0'.

Community
  • 1
  • 1
S Andrew
  • 5,592
  • 27
  • 115
  • 237
  • Have you tried adding simple debug code to see what `Rx[25]` outputs? – Jonny Henly Aug 02 '16 at 06:04
  • What is the `index` value at the time you did the screenshot? It seems you received `25` chars, so last checked is `Rx[24]`.... – LPs Aug 02 '16 at 06:09
  • You can simply check `if (!Rx[index]) rxFlag = 1;` as the *nul-character* `'\0'` has the numeric value of `0`. – David C. Rankin Aug 02 '16 at 06:17
  • I am sorry. I have used the wrong code. its not a while(1) it a function which is an event based and is fired whenever the data is received. the problem I am facing is because when the byte received is the last byte, it is then received and index is incremented but as it was the last byte so the event is not fired again and thus it doesnt check for null char. – S Andrew Aug 02 '16 at 06:22
  • Could you show us the declaration of `rxFlag`? – nalzok Aug 02 '16 at 06:23
  • @sunqingyao its `volatile int rxFlag = 0;` – S Andrew Aug 02 '16 at 06:25
  • Perhaps you should disable interrupts at the beginning of the function and enable them at the end of the function (or at least do it before and after `index++`), in order to ensure the persistence of `index` (i.e., ensure that `index++` is an atomic operation). – barak manos Aug 02 '16 at 06:28

1 Answers1

3

You have a typo when assigning rxFlag.

rxFlag == 1;

should be

rxFlag = 1;
PaulHK
  • 269
  • 1
  • 9