Arduino interrupts - arduino

I am working on a smart greenhouse project using an ESP32 as a microcontroller.
Data comes from a DHT22 temperature and humidity sensor and a soil moisture sensor. Those two tend to use delay() functions to read, because they need some time to warm up.
Example:
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
}
I am planning on posting this data on a web interface, which would have manual controls available too.
Since I am using delays, if I press the button on the website, first the delay executes, then the button press, so it's not instant. What could I do to fix that?

Don't use delay(). I'm not clear on exactly what you're trying to do here or how you're trying to handle the button, but in general you're better off doing something like this:
#define SENSOR_UPDATE_WARMUP 2000
#define SENSOR_UPDATE_INTERVAL 1000
void loop() {
static unsigned long next_sensor_update = SENSOR_UPDATE_WARMUP;
if(millis() > next_sensor_update) {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
next_sensor_update = millis() + SENSOR_UPDATE_INTERVAL;
}
}
This allows you to other processing in loop() while still having the warmup time and only updating the sensor readings periodically (adjust SENSOR_UPDATE_INTERVAL to the number of milliseconds between updates).
If you need to have other delays for other devices just repeat the pattern of having a static variable that tracks the timing for those devices.
Even simpler, you could just put the two second delay at the end of setup() rather than inside loop(), but I suspect you're not going to want to update the sensor values constantly, so you'll want to structure your program similarly to the code above.

Related

How to Get Data from Rotary Encoder at VERY High Speeds (>4500 RPM)

