Reading indutive sensors

Hi Guys,
I already read values of 6 indutive sensors, but now i want to write it to a data string.
I could do this by hand but want to do it in a for cycle, but i cant :slight_smile:

I done this for what i want:

// Display valores para cada sensor
  for (int i = 1;  i < 7;  i++)
  {
  int counterValue = counterValue[i];

  dataString += String(counterValue);

      if (i < 7) {

  //        Serial.println(counterValue[i]);
  //        Serial.println(counterValue);
          Serial.println("Passei aqui");
          delay(1000);

      dataString += ",";
 
    }
  } 

  dataFile.flush();

Just want that for every cycle the value of counterValue be : counterValue1, counterValue2 etc...
Thats where my variables are stored from sensors :slight_smile:

I got this error in compilation:
imagem

I can only guess at the surrounding code, but this fresh declaration of counterValue is masking any counterValue declaration in any wider scope:

1 Like

Hi,
Thanks for fast response,
You mean is global declared before? Is not :slight_smile:

Well, it it isn't ever declared an array in the invisible source code with something like:

 int counterValue[VALUES];

...then any use of counterArray[i]counterVallue[i] is doomed to failure.

1 Like

Monday will post entire code :slight_smile:
I´m was just trying and error this afternoon.

I got declared and with values counterValue1,2,3,4,5,6. That are values of number of passes in a inductive sensor.

Just want a solution that can increase this in auto and post it in my datastring for saving in my SDCARD. I can manually do that, just want a fancy way.

Just want that this be:

for (int i = 1;  i < 7;  i++)
  {
  int counterValue = counterValue1; //after other cycle counterValue2...6 and put it in my dataString

  dataString += String(counterValue);

Instead of doing this manually in code:

dataString += String(counterValue1);
dataString += ",";
dataString += String(counterValue2);
dataString += ",";
dataString += String(counterValue3);

etc...
    

Really thanks

Hi again @DaveX ,

Just done what you suggest, but still not got what i want. :slight_smile:

I use this time this:


 int counterValue[]{1, 2, 3, 4, 5, 6, 7}; // an array of indutive sensores that are attached
 int number_indutive_sensors = 7;
 
 // Display valores para cada sensor
  for (int i = 1;  i < number_indutive_sensors;  i++)
  {
    int Value = counterValue[i];
     
      dataString += String(Value);
      if (i < number_indutive_sensors) {
       //  Serial.println(Value); 
         Serial.println(counterValue[i]); 
         Serial.println("Passei aqui"); 
        // delay(3000);
      dataString += ",";
    } 
  }  

But I´m getting this:
imagem

Instead of this, that is the inductive counter values of the variables counterValue1, 2, 3, 4, 5, 6,7.:

imagem

For this i use this code:

//Gravar valores Sensores para datastring
  dataString += String(counterValue1);
  dataString += String(",");
  dataString += String(counterValue2);
  dataString += String(",");
  dataString += String(counterValue3);
  dataString += String(",");
  dataString += String(counterValue4);
  dataString += String(",");
  dataString += String(counterValue5);
  dataString += String(",");
  dataString += String(counterValue6);
  dataString += String(",");
  dataString += String(counterValue7);
  dataString += String(",");

The Full code is here:

/*********************************************
 *       *
 *********************************************
 */

//Bibliotecas Usadas
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"

RTC_DS1307 rtc;
char daysOfTheWeek[7][12] = {"Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"};

// Não posso usar os pins 11,12,13 e 10 porque são usados para o SD CARD
/*
 The circuit:
    SD card attached to SPI bus as follows:
 ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
 ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
 ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
 ** CS - depends on your SD card shield or module.  (chipSelect = 10; //specific to Arduino UNO)
*/

const int chipSelect = 10; //specific to Arduino UNO

File dataFile;


/* Two independant timed evenets */
const unsigned long eventTime_1_Leitura_Sensores =  50; // intervalo in ms
const unsigned long eventTime_2_Escrever_SD_Card =  5000;
unsigned long previousTime_1 = 0;
unsigned long previousTime_2 = 0;


void file_handling()
{
  dataFile.println("");
  dataFile.println("*******Início Captura Sensores Indutivos *******"); //Dar espaço começar novo file!!
//  dataFile.println("UIDI - Laboratório Software Confiável -> Hello World :) ");
//  dataFile.println("Legenda:Data,Dia,Hora,Valores sensores");

}

const byte Pin2 = 2;  // Arduino pin connected to Sensor Proximidade 1
const byte Pin3 = 3;  // Arduino pin connected to Sensor Proximidade 2
const byte Pin4 = 4;  // Arduino pin connected to Sensor Proximidade 3
const byte Pin5 = 5;  // Arduino pin connected to Sensor Proximidade 4
const byte Pin6 = 6;  // Arduino pin connected to Sensor Proximidade 5
const byte Pin7 = 7;  // Arduino pin connected to Sensor Proximidade 6
const byte Pin8 = 8;  // Arduino pin connected to Sensor Proximidade 7

int ledpin = 9; // Output display LED -  pin for lighting quando cada sensor for detetado individualmente

// Estados para Rising e FallingEdge
//Sensor1
int sensorValue1 = 0;
int prevsensorValue1 = 1;
int counterValue1 = 0;
//Sensor2
int sensorValue2 = 0;
int prevsensorValue2 = 1;
int counterValue2 = 0;
//Sensor3
int sensorValue3 = 0;
int prevsensorValue3 = 1;
int counterValue3 = 0;
//Sensor4
int sensorValue4 = 0;
int prevsensorValue4 = 1;
int counterValue4 = 0;
//Sensor5
int sensorValue5 = 0;
int prevsensorValue5 = 1;
int counterValue5 = 0;
//Sensor6
int sensorValue6 = 0;
int prevsensorValue6 = 1;
int counterValue6 = 0;
//Sensor7
int sensorValue7 = 0;
int prevsensorValue7 = 1;
int counterValue7 = 0;


void sdcard_handling()
{

//Código SD Card
  Serial.print("Inicializando SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(chipSelect, OUTPUT);

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1) ;
  }
  Serial.println("Cartão Inicializado.");

  // Open up the file we're going to log to!
  dataFile = SD.open("datalog.txt", FILE_WRITE);
  Serial.println("File opened ok");
  //dataFile.println("UIDI - Laboratório Software Confiável -> Hello World :) ");
  file_handling();
  
  // will create the file if it doesn't exist
  if (! dataFile) {
    Serial.println("error opening datalog.txt");
    // Wait forever since we can't write data
    while (1) ;
  } 
 
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1); // Wait forever since we can't log timestamp
  } 
}


