Go Down

Topic: a little help with pulsein (Read 686 times) previous topic - next topic


Trying to measure capacitance by turning on a digital output, with R to input pin and C to gnd, and measure the time delay. Arduino Uno.
Using pulsein (see code below) I get timeouts if R=infinity (open) or if tie the input pin low, which is expected.
But if I tie the pulsein input pin to +5V, or use a RC (100k and 0.1uF) to the pulsein pin, I get timeouts, where I expect a number  :~ 'scope signals look ok to me.

If I disconnect pulsein pin and touch (giving noise) I start to get wandering readings from pulsein. Otherwise, it's always timeouts, as if pulsein gets "stuck" or needs an edge?

Code: [Select]
#include <avr/io.h>

byte SensorPin = 3;   // pin "D3", PD3
byte PulseOutPin = 2; // pin "D2", PD2
byte ledPin = 13;

#define TRUE 1;
#define FALSE 0;

void setup() {

  digitalWrite(ledPin,LOW) ; // led off
  digitalWrite(PulseOutPin, LOW); 
  pinMode(PulseOutPin, OUTPUT); 
  pinMode(SensorPin, INPUT);
void loop() {

unsigned long duration;
const unsigned long pulsein_timeout = 100000; // in usec
const unsigned long pulse_triptime = 5000; // in usec

  digitalWrite(PulseOutPin, HIGH);  //
  duration = pulseIn(SensorPin, HIGH, pulsein_timeout);
  if (duration==0) {
      Serial.println("pulse timeout");
  else {
    Serial.print("tau= "); Serial.print(duration); Serial.print(" usec");
    if (duration>=pulse_triptime) {
       digitalWrite(ledPin,HIGH) ; // led on
       Serial.print("  * trip *");
    else { 
      digitalWrite(ledPin,LOW) ; // led off
  digitalWrite(PulseOutPin, LOW);  //

Nick Gammon

It looks like it looks for a transition:

Code: [Select]

        // wait for any previous pulse to end
while ((*portInputRegister(port) & bit) == stateMask)
if (numloops++ == maxloops)
return 0;

// wait for the pulse to start
while ((*portInputRegister(port) & bit) != stateMask)
if (numloops++ == maxloops)
return 0;

// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask) {
if (numloops++ == maxloops)
return 0;

Please post technical questions on the forum, not by personal message. Thanks!

More info:


You might use analogRead and use a micros() to determine start and stop and duration?

Code: [Select]

while (analogRead(PIN) < 10);  // accept some noise
start = micros();
while (analogRead(PIN) < 1020);  // ~5V reached
stop = micros();
Serial.println(stop - start);
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)


There is an ( thinks! more than one) example of doing this in the playground.


Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131