How to add a time delay when reading a sensor - arduino - arduino

I am making a project that has to sense ambient light with a LDR. The idea is, that when the value of the LDR is low for 3 seconds, the led turns on. Also when the value of that LDR gets higher again, and stays high for 3 seconds, the led should turn of. This is so I can avoid that just a cloud or somebody waving over the sensor turns the led on immediately.
I know that I can use the mills() function here like in the blink without delay tutorial. But it doesn't seem to work....
this is my code so far:
#define ledPin 2
#define ldrPin A0
int daylight = 430;
int night = 150;
int ledState = 0;
int lightState = 0;
const long timeOut = 2000;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;
unsigned long tNow = 0;
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
tNow = millis();
int value = analogRead(ldrPin);
switch (lightState) {
case 0:
ledState = 0;
if (value <= 200 && (tNow - previousMillis) >= timeOut)
{
previousMillis = tNow;
lightState = 1;
}
break;
case 1:
ledState = 1;
if (value >= 300 && (tNow - previousMillis2) >= timeOut)
{
previousMillis2 = tNow;
lightState = 0;
}
break;
}
switch (ledState) {
case 0:
digitalWrite(ledPin, LOW);
break;
case 1:
digitalWrite(ledPin, HIGH);
break;
}
Serial.println(value);
Serial.println(ledState);
}

You could try using smoothing to read a running average from the sensor. That way you'll have a smoothed average instead of an immediate value, so a short spike (like a hand) won't change the value if you keep the window long enough.
There is a tutorial on the arduino website explaining how to do this. Basically you store multiple previous values and keep track of the average.

Related

Arduino for loop completely not functional