void setup()
{
  
  Serial.begin(9600);    // Iniciar porta Serial 
  
  pinMode(ledpin, OUTPUT);   //Definir Pino led  arduino como saída  
  pinMode(Pin2, INPUT);  //Definir Pin2 Como entrada Sensor Proximidade Fluxo 1
  pinMode(Pin3, INPUT);  //Definir Pin3 Como entrada Sensor Proximidade Fluxo 2
  pinMode(Pin4, INPUT);  //Definir Pin4 Como entrada Sensor Proximidade Fluxo 3
  pinMode(Pin5, INPUT);  //Definir Pin5 Como entrada Sensor Proximidade Fluxo 4
  pinMode(Pin6, INPUT);  //Definir Pin6 Como entrada Sensor Proximidade Fluxo 5
  pinMode(Pin7, INPUT);  //Definir Pin7 Como entrada Sensor Proximidade Fluxo 6
  pinMode(Pin8, INPUT);  //Definir Pin8 Como entrada Sensor Proximidade Fluxo 7

  sdcard_handling();
  
  Serial.print("UIDI - Laboratório Software Confiável :) Dispositivos Configurados");
  

}

void ler_sensor_1()
{

// Lógica para sensores
// HIGH -> Sensor Indutivo  Sem Contato Metálico
// LOW  -> Sensor Indutivo  Com Contato Metálico

sensorValue1 = digitalRead(Pin2);
   
//Lógica sensor 1 Deteção Rising e Falling Edge       
 if(sensorValue1 != prevsensorValue1) { 
      //Serial.println("Estado Mudou para:"); 
      //Serial.println(sensorValue1);
     if(sensorValue1 == LOW){
       //Serial.println("Rising edge!");
      // Serial.println("Objecto Detetado No sensor Proximidade 1");
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue1++;
        Serial.print("Nº Objectos Detetados No sensor Proximidade 1: "); Serial.println(counterValue1);
       //prevsensorValue1 = sensorValue1;
       //Serial.println(prevsensorValue1);
       // Serial.print("\n");   //Nova linha espaçada para porta Serial Print
    }
    if(sensorValue1 == HIGH){
     //Serial.println("Falling edge!");
      digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue1 = sensorValue1;
//Fim Lógica sensor 1 Deteção Rising e Falling Edge   

}

void ler_sensor_2()
{

// Lógica para sensores
// HIGH -> Sensor Indutivo  Sem Contato Metálico
// LOW  -> Sensor Indutivo  Com Contato Metálico

sensorValue2 = digitalRead(Pin3);
   
//Lógica sensor 2 Deteção Rising e Falling Edge       
 if(sensorValue2 != prevsensorValue2) { 
       if(sensorValue2 == LOW){
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue2++;
    //  Serial.print("Nº Objectos Detetados No sensor Proximidade 2: "); Serial.println(counterValue2);
         }
    if(sensorValue2 == HIGH){
    digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue2 = sensorValue2;
//Fim Lógica sensor 2 Deteção Rising e Falling Edge   

}

void ler_sensor_3()
{

// Lógica para sensores
// HIGH -> Sensor Indutivo  Sem Contato Metálico
// LOW  -> Sensor Indutivo  Com Contato Metálico

sensorValue3 = digitalRead(Pin4);
   
//Lógica sensor 3 Deteção Rising e Falling Edge       
 if(sensorValue3 != prevsensorValue3) { 
       if(sensorValue3 == LOW){
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue3++;
    //  Serial.print("Nº Objectos Detetados No sensor Proximidade 3: "); Serial.println(counterValue3);
         }
    if(sensorValue3 == HIGH){
    digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue3 = sensorValue3;
//Fim Lógica sensor 3 Deteção Rising e Falling Edge   

}

void ler_sensor_4()
{

// Lógica para sensores
// HIGH -> Sensor Indutivo  Sem Contato Metálico
// LOW  -> Sensor Indutivo  Com Contato Metálico

sensorValue4 = digitalRead(Pin5);
   
//Lógica sensor 4 Deteção Rising e Falling Edge       
 if(sensorValue4 != prevsensorValue4) { 
       if(sensorValue4 == LOW){
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue4++;
    //   Serial.print("Nº Objectos Detetados No sensor Proximidade 4: "); Serial.println(counterValue4);
         }
    if(sensorValue4 == HIGH){
    digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue4 = sensorValue4;
//Fim Lógica sensor 4 Deteção Rising e Falling Edge   

}

void ler_sensor_5()
{
sensorValue5 = digitalRead(Pin6);
   
//Lógica sensor 5 Deteção Rising e Falling Edge       
 if(sensorValue5 != prevsensorValue5) { 
       if(sensorValue5 == LOW){
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue5++;
    //   Serial.print("Nº Objectos Detetados No sensor Proximidade 5: "); Serial.println(counterValue5);
         }
    if(sensorValue5 == HIGH){
    digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue5 = sensorValue5;
//Fim Lógica sensor 5 Deteção Rising e Falling Edge   

} 


void ler_sensor_6()
{
sensorValue6 = digitalRead(Pin7);
   
//Lógica sensor 6 Deteção Rising e Falling Edge       
 if(sensorValue6 != prevsensorValue6) { 
       if(sensorValue6 == LOW){
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue6++;
    //   Serial.print("Nº Objectos Detetados No sensor Proximidade 6: "); Serial.println(counterValue6);
         }
    if(sensorValue6 == HIGH){
    digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue6 = sensorValue6;
//Fim Lógica sensor 6 Deteção Rising e Falling Edge   

} 

void ler_sensor_7()
{
sensorValue7 = digitalRead(Pin8);
   
//Lógica sensor 7 Deteção Rising e Falling Edge       
 if(sensorValue7 != prevsensorValue7) { 
       if(sensorValue7 == LOW){
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue7++;
  //     Serial.print("Nº Objectos Detetados No sensor Proximidade 7: "); Serial.println(counterValue7);
         }
    if(sensorValue7 == HIGH){
    digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue7 = sensorValue7;
//Fim Lógica sensor 7 Deteção Rising e Falling Edge   

} 

void Escrever_sd_card()
{
DateTime now = rtc.now();

  // make a string for assembling the data to log:
  String dataString = "";
  
  /*
  if  (sensorValue1 == LOW) {
       dataString += String("Sens1_OK");
    }
  else {
    dataString += String("Sens1_NOK");
  } */

  //dataString += String(",");
  dataString += String("(");
  dataString += String(daysOfTheWeek[now.dayOfTheWeek()]);
  dataString += String(")");
  dataString += String(",");
  dataString += String(now.day(), DEC);
  dataString += String('/');
  dataString += String(now.month(), DEC);
  dataString += String('/');
  dataString += String(now.year(), DEC);
  dataString += String(" ");
  //dataString += String(",");*/
  dataString += String(now.hour(), DEC);
  dataString += String(':');
  dataString += String(now.minute(), DEC);
  dataString += String(':');
  dataString += String(now.second(), DEC);
  //dataString += String(" ");
  dataString += String(",");

  //Gravar valores Sensores para datastring
  dataString += String(counterValue1);
  dataString += String(",");
  dataString += String(counterValue2);
  dataString += String(",");
  dataString += String(counterValue3);
  dataString += String(",");
  dataString += String(counterValue4);
  dataString += String(",");
  dataString += String(counterValue5);
  dataString += String(",");
  dataString += String(counterValue6);
  dataString += String(",");
  dataString += String(counterValue7);
  dataString += String(",");
  
  

  /*
 int counterValue[]{1, 2, 3, 4, 5, 6, 7}; // an array of indutive sensores that are attached
 int number_indutive_sensors = 7;
 
 // Display valores para cada sensor
  for (int i = 1;  i < number_indutive_sensors;  i++)
  {
    int Value = counterValue[i];
     
      dataString += String(Value);
      if (i < number_indutive_sensors) {
       //  Serial.println(Value); 
         Serial.println(counterValue[i]); 
         Serial.println("Passei aqui"); 
        // delay(3000);
      dataString += ",";
    } 
  }  

*/
  dataFile.println(dataString);  


  // The following line will 'save' the file to the SD card after every
  // line of data - this will use more power and slow down how much data
  // you can read but it's safer!
  // If you want to speed up the system, remove the call to flush() and it
  // will save the file only every 512 bytes - every time a sector on the
  // SD card is filled with data.

  dataFile.flush();

  // print our dataString to the serial port too:
  Serial.println(dataString);
  
}

void loop()
{

/* Updates frequently */
unsigned long currentTime = millis();

/* This is event 1 stuff */
if( currentTime - previousTime_1 >= eventTime_1_Leitura_Sensores ){
 // Serial.print ("Teste Rotina 1: ");
   ler_sensor_1();
   ler_sensor_2();
   ler_sensor_3();
   ler_sensor_4();
   ler_sensor_5();
   ler_sensor_6();
   ler_sensor_7();
  //Serial.println(counterValue1);
    
  /* Update the timing for the next event */
  previousTime_1 = currentTime;

}


/* This is my event_2 */
  if ( currentTime - previousTime_2 >= eventTime_2_Escrever_SD_Card) {
    //Serial.println("Teste SDCARD Write: ");
    Escrever_sd_card();
    //Serial.println(counterValue1);
    /* Update the timing for the next event*/
    previousTime_2 = currentTime;
  }

//delay(1000); //Frequencia Amostragem Sinal

}

Other strange Behaviour is if i use a lot of serial.print functions in my read functions i start getting some strange behaviors in sdcard writing like this:

imagem

Just can handle some serialprints. For example can handle between sensor 1-4 but if i uncomment the
Serial.print("Nº Objectos Detetados No sensor Proximidade 5: "); Serial.println(counterValue5); got the behavior reported :slight_smile: or if i uncomment a lot of serialprint untill a limit i got this!!

Have arduino some kind of limitation on this topic?

Im getting a warning of low memory too:

Im thinking of buying the new giga Arduino GIGA R1 WiFi to start in IOT things and have more pins.

Real Thanks and Best Regards

Ah, these individual counterValueN variables:

are completely different variables from this counterValue[] array variable:

Array variables are very nice for dealing with sets of values like this with loops, but you'd need to use something like these:

 counterValue[0] = counterValue1;
 counterValue[1] = counterValue2;
 counterValue[2] = counterValue3;
 counterValue[3] = counterValue4;
 counterValue[4] = counterValue5;
 counterValue[5] = counterValue6;
 counterValue[6] = counterValue7;

...or something like this completely untested snippet of code with the associated Pin[], sensorValue[], prevsensorValue[], etc., array variables.

void ler_sensor_n(int n)
{

// Lógica para sensores
// HIGH -> Sensor Indutivo  Sem Contato Metálico
// LOW  -> Sensor Indutivo  Com Contato Metálico

sensorValue[n] = digitalRead(Pin[n]);
   
//Lógica sensor n Deteção Rising e Falling Edge       
 if(sensorValue[n] != prevsensorValue[n]) { 
      //Serial.println("Estado Mudou para:"); 
      //Serial.println(sensorValue1);
     if(sensorValue[n] == LOW){
       //Serial.println("Rising edge!");
      // Serial.println("Objecto Detetado No sensor Proximidade 1");
       digitalWrite(ledpin, HIGH);
       // increase the counter
       counterValue[n]++;
        Serial.print("Nº Objectos Detetados No sensor Proximidade 1: "); Serial.println(counterValue[n]);
       //prevsensorValue[n] = sensorValue[n];
       //Serial.println(prevsensorValue[n]);
       // Serial.print("\n");   //Nova linha espaçada para porta Serial Print
    }
    if(sensorValue[n] == HIGH){
     //Serial.println("Falling edge!");
      digitalWrite(ledpin, LOW);
    }
  }
  // save the previous button state for the next loop
  prevsensorValue[n] = sensorValue[n];
//Fim Lógica sensor N Deteção Rising e Falling Edge   
}

...
  for(int ii =0; ii<7; ++i){
    ler_sensor_n(ii);  // ler todos los sensores
  }
...

...et cetera.

Arrays start at index 0 and you skip the first value because you start at 1.

1 Like

Thanks for kind help guys

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