Equipment:
Arduino ATmega2560
Rotary Encoder: https://www.amazon.ca/gp/product/B08RS6M32J/ref=ppx_yo_dt_b_asin_title_o06_s01?ie=UTF8&psc=1
Manual Curved Treadmill (what it looks like if you've never seen one before): https://www.youtube.com/watch?v=0oil6cmUCog&ab_channel=ResolutionFitness
Background:
I have a manual treadmill and I want to use my Arduino to capture distance and speed data. To do this, my approach was to use a rotary encoder, attach it to a skateboard wheel (older picture is attached, I'm using a bigger wheel now and there's no photo for that right now) such that when I run on the treadmill, the wheel spins proportionately.
In the code below, whenever I run it, the counter variable would accumulate to about 2000 (pulses) every time the wheel makes a full rotation. The wheel diameter = 6cm, therefore, it's circumference = 18.8495559215 cm.
This means for every centimeter I travel, there are about 106 pulses. (2000 pulses/18.8495559215 cm = ~106 pulses/cm).
Here's the code: (I got it from this website and only changed 2 lines of code because my sensor doesn't need to go in reverse; the treadmill only travels in one direction - https://electricdiylab.com/how-to-connect-optical-rotary-encoder-with-arduino/)
volatile long temp, counter = 0; //This variable will increase or decrease depending on the rotation of encoder
void setup() {
Serial.begin (9600);
pinMode(2, INPUT_PULLUP); // internal pullup input pin 2
pinMode(3, INPUT_PULLUP); // internalเป็น pullup input pin 3
//Setting up interrupt
//A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
attachInterrupt(0, ai0, RISING);
//B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
attachInterrupt(1, ai1, RISING);
}
void loop() {
// Send the value of counter
if( counter != temp && counter % 106 == 0 ){ // Only print something if the wheel travels in increments of 1 cm.
Serial.println (counter);
temp = counter;
}
}
void ai0() {
// ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
// Check pin 3 to determine the direction
if(digitalRead(3)==LOW) {
counter++;
}else{
counter++; // The original code said counter-- but my treadmill only goes one direction and the this variable starts to decrease when I reach a certain speed (around 5 kmk/h or (3.1 mph) or so). After I changed it to counter++, this issue was resolved however, the arduino serial monitor kept freezing at high speeds.
}
}
void ai1() {
// ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
// Check with pin 2 to determine the direction
if(digitalRead(2)==LOW) {
counter++; //// The original code said counter-- but my treadmill only goes one direction and the this variable starts to decrease when I reach a certain speed (around 5 kmk/h or (3.1 mph) or so). After I changed it to counter++, this issue was resolved however, the arduino serial monitor kept freezing at high speeds.
}else{
counter++;
}
}
The Problem
*To get the speed is easy, it's just not in this code right now. Accomplished by using t1 and t2 variables and the Millis() function.
When I walk on the treadmill, I typically walk at about 4 or 5 km/h (3.1 mph). This works fine. However, the issue is I want to be able to sprint over 30 km/h (18.6 mph) and have the code be able to support up to 50 km/h (31 mph). Right now, I'm unable to run at speeds over 5 km/h without the serial monitor freezing periodically, or there being inaccurate data.
At these speeds, I would need the sensor to support the wheel moving at over 4500 RPM -> 75 RPS or (75 RPS x 2000 P/R = 150,000 Pulses/Second)
I have absolutely no idea why this issue is happening and how I should approach this to achieve my desired speeds.
Possible reasons why this is happening:
I'm not an expert at Arduino at all and am just starting to understand things like interrupts. I have my pins in 2 and 3. Should I leave this alone or change it?
If you click the Amazon link, you'll see that there is a 3rd Orange "Z" wire which I have absolutely no idea what it does. The few tutorials I could find only involve the two "A" and "B" wires. Maybe incorporating the "Z" wire would point me in the right direction?
My Rotary encoder sensor is using the Arduino's 5V. If you click on the Amazon link, you'd see that it actually supports up to 26V. Should I find an external power source that allows up to 26V and pair it with a relay? Not sure if the extra voltage will help me.
I'm not sure why by default, the sensor counted a full rotation for the wheel to be 2000 pulses. On Amazon, you'll see that it supports the following Pulses/Revolution:
Resolution (pulse/rotation) : 100, 200, 300, 360, 400, 500, 600, 1000, 1024, 1200, 2000, 2500, 3600, 5000 (optional)
How can I change my 2000 P/R to 5000 P/R for example? Would this help?
Summary
I want to use my Arduino and rotary sensor to collect speed and distance data from my manual treadmill. At slow speeds (up to 5 km/h), the code works fine, but at high speeds, the data is highly inaccurate, and the serial monitor freezes every few seconds. I want the Arduino to support speeds up to 50 km/h which is about 4500 RPM. If my solution with the rotary sensor is not feasible, I am 100% open to other ideas as I just want the speed and distance data. I'll purchase any new equipment that's necessary but ideally, I'd like to work with what I have right now.
Thank you for your help!
Well I looked at the datasheet of your encoder and I was also very confused regarding the multiple values of resolution... what I suspect is that maybe there are different E6B2-CWZ6C models with differnt ppr's...
But what was useful was that I found out that your encoder is an incermental rotary encoder (this video explains better the inner workings of your type of encoder) what this means is that you have three wires A black, B white and Z the orange one.
As described on the video when your shaft completes 1 full rotation you will get N quantity of pulses from A and B, but depending on which pulse you get first would determines the rotation, according to the diagram below, if you first get a pulse from A it would mean that the rotation is CW but if you get B first it would then be CCW.
So for example lets say you start with a pulse_count=0 and start turning your shaft CW and you start counting the pulses on A, the count would go 0,1,2... and so on, but how would you know when to stop counting? that's when the Z orange cable comes in place, because it makes a pulse only after a whole rotation has been made so let's say you counted up to 200 and then you get a pulse from Z then you would know that you should restart your count back to the begining.
So to solve your problem and if you are only interested in the measured speed i would sugest to only measure how long does it take from one Z pulse to the next one, which would tell you how long it took for your encoder to complete one rotation, which could then be use to calculate the speed.
If we solve for rpms using this formula we get that RPM=(V60)/(2pir) if V=50km/h=13.88 m/s and r=3cm=0.03m we get that at 50km/h we would get 4418.14 rpm or 4418/60= 73.63 revs per sec what means 73 pulses of Z every second.
What was maybe happening is that for example if A had a resolution of 2000 ppr would imply that for every second you were receiving 73*2000 = 146000 pulses every second and as you configured your baudrate for your serial communication at Serial.begin(9600) you were only capable of reading at most 9600 pulses for each second which is way less than your 146000 pulses in A. However there are different baudrates you can set: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. Just be sure to select the same audrate when using the serial monitor.
For extremely high speeds you have to use bit operators and port registers.
Try this code with the equivalent pins CLK and DT connected to A2 and A1 receptively.
// Rotary Encoder Inputs
#define CLK A2
#define DT A1
int counter = 0;
String currentDir ="";
unsigned char currentPairBit = 0b0; // 8 bits
unsigned char lastPairBit = 0b0; // 8 bits
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
DDRC = 0b00000000; // Set Analog(C) encoder pins as inputs
}
void loop() {
while(true) { // while cycle is faster than loop!
// reads the analog states!
currentPairBit = PINC >> 1 & 0b11; // Gets A2(PC2) and A1(PC1) bits on C (analog input pins) (>> 1 = Jumps pin 0)
if ((lastPairBit & 0b11) != currentPairBit) {
lastPairBit = lastPairBit << 2 | currentPairBit;
// Bit Pairs Cyclic Sequence:
// 1. 2. 3. 4. 5.
// 11 | 01 | 00 | 10 | 11 for CCW
// 11 | 10 | 00 | 01 | 11 for CW
if (lastPairBit == 0b01001011 || lastPairBit == 0b10000111) {
if (lastPairBit == 0b01001011) {
currentDir = "CCW";
counter--;
} else {
currentDir = "CW";
counter++;
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
}
}
}
Then check the Serial Monitor to see how fast it is. Note that you should avoid the delay() function in your code or any other that interrupts the cycle by too much time. Consider using a second auxiliary Arduino for anything else than counting.
Resulting Serial Output:

LM35 decreases when near heat

My LM35 connected to arduino decreases temperature value in celsius when near heat and increases value when far from heat. Could any one help or know why it's working other way round.
void setup() {
// put your setup code here, to run once:
//Start the serial connection with the computer
//to view the result open the serial monitor
// 9600 is the “baud rate”, or communications speed.
Serial.begin(9600);
}
void loop() {
delay(2000);
float tempValue = analogRead(A2);
// converting that reading to voltage
float tempVoltage = (tempValue/1024.0)*5.0;
float tempDegrees = (tempVoltage - 0.5) * 100.0 ;
//Multiplying tempDegrees by -1 to make it positive
tempDegrees =(tempDegrees * -1);
Serial.println("............................................");
Serial.println("Degrees");
Serial.println(tempDegrees);
delay(2000);
}
just randomly came accross your question. and it has been 6 years since I touched an LM35 :d
but I think you have a problem in that -0.5 thing. I did not really get that!
LM35's function as far as I remember was :
T = V/ 10mV
you might want to check the datasheet but I'm pretty positive this is the equation. when you get the voltage from ADC you have to put it in this equation and get the result.
be careful : you have to also attribute for the temperature error as well as ADC noise if temperature precision is important for you.
If you are using a 5 volts power supply to your arduino:
5 Volts in the Arduino are directly converted to 1023 in the output of the ADC
ADC_Outpput * 5000 / 1024, where 5000 is coming from 5volts as millivolts, 1024 is the 10 bist resolution
LM35 resolution is linearly generated with a rate of + 10-mV/°C
so the analogVolt = ADC_Outpput * 5000 / 1024
FinalTemperature = (analogVolt - 500) / 10

Arduino Mini Pro 3.3V does not use 1.1V internal reference for ADC

Using the Arduino Mini Pro 3.3V I just stumbled over a problem when switching between the "INTERNAL" and "DEFAULT" voltage reference for the ADC.
I want to measure the output of a voltage divider [GND - 110kOhm - A2 - 500kOhm - VCC] for calculating VCC. VCC has been measured as 3.3V. It is provided by a voltage regulator.
In the loop I firstly measure the voltage divider output with the internal reference and afterwards with the default voltage reference.
I saw code examples where people recommend to wait some milliseconds before reading the next value and the (analogReference() documentation) recommends to ignore the first readings after calling analogReference(). I follow these guidlines.
I'll provide a minimum example sketch:
// the setup function runs once when you press reset or power the board
void setup()
{
pinMode(A2, INPUT); // ADC pin
Serial.begin(9600);
Serial.println("----------------");
}
void burn8Readings(int pin)
{
for (int i = 0; i < 8; i++)
{
analogRead(pin);
}
}
// the loop function runs over and over again forever
void loop()
{
uint16_t nResult1, nResult2;
analogReference(INTERNAL); // set the ADC reference to 1.1V
delay(10); // idle some time
burn8Readings(A2); // make 8 readings but don't use them to ensure good reading after ADC reference change
nResult1 = analogRead(A2); // read actual value
analogReference(DEFAULT); // set the ADC reference back to internal for other measurements
delay(10); // idle again
burn8Readings(A2); // make 8 readings but don't use them to ensure good reading after ADC reference change
nResult2 = analogRead(A2); // do other measurements
// print result to serial interface..
Serial.print("1: ");
Serial.print(nResult1);
Serial.print(" - 2: ");
Serial.println(nResult2);
delay(2000);
}
The first pair of ADC results seems correct (553 / 184), but in the following iterations the first value is faulty without changing the actual voltage on the ADC pin. (240 / 183)
The ADC result of the DEFAULT reference is always fine.
For a 2.56V reference the value of 240 would be feasible. I know that some ATmegas use a 2.56V reference voltage, but the ATmega328 should have 1.1V only. Strangely the (ATmega328/P datasheet) mentions a 2.56V reference in an ADC example in chapter 28.7, so I'm confused.
Is there a possibility there is a 2.56V ADC reference in a certain ATmega328p version?
It turns out the similarity to the 2.56V was a coincidence and probably an error in the datasheet (or in my understanding).
The problem was that after the analogReference(INTERNAL) call the ADC value has to be read immediately! Not after some milliseconds as I did it. (Source)
Still it is important to also wait some milliseconds after doing the dummy readout. For me one readout and delay(5) was just enough, but I guess that depends on the charge left in the capacitor of the ADC: So I'd recommend higher delays.
The correct sequence is:
analogReference(INTERNAL); // set the ADC reference to 1.1V
burn8Readings(A2); // make 8 readings but don't use them
delay(10); // idle some time
nResult1 = analogRead(A2); // read actual value
and
analogReference(DEFAULT); // set the ADC reference back to internal
burn8Readings(A2); // make 8 readings but don't use them
delay(10); // idle again
nResult2 = analogRead(A2); // read actual value
Changing the reference back to DEFAULT seems to be less prone...but at least one readout still was necessary for precise results.
I hope no one has to spend time on this one anymore...

Inaccurate results for arduino uno and ultrasonic sensor

Good day, I have the following code for an ultrasonic sensor that I'm using, but the result is not being accurate and I'd like to display the distance from the target in centimetres.
#include <LiquidCrystal.h> //Load Liquid Crystal Library
LiquidCrystal LCD(10, 9, 5, 4, 3, 2); //Create Liquid Crystal Object called LCD
int trigPin=13; //Sensor Trip pin connected to Arduino pin 13
int echoPin=11; //Sensor Echo pin connected to Arduino pin 11
int myCounter=0; //declare your variable myCounter and set to 0
int servoControlPin=6; //Servo control line is connected to pin 6
float pingTime; //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
LCD.begin(16,2); //Tell Arduino to start your 16 column 2 row LCD
LCD.setCursor(0,0); //Set LCD cursor to upper left corner, column 0, row 0
LCD.print("Target Distance:"); //Print Message on First Row
}
void loop() {
digitalWrite(trigPin, LOW); //Set trigger pin low
delayMicroseconds(2000); //Let signal settle
digitalWrite(trigPin, HIGH); //Set trigPin high
delayMicroseconds(15); //Delay in high state
digitalWrite(trigPin, LOW); //ping has now been sent
delayMicroseconds(10); //Delay in high state
pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microceconds
pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
targetDistance= speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour
targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
targetDistance= targetDistance*63360; //Convert miles to inches by multipling by 63360 (inches per mile)
LCD.setCursor(0,1); //Set cursor to first column of second row
LCD.print(" "); //Print blanks to clear the row
LCD.setCursor(0,1); //Set Cursor again to first column of second row
LCD.print(targetDistance); //Print measured distance
LCD.print(" inches"); //Print your units.
delay(250); //pause to let things settle
}
I will appreciate any help.
You are performing a lot of floating point calculations on every iteration of your loop. Rather than performing these calculations you can pre-compute a single multiplier that will convert the pingTime to a distance in centimetres.
First we need to calculate the metric speed of sound from your 776.5 mph.
776.5 miles/hour * 1609.34 (meters in a mile) = 1249652.51 metres/hour
1249652.51 metres/hour / 3600 = 347.126 metres/second
So we can precompute a multiplier as follows:
float speedOfSound = 347.126; // metres per second
float speedOfSound_cm_p_us = speedOfSound * 100 / 1000000; // speedOfSound in centimetres per microsecond
Obviously, this could be reduced to simply:
float speedOfSound_cm_p_us = 0.0347126; // cm per microsecond
Next we can precompute the multiplier by dividing speedOfSound_cm_p_us by 2 as the sound has to travel to the reflective surface and back again.
float pingTime_multiplier = speedOfSound_cm_p_us / 2; // The sound travels there and back so divide by 2.
Again, we could simply replace this step with:
float pingTime_multiplier = 0.0173563;
However, this magic number should be well documented in your code.
Once we have pingTime_multiplier calculated the loop function becomes much simpler. Simply multiply the pingTime by the pingTime_multiplier to get the distance in centimetres.
pingTime = pulseIn(echoPin, HIGH); // pingTime is presented in microseconds
targetDistance = pingTime * pingTime_multiplier;
This significantly reduces the amount of work that the Arduino has to do each time through the loop.
Convert inches to centimeters by multiplying by 2.54
float targetDistanceCentimeters = targetDistance*2.54;
Your code looks correct, so my guess is that this is a hardware problem. In my experience ultra sound sensors are typically quite bad at measuring distance to any object that is not a wall or other large object with relatively flat surface. So if you want to test the accuracy of your system, test it against such object i.e. wall or book.
If your sensor is moving while making the measurements make sure that it is not moving too fast.
If you are measuring distance to small or thin object you will need to filter and take the average of the measurements. It’s all up to you how accurate you want to be, I’d say that average of twenty or so of filtered measurements will give you appropriate result.
Another things to consider is that you have the correct supply voltage and that the sensor is not directed against the floor at some angle, as this might give unwanted reflections.
I'd like to display the distance from the target in centimetres.
Google says an inch is 2.54 cm, so just multipy your result by this.
the result is not being accurate
For more accurate results, take an average of a number of samples (3 or more), and you could implement some heuristics which discard grossly over/under range results.
Say if three readings are around 0-5cm apart, then a fourth reading 40cm away is most likely an error. So just do the average of the three similar results.

Speed measurement with arduino and ultrasonic hc-sr04 sensor?

i want made speed detection "device" using with Arduino and two ultrasonic hc-sr04 like this link. but I want to make it with ultrasonic instead by LDR.
from that link. how lasers and ldr work, like this
The resistors are used as pull-down resistors and I wired the sensors and put them in a case, to avoid them detecting surrounding light. For each case, a hole was drilled so that the laser beam can light the sensor while the ambient light does not affect the sensor.
The working principle is easy: an object that passes by will "cut" the laser beams, this means the LDR sensor will detect this sudden drop of light intensity. First I defined a threshold value under which the sensor is considered triggered, once the value is under threshold for the first sensor then Arduino waits for the second one to be triggered. During this waiting time it counts the elapsed time between the two events. When the second beam is interrupted, the timer stops and now is just simple math. The distance between the 2 sensors is known, the time between the two events is known, and speed can be computed as speed = distance/time.
Below the Arduino code:
/*
by Claudiu Cristian
*/
unsigned long time1;
int photocellPin_1 = 0; // 1st sensor is connected to a0
int photocellReading_1; // the analog reading from the analog port
int photocellPin_2 = 1; // 2nd sensor is connected to a1
int photocellReading_2; // the analog reading from the analog port
int threshold = 700; //value below sensors are trigerd
float Speed; // declaration of Speed variable
float timing;
unsigned long int calcTimeout = 0; // initialisation of timeout variable
void setup(void) {
// We'll send debugging information via the Serial monitor
Serial.begin(9600);
}
void loop(void) {
photocellReading_1 = analogRead(photocellPin_1); //read out values for sensor 1
photocellReading_2 = analogRead(photocellPin_2); //read out values for sensor 2
// if reading of first sensor is smaller than threshold starts time count and moves to calculation function
if (photocellReading_1 < threshold) {
time1 = millis();
startCalculation();
}
}
// calculation function
void startCalculation() {
calcTimeout = millis(); // asign time to timeout variable
//we wait for trigger of sensor 2 to start calculation - otherwise timeout
while (!(photocellReading_2 < threshold)) {
photocellReading_2 = analogRead(photocellPin_2);
if (millis() - calcTimeout > 5000) return;
}
timing = ((float) millis() - (float) time1) / 1000.0; //computes time in seconds
Speed = 0.115 / timing; //speed in m/s given a separation distance of 11.5 cm
delay(100);
Serial.print(Speed);
Serial.print("\n");
}
how to implement the code with ultrasonic HC-SR04 sensors?
the coding is problem for me. hopefully someone can help me...... :(
Please excuse my poor English !
There are already lots of examples on the internet, so if all you want to do is copy, google arduino sr04
But if you want to know how to do it...
The sr04 has 4 pins, vin, gnd, trigger, and echo.
Connect vin and ground to +5 and gnd
Connect trigger to a digital output pin
Connect echo to a digital input pin
Trigger by going low for 2 microseconds (us) and then high for 10 us then low again
Then get the results with a pulseIn from the echo pin
Read the data sheet for more information

Resources