Pages: 1 [2]   Go Down
Author Topic: Measuring the Frequency of a TTL circuit  (Read 5819 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I have re-written the code and so let me know what you think-
Code:
#include <MsTimer2.h>

// Switch on LED on pin 13 each second

int signalstate = 0;
int laststate = 0;
long int counter = 0;
void flash() {
  Serial.println(counter, DEC);
  counter = 0;
}

void setup()
{
  pinMode(9, INPUT);
  MsTimer2::start();
}
//each time through the loop it does a read on the digital port,
//nothing happens till the pin goes "LOW" then each time through
// it checks to see if the state has changed, if so, then and
//only then does it increment the counter.
void loop()
{
  signalstate = digitalRead(9);
  if(signalstate == LOW)
  {
    laststate = 1;
  }
  if(laststate == 1 && signalstate == HIGH)
  {
    counter++;
    laststate = 0;
  }
  
}
« Last Edit: February 07, 2011, 05:15:04 pm by tchadwick » Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

So I re-wrote the program again due to my class using the Arduino Mega and the Mstimer2 not working with it.  So here is the new revision, which when outputting to the screen at 1/10th of a second, is fairly accurate, but when going above that, it quickly loses accuracy, any ideas why?
Code:
#include <SimpleTimer.h>
SimpleTimer timer;


int signalstate = 0;
int laststate = 0;
long int counter = 0;
long int screen = 0;
void repeatMe()
{
  long int tempequ = ((counter / 5) * 6);
  screen = tempequ;
  Serial.println(screen, DEC);
  counter = 0;
}
 
void setup()
{
  pinMode(9, INPUT);
  Serial.begin(9600);
  timer.setInterval(100, repeatMe);
}
//each time through the loop it does a read on the digital port,
//nothing happens till the pin goes "LOW" then each time through
// it checks to see if the state has changed, if so, then and
//only then does it increment the counter.
void loop()
{
  timer.run();
  signalstate = digitalRead(9);
  if(signalstate == LOW)
  {
    laststate = 1;
  }
  if(laststate == 1 && signalstate == HIGH)
  {
    counter++;
    laststate = 0;
  }
 
}
Logged

nr Bundaberg, Australia
Offline Offline
Tesla Member
***
Karma: 126
Posts: 8471
Scattered showers my arse -- Noah, 2348BC.
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
1/10th of a second, is fairly accurate, but when going above that, it quickly loses accuracy, any ideas why?
By that do you mean of the timer has a lower value and is therefore triggered at a faster rate?

If so it's possible that all the overhead in the code and the Serial.print becomes more significant at shorter periods. Try upping the bit rate to 115200 and see if that makes a difference.

______
Rob
Logged

Rob Gray aka the GRAYnomad www.robgray.com

Atlanta
Offline Offline
Sr. Member
****
Karma: 1
Posts: 254
Arduino still rocks
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Here is freq counter we use for DCDW, its speed is determined by the incoming freq and the number of digits of precision you specify.  It also has code to reject noisy signals.  Probably slower than you want and too many features, but you might find the autoscaling approach useful.  There is a fundamental limit on precision vs measurement rate and this is one way to approach it.

Code:
long countFrequency (int pin, int precision) 
{
// counts frequency of an incoming pulse train
// this code is licensed under Creative Commons Attribution-ShareAlike
//
// pin              any digital input pin (int)
// precision        number of significant digits, 2, 3 or 4 (int)
// returns:         frequency in Hz (long)
//
// written for Dirt Cheep Dumb Wireless sensor telemetry boards
// using OOK radio links (SparkFun etc) which output noise on no RF in
// so this looks for consistent pulse width as criterion against noise
// returns negative numbers for all errors such as noise
//
  int pulses;                   // total number of pulses to time
  int pulse;                    // pulse count
  unsigned long timeout= 10000; // microsecs for pulseIn() to wait before giving up
  unsigned long t0;             // start time hack
  unsigned long time;           // delay in millisec
  unsigned long needTime = 1;   // delay needed for precision in millisec
  unsigned long duration;       // length of one pulse
  unsigned long totDuration;    // total duration of first ten pulses
  unsigned long minDuration;    // minimum length of a valid pulse
  unsigned long maxDuration;    // maximum length of a valid pulse
  constrain (precision, 1, 5);                 // keepin it sane
  for (int i = 1; i < precision; i++) {
    needTime = needTime * 10;
  }  // millisecs of tone count needed to get desired precision
  long DCDWfrequency = 0;                      // nothin' yet
  totDuration = 0;                             // clear this to start
  for(pulse = 0; pulse < 10; pulse += 1)       // count 10 incoming pulses
  {                                   
    duration = pulseIn(pin, LOW, timeout);     // wait for one complete pulse cycle
    if (duration == 0) {
      return -(long)pulse;
    }  // if pulse timout then abort, return neg of bad pulse
    totDuration += duration;
  }
  maxDuration = totDuration / 7;
  minDuration = totDuration / 14;
  // now we have a range of average pulse durations
  // so start counting 'pulses' pulses, increasing 'pulses' by 10x each time
  // until a string of pulses meets the minimum total time for accuracy
  for (pulses = 10; pulses < 100000; pulses = pulses * 10)
  {
    DCDWfrequency = 0;                           // nothin' yet
    t0 = millis();                               // start time
    for(pulse = 0; pulse < pulses; pulse += 1)   // count incoming pulses
    {                                   
      duration = pulseIn(pin, LOW, timeout);     // wait for one complete pulse cycle
      if (duration == 0) {
        return -(long)pulse;
      }    // pulse timout: abort, return neg of bad pulse
      if (duration > maxDuration)                  // pulse too long: abort, return error code
      {
        return -(long)duration;
      }
      if (duration < minDuration)
      {
        return -(long)duration;
      }
    }
    time = millis()-t0;                          // got all pulses, so time = now - start

    if (time > needTime)                              // if time is enough for precision we are done
    {
      if (debug)
      {
        Serial.print(precision); 
        Serial.print(" digits "); 
        Serial.print(needTime); 
        Serial.println(" ms need:   "); 
        Serial.print(pulses); 
        Serial.print(" pulses = "); 
        Serial.print(time); 
        Serial.println(" millisecs "); 
      }
      DCDWfrequency = 1000 * (unsigned long)pulses / time;  // frequency in Hz
      return (long)DCDWfrequency;
    }
  }
  return -9999;


Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you for your post, and we will probably give it a try if we can't get the freqcounter.h library to work, which is currently having problems, because it won't work with the arduino mega 2560.  (Keeps saying sbi and cbi are not defined, which I don't understand)   I'm pulling most of what I'm doing from this forum: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1231326297/15
Anyone with ideas on how to fix the freqcounter.h for the mega 2560, that would be amazing!  I've tried entering the 2560 to the #define section, but no luck.  Please help!  Thanks ahead of time! smiley
« Last Edit: February 24, 2011, 10:14:43 pm by tchadwick » Logged

Left Coast, CA (USA)
Offline Offline
Brattain Member
*****
Karma: 361
Posts: 17261
Measurement changes behavior
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Here is freq counter we use for DCDW, its speed is determined by the incoming freq and the number of digits of precision you specify.  It also has code to reject noisy signals.  Probably slower than you want and too many features, but you might find the autoscaling approach useful.  There is a fundamental limit on precision vs measurement rate and this is one way to approach it.


That code looks interesting but it's not Arduino ready is it, no setup, loop, Serial.begin(), etc.

I tried adding stuff to try and run it, but gave up after two or three fixes. Compilers are so finicky.  smiley-grin

Lefty
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Also, does anyone know off the top of their head, what the precision and maximum measurable frequency is for the Arduino? (using freqCounter.h)
Thanks again for all the great posts, keep them coming!  (Oh after we finish this project, I plan on posting everything learned for others so they don't have to struggle like we are!  smiley-razz )
Logged

nr Bundaberg, Australia
Offline Offline
Tesla Member
***
Karma: 126
Posts: 8471
Scattered showers my arse -- Noah, 2348BC.
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
(Keeps saying sbi and cbi are not defined, which I don't understand)
That can be fixed with a define or or some inline assembler. SBI/CBI are single assembler instructions, I didn't look at the code but you can replace all occurances that are giving you trouble with

asm ("sbi");

and

asm ("cbi");

EDIT: Are we talking about the code a couple of posts up? There is no tCBI/SBI in that.

______
Rob
« Last Edit: February 24, 2011, 11:02:34 pm by Graynomad » Logged

Rob Gray aka the GRAYnomad www.robgray.com

Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

No the code above was a sample attempt at programming, however, we have finally achieved success! (With getting RPM)  Using the extra Interrupt on the Arduino Mega, it was much easier.
So the way it works is by attaching the encoder's output (either A or B or the Index) to pin 18, then attaching the interrupt to interrupt 5
which is only triggered when pin 18 goes from low to high.
It then calls the incrementit function that does just that, increments the counter.
Then after 10, or 100 ms the count is tallied.
(Thus far tested to 17Khz or 1900+ RPM)
Code:
#include <MsTimer2.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(52, 50, 48, 46, 44, 42);

volatile int count = 0;
double out = 0.0;
double motorout = 0.0;
double kp = 3.0;
double setpoint = 1450.0;

void setup()
{
  lcd.begin(16, 2);
  pinMode(12, OUTPUT);
  Serial.begin(115200);   // start serial communication
  attachInterrupt(5, incrementit, RISING);  //attaches interrupt to the mega's pin 18 (interrupt 5)
  MsTimer2::set(100, flash); // 100ms period
  MsTimer2::start();
}



void loop()
{
//  out = (1450 - out);
//  lcd.print(out);
//  delay(500);
//  lcd.clear();
}

void incrementit()
{
  count++;
}
void flash()
{
  lcd.clear();
  out = count;
  out = (setpoint - out);
  lcd.print(out);
 
  motorout = (setpoint+kp*out)*(5735.0/10000.0) - 661;
  motorout = constrain(motorout, 0, 255);
  Serial.println(motorout,DEC);
  analogWrite(12, motorout);
  //Serial.println(count,DEC);
  count = 0;
}
Logged

Pages: 1 [2]   Go Up
Jump to: