Problem using Arduino pulsein function

Thread Starter

AlbertHall

Joined Jun 4, 2014
12,624
I am using a nano.
The input signal is connected to A5. It is an MSF time data signal - high pulses 100ms, 200ms, etc.
This is the code I am using with pulsein.

Code:
#define pulse_ip A5

uint16_t pulsetime;

void setup() {
  Serial.begin(9600);
  pinMode(pulse_ip, INPUT);
}

void loop() {
  pulsetime = pulseIn(pulse_ip, HIGH, 1500000ul);

  if (pulsetime > 1000000) {
    Serial.print(pulsetime / 1000000);
    Serial.println("s");
  } else if (pulsetime > 1000) {
    Serial.print(pulsetime / 1000);
    Serial.println("ms");
  } else {
    Serial.print(pulsetime);
    Serial.println("us");
  }
  //delay(1);
}
This is the result in the serial monitor - 40ms to 60ms:
12:40:31.165 -> 43ms
12:40:32.182 -> 42ms
12:40:33.174 -> 44ms
12:40:34.224 -> 56ms
12:40:35.226 -> 58ms
12:40:36.231 -> 58ms
12:40:37.151 -> 44ms
12:40:38.174 -> 44ms

Then I tried this program reading the pin and printing the value.
Code:
int pushButton = A5;

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(20);  // delay in between reads for stability
}
That gives me, for instance, if I read it correctly, a 184ms high pulse:
12:46:45.188 -> 0
12:46:45.224 -> 0
12:46:45.224 -> 1
12:46:45.256 -> 1
12:46:45.256 -> 1
12:46:45.290 -> 1
12:46:45.337 -> 1
12:46:45.337 -> 1
12:46:45.337 -> 1
12:46:45.372 -> 1
12:46:45.408 -> 1
12:46:45.408 -> 1
12:46:45.447 -> 0
12:46:45.447 -> 0

What is going wrong with the pulsein program?
 
Last edited:

be80be

Joined Jul 5, 2008
2,395
Code:
int pin = 7;
    unsigned long duration;

    void setup() {
      Serial.begin(9600);
      pinMode(pin, INPUT);
    }

    void loop() {
      duration = pulseIn(pin, HIGH);
      Serial.println(duration);
    }
They don't say nothing about using this 1500000ul
 

Thread Starter

AlbertHall

Joined Jun 4, 2014
12,624
Syntax

pulseIn(pin, value)
pulseIn(pin, value, timeout)
Parameters

pin: the number of the Arduino pin on which you want to read the pulse. Allowed data types: int.
value: type of pulse to read: either HIGH or LOW. Allowed data types: int.
timeout (optional): the number of microseconds to wait for the pulse to start; default is one second. Allowed data types: unsigned long.

Arduino reference
 

be80be

Joined Jul 5, 2008
2,395
I know that but I not seen it used in arduino ide
C and C++ but arduino it maybe not work like the rest
Just thinking
 
Top