Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 2 of 2

Thread: Using EEPROM in Teensy 3.2

  1. #1
    Junior Member
    Join Date
    Aug 2020
    Posts
    10

    Using EEPROM in Teensy 3.2

    Hi,
    We are trying to get telemetry data and we want the number of packets to resume in case of any power failure. but we failed.
    The code is as follows. We did not know if there is an error in the code.
    what could be caused by the problem?

    Code:
    #include <Wire.h>
    #include <Adafruit_BMP280.h>
    #include <OneWire.h>
    #include "MPU9255.h"
    #include <SPI.h>
    #include <SD.h>
    #include <TinyGPS.h>
    #include <EEPROM.h>
    
    int16_t accelCount[3];
    int16_t gyroCount[3];
    int16_t magCount[3];
    int16_t tempCount;
    float f_accelCount[3];
    float f_gyroCount[3];
    float f_magCount[3];
    float AccelScale, GyroScale, MagScale;
    float temperature;
    int doklG = 250; // stopni / sekunde - dokladnosc dla czujnika zyroskopowego
    int doklA = 2; // +- 2g - dokladnosc dla akcelerometru
    int doklM = 6; // 0.6 mGaussa - dokladnosc dla magnetometru
    float approxGndPress;
    
    Adafruit_BMP280 bmp; // inicjalizacja czujnika cisnienia/altymetru + termometru
    MPU9255 mpu(12, doklG, doklA,doklM); // inicjalizacja akcelerometru-zyroskopu-magnetometru
    
    
    /* START WIFI */
    
    String agAdi = "POCOFONE";                 //Ağımızın adını buraya yazıyoruz.    
    String agSifresi = "fener1234";           //Ağımızın şifresini buraya yazıyoruz.
    
    //esp nin rx = 1 - tx = 0
    
    String ip = "184.106.153.149";                                //Thingspeak ip adresi
    float sicaklik, nem;
    
    /* END WIFI */
    
    /* START VOLTAJ BOLUCU */
    int analogInput = 0;
    float vout = 0.0;
    float vin = 0.0;
    float R1 = 100000.0; // 100K ohm direnç
    float R2 = 10000.0; // 10K ohm direnç
    int valueVoltajBolucu = 0;
    /* END VOLTAJ BOLUCU */
    
    /* START SD CARD ADAPTOR */
    Sd2Card card;
    SdVolume volume;
    SdFile root;
    
    const int chipSelect = 15;  
    File myFile;
    /* END SD CARD ADAPTOR */
    
    /* START GPS */
    TinyGPS gps;
    
    static void smartdelay(unsigned long ms);
    static void print_float(float val, float invalid, int len, int prec);
    static void print_int(unsigned long val, unsigned long invalid, int len);
    static void print_date(TinyGPS &gps);
    static void print_str(const char *str, int len);
    
    /* END GPS */
    
    
    int buzzerPin = 5;
    
    int paketNo = 1;
    
    
    bool espBuldu = false;
    
    String telemetri = "";
    
    String sdCardFile = "21072020.txt";
    
    boolean sdError = false;
    
    
    int uyduStatusu = 1;
    int ilkYukseklik = 0;
    
    int ilkZaman = 0;
    int sonZaman = 0;
    
    bool gpsCalissinMi = true;
    
    void setup()
    {
      delay(2000);
      
      Serial.begin(115200);
    
    
      EEPROM.write(1, "CANLI"); //UÇUŞ ANINDA ÖNCE TEST YAZILACAK ÇALIŞTIRILACAK. SONRA CANLI YAZILACAK VE UÇUŞA GEÇİLECEK.. (BU YAPILMAZSA SÜREKLİ ESKİ PAKETNO KALIR) 
    
      if (EEPROM.read(1) == "TEST")
      {
        EEPROM.write(0, 1);
      }
      
      
      pinMode(analogInput, INPUT); // voltaj bolucu - a0 (14)
      
      pinMode(buzzerPin, OUTPUT); //BUZZER
      
      /* START SD CARD ADAPTOR */
    
      SPI.setCS(chipSelect);
    
       Serial.print("\nInitializing SD card...");
    
      pinMode(chipSelect, OUTPUT);     
      
     sdError = false;
     
      if (!card.init(SPI_QUARTER_SPEED, chipSelect)) {
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card is inserted?");
        Serial.println("* Is your wiring correct?");
        Serial.println("* did you change the chipSelect pin to match your shield or module?");
        sdError = true;
      } else {
       Serial.println("Wiring is correct and a card is present.");
      }
    
      
      // print the type of card
      Serial.print("\nCard type: ");
      switch(card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          break;
        default:
          Serial.println("Unknown");
      }
     
      // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
      if (!volume.init(card)) {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        sdError = true;
      }
    
      if (sdError == false)
      {
            
          // print the type and size of the first FAT-type volume
          long volumesize;
          Serial.print("\nVolume type is FAT");
          Serial.println(volume.fatType(), DEC);
          Serial.println();
         
          volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
          volumesize *= volume.clusterCount();       // we'll have a lot of clusters
          volumesize *= 512;                            // SD card blocks are always 512 bytes
          Serial.print("Volume size (bytes): ");
          Serial.println(volumesize);
          Serial.print("Volume size (Kbytes): ");
          volumesize /= 1024;
          Serial.println(volumesize);
          Serial.print("Volume size (Mbytes): ");
          volumesize /= 1024;
          Serial.println(volumesize);
         
          Serial.println("\nFiles found on the card (name, date and size in bytes): ");
          root.openRoot(volume);
         
          // list all files in the card with date and size
          root.ls(LS_R | LS_DATE | LS_SIZE);
         
          delay(2000);
        
           if (!SD.begin(chipSelect)) {
            Serial.println("initialization failed!");
            //return;
            
          } else {
            Serial.println("SD card initialized");
            myFile = SD.open(sdCardFile.c_str(), FILE_WRITE);    // open file for writing
            if (myFile) {  // if file can be opened, write to it
              Serial.print(sdCardFile + " file opened for writing");
              myFile.close();
            } else {  // if not, show an error
              myFile.println("asdwfkq");
              Serial.println("ERROR: not able to open " + sdCardFile);
              myFile.close();
            }
          }
    
      
      }
     
      
      /* END SD CARD ADAPTOR */
      
    	Wire.begin();//inicjalizacja protokolu I2C
    	TWBR = 24;
    	mpu.initMPU9250();//inicjalizacja akcelerometru-zyroskopu
    	float magCalibration[3];
    	mpu.initAK8963(magCalibration);//inicjalizacja magnetometru
    	if (!bmp.begin()) {
    		Serial.println("10 dof imu hatali - Nie mozna nawiazac polaczenia z czujnikiem cisnienia BMP280!");
    		//while (1);
    	}
    	
      for(int i=0;i<5;i++)
      {
        approxGndPress+=bmp.readPressure();
        delay(1000);
        }
        approxGndPress/=5;
    	switch (doklG)
    	{
    	case 250: GyroScale = 131.0; break;
    	case 500: GyroScale = 65.5; break;
    	case 1000: GyroScale = 32.8; break;
    	case 2000: GyroScale = 16.4; break;
    	default: GyroScale = 131.0; break;
    	}
    	switch (doklA)
    	{
    	case 2: AccelScale = 16384.0; break;
    	case 4: AccelScale = 8192.0; break;
    	case 8: AccelScale = 4096.0; break;
    	case 16: AccelScale = 2048.0; break;
    	default: AccelScale = 16384.0; break;
    	}
    	switch (doklM)
    	{
    	case 6: MagScale=0.6; break;
    	case 15: MagScale=0.15; break;
    	default: MagScale =1; break;
    	}
    Serial.println("10 dof imu sensoru ayarlari yapildi.");
    /* START WIFI */
    
     Serial.println("WİFİ Started");
      Serial3.begin(115200);                                          //ESP8266 ile seri haberleşmeyi başlatıyoruz.
      Serial3.println("AT");                                          //AT komutu ile modül kontrolünü yapıyoruz.
      Serial.println("AT Yollandı");
      int espDenemeSayisi = 0;
      while(!Serial3.find("OK") && espDenemeSayisi < 5){                                     //Modül hazır olana kadar bekliyoruz.
        Serial3.println("AT");
        Serial.println("ESP8266 Bulunamadı."); //TODO HASAN (20 kere dene yoksa diğer kodlara geç)
        espDenemeSayisi++;
      }
    
      if (!(espDenemeSayisi >= 1))
      { 
        Serial.println("OK Komutu Alındı");
        Serial3.println("AT+CWMODE=1");                                 //ESP8266 modülünü client olarak ayarlıyoruz.
        espDenemeSayisi = 0;
        while(!Serial3.find("OK") && espDenemeSayisi < 5){                                     //Ayar yapılana kadar bekliyoruz.
          Serial3.println("AT+CWMODE=1");
          Serial.println("Ayar Yapılıyor....");
          espDenemeSayisi++;
        }
        Serial.println("Client olarak ayarlandı");
        Serial.println("Aga Baglaniliyor...");
        Serial3.println("AT+CWJAP=\""+agAdi+"\",\""+agSifresi+"\"");    //Ağımıza bağlanıyoruz.
        espDenemeSayisi = 0;
        while(!Serial3.find("OK") && espDenemeSayisi < 5)
        {
            espDenemeSayisi++;  
        }
        if (!(espDenemeSayisi >= 1))
        {
          Serial.println("Aga Baglandi.");
          espBuldu = true;
          delay(1000);
        }
        else
        {
          
          //  _reboot_Teensyduino_();       
              
          Serial.println("WIFI ESP ağa bağlanmadı");
        }
        
      }
      else
      {
        Serial.println("WIFI ESP CALISMADI");
      }
      
    /* END WIFI */
    
    
      /* START GPS */
    
    Serial1.begin(9600);
      
      Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
      Serial.println("by Mikal Hart");
      Serial.println();
      Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
      Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
      Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");
    
      
      /* END GPS */
    
    
    
    
      /* START XBEE */
    
      Serial2.begin(9600);
      
      /* END XBEE */
    }
    void loop()
    {
    
      
      /* START GPS */
      
    float flat, flon;
      unsigned long age, date, time, chars = 0;
      unsigned short sentences = 0, failed = 0;
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
      boolean gpsCalisiyorMu = false;
    
    int year;
          byte month, day, hour, minute, second, hundredths;
    
          //ilkZaman = millis();
      while (1)
      {
        if (gpsCalissinMi == false)
        {
          break;
        }
            
          print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
          print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
          gps.f_get_position(&flat, &flon, &age);
          print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
          print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
          print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
        
          /* START GÜN - AY YIL */
           
          //unsigned long age;
          gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
          if (age == TinyGPS::GPS_INVALID_AGE)
            Serial.print("********** ******** ");
          else
          {
            char sz[32];
            sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
                month, day, year, hour, minute, second);
            Serial.print(sz);
          }
          print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
          smartdelay(0);
        /* END GÜN - AY YIL */
          
          print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
          print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
          print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
          print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
          print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
          print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
          print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
        
          gps.stats(&chars, &sentences, &failed);
          print_int(chars, 0xFFFFFFFF, 6);
          print_int(sentences, 0xFFFFFFFF, 10);
          print_int(failed, 0xFFFFFFFF, 9);
          Serial.println();
          
          smartdelay(1000);
    
          if (flat != TinyGPS::GPS_INVALID_F_ANGLE)
          {
            gpsCalisiyorMu = true;
    
            if (ilkYukseklik != 0)
            {
              ilkYukseklik = gps.f_altitude();
            }
          }
    
          if (gpsCalisiyorMu == true)
          {
            break;
          }
    
          sonZaman = millis();
    
          if (sonZaman - ilkZaman >= (1000 * 60 *15))
          {
              gpsCalissinMi = false;
              break;
          }
      }
        
      /* END GPS */
    
    
        double yukseklik = gps.f_altitude();
    
        if (uyduStatusu == 1 && yukseklik - ilkYukseklik >= 200)
        {
           uyduStatusu = 2;
        }
        else if (uyduStatusu == 2 && yukseklik - ilkYukseklik <= 50)
        {
          uyduStatusu = 3;
        }
    
      
      
    /* START 10 DOF İMU */
    
    		mpu.readAccelData(f_accelCount);
        
        for(int i=0;i<3;i++)f_accelCount[i]/=AccelScale; // podziel kazda ze skladowych przyspieszenia przez czynnik skali dla akcelerometru
    
    /*
          Serial.print("\tax "); Serial.print(f_accelCount[0]);
    		Serial.print("\tay "); Serial.print(f_accelCount[1]);
    		Serial.print("\taz "); Serial.print(f_accelCount[2]);
    */
    
        //Serial.print("\t |a| = "); Serial.print(sqrt(sq(f_accelCount[0]) + sq(f_accelCount[1]) + sq(f_accelCount[2])));
        mpu.readGyroData(f_gyroCount);
        for(int i=0;i<3;i++)f_gyroCount[i]/=GyroScale;
    
        Serial.print("\tal_x "); Serial.print(f_gyroCount[0]);
        Serial.print("\tal_y "); Serial.print(f_gyroCount[1]);
        Serial.print("\tal_z "); Serial.print(f_gyroCount[2]);
        
        
    		tempCount = mpu.readTempData();
    		Serial.print("\tT ");
    		Serial.print(tempCount / 100.0);
    		Serial.print(" *C");
    		Serial.print("\tP = ");
    		Serial.print(bmp.readPressure()/100.0);
    		Serial.print(" hPa");
    		Serial.print("\tApprox alt = ");
    		Serial.print(bmp.readAltitude(1019.0)); // wysokość liczona wzgledem cisnienia przy powierzchni
    		Serial.println(" m");
    
    /* END 10 DOF İMU */
    
    /* START WIFI */
    
        if (espBuldu == true)
        {
              Serial3.println("AT+CIPSTART=\"TCP\",\""+ip+"\",80");           //Thingspeak'e bağlanıyoruz.
              if(Serial3.find("Error")){                                      //Bağlantı hatası kontrolü yapıyoruz.
                Serial.println("AT+CIPSTART Error");
               }
      
              String tweet = "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n";
                  tweet+="Host: api.thingspeak.com\n";
                  tweet+="Connection: close\n";
                  tweet+="Content-Type: application/x-www-form-urlencoded\n";
                  tweet+="Content-Length:51\r\n\r\napi_key=";
                  tweet+=String("9E5QX2123KGHVXLB");                             //ThingSpeak'den aldığımız Twitter API KEY'ini buraya yazıyoruz.
                  tweet+=String("&status=");
                  tweet+=String("#helloesp8266 Try 2");                           // Yollamak istediğimiz tweeti buraya yazıyoruz.
              
               Serial3.print("AT+CIPSEND=");                    //veri yollayacağımız zaman bu komutu kullanıyoruz. Bu komut ile önce kaç tane karakter yollayacağımızı söylememiz gerekiyor.
               delay(100);
               Serial3.println(tweet.length());
               
               if(Serial3.find(">")){                           //eğer sunucu ile iletişim sağlayıp komut uzunluğunu gönderebilmişsek ESP modülü bize ">" işareti ile geri dönüyor.
                                                               // arduino da ">" işaretini gördüğü anda sıcaklık verisini esp modülü ile thingspeak sunucusuna yolluyor.
                 Serial3.println(tweet);
                 Serial3.println("AT+CIPCLOSE=0");
                
                 Serial.println(tweet);
                    Serial.println("tweet gonderildi.");
                    
                }
              
                Serial.println("Baglantı Kapatildi.");
                Serial3.println("AT+CIPCLOSE");                                //Bağlantıyı kapatıyoruz
                
    
        }
        
    /* END WIFI */
    
    
      /* START VOLTAJ BOLUCU */
       valueVoltajBolucu = analogRead(analogInput);
       Serial.print("value= ");
    
        Serial.println(valueVoltajBolucu);
        
       vout = (valueVoltajBolucu * 5) / 1024.0; 
       vin = vout / (R2/(R1+R2)); 
       if (vin<0.09) {
          vin=0.0;
        } 
        Serial.print("VOLTAJ Vout= ");
    
        Serial.println(vout);
        
        Serial.print("VOLTAJ Vin= ");
    
        Serial.println(vin);
        
        /* END VOLTAJ BOLUCU */
    
      telemetri = "3431,";
    
    
      if (EEPROM.read(0) != 1)
      {
        paketNo = EEPROM.read(0);
      }
    
      
      
      telemetri += String(paketNo) + ",";
    
      //double vout2 = static_cast<double>(vout);
      //vout2 = 50001.0;
      //String vout3 = String(vout2).substring(0,3);
      //Serial.println(vout3);
      paketNo = paketNo + 1; //paketNo verisindeki değeri 1 arttır.
        telemetri += String(static_cast<int>(day)) + "/" + String(static_cast<int>(month)) + "/" + String(year);
        telemetri += "-" + String(static_cast<int>(hour+3)) + ":" + String(static_cast<int>(minute)) + ":" + String(static_cast<int>(second)) + ",";
        telemetri += String(uyduStatusu) + ",";
        telemetri += String(bmp.readAltitude(1019.0)) + ","; // yükseklik
        telemetri += String(bmp.readPressure()/100.0) + ","; // basınc
        telemetri += String(tempCount / 100.0) + ","; //sıcaklık
        telemetri += String(vin,2) + ","; //pil gerilimi (voltaj bolucu)
        //telemetri += String(f_accelCount[0]) + ","; //yunuslama (ax)
        //telemetri += String(f_accelCount[1]) + ","; //yalpalanma (ay)
        //telemetri += String(f_accelCount[2]) + ","; //yuvarlanma (az)
        telemetri += String(f_gyroCount[0]) + ","; //yunuslama (ax)
        telemetri += String(f_gyroCount[1]) + ","; //yalpalanma (ay)
        telemetri += String(f_gyroCount[2]) + ","; //yuvarlanma (az)
        telemetri += String(flat,7) + ","; //boylam (latitute)
        telemetri += String(flon,7) + ","; //enlem (longitute)
        
        //telemetri += String(gps.altitude()) + ",F:"; //gps yukseklik (altitude cm)
        telemetri += String(gps.f_altitude()); //gps yükseklik
    /*
     * 
     * 
     * 
     * <3431>,<13>,<29/08/2020-12:37:48>, <3>, <153.75>, <101900>,<22.3>,<3.7>,<23.44>,<13.89>,<21.03>,<28.539>,<41.02>,<14.5>
    
    
    < Takım Numarası >, < Paket Numarası >, < Gönderme Zamanı >, < Uydu Statüsü >, <Yükseklik>, <Basınç>, < Sıcaklık >, < Pil Gerilimi >, < Yunuslama >, < Yalpalanma >, <Yuvarlanma >, < GPS Boylam >, < GPS Enlem >, < GPS Yükseklik >
    
    
    
     */
        Serial.println("\ntelemetri verisi:");
        Serial.println(telemetri);
    
    
        /* START SD KART */
       myFile = SD.open(sdCardFile.c_str(), FILE_WRITE);            
                      myFile.println(telemetri);
                      Serial.println("SD Karta kaydedildi. Paket: " + String(paketNo)); //Yazılanları ekstra ekranda görmek için..
    
                      myFile.close();
    
        /* END SD KART */
    
        
        /* START XBEE */
    
      Serial2.println(telemetri);//Ending symbol
    
        EEPROM.write(0, paketNo);
      
      
        /* END XBEE */
    
    
        if (uyduStatusu == 2 || uyduStatusu == 3) //yere indiğinde buzzer ı çalıştır.
        {
          digitalWrite(buzzerPin, HIGH);
          
          digitalWrite(buzzerPin, LOW);
        }    
        else
        {
          delay(400);
        }
        
    
    
        
    }
    
    
    
    /* START GPS FUNCTIONS */
    static void smartdelay(unsigned long ms)
    {
      unsigned long start = millis();
      do 
      {
        while (Serial1.available())
            gps.encode(Serial1.read());
      } while (millis() - start < ms);
    }
    
    static void print_float(float val, float invalid, int len, int prec)
    {
      if (val == invalid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartdelay(0);
    }
    
    static void print_int(unsigned long val, unsigned long invalid, int len)
    {
      char sz[32];
      if (val == invalid)
        strcpy(sz, "*******");
      else
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0) 
        sz[len-1] = ' ';
      Serial.print(sz);
      smartdelay(0); 
    }
    
    static void print_date(TinyGPS &gps)
    {
     
    }
    
    static void print_str(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartdelay(0);
    }
    /* END GPS FUNCTIONS */

  2. #2
    Senior Member
    Join Date
    May 2017
    Posts
    106
    Hello,

    if you use EEPROM.write or EEPROM.read you access just one byte of storage.
    To store variables (strings) independent of size use EEPROM.get and EEPROM.put instead.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •