Go Down

Topic: reading pulse from rotary dialer (Read 1 time) previous topic - next topic


I was trying to read the number of on/off pulses from a rotary dialer. I found some script from Tom Igoe, and it almost works...as I can count the number of reads from serial to corresponds with the number I dial on the rotary dialer. I have no idea how this code is exactly working...can someone help?

Code: [Select]
by Tom Igoe

Reads the values from a Memsic 2125 2-axis accelerometer.
In order to do so, uses a function called pulseIn, which reads
the width of a pulse on a pin.

Created 11 Feb. 2006


int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status
int p;

// Function prototypes:
int pulseIn(int inPin, int desiredState);

void setup() {
 pinMode(ledPin, OUTPUT);  // declare LED as output
 pinMode(inPin, INPUT);    // declare pushbutton as input

void loop() {
 p = pulseIn(inPin, HIGH);    // read pulsewidth
 printString("got a roll\n");
 printInteger(p);            // print p value
 printString("\r\n");           // print return character and newline character
val = digitalRead(inPin);  // read input value
 if (val == HIGH) {         // check if the input is HIGH
   digitalWrite(ledPin, HIGH);  // turn LED on
 } else {
   digitalWrite(ledPin, LOW);  // turn LED off

 pulseIn function.  reads the width of a pulse on a pin.
Takes a pin number and the desired state, HIGH or LOW.
Watches for the pin to change from the non-desired state to
the desired state, then counts loops until the pin changes
back again.

int pulseIn(int inPin, int desiredState) {
 int count = 0;        // local counter
 int finalCount = 0;   // final number of loops the pulse takes
 int pinState;         // state of the pin you're watching        
 int lastState = desiredState;   // place to store the previous state of the pin
 int difference = 0;

 while (finalCount <= 0) {
   pinState = digitalRead(inPin);
   difference = pinState - lastState;

   if ((difference > 0) &&(desiredState == HIGH)) {
     // start counting pulses

   if ((difference < 0) &&(desiredState == HIGH)) {
     // stop counting pulses
     finalCount = count;
     count = 0;

   if ((difference < 0) &&(desiredState == LOW)) {
     // start counting pulses

   if ((difference > 0) &&(desiredState == LOW)) {
     // stop counting pulses
     finalCount = count;
     count = 0;

   // save the state of the pin as the old state,
   // so we can get a new state to compare it to:
   lastState = pinState;
 // you're done.  Return the final count:
 return finalCount;


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