Frequency based switch. Working =)

I want to make an output of the arduino "lets say pin2" switch to high when frequency of lets say pin 0 is above 40hz. I've read up on the pulseIn function and came up with the following code, but it doesn't work. Feeding the input with a 5v 50% duty 30-50hz and led just stays dim...

Can anybody elaborate?

const int input = 0;
const int output = 2;

void setup() {
 pinMode(input, INPUT);
 pinMode(output, OUTPUT);
}

void loop() {
 int Speed;
 Speed =  500000/pulseIn(input, HIGH);
 {
 if (Speed > 40);
 digitalWrite(output, HIGH);
 if (Speed < 39);
 digitalWrite(output, LOW);
 }
}

lets say pin 0 is above 40hz

Let's not use pin 0 shall we, because that is used by the Serial interface.

 if (Speed > 40);
 digitalWrite(output, HIGH);
 if (Speed < 39);
 digitalWrite(output, LOW);

What should happen when Speed equals 39 or 40 ?

simple switch of pin. Okay, 39 or 40 is just going to stay at last state. Not to critical of the threshold.

int Speed;
 Speed =  500000/pulseIn(input, HIGH);

nope, lookup "arduino int"

int in this case is a read and rewriteable internal value. Can't use const int in this case.

Tried this code and got 30-50hz serial print on the monitor. Why wont the output pin switch?

int Speed;

void setup() {
  Serial.begin(9600);
 pinMode(3, INPUT);
 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);
}

void loop() {
  Speed = 500000/pulseIn(3, HIGH);
 {
 if (Speed > 40);
 digitalWrite(13, HIGH);
 if (Speed < 40);
 digitalWrite(13, LOW);
 }
 Serial.println(Speed);
 delay(10);
}

Hi. You have braces and semicolons in the wrong places in your if statements.

if (Speed > 40)
{
   digitalWrite(13, HIGH);
}
else
{
   digitalWrite(13, LOW);
{

Oh my, I can't believe i didn't see that. That worked like a charm, thankyou so very much Hackscribble! :slight_smile:

int Speed;
 Speed =  500000/pulseIn(input, HIGH);

Let me try this again, "Speed" is an int, int has a maximum of 32767. Now, which number above is above that maximum, because simply writing something like 32770 / 2 does NOT give you 16385, instead it will give you -32766 / 2 because it rolled over.

So here is your correction, put an L (meaning long, or 32 bit). I was hoping you would spot the error yourself.

int Speed;
 Speed =  500000L/pulseIn(input, HIGH);