1

Ok, I made some changes to the code and I wish they would see it.

At the moment the program has a bug, it is not saving the contents of the txt file to the table, can someone give some lights?

#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
int x = 1;
String files, memo, memo1;
int sizef = 0;
int sizef1 = 0;
int sizef2 = 0;
int y=0;
int z=1;
int d=0;
int u=0;
int r=0;
int l=0;
int indice_objetos=0;

struct objeto_celeste_s {
  char nome[20];
  float ar;
  float dec; 
  };
typedef struct objeto_celeste_s objeto_celeste; 

void rightfunction (int rate){
 char cmd[] = {'P',2,16,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void leftfunction (int rate){
 char cmd[] = {'P',2,16,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void upfunction (int rate){
 char cmd[] = {'P',2,17,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

void downfunction (int rate){
 char cmd[] = {'P',2,17,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

File file;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

char * list[]={"1.Modo Normal    ","2.Modo Teste    "};

// read the buttons
int read_LCD_buttons()
{

adc_key_in = analogRead(0);
if (adc_key_in > 1000) return btnNONE;
if (adc_key_in < 50)   return btnRIGHT;  
if (adc_key_in < 250)  return btnUP; 
if (adc_key_in < 400)  return btnDOWN; 
if (adc_key_in < 450)  return btnLEFT;
if (adc_key_in < 650)  return btnSELECT;   

return btnNONE;  // when all others fail, return this...
}

void setup() {

 Serial.begin(9600);
 Serial1.begin(9600);
 while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
 } 
 Serial.println ("Welcome!");
 Serial.println ("Efectue o alinhamento do telescópio, depois carregue no botão UP.");
 lcd.begin (16,2);
 lcd.setCursor (0,0);
 lcd.print ("Efectue alinham.");
 lcd.setCursor (0,1);
 lcd.print ("E carregue UP");
 delay (1000);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
}


void loop() {

lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)  // depending on which button was pushed, we perform an action
 {
   case btnRIGHT:   
     if (z==0){
      rightfunction (9);
      Serial.println ("Andar para a direita a uma velocidade de 9.");
      z=1;
      r=1;
      break;
     }

     if (r==1){
      rightfunction (0);
      Serial.println ("Parar de andar para a direita.");
      z=0;
      r==0;
      break;
     }

   case btnLEFT:
     if (z==0){
      leftfunction (9);
      Serial.println ("Andar para a esquerda a uma velocidade de 9");
      z=1;
      l=1;
      break;
     }

     if (l==1){
      leftfunction (0);
      Serial.println ("Parar de andar para a esquerda.");
      z=0;
      l=0;
      break;
     }

   case btnUP:
      if (z==0){
       upfunction (9);
       Serial.println ("Andar para cima a uma velocidade de 9");
       z=1;
       u=1;
       break;
     }

      if (u==1){
       upfunction (0);
       Serial.println ("Parar de andar para cima.");
       z=0;
       u=0;
       break;
     }


      if(x==1){
        x--;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[0]);
        lcd.setCursor(0,1);
        lcd.print (" ");
        lcd.println(list[1]);
        break;
      }
   case btnDOWN:
      if (z==0){
       downfunction (9);
       Serial.println ("Andar para baixo a uma velocidade de 9.");
       z=1;
       d=1;
       break;
      }

      if (d==1){
       downfunction (0);
       Serial.println ("Parar de andar para baixo.");
       z=0;
       d=0;
       break;
      }


      if(x==0){
        x++;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[1]);
        lcd.setCursor(0,1);
        lcd.println("                ");
        break;
      }

   case btnSELECT:
    if (x==2){
      Serial.println ("Bem-vindo ao Modo Manual.");
      lcd.clear ();
      lcd.print ("Modo Manual");
      lcd.setCursor (0,1);
      lcd.print ("Reset p/mod GoTo");
      Serial.println ("Pressione os botões UP, DOWN, RIGHT ou LEFT no arduíno para controlar o telescópio.");
      z=0;
      break;
    }


    if (x==0){
    lcd.clear ();  
    lcd.print ("Modo Normal");
    Serial.println ("Selecionou o modo normal!");
    delay (1000);
    if (SD.exists("objectos.txt")) {
    Serial.println("O ficheiro 'objetos' foi encontrado!");
    lcd.clear ();
    lcd.setCursor (0,0);
    lcd.print ("Modo Normal");
    delay (1000);

    file = SD.open("objectos.txt", FILE_READ);
    if (file) {
    while (file.available()) {
     String line = file.readStringUntil('\n');
     sizef++;
    }
    } else {//se houver erro a abrir o ficheiro 
     Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
    }
     Serial.print ("Contados ");
     Serial.print (sizef);
     Serial.println (" objetos no ficheiro objectos.txt.");

     objeto_celeste *tab =(objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));

     if (tab==NULL){
      lcd.clear ();
      lcd.print ("Erro a alocar memoria");
      Serial.println ("Erro a alocar memória");
      while (1){ }; 

     }else{

      Serial.print ("Memória alocada para ");
      Serial.print (sizef);
      Serial.println (" objectos.");
      lcd.setCursor (0,1);
      lcd.print ("Alocados ");
      lcd.print (sizef);
      lcd.print (" obj");
      }

      file.close(); 


    char * line1 =(char*) malloc(sizeof(String)); 

    file = SD.open("objectos.txt", FILE_READ); 

    if (file) {
     Serial.println ("Carregando informação para a memória:");

     while (file.available()) {

     char c = file.read ();

     if (c=='\n'){ 

     char * justafun = strtok (line1," "); //divide em tokens 

     while (justafun !=NULL){

      switch (indice_objetos) {
          case 1:
            tab[sizef2].ar = atof(justafun); //to float


            indice_objetos++;
            break;
          case 2:
            tab[sizef2].dec = atof(justafun);

            sizef2++;
            indice_objetos=0;
            break;
          case 0:
            strcpy(tab[sizef2].nome, justafun); //this one is a string
            indice_objetos++;
            break; 
      }
      justafun = strtok (NULL, " ");  
      }

      if (line1==NULL){
      Serial.print ("Falhou na linha ");
      Serial.println (sizef2);

     }else{
       line1="";
    }  
   }else{
     sprintf(line1, "%s%c", line1, char(c));
     }
    }
   }
  file.close (); 

  delay (1500); 

  if (Serial1.available()) {
   int inByte = 'V';
   Serial1.write (inByte);
   int inByte1 = 'e';
   Serial1.write (inByte1);
  }

delay (1000);

Serial.println ("Tabela ordenada alfabeticamente:");

 x=2;
 delay (1000);
 lcd.clear ();
 Serial.println ("Modo GoTo. Para entrar em Modo Manual pressione o botão select.");
 lcd.print ("Modo GoTo");
 lcd.setCursor (0,1);
 lcd.print ("Slct p/Modo Man.");


 }else {

    Serial.println ("O ficheiro 'objetos' não existe.");
    lcd.clear ();
    lcd.print ("Erro nao encontrado");
    delay (2000);
    while(1) { };
  }
 } 

    if (x==1){
      lcd.clear ();
      lcd.print ("Modo Teste");
      Serial.println ("Selecionou o modo teste!");
      delay (2000);

      if (SD.exists("teste.txt")) {
      Serial.println("O ficheiro 'teste.txt' foi encontrado!");
      lcd.clear ();
      lcd.setCursor (0,0);
      lcd.print ("Modo Teste");
      lcd.setCursor (0,1);
      lcd.print ("Ficheiro encontrado");
      delay (2000);

      file = SD.open("teste.txt", FILE_READ);

      if (file) {
      while (file.available()) {//ler o ficheiro
      String line = file.readStringUntil('\n');
      sizef++;
     }

      files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
      Serial.println (files);
      objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
      memo = "Alocados " + String (sizef) + " obj  ";
      memo1= "Memória alocada para " + String (sizef) + " objetos.";

      if (tab==NULL){
        lcd.clear ();
        lcd.print ("Erro alocar memoria");
        Serial.println ("Erro a alocar memória");
        while (1){ };

      }else{

        Serial.println (memo1);
        lcd.setCursor (0,1);
        lcd.print (memo);
      }

      file.close();

     } else {//se houver erro a abrir o ficheiro 
      Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
     }

    }else {
      Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
      lcd.clear ();
      lcd.print ("Erro nao encontrado");
      delay (2000);
      while(1) { };
    }
   }
     break;

   case btnNONE:
      break;
 }    
 delay (200);
}   

This is the content of txt.

P.S. I know the "Ar" section is wrong, it's just for test purposes.

Syrius 6.45 -16.42 
Deneb 20.41 +45.16 
Capella 5.16 +45.59 
Rigel 5.14 -8.12 
Vega 18.36 +38.47 
Alnitak 05.40 -01.56 
9
  • Possible duplicate of arduino.stackexchange.com/questions/51957/…
    – chrisl
    Apr 21, 2018 at 14:38
  • Hi, this is too long for a comment in other post. Apr 21, 2018 at 14:40
  • And the code is not the same... Apr 21, 2018 at 14:40
  • Why do you except the contents of your textfile to be saved into the array tab? You read one character at a time but aren't doing anything else with it than using it in an if-statement. You have to actually put your information into your data array
    – chrisl
    Apr 21, 2018 at 14:41
  • Consider that you always can edit your question. Code or other long things should not be placed in code, but the question should be edited. For me it seems, that you have the same problem as last time. If not, please be more specific
    – chrisl
    Apr 21, 2018 at 14:42

1 Answer 1

1

Maybe I have found your problem:

Before reading the file you are allocating memory with malloc() and creating a pointer line1 to it. malloc() takes the number of bytes to allocate as a parameter. Here you use sizeof(String), which would give you the size of a new String object. But the point of the String object is, that is dynamically allocates the memory for the string of characters. So the created buffer line1 is most likely to small for your text. You have to allocate the buffer with the maximum number of characters of all lines.

But you should consider, that using malloc() or any other dynamic memory allocation is dangerous on microcontrollers, which don't have much RAM. If you are doing it to often you get heap fragmentation, essentially making swiss cheese of your heap. If possible you should use a statically declared array or at least allocate memory only once during the lifecycle of your program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.