Error while receiving RS232 data

Hello,
I have this code:

static uint16_t Compteur;
static char OrdreRecu;

void setup() {
  Serial.begin(9600);
  Compteur=0;
    pinMode(LED_BUILTIN, OUTPUT);

}

// the loop routine runs over and over again forever:
void loop() {
  if (Serial.available()>0)
  {
    OrdreRecu=Serial.read();
    switch (OrdreRecu)
    {
    case 'W':  
      digitalWrite(LED_BUILTIN, HIGH); // Allume la LED intégrée
      byte lowByte = Serial.read();
      byte highByte = Serial.read();
      // Reconstruction de l'entier 16 bits signé (little endian)
      int16_t valeur = (int16_t)((highByte << 8) | lowByte);
      Compteur=valeur;
      Compteur=512;
      Serial.write((uint8_t*)&valeur, 2);
      break;
    case 'R':
      digitalWrite(LED_BUILTIN, HIGH); // Allume la LED intégrée
      uint16_t C=Compteur;
      Serial.write((uint8_t*)&C, 2);
      break;
    default:
      digitalWrite(LED_BUILTIN, HIGH); // Allume la LED intégrée
      break;
    }      
    
  }

}

the led does not light up, but if I had this:

    OrdreRecu=Serial.read();
    digitalWrite(LED_BUILTIN, HIGH); // Allume la LED intégrée
    switch (OrdreRecu)

Thge led light up, it means that I received a byte, but it's never processed in the switch!!
I don't understand, perhaps it's a stupid error!!
Thanks for your help

Give some time for the serial connection to be completed before using it! Perhaps a 1 second delay?

The above attempts to read characters, even if none are available to be read.

To learn how to do this correctly, I recommend to study the Serial Input Basics tutorial.

I have a feeling you just copied the code and do not understand it.
Try this:

void loop() {
  if (!Serial.available()) return;

  char cmd = Serial.read();
  switch (cmd) {
    case 'W': {                                // write new value
      uint16_t val;
      if (!readUint16LE(val)) return;          // abort if timeout
      Compteur = val;                          // store
      writeUint16LE(Compteur);                 // echo
      break;
    }
    case 'R':                                  // read current value
      writeUint16LE(Compteur);
      break;
    default:
      // ignore unknown commands
      break;
  }
  digitalWrite(LED_BUILTIN, HIGH);
  delay(10);
  digitalWrite(LED_BUILTIN, LOW);
}

I found this on the internet, I have not tried this but It should work.

If your LED does not light up you do not receive the expected data ('W' or 'R') but something else. It might be an incorrect baud rate, maybe parity or format.

What is the sender/receiver of the data? What is the format of the data? I have some doubts that it is Serial Monitor.

If I compile your code I get plenty of warnings because you declare variables inside cases. I suggest that you set the warning level under file → preferences to All. Not sure if that is the cause of your problem.

@gilshultz, your code does not compile; what are readUnint16LE() and writeUnint16LE()?

Hello,
No I haven't copy any program. I think that all of you don't understand where is the problem. In the code, the serial.available told that there is a byte ready in RS232 buffer, whatever the byte received, one of the switch's three possibilities should be executed, but this is not the case! The led is only use to debug and see where the program runs out. When you have a switch with two possibilities and a 'default', you MUST have one!
Thanks

I see the problem but can't explain it :frowning:

What if you initially set LED_BUILTIN LOW?

It is rarely a good idea to declare new variables within cases of a switch; in your code, you do this more than once. Move those declarations outside the switch, and see if that solves it. IDR what the formal description of the error is, but I think that’s your problem.

Alternatively, try this:

static uint16_t Compteur;
static char OrdreRecu;

void setup() {
  Serial.begin(9600);
  Compteur = 0;
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  if (Serial.available() > 0)  {
    OrdreRecu = Serial.read();
    switch (OrdreRecu)    {
      case 'W': {
          digitalWrite(LED_BUILTIN, HIGH); // Allume la LED intégrée
          byte lowByte = Serial.read();
          byte highByte = Serial.read();
          // Reconstruction de l'entier 16 bits signé (little endian)
          int16_t valeur = (int16_t)((highByte << 8) | lowByte);
          Compteur = valeur;
          Compteur = 512;
          Serial.write((uint8_t*)&valeur, 2);
        }
        break;
      case 'R': {
          digitalWrite(LED_BUILTIN, HIGH); // Allume la LED intégrée
          uint16_t C = Compteur;
          Serial.write((uint8_t*)&C, 2);
        }
        break;
      default:
        digitalWrite(LED_BUILTIN, HIGH); // Allume la LED intégrée
        break;
    }
  }
}

If you go into preferences and enable verbose compiler output, then enable ALL warnings, you’ll see that the compiler is trying to tell you your code has structural problems.