I am trying to send data from an accelerometer to Java from an Arduino. I am using delta time to limit it to sending only every 250 ms.
The problem is that all the Java program is reading is the first message sent in the setup() over and over.
I added a test Serial.write to check if the program is ever entering the delta time block, and it seems to be sending (or at least, reading) the first 2 characters of that message. The Arduino code is below.
#include <SparkFun_MMA8452Q.h>
int sleepPin = 7;
int stepPin = 6;
int buttonPin = 8;
int stepCount = 0;
boolean stepMode = true;
int delTime = 5000;
MMA8452Q accel; //accelerometer
void setup() {
Serial.begin(9600);
while (millis() < 4000); //wait so I can start java program
Serial.write("Connected");
//set pins
pinMode(sleepPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(stepPin, HIGH); //starts in step mode
delTime = millis() + 250;
}
void loop() {
if (digitalRead(buttonPin) == HIGH) stepMode = !stepMode;
if (millis() > delTime) {
Serial.write("delTime"); //test case
//set led's according to mode
if (stepMode) {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
} else {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
}
//create string to store data
String data = "";
if (stepMode) data += "s"; //s is step mode key
else data += "z"; //z is sleep mode key
//add actual reading stuff
data += String(accel.getX()) + "," + String(accel.getY());
Serial.write(data.c_str()); //send the lad over
}
}
The Java side is nearly identical (sans the conditions of an if statement, but it doesn't matter because if it doesn't meet the statement it just prints what it sees) to a functional program for serial communication that I've used before. I can include it if necessary though.
The Java console output appears as:
Connected
de
Connected
de
Connected
de
where a new iteration appears about once a second. What am I doing that prevents the Arduino from sending the data?
Not a proper answer yet, more of a test, but I couldn't fit it in a comment.
Changes made:
delTime is now an unsigned long int;
delTime is now reset at the end of the loop();
String object and manipulations were replaced by heap-friendlier code.
Added accel.begin();
Let me know if this works for you, and if not, where it complains. Haven't fully tested the code. You could also try replacing accel.getX() and accel.getY() with numbers; they return short ints, I think.
BTW the button needs debouncing.
#include <SparkFun_MMA8452Q.h>
int sleepPin = 7;
int stepPin = 6;
int buttonPin = 8;
boolean stepMode = true;
unsigned long int delTime = 0;
MMA8452Q accel; //accelerometer
void setup(){
Serial.begin(9600);
while(millis() < 4000); //wait so I can start java program
Serial.write("Connected");
//set pins
pinMode(sleepPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(buttonPin, INPUT);
accel.begin();
digitalWrite(stepPin, HIGH); //starts in step mode
delTime = millis() + 250;
}
void loop() {
char str[15];
if (digitalRead(buttonPin) == HIGH)
stepMode = !stepMode;
if (millis() > delTime) {
//set led's according to mode
if (stepMode) {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
Serial.write('s');
} else {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
Serial.write('z');
}
sprintf(str, "%d", accel.getX());
Serial.write(str);
Serial.write(',');
sprintf(str, "%d", accel.getY());
Serial.write(str);
Serial.write('\n');
delTime = millis() + 250;
}
}

How can I make an LED blink every n seconds without developing a lag?

I'm using an Arduino Uno to control LED. I want the LED to turn on every m seconds and remain ON for n seconds.
I've tried this code using the delay() function (by adding delays after LED is turned ON and OFF) and also using the millis() function (by keeping a track of the time passed since the previous event - ON/OFF). However, in both the approaches, the LED develops a lag of ~1 second after a few (!10) iterations of the ON-OFF cycle. What can I do to increase the accuracy of the time at which the events occur?
int led = 13;
long experimentTime = 240000;
long ledOFFDuration = 8000;
void setup() {
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}
void loop() {
for (int i = 0; i < 100; i++){
digitalWrite(led, HIGH);
delay(10000);
digitalWrite(led, LOW);
delay(10000);
}
}
I've also tried using the watchdog timer (shown below). However, it has the same issue:
#include <avr/wdt.h>
int led = 13;
volatile byte watchDogState = 0b01000000;
volatile int counter = 0;
int counterMax = 5;
bool state = 1;
void setup() {
// put your setup code here, to run once:
wdt_disable();
pinMode(led, OUTPUT);
digitalWrite(led, 1);
setWDT(watchDogState);
}
void loop() {
// put your main code here, to run repeatedly:
// if (time_elapsed == 40){
//state = !state;
//}
}
void setWDT(byte sWDT){
WDTCSR |= 0b00011000;
WDTCSR = sWDT | WDTO_2S;
wdt_reset();
}
ISR (WDT_vect){
counter++;
if (counter >= counterMax){
state = !state;
digitalWrite(led, state);
counter = 0;
}
}
I tried using the port registers directly to avoid using digitalWrite completely. But that doesn't work either. There's a lag of ~5s after 20 minutes using the following code:
int led = 13;
int m = 10;
int n = 10;
boolean on;
long change;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
long now = millis();
if (!on && change < now) {
on = true; //led is now on
change = now + n*1000; //turn off in <n> seconds
PORTB |= B00100000;
}
else if (on && change < now){
on = false; //led is now off
change = now + m*1000; //turn on in <m> seconds
PORTB &= B11011111; // Set pin 4 to 0
}
}
The lag is caused by the digitalWrite-calls. Your processing application waits until digitalWrite has finished and this may take 0.05 seconds or so. To fix your problem I would save the current time in milliseconds.
int led = 13;
int m = 24;
int n = 8;
boolean on;
long change;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
long now = System.currentTimeMillis();
if (!on && change < now) { //led is off and time for change has come
on = true; //led is now on
change = += n*1000; //turn off in <n> seconds
digitalWrite(led, HIGH); //turn on led
} else if (on && change < now) { //led is on and time for change has come
on = false; //led is now off
change = += m*1000; //turn on in <m> seconds
digitalWrite(led, LOW); //turn off led
}
}
the lamp will now instantly turn on on startup, wait n seconds, turn off, wait m seconds and restart from the beginning.
If you want to create a delay at the beginning so that the lamp doesn't get turned on immediately you can simply add this to your setup-function:
change = now + SECONDS*1000;
EDIT
You pointed out that it still gives you lag.
One problem might be that loop() is not run every millisecond. So I maybe got a solution for you.
Replace the following two lines:
change = now + n*1000; //turn off in <n> seconds
...
change = now + m*1000; //turn on in <m> seconds
to this:
change += n*1000; //turn off in <n> seconds
...
change += m*1000; //turn on in <m> seconds
Now it won't take the current time anymore which means that even if loop is only run every second or two it should still not cause any lag.
If this won't work I'm afraid it looks like the timer on the arduino might not be the most precise one. If this is the case try to measure the exact offset and then create a miltiplicator for the time.

