arduinoarduino-unopulsecpu-cycles

CPU cycles in Arduino uno for Digital read and counting pulses


I'm trying to count number of HB100 microwave sensor pulses in 200ms time quanta.

Here is the code:

#include <SoftwareSerial.h>
#include <elapsedMillis.h>
elapsedMillis ElapsedTime;

#define Sensor A0
#define TimeQuanta 200

int Counter = 0;
boolean LastState;

void setup()
{
  Serial.begin(250000);
  pinMode(Sensor, INPUT);  
}

void loop()
{
  Counter = 0;
  ElapsedTime = 0;
  while (ElapsedTime < TimeQuanta ){
    LastState = digitalRead(Sensor);
    if (LastState == LOW && digitalRead(Sensor) == HIGH ){
      Counter += 1;  //Compare Last state with current state 
    }
  }
  Serial.print(digitalRead(Sensor));
  Serial.print("\t");
  Serial.println(Counter);
}

I need to know the digital read cycles. I'm comparing the last state of the sensor with current state and if a change is made (LOW TO HIGH) the counter is incremented. However, my counter is always 0!

Here is the Logic Analyzer output of Microwave Sensor:

enter image description here


Edit: if I add delay(1); before if then the counter is not 0 anymore.


Solution

  • You can use timer1 to calculate the elapsed time.

    // Set Timer1 without prescaler at CPU frequency
    TCCR1A = 0; // TCCRx - Timer/Counter Control Register. The pre-scaler can be configured here. 
    TCCR1B = 1;
    
    noInterrupts ();  // Disable interrupts.
    
    uint16_t  StartTime = TCNT1;  // TCNTx - Timer/Counter Register. The actual timer value is stored here.
    digitalRead(pin); // your code.
    uint16_t EndTime = TCNT1
    uint16_t ElapsedTime = EndTime - StartTime;
    
    interrupts (); //Enable interrupts.
    

    As a second solution you can set and unset a pin and calculate the time with your Logic Analyzer.

    DDRD = DDRD | B10000000; // Set digital pin 7 as output.
    PORTD = PORTD | B10000000; // Set digital pin 7.
    digitalRead(pin); // your code.
    PORTD = PORTD & B01111111; // Unset digital pin 7.