Arduino frequency counter Issue - arduino

I am successfully using this great Arduino frequency library: Arduino frequency counter.
But there is one issue with my LEDs. They are working if I give them the value "HIGH" or "255". But however they are not working with a lower value. I have tested the LEDs in another sketch. So they are correctly wired and are working fine, also the Arduino. It seems to be a problem with the "FreqCounter::start(100);" line. If I remove it, the lower values are working, but of course the frequency counter is not...
How can I fix this problem?
Here's the code:
#include <FreqCounter.h>
unsigned long frq;
/*** OUTPUT LED ***/
int ledGreen = 9;
int ledYellow = 10;
int ledRed = 11;
void setup() {
pinMode(ledGreen, OUTPUT);
pinMode(ledYellow, OUTPUT);
pinMode(ledRed, OUTPUT);
Serial.begin(115200);
Serial.println("Frequency Counter");
}
void loop() {
/*** WRITE ***/
analogWrite(ledGreen, 255);
analogWrite(ledYellow, 100);
analogWrite(ledRed, 10);
/*** FREQUENCY COUNTER ***/
FreqCounter::f_comp = 10; // Calibration value / calibrate with a professional frequency counter
FreqCounter::start(100); // 100 ms gate time
while (FreqCounter::f_ready == 0){
frq = FreqCounter::f_freq;
}
}

According to the documentation this library repurposes TIMER1 for counting the frequency. However PWM for pins 9 and 10 requires TIMER1 with the default setup.

Related

Why does the ledstrip stop partway and then go all the way and can I make this more efficient

So I need some help reviewing and editing the code below. Is there a way to make it more efficient instead of what I did? Also, are there better ways to do some of the methods I did? Answers are appreciated greatly (I'm fairly new to Arduino).
The code below is for a corridor ledstrip that lights up when the distance sensor on the Arduino detects anything below a certain distancenear it (yes, I thought of using a motion sensor but I only had distance sensors on hand).
const int trigPin = 9;
const int echoPin = 10;
float duration, distance;
#include <FastLED.h>
#define LED_PIN 6
#define NUM_LEDS 60
int timingnum = 0;
//#define BRIGHTNESS bright
int bright = 100;///the brightness of the leds
int lednum = 60;///the number of leds available
int timer;
CRGB leds[NUM_LEDS];
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
// FastLED.setBrightness( BRIGHTNESS );
}
void loop() {
lights();
}
void sensor() { ///THIS IS CLEAN
digitalWrite(trigPin, LOW);
delayMicroseconds(timingnum);
digitalWrite(trigPin, HIGH);
delayMicroseconds(timingnum);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
Serial.print("Distance: ");
Serial.println(distance);
}
// in the lights the reason why it wouldnt output the data for the
// represented while loops is because the while loop continued running
// without the data from the distance and thus it needs to constantly
// be updated in the while loop conditional statments
void lights() {
sensor(); //data update
while (distance <= 10) {
for (int x = 0; x <= 60; x++) {
leds[x] = CRGB(255,255,255);
FastLED.show();
sensor(); //sensor update
}
for (timer = 0; timer <=800; timer++) {
sensor();
}
sensor(); //replaces the data updates above
}
sensor(); //sensor update
while (distance >= 11) {
for (int x = 0; x <= 60; x++) {
leds[x] = CRGB(0,0,0);
FastLED.show();
}
sensor(); //data update
}
}
I would be tempted to make a little function to set the RGB colors of your LED strip: void fillup(byte r, byte g, byte b). Then you would call it in two places: fillup(0,0,0) and fillup(127,127,127) (yeah, not 100% on).
Also, I'm confused why you have so many sensor() calls in the first while loop. Seems like you only need to call it once when you need updated values for distance.
Also, the comments on the sensor calls are confusing... after reading them I have no idea what sensor is supposed to do. I tend to put a comment before functions that describes what they do, and put a stand-alone comment in the code to explain what the next "paragraph" does. And I avoid banners - they get in the way.
Do you want FastLED.show() inside the loop that updates the colors? Or just after the loop, to update the hardware after the array is changed? IDK, just asking.
I usually do not mind globals, but in this case you would be better off letting sensor return the distance. Then you could while ( sensor() <= 10 ). Or use a do.. while loop with one call to sensor at the bottom if you want to keep the global.
I'd try to get rid of the floating point, too... just calculate what your thresholds are in the raw echo values, and use those. Do we really care what the internal units of measurement are?
Sorry for the long unload... There's nothing wrong with what you have.

Arduino interrupt returning unreliable values