Arduino Rotary Encoder Timer

This is what I am trying to achieve:
User inputs time using a rotary encoder.
The Arduino Serial Monitor must display real-time values of time as the user keeps rotating the encoder.
The user then hits a physical switch (push switch) to initiate the countdown.
Initially, my code worked perfectly with delay() function.
But my application also requires me to run a motor as long as the timer lasts. For this, I need a non-blocking delay. I am having a hard time with that. Please help. Here is my code:
unsigned long previousMillis = 0; // will store last time LED was updated
// constants won't change:
const long interval = 1000; // interval at which to blink (milliseconds)
#define outputA 6
#define outputB 7
int i;
int button=5;
int counter = 0;
int aState;
int aLastState;
void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
pinMode (button,INPUT);
Serial.begin (9600);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
}
void loop() {
// here is where you'd put code that needs to be running all the time.
aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState) {
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter = counter+1;
} else {
counter = counter-1;
}
Serial.print("Time (secs): ");
Serial.println(counter);
i = counter;
if (digitalRead(button) == HIGH) {
while (i != 0) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis == interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
i--;
Serial.println(i);
}
}
}
aLastState = aState;
}
}
If I understand well you are decrementing i only when entering if (currentMillis - previousMillis == interval). It means you are decrementing very slowly, and not millisecond by milliseconds…
To correct this I'm suggesting:
unsigned long startMillis = millis();
while (millis() - startMillis() < counter){ //check if your time has elapsed
unsigned long currentMillis = millis();
if (currentMillis - previousMillis == interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
Serial.println((int) counter - (millis() - startMillis()));
}
}
Hope it helps!

How to convert delay to millis

I have a simple code with delays.
I'd like to know how to convert this code to millis? Is there a function to do so?
long revers = 1000;
void setup() {
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT);
}
void loop() {
digitalWrite(D1, LOW);
delay(revers);
digitalWrite(D2, HIGH);
delay(revers);
digitalWrite(D2, LOW);
delay(revers);
digitalWrite(D1, HIGH);
delay(revers);
}
The basic concept is this: record the millis() at a given moment in a variable - say 'starttime'. Now, during every loop(), check the time that has elapsed by subtracting millis() from 'starttime'. If the elapsed time is greater than the delaytime you set, execute code. Reset the starttime to create a repeating pattern.
That may be too short of an explanation for you, so before you dive into the code, I highly advise you to read this introduction about using millis() for timing. It's lengthy, but it explains the principle extensively. This will help you understand the code below.
Lastly, there are several libraries written to make the use of timing easier. For instance the SimpleTimer-library, but you can google "arduino timer library" for others. I've included an example below.
1 second on, 3 seconds off:
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 1000; //the value is a number of milliseconds
int fase; //value used to determine what action to perform
void setup() {
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
startMillis = millis(); //initial start time
fase = 0;
}
void loop() {
currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started)
if (currentMillis - startMillis >= period) //test whether the period has elapsed
{
if (fase == 0)
{
digitalWrite(8, LOW);
startMillis = currentMillis; //IMPORTANT to save the start time of the current LED state.
fase = 1; //increment fase, so next action will be different
}
else if (fase == 1)
{
digitalWrite(7, HIGH);
startMillis = currentMillis;
fase = 2;
}
else if (fase == 2)
{
digitalWrite(7, LOW);
startMillis = currentMillis;
fase = 3;
}
else if (fase == 3)
{
digitalWrite(8, HIGH);
fase = 0;
startMillis = currentMillis;
}
}
}
Example of a flashing led using the SimpleTimer library
#include <SimpleTimer.h>
// the timer object
SimpleTimer timer;
int ledPin = 13;
// a function to be executed periodically
void repeatMe() {
digitalWrite(ledPin, !digitalRead(ledPin));
}
void setup() {
pinMode(ledPin, OUTPUT);
timer.setInterval(1000, repeatMe);
}
void loop() {
timer.run();
}

