Arduino pause and resume commands and saving data into a matrix."

I want to save the data from the x, y, and z axes of an ADXL345 sensor in the Arduino IDE into a matrix in 2-second intervals every 5 minutes. Later, I intend to send this matrix to Firebase Realtime Database. However, I haven't figured out how to implement the 5-minute pause and 2-second resume intervals yet. Additionally, I am not sure how to use a matrix

"I tried something like the following, but the result didn't turn out as expected. The process continues without stopping."

void loop() {
  static unsigned long previousMillis = 0;
  static unsigned long interval = 2000; // 2 saniye çalışma aralığı
  static unsigned int loopCount = 0;

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis < interval) {
    // İşlemler buraya
    sensors_event_t event; 
    accel.getEvent(&event);
    Serial.print("X: "); Serial.print(event.acceleration.x); Serial.print("  ");
    Serial.print("Y: "); Serial.print(event.acceleration.y); Serial.print("  ");
    Serial.print("Z: "); Serial.print(event.acceleration.z); Serial.print("  "); Serial.println("m/s^2 ");
    loopCount++;
  } else if (currentMillis - previousMillis >= interval) {
    // Belirli süre boyunca hiçbir şey yapma
    Serial.print("Döngü Sayısı Saniyede: ");
    Serial.println(loopCount);

    // Sıfırla ve bir sonraki bekleme süresini ayarla
    loopCount = 0;
    previousMillis = currentMillis;
    interval = 60000; // 1 dakika bekleme süresi
  }
}

Welcome to the forum

You started a topic in the Uncategorised category of the forum whose description is

:warning: DO NOT CREATE TOPICS IN THIS CATEGORY :warning:

Your topic has been moved to a more relevant category

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

Please post your full sketch

won't resetting previousMillisin the 2nd condition immediately re-enable the 1st condition?

I apologize, I didn't fully understand. What do I need to do to comprehend the issue?

you want the processing to stop after 2 seconds

but you immediately reset previousMillis when it has

I understand my mistake, but unfortunately, I couldn't manage to fix it. Can you help me?

Please describe what that section of code should do

2 second-interval means save data every two seconds?

0:00 save data
0:02 save data
0:04 save data
0:06 save data
....
how long shall this once every 2 seconds go on?
because you wrote

You should post an example that shows how the data shall be saved over time.

Deleted

I apologize if I may have expressed it incorrectly.

0.00 - 0.02: Save data
0.02 - 5.02: Pause
5.02 - 5.04: Save the data
...
...
:
:
:
:
:

seems that you need a 2nd 5 minute timer that re-enables the 2 second capture

I am not sure if you really want to save data for 2 seconds as fast as possible.
This might be a lot of data.

Here is a WOKWI-simulation of such a code
It uses non-blocking timing based on function millis()

Here is a demo-code that works as you described it

// demo-Code non-blocking timing 2 seconds active 5 minutes pausing
// https://wokwi.com/projects/385183690731707393
// https://forum.arduino.cc/t/arduino-pause-and-resume-commands-and-saving-data-into-a-matrix/1203804/11

unsigned long dataSavingStarted;
unsigned long saveDataInterval = 2000UL;          // save data for 2 seconds long

unsigned long myPausingTimer = 0;                 // Timer-variables MUST be of type unsigned long
unsigned long pausingInterval  = 5 * 60 * 1000UL; // pause 5 minutes
unsigned long pausingStarted;
boolean SaveDataActiveMode;

const byte    OnBoard_LED = 13;

byte ledState = LOW;

void setup() {
  Serial.begin(115200);
  Serial.println("Setup-Start");
  pinMode(OnBoard_LED, OUTPUT);
  SaveDataActiveMode = true;
  dataSavingStarted = millis();
}


void loop() {
  blinkOnBoardLED();

  if ( SaveDataActiveMode == true) {
    SaveDataFor2Seconds(); 

    // check if more than 2 seconds have passed by
    if ( millis() - dataSavingStarted >= saveDataInterval) {
      SaveDataActiveMode = false;
      pausingStarted = millis();
    }
  }
  else { // the pausing is "active"
    printPausingCountDown();
    if (millis() - pausingStarted >= pausingInterval) {
      dataSavingStarted = millis();
      SaveDataActiveMode = true;
    }
  }
}

void SaveDataFor2Seconds() {

  static unsigned long delayPrinTtimer;

  if ( TimePeriodIsOver(delayPrinTtimer, 500) ) {
    Serial.println("Saving Data");
  }
}


