Measure PWM width

Hello, I am trying to read the time when a push button is pressed by using micro () function and the to use delay function for commanding a motor.

I need help because it is not possible to have a good accuracy. Any idea? Thanks

// set pin numbers:
int start_button = 1; // the number of the pushbutton pin
int pump = 2; // the number of the LED pin
int time_button = 0; // the time captured pin

//unsigned long time = 0;
int start;

volatile unsigned long injTime1; //Time of front raising
volatile unsigned long injTime2; //Time of front falling
unsigned long injTime = 0;

void setup() {
// initialize the LED pin as an output:
pinMode(pump, OUTPUT);
pinMode(start_button, INPUT);
pinMode(time_button, INPUT);

digitalWrite (pump, LOW); //Pull-up pin - as our injector is driven by connecting it to ground, i suppose i need to pull-up pin to get it's value as 1 when injector is turned off
attachInterrupt(0, measure, CHANGE); //interrupt on raising front
}

void loop() {

// read the state of the pushbutton value:
start = digitalRead(start_button);

if (start == HIGH) {
digitalWrite (pump, HIGH);
delay (injTime);
digitalWrite (pump, LOW);
}
else {
digitalWrite (pump, LOW);
}
}

void measure()
{
if ( digitalRead(time_button) == HIGH ) //Or i need to digitalRead it first? YES.[/glow]
{
injTime = 0;
injTime1 = micros(); //get time of pulse going down
}
else
{
injTime2 = micros(); //get time of pulse going up
injTime = injTime2 - injTime1; //measure time between down and up
injTime = injTime /4;
injTime= injTime / 1024;
}

}

  1. Code tags - you can go back and edit them in…

  2. You attach the interrupt to channel 0, which is triggered by pin 2, yet
    you read pin 0 (which has no interrupt) in the ISR (time_button)

  3. Logic inverted in the ISR?

void measure()
{
  if ( digitalRead(time_button) == HIGH ) //Or i need to digitalRead it first? YES.[/glow]
 {
  injTime = 0;
  injTime1 = micros(); //get time of pulse going down <<<< NO, ITS HIGH, ITS GONE UP
 }
 else
 {
  injTime2 = micros();  //get time of pulse going up <<<< DOWN!
  injTime = injTime2 - injTime1;  //measure time between down and up  <<< UP then DOWN
  injTime = injTime /4;
  injTime=  injTime / 1024;
 }
 
 }
  1. You don’t declare every variable used by measure() as volatile, only some of them
  1. You don't declare every variable used by measure() as volatile, only some of them

Only those variables that are used in the interrupt handler AND in other functions needs to be volatile. The ISR know that is has revised variables. The other functions do not, unless the variables are volatile.