Light flashes more times than it's asked to

I am trying to get my LED to flash when the hypotenuse enters certain range. But it seems like it's passing that value of hypotenuse range more times than it should. LED Flashes for about good 30 -40 times before it goes back to being normal. Not sure how to fix this problem.
This is my processing code:
import processing.serial.*;
float r_height; // rise of the slope
float r_width; // run of the slope
float hypotnuse; // hypotenuse of the right angle
int d = 20; // diameter of the chocolate
float x ; // x of the chocolate destination
float y ; // y of the chocolate destination
int ledGlow; // how much the LED will glow
Serial myPort; // serial port object
void setup () {
size (510, 510); // size of the canvas
String portName = Serial.list()[8]; // my arduino port
myPort = new Serial(this, portName, 9600);
background (0); // color of the background
fill(204); // fill of the ellipse
ellipseMode (CORNER); //Ellipse mode
x = 0; //The placement on initial X for chocolate
y = 0; // the placement on initial Y for chocolate
ellipse (x, y, d, d); // ellipse
frameRate (30);
}
void draw () {
r_height = mouseY - y; // rise
r_width = mouseX - x; //run
hypotnuse = sqrt (( (sq(r_height)) + (sq (r_width)))); //A^2 +B^2 = C^2
ledGlow = 255 - (round (hypotnuse/2.84)); // flipping the values
myPort.write(ledGlow); // The value being sent to the Arduino
println (ledGlow);
}
This is the arduino code:
float val; // Data received from the serial port
int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (Serial.available())
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
// long steps2move = val.toInt();
}
if (val > 230) {
analogWrite (ledPin, 255) ; // I have already tried digitalWrite
delay (100);
analogWrite (ledPin, 1) ;
delay (100);
}
else if (val < 230) {
analogWrite(ledPin, val);
}
}
UPDATED ARDUINO:
float val; // Data received from the serial port
int ledPin = 9; // Set the pin to digital I/O 13
unsigned long currentTime = 0;
unsigned long pastTime = 0;
int currentState = 0;
int wait = 0;
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (Serial.available())
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
// long steps2move = val.toInt();
}
if (val > 230) {
pastTime = currentTime;
currentTime = millis();
unsigned long timePassed = currentTime - pastTime;
if(timePassed >= wait)
{
switch(currentState )
{
case 0:
digitalWrite(9, HIGH);
wait = 500;
currentState = 1;
break;
case 1:
digitalWrite(9, LOW);
wait = 500;
currentState = 0;
break;
}
}
}
else if (val < 230) {
analogWrite(ledPin, val/2);
}
}
The processing code is presumably writing out to serial constantly. However, when the hypotenuse enters the range you've set, the Arduino has those delay() calls. I think that will be causing it to lag behind, so it keeps flashing while it clears the backlog of serial data that came in during the delays.
I think a better approach is to avoid using delay() at all, so the Arduino can handle the serial data as fast as possible. On each loop, it should first grab the latest serial data (if there is any). Based on that, it should figure out and store what the LED should currently be doing (i.e. whether it should be flashing, or else what brightness it should be).
After that (regardless of whether any serial data was actually received), the LED can be updated from the stored state. Remember not to use delay() for the flashing though. Instead, you could keep track of the last time it flashed on, and figure out if 100 ms has passed since then (using millis()). If so, switch it off. If another 100 ms has passed, switch it back on.
This approach decouples the flash timing from the serial data, so hopefully it should work better.

Resources