Go Down

Topic: variable disappearing when reading data? (Read 444 times) previous topic - next topic

karl101

Hello,

I have written this code, but one of the variables goes missing. It is for coverting the hex codes from an IR remote to a maningful string. It reads a text file from a SD card, like the extract below, its is in the format <IR Code>=<IR button> #<comment>:
Code: [Select]

C0E8=PWR  # Power
C091=PLY  # Play
C04D=REC  # Record
C061=STP  # Stop
C001=PSE  # Pause
C07D=FFW  # Fast Forward


here is my code:
Code: [Select]

#include <SD.h>

File myFile;

void setup() {

  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);
  if (!SD.begin(4)) {
    Serial.println("failed!");
    return;
  }
  Serial.println("done.");

  char irCmd[4];   // IR Command: C0E8
  char irBut[3];   // IR meaning: PWR
  int i = 0;
  int ic = 0;
  int ib = 0;
  int line = 0;
 
  myFile = SD.open("IR_SONY.TXT");
  if (myFile) {
    while (myFile.available()) {
      int c = myFile.read();
      if (i < 4) {  // read first 4 bytes
        Serial.write(c);
        irCmd[ic++] = c;
        irCmd[ic] = '\0';
      }     
      else if (i > 4 && i < 8) { // read the last three bytes
        Serial.write(c);
        irBut[ib++] = c;
        irBut[ib] = '\0';
      } 
     
      i++;
      if (c == '\n' || c== '\r') {
        i = 0;  // reset counters at end of line
        ic = 0;       
        ib = 0;
        Serial.print("\n");
        Serial.print(line);
        Serial.print(". irCmd: ");
        Serial.print(irCmd);
        Serial.print(",irBut: ");
        Serial.println(irBut);
        line++;
      }
    }
    myFile.close();
  }
  else {
    Serial.println("could not open ");
  }

  Serial.print("xxxx\n");
}

void loop()
{
  // nothing happens after setup
}


Output:
Code: [Select]

C0E8PWR
0. irCmd: ,irBut: PWR
C091PLY
1. irCmd: ,irBut: PLY
C04DREC
2. irCmd: ,irBut: REC
C061STP
3. irCmd: ,irBut: STP
C001PSE
4. irCmd: ,irBut: PSE
C07DFFW
5. irCmd: ,irBut: FFW


the irCmd variable is dssapering and is not being displayed. Howver if I comment out the two lines: 
Code: [Select]
irBut[im++] = c;
irBut[im] = '\0';
the irCmd is displayed.

Can you help?
Thanks
Karl.


billroy

Your arrays look too short by me, off by one.  Unless I am mistaken, the code is trying to put four bytes and a null into a four byte buffer.

Make the arrays longer by one and see if the problem resolves.

-br

karl101

Yes, its as simple as that, I spent most of the day puzzing over it.

Thanks for the reply.

Karl

billroy

Everybody makes that mistake once.  Smart people _only_ make it once.

Good luck with your project.

-br

Go Up