void printPausingCountDown() {
  static unsigned long delayPrinTtimer;
  static unsigned long timeLeftPausing;

  timeLeftPausing = (pausingInterval -  (millis() - pausingStarted) ) / 1000;
  if ( TimePeriodIsOver(delayPrinTtimer, 2000) ) {
    Serial.print("Pausing goes on for ");
    Serial.print(timeLeftPausing);
    Serial.println(" seconds");
  }
}


void blinkOnBoardLED() {
  static unsigned long myBlinkTimer;

  if ( TimePeriodIsOver(myBlinkTimer, 500) ) {
    // when REALLY 500 milliseconds have passed by
    if (ledState == LOW) {
      ledState = HIGH; // change to HIGH
    }
    else {            // ledState is HIGH
      ledState = LOW; // change to LOW
    }

    digitalWrite(OnBoard_LED, ledState);
  }
}

// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}

best regards Stefan

Thank you Stefan. I solve the problem different way. Here is the code

void loop() {
  static unsigned long previousMillis = 0;
  static unsigned long intervalRun1 = 2000;     // 2 saniye çalışma aralığı
  static unsigned long intervalWait1 = 60000;   // 1 dakika bekleme süresi

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis < intervalRun1) {
    // İlk durum: 0 saniye - 2 saniye aralığı
    sensors_event_t event; 
    accel.getEvent(&event);
    Serial.print("X: "); Serial.print(event.acceleration.x); Serial.print("  ");
    Serial.print("Y: "); Serial.print(event.acceleration.y); Serial.print("  ");
    Serial.print("Z: "); Serial.print(event.acceleration.z); Serial.print("  "); Serial.println("m/s^2 ");
  } else if (currentMillis - previousMillis < intervalRun1 + intervalWait1) {
    // İkinci durum: 2 saniye - (2 saniye + 1 dakika) aralığı
    // Poogram beklemede
  } else {
    // Üçüncü durum: 2 saniye + 1 dakika sonrası
    previousMillis = currentMillis;  // Bir sonraki çalışma süresini ayarla
  }
}
1 Like

@faruk_7586 Why did you start a second topic on the same subject ?

We are currently working on a project using ADXL 345 to measure vibrations. In our project, we use the NodeMcu Esp 8266 development board. We want the system to work as follows: run for 2 seconds, send the collected data to Firebase Realtime Database, pause for 1 minute, and then run for another 2 seconds. I wrote a code to test this loop, and I can print the data to the serial monitor with a 1-minute break. However, despite setting the sampling rate of ADXL 345 to 3200Hz in my code, I can only print 320 data points per second on the serial monitor. Can you help me find the error in my code?

#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
#include <ESP8266WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// Veritabanına düzgün bağlanmak için gerekli olan ilaveler
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"

// Ağ bilgileri
#define WIFI_SSID "ROKKET"
#define WIFI_PASSWORD "faruk7070"

// Firebase proje API Key
#define API_KEY "AIzaSyCjqHBvbPTRVjYpm6wPwP7itvUHsgYvHrQ"

// Veritabanı URL
#define DATABASE_URL "https://vibration-analysis-7f893-default-rtdb.firebaseio.com/"

// Firebase veri objesi
FirebaseData fbdo;
// Yetki ve ayar nesneleri
FirebaseAuth auth;
FirebaseConfig config;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define OLED_RESET -1

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);


// ADXL345 örnek
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