I have a simple app to count water flux using a sensor that is equipped with a reed switch.
So the app should only count the number of times the switch closes.
My first code was:
const int sensorPin = 2;
volatile int counter = 0;
void setup() {
Serial.begin(115200);
pinMode(sensorPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(sensorPin), sensorISR, FALLING);
}
void loop() {
Serial.print("Counter: ");
Serial.println(counter);
}
void sensorISR() {
counter++;
}
And once a bottle of 20 liters was full the counter would show something like 120.
Then I changed the code as follows:
const int sensorPin = 2;
volatile int counter = 0;
void setup() {
Serial.begin(115200);
pinMode(sensorPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(sensorPin), sensorISR, FALLING);
}
void loop() { }
void sensorISR() {
counter++;
Serial.print("Counter: ");
Serial.println(counter);
}
And counter went down to 40 (using the same 20 liters bottle).
The count should be 20L but that is not my problem as it results from bouncing of the reed switch (I will address that latter).
As the project will have 3 sensors and 3 ISRoutines I wonder why putting the Serial.print() command into the main loop can result in such strange results.
Thanks
Paulo
Serial print statements rely on interrupts that are disabled during your ISR. So Serial.print statements don't belong in an ISR.
The reason your count went down is that now your ISR takes longer to execute and it covers up some of the bounce. There are innumerable tutorials on how to debounce something with an Arduino. You can surely find one.
The two easiest are to use a capacitor between the pin and ground for a hardware debounce or to just use millis or micros to note the time that an interrupt occurs and ignore any interrupts that occur within some small time of that.

Arduino infiniti tone

I am making a smoke detector.
When it detects smoke iz should alert with buzzer.
Is there any way I could make it to buzz forever until external interupt such as restart pin?
Or could I just remove timing from tone() function.
Here is the code I use.
int sensorValue;
int digitalValue;
int green = 8;
int red = 7;
void setup(){
Serial.begin(9600);
pinMode( 0, INPUT);
pinMode(green, OUTPUT);
pinMode(red, OUTPUT);
}
void start(){
digitalWrite(green, HIGH);
}
void loop() {
sensorValue = analogRead(0);
digitalValue = digitalRead(0);
Serial.println(sensorValue,DEC);
Serial.println(digitalValue,DEC);
delay(2000);
if(analogRead(0) < 100){
tone(9,200,1000);
digitalWrite(red,HIGH);
}
}
Playing a sound "forever" is straightforward:
if(analogRead(A0) < 100 ) {
tone(9,2000); // once triggered, will play the sound forever
}
To switch it off, you seem to like the RESET button. So there's no need to ever call
noTone(9);
BTW: what about reading the reference ?
There is lots of ways:
Change your logic that activate the buzzer.
while (analogRead(0) < 100){
tone(9,200,1000);
}
Just use an infinite loop:
while (1) {
tone(9,200,1000);
}
Reset the Arduino to get out of the infinite loop.
An variation on this would be to replace (1) with the code that checks a pin to exit the loop or reads the sensor.
if you're really bent on using interrupts
you didn't specify what board you're working with but
for uno the 2 3 pins can be attached as interrupts and just trigger a function that turns off the tone
check out this:
attachinterrupt

Arduino Interfacing with Magnetic Pickup