Other than that, you haven’t mentioned WHAT Arduino this is on - it sometimes matters a whole lot, so please tell us!

I tried it, it does!

Also, if you are using an Uno or similar AVR,lowByte and highByte are macros so you should use different variable names.

Hello,
I have made some changes, first all declaratrions of variable are made at the beginning, not in the loop part. And, it's solves the problem, I have add {} after the case declaration (why???). Now I read properly my linear encoder, and I can change the value. The only problem remaining is that the Compteur variable is a 16bits variables and can not be change with an atomic instruction, and I can't use noInterrupts() / interrupts() because if I use them I could miss a step of the encoder.
Michel

const byte A = 2;
const byte B = 3;
static uint16_t Compteur;
static uint16_t ReadCompteur;
static char OrdreRecu;
static byte LByte;
static byte HByte;
static byte ChangeOK;
static int16_t NewCompteur;

void setup() {
  Serial.begin(38400);
  pinMode(A, INPUT_PULLUP);
  pinMode(B, INPUT_PULLUP);
  ChangeOK=false;
  Compteur=0;
  attachInterrupt(digitalPinToInterrupt(A), onEventA, CHANGE);
  attachInterrupt(digitalPinToInterrupt(B), onEventB, CHANGE);
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  if (Serial.available()>0)
  {
    OrdreRecu=Serial.read();
    switch (OrdreRecu)
    {
    case 'W': { 
      while (Serial.available()==0);
      LByte = Serial.read();
      while (Serial.available()==0);
      HByte = Serial.read();
      // Reconstruction de l'entier 16 bits signé (little endian)
      NewCompteur = (int16_t)((HByte << 8) | LByte);
      ChangeOK = true;
    }
      break;
    case 'R':{
      if (ChangeOK){
        ReadCompteur=NewCompteur;
      }
      else{
        ReadCompteur=Compteur;
      }
      Serial.write((uint8_t*)&ReadCompteur, 2);
    }
      break;
    default:
      break;
    }      
  }
}

void onEventA() {             // Changement d'état de A 
  if (ChangeOK){
    Compteur=NewCompteur;
    ChangeOK=false;
  }
  if (digitalRead(A)==1) {
    if (digitalRead(B)==0) {  // A=1 B=0
      Compteur--;
    }
    else{                     // A=1 B=1
      Compteur++;
    }
  }
  else{
    if (digitalRead(B)==0) {
      Compteur++;             // A=0 B=0
    }
    else{
      Compteur--;             // A=0 B=1
    }
  }
}

void onEventB() {             // Changement d'état de B
  if (ChangeOK){
    Compteur=NewCompteur;
    ChangeOK=false;
  }
  if (digitalRead(B)==1){
    if (digitalRead(A)==1) {  // A=1 B=1
      Compteur++;
    }
    else{                     // A=0 B=1
      Compteur--;
    }
  }
  else{
    if (digitalRead(A)==0) {  // A=0 B=0
      Compteur--;
    }
    else{
      Compteur++;             // A=1 B=0
    }
  }
}

Which Arduino are you using?

An Elegoo UNO R3

You misunderstand the purpose and function of these calls. The interrupt does not go away, it will still be there when you re-enable interrupts; the noInterrupts() call simply results in the suppression of the call to the interrupt function until interrupts() re-enables the interrupt. So unless your interrupt frequency is extreme, you won’t miss one, unless your interrupt routine itself is longer than necessary.

If your interrupt frequency is so high that you actually do miss interrupts despite optimizing the interrupt routine, you’d be best to move to a faster processor - although we don’t know that, because you have yet to tell us what Arduino this is running on.

Edit - Thank you for finally revealing your processor.

If you don't service the interrupts fast enough, you could miss a step or several steps no matter what you do.

How fast do the interrupts occur?

Well, since there’s no interrupt code in the posted code, I guess helping further isn’t feasible.

Please describe your actual application in more detail.

No more than 1000 interrupts per second, but if an interrupt arrive just after the noInterrupts and before the Interrupts, I will miss an interrupt? In this case I will lose the precision of my linear encoder https://www.posic.com/products/linear-encoders.html
My idea was to write:

noInterrupts;
Compteur =NewCompteur;
Interrupts;

outside of the interrupt code.
The system I am building is to mesure precisely during all the night the position of a focuser on a telescope.

No. You only miss interrupts if multiple interrupt occur while interrupts are off,

That’s interesting, but I see we must continue to help you design the code, and eke details out as we go.

  1. write your best guess at the interrupt routine

  2. write your best guess at the loop() code

  3. compile it, test it, and report back on what doesn’t work, and what the symptoms are, and we can go from there.

Best of luck, I have things to do today.

I don't understand, for me with noInterrupts, you have no more interrupt?