void displaySensorDetails(void)
{
  sensor_t sensor;
  accel.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" m/s^2");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" m/s^2");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" m/s^2");  
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void displayDataRate(void)
{
  Serial.print  ("Data Rate:    "); 
  
  switch(accel.getDataRate())
  {
    case ADXL345_DATARATE_3200_HZ:
      Serial.print  ("3200 "); 
      break;
    case ADXL345_DATARATE_1600_HZ:
      Serial.print  ("1600 "); 
      break;
    case ADXL345_DATARATE_800_HZ:
      Serial.print  ("800 "); 
      break;
    case ADXL345_DATARATE_400_HZ:
      Serial.print  ("400 "); 
      break;
    case ADXL345_DATARATE_200_HZ:
      Serial.print  ("200 "); 
      break;
    case ADXL345_DATARATE_100_HZ:
      Serial.print  ("100 "); 
      break;
    case ADXL345_DATARATE_50_HZ:
      Serial.print  ("50 "); 
      break;
    case ADXL345_DATARATE_25_HZ:
      Serial.print  ("25 "); 
      break;
    case ADXL345_DATARATE_12_5_HZ:
      Serial.print  ("12.5 "); 
      break;
    case ADXL345_DATARATE_6_25HZ:
      Serial.print  ("6.25 "); 
      break;
    case ADXL345_DATARATE_3_13_HZ:
      Serial.print  ("3.13 "); 
      break;
    case ADXL345_DATARATE_1_56_HZ:
      Serial.print  ("1.56 "); 
      break;
    case ADXL345_DATARATE_0_78_HZ:
      Serial.print  ("0.78 "); 
      break;
    case ADXL345_DATARATE_0_39_HZ:
      Serial.print  ("0.39 "); 
      break;
    case ADXL345_DATARATE_0_20_HZ:
      Serial.print  ("0.20 "); 
      break;
    case ADXL345_DATARATE_0_10_HZ:
      Serial.print  ("0.10 "); 
      break;
    default:
      Serial.print  ("???? "); 
      break;
  }  
  Serial.println(" Hz");  
}

void displayRange(void)
{
  Serial.print  ("Range:         +/- "); 
  
  switch(accel.getRange())
  {
    case ADXL345_RANGE_16_G:
      Serial.print  ("16 "); 
      break;
    case ADXL345_RANGE_8_G:
      Serial.print  ("8 "); 
      break;
    case ADXL345_RANGE_4_G:
      Serial.print  ("4 "); 
      break;
    case ADXL345_RANGE_2_G:
      Serial.print  ("2 "); 
      break;
    default:
      Serial.print  ("?? "); 
      break;
  }  
  Serial.println(" g");  
}

void setup(void) 
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif
  Serial.begin(115200);
  Serial.println("Accelerometer Test"); Serial.println("");

  // WiFi bağlantısı
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Ağa bağlanıyor");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Bağlandı. IP Adresi: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  // Firebase ayarları
  config.api_key = API_KEY;
  config.database_url = DATABASE_URL;

  // Giriş yapma
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("Firebase'e giriş yapıldı");
  } else {
    Serial.printf("Firebase giriş hatası: %s\n", config.signer.signupError.message.c_str());
  }

  // Firebase bağlantısı başlatma
  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);

  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }

  /* Set the range to whatever is appropriate for your project */
  accel.setRange(ADXL345_RANGE_16_G);
  
  /* Set the data rate to 100 Hz */
  accel.setDataRate(ADXL345_DATARATE_3200_HZ);

  /* Display some basic information on this sensor */
  displaySensorDetails();
  
  /* Display additional settings (outside the scope of sensor_t) */
  displayDataRate();
  displayRange();
  Serial.println("");
}


void loop() {
  static unsigned long previousMillis = 0;
  static unsigned long intervalRun1 = 2000;     // 2 saniye çalışma aralığı
  static unsigned long intervalWait1 = 60000;   // 1 dakika bekleme süresi

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis < intervalRun1) {
    // İlk durum: 0 saniye - 2 saniye aralığı
    sensors_event_t event; 
    accel.getEvent(&event);
    Serial.print("X: "); Serial.print(event.acceleration.x); Serial.print("  ");
    Serial.print("Y: "); Serial.print(event.acceleration.y); Serial.print("  ");
    Serial.print("Z: "); Serial.print(event.acceleration.z); Serial.print("  "); Serial.println("m/s^2 ");
  } else if (currentMillis - previousMillis < intervalRun1 + intervalWait1) {
    // İkinci durum: 2 saniye - (2 saniye + 1 dakika) aralığı
    // Poogram beklemede
  } else {
    // Üçüncü durum: 2 saniye + 1 dakika sonrası
    previousMillis = currentMillis;  // Bir sonraki çalışma süresini ayarla
  }
}
kodu buraya yazın veya yapıştırın

try a higher bit rate than 115200?

Let me change my question to this: I can never print 3200 data on the Serail Monitor. However, if I send the data to any database or SD card without printing it to the serial monitor. Can I send 3200 data per second?

This depends on how many bytes each "data" is.

You will have to specify how many bytes this are.
How fast this will be transmitted depends on the interface.
If you use WiFi it will depend on the actual bitrate which depends on the WiFi-signal strength.

As you record 6400 datapoints and then pause a minute
you could collect all the data into a big array. And send it after finishing the collecting. As you have almost a minute the bytes per second can be rather slow

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.