Currently I have a diesel engine with magnetic pickup attached to it. I want to use Arduino (Uno/Nano) to measure engine RPM.
Magnetic Pickup Description: A magnetic pickup is installed over a gear, (most commonly the flywheel inside a vehicle’s bell housing) and as the gear turns the pickup will create an electric pulse for each tooth on the gear. These pulses are then read by the instrument which interprets it to indicate the correct RPMs or speed.The signal from the magnetic speed Sensor, teeth per second(HZ), is directly proportional to engine speed.
Magnetic Pickup Image:
MP - Self Powered
I've tried to rectify the signal using diode then limit the current using a resistor with .1Uf capacitor to filter the noise, then connected it to Optocopler 4N35 and the output from Opto to Arduino interrupt pin, by just observing Arduino interrupt ping is highly affected by surroundings.
Also I have tried to directly connect the magnetic pickup to "A0" pin and use analogue read and connect a led to pin 13 just to monitor the pulses from MP.
int sensorPin = A0;
int ledPin = 13;
int sensorValue = 0;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH);
delay(sensorValue);
digitalWrite(ledPin, LOW);
Serial.println(sensorValue);
Serial.println(" ");
}
Using analogueRead works with the LED as indicator for pulses generated by pickup. (Tested using small motor and small gear to protect Arduino).
Also I tried to use LM139 Comparator but the readings make no sense
(ex: 60 RPM, 1500 RPM,2150 RPM, 7150 RPM).
LM139 Circuit
Code used with LM139:
// read RPM
volatile int rpmcount = 0;
//see http://arduino.cc/en/Reference/Volatile
int rpm = 0;
unsigned long lastmillis = 0;
void setup() {
Serial.begin(9600);
attachInterrupt(0, rpm_fan, RISING);
//interrupt cero (0) is on pin two(2).
}
void loop() {
if (millis() - lastmillis == 500) {
/*Update every one second, this will be equal to reading frequency (Hz).*/
detachInterrupt(0); //Disable interrupt when calculating
rpm = rpmcount * 60;
/* Convert frequency to RPM, note: this works for one interruption per full rotation. For two interrupts per full rotation use rpmcount * 30.*/
Serial.print(rpm); // print the rpm value.
Serial.println(" ");
rpmcount = 0; // Restart the RPM counter
lastmillis = millis(); // Update lastmillis
attachInterrupt(0, rpm_fan, RISING); //enable interrupt
}
}
void rpm_fan() {
/* this code will be executed every time the interrupt 0 (pin2) gets low.*/
rpmcount++;
}
// Elimelec Lopez - April 25th 2013
What is the best way or approach to interface a magnetic pickup with Arduino to display RPM?
Your use of analogRead is wrong. Besides, analogRead will not get you anywhere close to what you want to achieve.
What you want from your pickup is a clear 0-5v digital signal. You can obtain that by playing with the input resistor on your opto-coupler. I'd do some measurements, and place a trimpot + resistors on the board do the actual value can be tweaked after the system is installed.
Once you get the electrical signal as clean as you can get, you can the use an interrupt pin on the Arduino to keep count of the number of pulses.
#define SENSOR_PIN (2) // using define instead of variable for constants save memory.
#define LED_PIN (13)
#define READ_DELAY (100) // in milliseconds.
// we'll get a reading every 100ms, so 8 bits are enough to keep
// track of time. You'd have to widen to unsigned int if you want
// READ_DELAY to exceed 255 ms.
//
typedef delay_type unsigned char;
typedef unsigned int counter_type; // You may want to use
// unsigned long, if you
// experience overflows.
volatile counter_type pulseCount = 0; // volatile is important here
counter_type lastCount = 0;
delay_type lastTime = 0;
// pulse interrupt callback, keep short.
void onSensorPulse()
{
++pulseCount;
// the following may already be too long. Use for debugging only
// digitalWrite() and digitalRead() are notoriously slow.
//
//
// digitalWrite(LED_PIN, !digitalRead(LED_PIN));
//
// using fastest direct port access instead. (for ATMega)
//
if (pulseCount & 1)
PORTB |= (1 << PB5);
else
PORTB &= ~(1 << PB5);
}
void setup()
{
pinMode(SENSOR_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), onSensorPulse, RISING);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
// control frequency of readings
//
delay_type now = (delay_type)millis();
if (now - lastTime < READ_DELAY)
{
return;
}
lastTime = now;
// get a reading. must disable interrupts while doing so.
// because pulseCount is multi-bytes.
//
noInterrupts();
counter_type curCount = pulseCount;
interrupts();
// get the number of pulses since last reading.
//
counter_type delta = curCount - lastCount;
lastCount = curCount;
// to convert to RPMs, you will need to use this formula:
// note the use of long (UL) to avoid overflows in the
// computation. 60000 = miliseconds per minute.
//
// RPM = delta * 60000UL / (READ_DELAY * TEETH_COUNT);
// send delta to client for now.
//
Serial.println(delta);
}

Creating a wave using MEGA2560 (analogWrite)

Been trying to create a wave using the PWM ports (because this Arduino doesn't have DAC)of an Arduino Mega using this code. In the simulation I use a wave form generator that goes to A0, then I just want to convert it from 1023 bits to 255 but I get nothing as output.
int in = A0;
int out = 10;
void setup()
{
pinMode(in, INPUT);
pinMode(out, OUTPUT);
}
void loop(){
analogRead(in);
analogWrite(10, in/4);
}
Any suggestion would be great, thanks in advance!
You're discarding the returned value from analogRead. Change:
void loop(){
analogRead(in);
analogWrite(10, in/4);
}
to:
void loop(){
int p = analogRead(in);
analogWrite(out, p / 4);
}
The pin 10 is digital output, isn't it ?
Moreover there is a function for creating a wave : tone(pin, freq, time);

Resources