You are on page 1of 559

1. This is the updated code including the stepper motor drive.

It
is set to about 1/4 revolution every 15 min
Temperature is set to 98F

// Incubator code
// ---------------------------------------------
#include <LiquidCrystal.h>
#include "DHT.h"
#define DHTPIN 2 // Define the temp sensor data pin
#define DHTTYPE DHT22 // define the temp/hum sensor type
#define RELAY 0 // define the relay control pin
#include <Stepper.h>
#define STEPS_PER_MOTOR_REVOLUTION 32 //define the
number of steps per motor revolution
// #define STEPS_PER_OUTPUT_REVOLUTION 32 * 64
#define STEPS_PER_OUTPUT_REVOLUTION 8 * 64 //define the
number of steps to take each time the code loops
// 6 should give about 1 revolution per hour with a 2 second
delay at the end of the loop
DHT dht(DHTPIN, DHTTYPE); //initialize the temp sensor
// LCD Connections:
// rs (LCD pin 4) to Arduino pin 12
// rw (LCD pin 5) to Arduino pin 11
// enable (LCD pin 6) to Arduino pin 10
// LCD pin 15 to Arduino pin 13
// LCD pins d4, d5, d6, d7 to Arduino pins 5, 4, 3, 1
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 1); //set up what port the
LCD will use
int backLight = 13; // pin 13 will control the backlight
int is,im,ih,id,ida; // variables for time
float time,s1,m1,h1,d1; // Set up variables to calculate time
int ic,ip,ik;
int Steps2Take; // define the steper motor steps
byte thermo[8]
={B00100,B01010,B01010,B01110,B01110,B11111,B11111,B
01110}; //thermometer icon
byte drop[8]
={B00100,B00100,B01010,B01010,B10001,B10001,B10001,B
01110}; //drop icon
byte smile[8] =
{B00000,B10001,B00000,B00000,B10001,B01110,B00000};
// smile icon
byte tim[8] =
{B00000,B01110,B10101,B10101,B10011,B10001,B01110,};
// clock icon
//The pin connections need to be 4 pins connected
// to Motor Driver In1, In2, In3, In4 and then the pins entered
// here in the sequence 1-3-4-2 for proper sequencing (hook
up driver bard pins to arduino 6789
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 7,
9,8, 6);
void setup()
{
dht.begin(); //start the temp sensor
pinMode(RELAY, OUTPUT);
pinMode(backLight, OUTPUT);
digitalWrite(backLight, LOW); // turn backlight on. Replace
'HIGH' with 'LOW' to turn it off.
lcd.begin(20,4); // columns, rows. use 16,2 for a 16x2 LCD,
etc.
lcd.clear(); // start with a blank screen
lcd.setCursor(0,0); // set cursor to column 0, row 0 (the first
row)
lcd.print("Incubator); // opening line
lcd.setCursor(0,1); // set cursor to column 0, row 1
lcd.print("Hatch!");
delay(2000);
// Uncomment if you want more text on the 4 line LCD (not
used in 2 line LCDs)
// lcd.setCursor(0,2); // set cursor to column 0, row 2
// lcd.print("Row //Text for line 3
//lcd.setCursor(0,3); // set cursor to column 0, row 3
//lcd.print("Row // Text for line 4
lcd.createChar(0,thermo);
lcd.createChar(1,drop);
lcd.createChar(2,smile);
lcd.createChar(3,tim);
}
//loop to read the sensor and display
void loop(){
float h = dht.readHumidity(); // Read the humidity
float t = dht.readTemperature(); // Read temperature in
celsius
float f = dht.readTemperature(true); // get the temperature in
Fahreheit
// uncomment to compute heat index in Fahrenheit (the
default)
//float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
//float hic = dht.computeHeatIndex(t, h, false);
time=millis(); // Get time in milliseconds since tunit turn on
s1=time/1000; // Convert time to seconds, minutes, hours,
days
m1=s1/60;
h1=m1/60;
d1=h1/24;
id=int(d1); // Strip out remainder to leave
Days:Hours:Minutes:Seconds
ih=int((d1-int(d1))*24);
im=int((h1-int(h1))*60);
is=int((m1-int(m1))*60);
// Calculate approximate days till hatch (assume 21 days to
hatch)
ida=21-id;
if (isnan(h) || isnan(t) || isnan(f)){
// if sensor can't be read
lcd.clear();
lcd.setCursor(0,0);
lcd.print("failedead sensor");
delay(50000);
return;
}
else {
//sensor was read succesfully so print values to LCD
lcd.clear(); // Clear the LCD
//Print temperature and humidity in first two lines
lcd.setCursor(0,0);
// lcd.print("Temperature
lcd.print(" ");
lcd.write(byte(0)); // Write the Thhermometer icon
lcd.print(" ");
lcd.print(f,1);
lcd.print(" F ");
//lcd.setCursor(0,1);
lcd.write(byte(1)); // Write the drop icon
// lcd.print("Humidity
lcd.print(" ");
lcd.print(h,0);
lcd.print(" %");
lcd.setCursor(0,1);
lcd.print(" ");
lcd.write(byte(3));
lcd.print(" ");
// Print time in format Time: xxd:xxh:xxm:xxs
lcd.print(id);
lcd.print("d
lcd.print(ih);
lcd.print("h
lcd.print(im);
lcd.print("m
lcd.print(is);
lcd.print("s
lcd.setCursor(0,2);
lcd.print("_-_-_-_-_-_-_-_-_-_
lcd.setCursor(0,3);
// Print days left till hatch
lcd.print("Days:");
lcd.print(21-id);
lcd.print(" ");
lcd.write(byte(2));
//Temperature controller
if(f < 98.0){ // Set the temperature for the relay to come on
(somewhere around 90-101F to get eggs to hatch)
digitalWrite(RELAY,LOW); // Turns ON Relay
}
else{
digitalWrite(RELAY,HIGH); // Turns Relay Off
}
ic= im % 15;
ik=im-ip;
if(ic==0 && ik != 0){
ip=im;
lcd.setCursor(0,2);
lcd.print("Turning!_-_-_-_");
Steps2Take = STEPS_PER_OUTPUT_REVOLUTION ; // define
stepper CW steps
small_stepper.setSpeed(50); // set stepper max speed
small_stepper.step(Steps2Take); // take the steps
// Steps2Take = - STEPS_PER_OUTPUT_REVOLUTION; //
define stepper CCW 1 steps
// small_stepper.setSpeed(700); // set stepper to max speed
// small_stepper.step(Steps2Take); // take the steps
}
// Puase for 2 seconds
delay(2000);
}
}

Last edited: Oct 25, 2015

2.

3. Oct 26, 2015#13

MetoliousOut Of The Brooder


15
2
24

Oct 17, 2015


Thanks for sharing. I love it because it provides a meaningful project for me to learn
coding. Definitely going to use this to help me get into it.
4.

5. Nov 1, 2015#14

crankOut Of The Brooder


45
8
24

Mar 4, 2014
Utah

Very cool. I love chick and chicken oriented Arduino projects here. Keep us up to date
with the progress of your project. I also have an Arduino based chicken project
too. https://www.backyardchickens.com/t/...sensor-ambient-air-temp-and-relative-
humidity
6.

7. Nov 12, 2015#15

abqchickenOut Of The Brooder


64
9
31

Sep 26, 2015

Update - I have had the system working for a while and all seems to be stable with the
setup and code I posted. I now need to figure out a reliable egg-turning scheme
without making it too complicated. As an alternative to the stepper motor I have been
thinking about is a servo. I have a few from a couple of deceased RC helicopters. The
two options I am thinking about are:

1) rotating arns to push the eggs around in a circle


2) servo rocking mechanism to move the eggs from side to side.

I will probably prototype each to see which one works best. I really do not want to buy
fertile eggs before I am sure things will work.
8.

9. Nov 20, 2015#16

abqchickenOut Of The Brooder


64
9
31

Sep 26, 2015

Changed the code to work with a servo instead of a stepper - this will "rock" the eggs
by raising one end up and down. Servo control wire is set to Pin 9 and other two wire
go to ground and +5V (on my servos yellow is control, red is +5V, black is ground).

// Servo version of
// Incubator code
// ---------------------------------------------
#include <LiquidCrystal.h>
#include "DHT.h"
#include <Servo.h>
#define DHTPIN 2 // Define the temp sensor data pin
#define DHTTYPE DHT22 // define the temp/hum sensor type
#define RELAY 0 // define the relay control pin
#define STEPS_PER_MOTOR_REVOLUTION 32 //define the number of steps per motor
revolution
Servo myservo; // create servo object to control a servo
DHT dht(DHTPIN, DHTTYPE); //initialize the temp sensor
// LCD Connections:
// rs (LCD pin 4) to Arduino pin 12
// rw (LCD pin 5) to Arduino pin 11
// enable (LCD pin 6) to Arduino pin 10
// LCD pin 15 to Arduino pin 13
// LCD pins d4, d5, d6, d7 to Arduino pins 5, 4, 3, 1
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 1); //set up what port the LCD will use
int backLight = 13; // pin 13 will control the backlight
int pos = 0; // variable to store the servo position
int istate = 0;
int is, im, ih, id, ida; // variables for time
float time, s1, m1, h1, d1; // Set up variables to calculate time
int ic, ip, ik;
byte thermo[8] = {B00100, B01010, B01010, B01110, B01110, B11111, B11111,
B01110}; //thermometer icon
byte drop[8] = {B00100, B00100, B01010, B01010, B10001, B10001, B10001,
B01110}; //drop icon
byte smile[8] = {B00000, B10001, B00000, B00000, B10001, B01110, B00000}; //
smile icon
byte tim[8] = {B00000, B01110, B10101, B10101, B10011, B10001, B01110,}; //
clock icon
// done with initial parameters
void setup()
{
dht.begin(); //start the temp sensor
pinMode(RELAY, OUTPUT);
pinMode(backLight, OUTPUT);
digitalWrite(backLight, LOW); // turn backlight on. Replace 'HIGH' with 'LOW' to turn it
off.
lcd.begin(20, 4); // columns, rows. use 16,2 for a 16x2 LCD, etc.
lcd.clear(); // start with a blank screen
lcd.setCursor(0, 0); // set cursor to column 0, row 0 (the first row)
lcd.print("Incubator); // opening line
lcd.setCursor(0, 1); // set cursor to column 0, row 1
lcd.print("Hatch!");
delay(2000);
// Uncomment if you want more text on the 4 line LCD (not used in 2 line LCDs)
// lcd.setCursor(0,2); // set cursor to column 0, row 2
// lcd.print("Row //Text for line 3
//lcd.setCursor(0,3); // set cursor to column 0, row 3
//lcd.print("Row // Text for line 4
lcd.createChar(0, thermo);
lcd.createChar(1, drop);
lcd.createChar(2, smile);
lcd.createChar(3, tim);
myservo.attach(9); // servo control is set to pin 9 (usually yellow wire is control, black
goes to ground red goes to +5V)
myservo.write(16); //put the servo at intitial posistion of 16 degrees
}
//loop to read the sensor and display
void loop() {
float h = dht.readHumidity(); // Read the humidity
float t = dht.readTemperature(); // Read temperature in celsius
float f = dht.readTemperature(true); // get the temperature in Fahreheit
// uncomment to compute heat index in Fahrenheit (the default)
//float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
//float hic = dht.computeHeatIndex(t, h, false);
time = millis(); // Get time in milliseconds since tunit turn on
s1 = time / 1000; // Convert time to seconds, minutes, hours, days
m1 = s1 / 60;
h1 = m1 / 60;
d1 = h1 / 24;
id = int(d1); // Strip out remainder to leave Days:Hours:Minutes:Seconds
ih = int((d1 - int(d1)) * 24);
im = int((h1 - int(h1)) * 60);
is = int((m1 - int(m1)) * 60);
// Calculate approximate days till hatch (assume 21 days to hatch)
ida = 21 - id;
if (isnan(h) || isnan(t) || isnan(f)) {
// if sensor can't be read
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("failedead sensor");
delay(50000);
return;
}
else {
//sensor was read succesfully so print values to LCD
lcd.clear(); // Clear the LCD
//Print temperature and humidity in first two lines
lcd.setCursor(0, 0);
// lcd.print("Temperature
lcd.print(" ");
lcd.write(byte(0)); // Write the Thhermometer icon
lcd.print(" ");
lcd.print(f, 1);
lcd.print(" F ");
//lcd.setCursor(0,1);
lcd.write(byte(1)); // Write the drop icon
// lcd.print("Humidity
lcd.print(" ");
lcd.print(h, 0);
lcd.print(" %");
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.write(byte(3));
lcd.print(" ");
// Print time in format Time: xxd:xxh:xxm:xxs
lcd.print(id);
lcd.print("d
lcd.print(ih);
lcd.print("h
lcd.print(im);
lcd.print("m
lcd.print(is);
lcd.print("s
lcd.setCursor(0, 2);
lcd.print("_-_-_-_-_-_-_-_-_-_
lcd.setCursor(0, 3);
// Print days left till hatch
lcd.print("Days:");
lcd.print(21 - id);
lcd.print(" ");
lcd.write(byte(2));
//Temperature controller
if (f < 98.0) { // Set the temperature for the relay to come on (somewhere around 90-
101F to get eggs to hatch)
digitalWrite(RELAY, LOW); // Turns ON Relay
}
else {
digitalWrite(RELAY, HIGH); // Turns Relay Off
}
ic = im % 15; // set the interval of turning to 15 min
ik = im - ip; // (change the vatiasblr "im" to "is" in the next three lines to turn in hour
intervals
if (ic == 0 && ik != 0) {
ip = im;
// this section is to rock the eggs
if(istate == 0){
for (pos = 16; pos <= 80; pos += 1) { // goes from 16 degrees to 80 degrees in steps
of 1 degree
myservo.write(pos);
istate=1;
delay(50);
}
}
else if( istate == 1){
for (pos = 80; pos >=16; pos -= 1) { // goes from 80 degrees to 0 degrees
myservo.write(pos);
istate = 0;
delay(50); // slow the servo down a bit to turn the eggs
}
}
}
// Puase for 2 seconds
delay(2000);
}
}

/* ------------------------------------------------------------------------------- */
Last edited: Nov 20, 2015

10.
11. Nov 20, 2015#17

gpop1Chillin' With My Peeps


530
44
94

May 2, 2015

I built my incubator about 6 months ago using a arduino mega and dht22 and that's
still running good. I used a rtc (real time clock) that cost about $2.

For the turner I used a geared motor as a servo has to hold the load where a angle
drive holds it by the nature of its design. I did go a little over board with the code as
you can control every aspect of the incubator but I figured it was better to have to
many options then not enoght. Im collecting and testing all the parts for my next
incubator at the moment. .

If you need a hand im more than willing to help

https://www.backyardchickens.com/t/976303/building-a-incubator-from-a-wine-
cooler link to the first arduino one I built.
12.

13. Nov 21, 2015#18

abqchickenOut Of The Brooder


64
9
31

Sep 26, 2015


Impressive machine! Well done! That is way too many eggs for me to hatch!

I am shooting for a bit smaller machine to hatch maybe 12 eggs and keep it
inexpensive. I don't have enough room in my back yard and city ordinance will not
allow for more than 15 chickens (already have 7). I am mostly doing it as a challenge
and to see if I can hatch some breeds I cannot get locally. I really like the different
colored eggs.

Right now the challenge is to build a small egg turner. I was simply going to do use a
stepper to sweep around an arm (I may go back to that). The small cheap stepper I
have does not have enough torque. I am now trying a servo to "rock" the eggs
somewhat like you have done, but much smaller. I have a feeling I will have to get a
new servo since the one I have is a "micro" one from a long crashed RC helicopter. I
may just have to go to a large stepper.
14.

15. Nov 21, 2015#19

gpop1Chillin' With My Peeps


530
44
94

May 2, 2015

how about any small dc motor that's gear reduced and a few prox sensors or ir beam
sensors (few bucks each for arduino) then turn the whole incubator like brimasea does.
16.

17. Nov 21, 2015#20

abqchickenOut Of The Brooder


64
9
31

Sep 26, 2015

That might be worth thinking about. I have the prox sensors. would need to figure out
the gearing. Not sure where to buy the gears. I have a few Helicopter motors that
should be strong enough.
18.
(You must log in or sign up to reply here.)
Page 2 of 7< Prev1234567Next >

Recent

// Example testing sketch for various DHT humidity/temperature sensors

// Written by ladyada, public domain

// mod by fama for servo meter, DC FAN, LCD

#include "DHT.h"

#include <LiquidCrystal.h>

#include <Servo.h>

#define STEPS_PER_MOTOR_REVOLUTION 32 //define the number of steps per motor revolution

#define RELAY 9

#define DHTPIN 10 // what pin we're connected to

// Uncomment whatever type you're using!

#define DHTTYPE DHT11 // DHT 11

// #define DHTTYPE DHT22 // DHT 22 (AM2302)

//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino


DHT dht(DHTPIN, DHTTYPE);

Servo myservo;

int pos = 0;

int istate = 0;

int is, im, ih, id, ida; // variables for time

float time, s1, m1, h1, d1; // Set up variables to calculate time

int ic, ip, ik;

LiquidCrystal lcd( 12, 11, 5, 4, 3, 2); //pins for LCD display

void setup() {

Serial.begin(9600);

Serial.println("DHTxx test!");

lcd.clear();

lcd.print("DHT11 - Super");

dht.begin();

myservo.attach(8);

pinMode(RELAY, OUTPUT);

delay(2000);

void loop() {

// 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


float t = dht.readTemperature();

// Read temperature as Fahrenheit

float f = dht.readTemperature(true);

time = millis(); // Get time in milliseconds since tunit turn on

s1 = time / 1000; // Convert time to seconds, minutes, hours, days

m1 = s1 / 60;

h1 = m1 / 60;

d1 = h1 / 24;

id = int(d1); // Strip out remainder to leave Days:Hours:Minutes:Seconds

ih = int((d1 - int(d1)) * 24);

im = int((h1 - int(h1)) * 60);

is = int((m1 - int(m1)) * 60);

// Calculate approximate days till hatch (assume 21 days to hatch)

ida = 21 - id;

// Check if any reads failed and exit early (to try again).

if (isnan(h) || isnan(t) || isnan(f)) {

Serial.println("Failed to read from DHT sensor!");

return;

// Compute heat index

// Must send in temp in Fahrenheit!

float hi = dht.computeHeatIndex(f, h);

Serial.print("Humidity: ");
lcd.print("Humidity: ");

Serial.print(h);

Serial.print(" %\t");

lcd.begin(16,2);

lcd.clear();

lcd.setCursor(0,0);

lcd.print(h);

lcd.print(" h");

lcd.print(t);

lcd.print(" *c");

lcd.setCursor(1,1);

lcd.print(f);

lcd.print(" *f");

Serial.print("Temperature: ");

Serial.print(t);

Serial.print(" *C ");

Serial.print(f);

Serial.print(" *F\t");

Serial.print("Heat index: ");

Serial.print(hi);

Serial.println(" *F");

//Temperature controller

if (t < 37) { // Set the temperature for the relay to come on (somewhere around 90-101F to get eggs to
hatch)

digitalWrite(RELAY, LOW); // Turns ON Relay


}

else {

digitalWrite(RELAY, HIGH); // Turns Relay Off

ic = im % 15; // set the interval of turning to 15 min

ik = im - ip; // (change the vatiasblr "im" to "is" in the next three lines to turn in hour intervals

if (ic == 0 && ik != 0) {

ip = im;

// this section is to rock the eggs

if(istate == 0){

for (pos = 0; pos <= 180; pos += 1) { // goes from 16 degrees to 80 degrees in steps of 1 degree

myservo.write(pos);

istate=1;

delay(50);

else if( istate == 1){

for (pos = 180; pos >=0; pos -= 1) { // goes from 80 degrees to 0 degrees

myservo.write(pos);

istate = 0;

delay(50); // slow the servo down a bit to turn the eggs

}
delay(2000);

Hello there. Im currently working on a project that are using servo motor. I intend to do an automated rain
sensing wiper. whenever there is rain, the wiper will be automatically turn on. I managed to make it to
work for now. I wonder would it be possible if it is not raining and the wiper is currently moving, i send
an order to ask the wiper to stop?

here is an example of the code

#define Grove_Water_Sensor 13 // Attach Water sensor to Arduino Digital Pin 13


#include <Servo.h>
#include <LiquidCrystal.h>
#include <DHT.h>
#include "DHT.h"
#define DHTPIN A0 // what pin we're connected to
#define DHTTYPE DHT11 // we are using the DHT11 sensor
Servo myservo;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DHT dht(DHTPIN, DHTTYPE);
int pos = 0; // variable to store the servo position

void setup() {
pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an Input
myservo.attach(3);
Serial.begin(9600);
for (int DigitalPin = 7; DigitalPin <= 9; DigitalPin++)
{
pinMode(DigitalPin, OUTPUT);
}
lcd.begin(16,2); //16 by 2 character display

dht.begin();
}

void loop() {

if( digitalRead(Grove_Water_Sensor) == HIGH) {


for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in
variable 'pos'
delay(15); // waits 15ms for the servo to reach the
position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable
'pos'
delay(15); // waits 15ms for the servo to reach the
position
}
delay(1000);
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();

float t = dht.readTemperature(); // Read temperature as Celsius (the default)

lcd.clear();
lcd.setCursor(0,0);
lcd.print("Temp: ");
lcd.print(t); //printing temperarture to the LCD display

lcd.print("'C");

lcd.setCursor(0,1);
lcd.print("Humid: ");
lcd.print(h); //printing humidity to the LCD display
lcd.print("%");
}

else {
myservo.detach();
}
}

Brattain Member
Posts: 15,453
Karma: 1029 [add]
May all of your blinks be without delay()

Re: Working with servo motor

#1

Feb 27, 2017, 08:14 am


Quote

I wonder would it be possible if it is not raining and the wiper is currently moving, i send an order to ask the wiper
to stop?

Presumably the sensor returns HIGH when it detects water. What happens at present when the sensor
returns LOW ? What do you want to happen ?

Please do not send me PMs asking for help. Post in the forum then everyone will benefit from seeing the
questions and answers.
luqmansss_

Newbie
Posts: 10
Karma: 1 [add]

Re: Working with servo motor

#2

Feb 27, 2017, 08:24 am


Quote from: UKHeliBob on Feb 27, 2017, 08:14 am

Presumably the sensor returns HIGH when it detects water. What happens at present when the sensor returns LOW
? What do you want to happen ?

If the sensors returns LOW, the wiper would turn off (if it is previously on) or the wiper remains off (if it
is previously off). And after 1 minute delay, the device would loop back right from the beginning

UKHeliBob

Brattain Member
Posts: 15,453
Karma: 1029 [add]
May all of your blinks be without delay()

Re: Working with servo motor

#3

Feb 27, 2017, 09:13 am


Sorry, but I am not getting what you want to happen.

It seems to me that if it is raining then the wipers should sweep back and forth but when it is not raining
they should go to a parked position and not just stop. Is that right ?

Also, presumably independently of the wipers, the temperature and humidity should be displayed, perhaps
continuously, perhaps every so often. Is that right ?

Full Member
Posts: 195
Karma: 1 [add]
Arduino rocks

Arduino - Temperature & Humidity DHT11 without delay example

May 27, 2012, 02:38 pm Last Edit: May 27, 2012, 02:47 pm by nathanas Reason: 1
Hi there!
I've been using the DHT11 sensor a lot and I spent time making the code its time. So I made a sketch
example so anyone can use it.
I've been hoping that you can post my code to the examples, because its frustrating for new arduino users
to use the DHT11 example code directly.
It also is very slow (2seconds delay in each loop).

So I made a sketch to match all your needs.


It reads the sensor every 2 seconds without delays.
The user can also use the temperature and humidity values directly as an integer and compare it to
other values without making new arrays.
Please check it out and let me know if you find any errors.
/* DHT11 Example Sketch Code for reading the sensor without delay on your program!
Example Code by: Nick Athanasoulas
Date: 27/5/2012
FUNCTION: It reads the sensor every 2 seconds without delays.
The user can also use the temperature and humidity values directly as an integer
and compare it to other values without making new arrays.
*/
#define DHT11_PIN 4 // ADC0 Define the ANALOG Pin connected to DHT11 Sensor
int temp1[3]; //Temp1, temp2, hum1 & hum2 are the final integer values
that you are going to use in your program.
int temp2[3]; // They update every 2 seconds.
int hum1[3];
int hum2[3];

byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

while(!(PINC & _BV(DHT11_PIN))); // wait for 50us


delayMicroseconds(30);

if(PINC & _BV(DHT11_PIN))


result |=(1<<(7-i));
while((PINC & _BV(DHT11_PIN))); // wait '1' finish

}
return result;
}

long dht11delay_previousMillis = 0; // will store last time LED was updated


long dht11delay_interval = 1000; // dht11delay_interval at which to blink
(milliseconds)

void setup()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("DHT11 without delay");
Serial.println("Example code by: Nick Athanasoulas");
Serial.println("Ready");
delay(1000);
}

void loop()
{

unsigned long dht11delay_currentMillis = millis();

if(dht11delay_currentMillis - dht11delay_previousMillis > dht11delay_interval) {


// save the last time you blinked the LED
dht11delay_previousMillis = dht11delay_currentMillis;
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);


delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
Serial.println("dht11 start condition 1 not met");
return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
Serial.println("dht11 start condition 2 not met");
return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];


// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
Serial.println("DHT11 checksum error");
}

temp1[0]=dht11_dat[2];
temp2[0]=dht11_dat[3];
Serial.print("Temperature: ");
Serial.print(temp1[0]);
Serial.print(".");
Serial.print(temp2[0]);
Serial.print(" C");
Serial.print(" ");
hum1[0]=dht11_dat[0];
hum2[0]=dht11_dat[1];
Serial.print("Humidity: ");
Serial.print(hum1[0]);
Serial.print(".");
Serial.print(hum2[0]);
Serial.println("%");

}
}
// END OF CODE

Re: Arduino - Temperature & Humidity DHT11 without delay example

#1

May 27, 2012, 03:53 pm

Seems like working code (did not test it) - recognize the handshake, CRC checking etc - would prefer it in
a separate class.

For the DHT11 there is no decimal part so it makes not much sense to print allways .0 for temp and
humidity.
Another drawback is that not all pins are possible because you hardcoded PORTC ...

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -


(Please do not PM for private consultancy)

nathanas

Full Member
Posts: 195
Karma: 1 [add]
Arduino rocks

Re: Arduino - Temperature & Humidity DHT11 without delay example

#2

May 27, 2012, 06:56 pm


It seems to be a problem sometimes though.
The DHT11 is not communicating because of a program error.
I get "dht11 start condition 1 not met"

Many have the same problem. I found a post of someone that has fixed this error. But his code is not
compiling. Please take a look, because sometimes Arduino can't see the readings correctly.

http://linux-utils.blogspot.com/2010/10/dht11-arduino-with-
virtualwire.html?showComment=1338136957757#c8321490607167585796

nathanas

Full Member
Posts: 195
Karma: 1 [add]
Arduino rocks
Re: Arduino - Temperature & Humidity DHT11 without delay example

#3

May 27, 2012, 07:08 pm


The ground Pin of the DHT11 was broken. That's why I received the "dht11 start condition 1 not met"
error.

All are working like a charm now!

robtillaart

Global Moderator
Brattain Member
Posts: 18,352
Karma: 1035 [add]
In theory there is no difference between theory and practice, however in practice there are many...

Re: Arduino - Temperature & Humidity DHT11 without delay example

#4

May 27, 2012, 07:31 pm


Good to hear!

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -


(Please do not PM for private consultancy)

Thinkerion
Guest

Re: Arduino - Temperature & Humidity DHT11 without delay example

#5
Oct 13, 2014, 05:41 pm
i know this topic is old but i have a question about this code,,

as it is i have a lot of things i am going to hook up to the arduino at the same time and i need to avoid any
delays.

right now i have a clock and an lcd hooked up through I2c units, meaning both on pin A4, and A5.
I will add two DHT11 sensors and some other temperature sensors, moisture sensors some relays to
controll 230V feed, IR controll to change temperature and moisture settings and a servo.

hence i need all my code to be seamless without Delays.

i see there are delayMicroseconds in this loop will it disrupt the other actions ?
And how should i write the code to be non disruptive?

robtillaart

Global Moderator
Brattain Member
Posts: 18,352
Karma: 1035 [add]
In theory there is no difference between theory and practice, however in practice there are many...

Re: Arduino - Temperature & Humidity DHT11 without delay example

#6

Oct 13, 2014, 07:34 pm


The handshake of the DHT11 is quite timing sensitive. Most libraries for it are blocking but there is at
least one that uses interrupts
discussed here - http://forum.arduino.cc/index.php/topic,155800.0.html -

That might be what you are looking for.


Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -


(Please do not PM for private consultancy)

PRINT

Go Up

Pages: [1]

Jump to:

NEWSLETTER

DHT11 Arduino with VirtualWire


By some reason when using VirtualWire library and using vw_setup(2000) caused the readings
from humidity sensor to fail (dht11 start condition 1 not met). I looked at datasheet and changed
a the times how the MCU starts to talk with the sensor.

The code is based from this post

Here is the the fixed code:

void InitDHT() {
pinMode(TEMP_RH_PIN, OUTPUT);
delay(1000);
digitalWrite(TEMP_RH_PIN,HIGH);
}

void ReadDHT() {

bGlobalErr=0;
byte dht_in;
byte i;

// see datasheet to understand this


pinMode(TEMP_RH_PIN, OUTPUT);
digitalWrite(TEMP_RH_PIN,HIGH);
digitalWrite(TEMP_RH_PIN,LOW);
delay(18);

digitalWrite(TEMP_RH_PIN,HIGH);
delayMicroseconds(22);

pinMode(TEMP_RH_PIN,INPUT);
delayMicroseconds(5);

dht_in=digitalRead(TEMP_RH_PIN);

if(dht_in) {
bGlobalErr=1;
Serial.println("<dht11 start condition 1 not met");
return;
}

delayMicroseconds(80);
dht_in=digitalRead(TEMP_RH_PIN);

if(!dht_in) {
bGlobalErr=2;
Serial.println("<dht11 start condition 2 not met");
return;
}
delayMicroseconds(80);

//now ready for data reception... pick up the 5 bytes coming from the
sensor
for (i=0; i<5; i++)
dht_dat[i] = read_dht_dat();

//Next: restore pin to output duties


pinMode(TEMP_RH_PIN,OUTPUT);
digitalWrite(TEMP_RH_PIN,HIGH);

byte dht_check_sum = dht_dat[0]+dht_dat[1]+dht_dat[2]+dht_dat[3];

/*Condition in following "if" says "if fifth byte from sensor


not the same as the sum of the first four..."*/
if(dht_dat[4]!= dht_check_sum) {
bGlobalErr=3;
Serial.println("DHT11 checksum error");
}

}
byte read_dht_dat() {
//Collect 8 bits from datastream, return them interpreted
//as a byte. I.e. if 0000.0101 is sent, return decimal 5.
//Code expects the system to have recently entered the
//dataline low condition at the start of every data bit's
//transmission BEFORE this function is called.
byte i = 0;
byte result=0;
for (i=0; i< 8; i++) {
//We enter this during the first start bit (low for 50uS) of the byte
//Next: wait until pin goes high
while(digitalRead(TEMP_RH_PIN)==LOW);
delayMicroseconds(30);
if (digitalRead(TEMP_RH_PIN)==HIGH)//Was: if(PINC & _BV(dht_PIN))
result |=(1<<(7-i));
while (digitalRead(TEMP_RH_PIN)==HIGH);
//Was: while((PINC & _BV(dht_PIN)));
}
//end of "for.."
return result;
}
Posted by one2one at 02:55

Labels: arduino, dht11, virtualwire

4 comments:
1.

olli23 September 2011 at 12:32

hi you :-) the code work on my arduino with dht11. thank you. - but i have one problem: i
have temperature under 1C. have you a idea for this problem? i can not display under 1C an
im newbie... i hope you can help...
Reply

2.

olli23 September 2011 at 13:07

sorry - i have read the data sheet :-))))


Reply

3.

NaThAN27 May 2012 at 09:42


I am trying to use your code but most of the variables are not declared. I guess I am doing
something wrong..

I am using Arduino 1.0.1 and don't know if there needs to be a library or something included.
Can you just give me a sketch that I copy /paste it to arduino and compiles successfully?
Can you please help me as soon as possible?

Thanks in advance!
Reply

4.

Anonymous28 May 2012 at 05:27

Hi NaThAN, you need to add the VirtualWire lib to your arduino


Reply

Add comment

dht11 with comparators

Nov 20, 2012, 09:32 pm


Hi, i have this code working with dht11 + lcd but i need to introduce a comparators something like if
humidity is lower than 40% then turn a led and with temperature the same thing like if higher than 23 C
then turn another led

Code working with no comparators DHT11 + LCD

#define dht_dpin 14
#define LIGHT_SENSOR_PIN 1
#include <LiquidCrystal.h>

LiquidCrystal lcd(0, 1, 2, 3, 4, 5);

byte bGlobalErr;
byte dht_dat[4];
int light_intensity = 0;
unsigned int flip = 0;

void setup(){
pinMode(13, OUTPUT);
lcd.begin(16, 2);
lcd.print("Heeeeeello!");
InitDHT();
delay(300);
delay(700);
}

void loop(){

if ( flip & 1 )
{
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}

flip++;

light_intensity=analogRead(LIGHT_SENSOR_PIN);

ReadDHT();
switch (bGlobalErr) {
case 0:
lcd.setCursor(0, 0);
lcd.print("temp = ");
lcd.setCursor(7, 0);
lcd.print( dht_dat[2], DEC);

lcd.setCursor(0, 1);
if ((flip % 15) > 7 )
{
lcd.print("humidity = ");
lcd.setCursor(11, 1);
lcd.print( dht_dat[0], DEC);
} else {
lcd.print("Light = ");
lcd.setCursor(8, 1);
lcd.print( light_intensity, DEC);
}
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
delay(800);

void InitDHT(){
pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,HIGH);
}

void ReadDHT(){

bGlobalErr=0;
byte dht_in;
byte i;
digitalWrite(dht_dpin,LOW);
delay(18);
delayMicroseconds(600);
digitalWrite(dht_dpin,HIGH);
delayMicroseconds(40);
pinMode(dht_dpin,INPUT);
delayMicroseconds(40);

dht_in=digitalRead(dht_dpin);

if(dht_in) {
bGlobalErr=1;
return;
}
delayMicroseconds(80);

dht_in=digitalRead(dht_dpin);

if(!dht_in) {
bGlobalErr=2;
return;
}
delayMicroseconds(70);
for (i=0; i<5; i++)
dht_dat = read_dht_dat();

pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,HIGH);
byte dht_check_sum =
dht_dat[0]+dht_dat[1]+dht_dat[2]+dht_dat[3];
if(dht_dat[4]!= dht_check_sum)
{bGlobalErr=3; }
};

byte read_dht_dat(){

byte i = 0;
byte result=0;
for(i=0; i< 8; i++) {
while(digitalRead(dht_dpin)==LOW) ;
delayMicroseconds(30);
if (digitalRead(dht_dpin)==HIGH)
result |=(1<<(7-i));
while (digitalRead(dht_dpin)==HIGH) ;
}
return result;
}
dhenry
Guest

Re: dht11 with comparators

#1

Nov 20, 2012, 09:44 pm


Quote

if humidity is lower than 40% then turn a led and with temperature the same thing like if higher than 23 C then turn
another led

That's easy:

read_dht11();
if dht11.humidity < 40% turn on a led;
else turn off the led;
if hdt11.temperature > 23 turn on another led;
else turn off the led;

for (i=0; i<5; i++)


dht_dat = read_dht_dat();

Re: dht11 with comparators

#2

Nov 20, 2012, 09:49 pm


thank you dhenry for your reply, in fact i did that but im not sure where should i put that sentence on the
code and i have doubts if its gonna be simple as that

eclipsear
Guest

Re: dht11 with comparators

#3

Nov 20, 2012, 10:47 pm Last Edit: Nov 20, 2012, 10:49 pm by eclipsear Reason: 1
i added a servo but with no control of comparators.. i have problem with that part .I wanna turn the
servo on for 20 secs when humidity is lower than 40%. Anyone?
#define dht_dpin 14
#define LIGHT_SENSOR_PIN 1
#include <LiquidCrystal.h>
#include <Servo.h>

LiquidCrystal lcd(0, 1, 2, 3, 4, 5);


Servo myservo;

byte bGlobalErr;
byte dht_dat[4];
int light_intensity = 0;
int pos = 0;
unsigned int flip = 0;

void setup(){
pinMode(13, OUTPUT);
myservo.attach(9);
lcd.begin(16, 2);
lcd.print("Heeeeeello!");
InitDHT();
delay(300);
delay(700);
}

void loop(){

if ( flip & 1 )
{
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}

flip++;

light_intensity=analogRead(LIGHT_SENSOR_PIN);
ReadDHT();
switch (bGlobalErr) {
case 0:
lcd.setCursor(0, 0);
lcd.print("temp = ");
lcd.setCursor(7, 0);
lcd.print( dht_dat[2], DEC);

lcd.setCursor(0, 1);
if ((flip % 15) > 7 )
{
lcd.print("humidity = ");
lcd.setCursor(11, 1);
lcd.print( dht_dat[0], DEC);
} else {
lcd.print("Light = ");
lcd.setCursor(8, 1);
lcd.print( light_intensity, DEC);
}
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
delay(800);
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

void InitDHT(){
pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,HIGH);
}

void ReadDHT(){

bGlobalErr=0;
byte dht_in;
byte i;
digitalWrite(dht_dpin,LOW);
delay(18);
delayMicroseconds(600);
digitalWrite(dht_dpin,HIGH);
delayMicroseconds(40);
pinMode(dht_dpin,INPUT);
delayMicroseconds(40);

dht_in=digitalRead(dht_dpin);

if(dht_in) {
bGlobalErr=1;
return;
}
delayMicroseconds(80);

dht_in=digitalRead(dht_dpin);

if(!dht_in) {
bGlobalErr=2;
return;
}
delayMicroseconds(70);
for (i=0; i<5; i++)
dht_dat = read_dht_dat();

pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,HIGH);
byte dht_check_sum =
dht_dat[0]+dht_dat[1]+dht_dat[2]+dht_dat[3];
if(dht_dat[4]!= dht_check_sum)
{bGlobalErr=3; }
};

byte read_dht_dat(){

byte i = 0;
byte result=0;
for(i=0; i< 8; i++) {
while(digitalRead(dht_dpin)==LOW) ;
delayMicroseconds(30);
if (digitalRead(dht_dpin)==HIGH)
result |=(1<<(7-i));
while (digitalRead(dht_dpin)==HIGH) ;
}
return result;
}

PaulS

Brattain Member
Posts: 81,060
Karma: 2286 [add]
Seattle, WA USA

Re: dht11 with comparators


#4

Nov 21, 2012, 01:28 am

Quote

I wanna turn the servo on for 20 secs when humidity is lower than 40%. Anyone?

You don't "turn on a servo". Please describe exactly what you mean by that. While you are thinking about
it, look at the blink without delay example.

The art of getting good answers lies in asking good questions.

eclipsear
Guest

Re: dht11 with comparators

#5

Nov 21, 2012, 12:59 pm

Quote

You don't "turn on a servo". Please describe exactly what you mean by that. While you are thinking about it, look at the blink
without delay example.

yeah sorry for the misleading words, i have the sweep servo code but i still need the comparations when
temperature is higher than 25 C and the when humidity is lower than 40% turn on a led

this code have the servo sweep, the dht11 + lcd but no parameters for comparation
#define dht_dpin 14
#define LIGHT_SENSOR_PIN 1
#include <LiquidCrystal.h>
#include <Servo.h>

LiquidCrystal lcd(0, 1, 2, 3, 4, 5);


Servo myservo;

byte bGlobalErr;
byte dht_dat[4];
int light_intensity = 0;
int pos = 0;
unsigned int flip = 0;

void setup(){
pinMode(13, OUTPUT);
myservo.attach(9);
lcd.begin(16, 2);
lcd.print("Heeeeeello!");
InitDHT();
delay(300);
delay(700);
}

void loop(){

if ( flip & 1 )
{
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}

flip++;

light_intensity=analogRead(LIGHT_SENSOR_PIN);

ReadDHT();
switch (bGlobalErr) {
case 0:
lcd.setCursor(0, 0);
lcd.print("temp = ");
lcd.setCursor(7, 0);
lcd.print( dht_dat[2], DEC);

lcd.setCursor(0, 1);
if ((flip % 15) > 7 )
{
lcd.print("humidity = ");
lcd.setCursor(11, 1);
lcd.print( dht_dat[0], DEC);
} else {
lcd.print("Light = ");
lcd.setCursor(8, 1);
lcd.print( light_intensity, DEC);
}
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
delay(800);
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

void InitDHT(){
pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,HIGH);
}
void ReadDHT(){

bGlobalErr=0;
byte dht_in;
byte i;
digitalWrite(dht_dpin,LOW);
delay(18);
delayMicroseconds(600);
digitalWrite(dht_dpin,HIGH);
delayMicroseconds(40);
pinMode(dht_dpin,INPUT);
delayMicroseconds(40);

dht_in=digitalRead(dht_dpin);

if(dht_in) {
bGlobalErr=1;
return;
}
delayMicroseconds(80);

dht_in=digitalRead(dht_dpin);

if(!dht_in) {
bGlobalErr=2;
return;
}
delayMicroseconds(70);
for (i=0; i<5; i++)
dht_dat = read_dht_dat();

pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,HIGH);
byte dht_check_sum =
dht_dat[0]+dht_dat[1]+dht_dat[2]+dht_dat[3];
if(dht_dat[4]!= dht_check_sum)
{bGlobalErr=3; }
};

byte read_dht_dat(){

byte i = 0;
byte result=0;
for(i=0; i< 8; i++) {
while(digitalRead(dht_dpin)==LOW) ;
delayMicroseconds(30);
if (digitalRead(dht_dpin)==HIGH)
result |=(1<<(7-i));
while (digitalRead(dht_dpin)==HIGH) ;
}
return result;
}
PRINT

Go Up

Pages: [1]

Jump to:

NEWSLETTER

Newbie
Posts: 6
Karma: 0 [add]

Help with programming servo and stepper motor at the same time
Jan 06, 2017, 06:34 pm
Hi, I'm new to arduino with very little programming experience, so please excuse horrible programming
and bad copy pasting. So, I am working on a project that uses a unipolar stepper motor and a non-
continuous servo. Here is what i want to happen in steps...

Step 1- Servo rotates a full 180 degrees in either direction slowly (10 seconds for 180 degrees).

Step 2-stepper motor rotates one step.

Step 3-Servo rotates 180 degrees in the opposite direction of step one.

Step 4- Repeat all steps continuously.

Here is my code:

#include <Servo.h>
class Sweeper
{
Servo servo;
int pos; // current servo position
int increment; // increment to move for each interval
int updateInterval; // interval between updates
unsigned long lastUpdate; // last update of position

public:
Sweeper(int interval)
{
updateInterval = interval;
increment = 1;
}

void Attach(int pin)


{
servo.attach(pin);
}

void Detach()
{
servo.detach();
}

void Update()
{
if((millis() - lastUpdate) > updateInterval) // time to update
{
lastUpdate = millis();
pos += increment;
servo.write(pos);
Serial.println(pos);
if ((pos >= 180) || (pos <= 0)) // end of sweep
{
// reverse direction
increment = -increment;
}
}
}
};
Sweeper sweeper1(250); //inside parenthesis indicates speed, 10 would be about 4 seconds(not
exactly)
#include <Stepper.h>
#include <LiquidCrystal.h>
#include <dht11.h>
dht11 DHT; //Note:DHT on behalf of the temperature and humidity sensor
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 13);
const int dht11_data = 6;
const int sensorPin = 0;
int stepCount = 0;
int temp=0;
int hum=0;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
long previousMillis = 0;
long interval = 500;
void setup()
{
sweeper1.Attach(A1);
lcd.begin(16,2);
lcd.print(" Welcome to ");
lcd.setCursor(0,1);
lcd.print(" DHT11");
delay(2000);
lcd.clear();
}
void loop()
{
sweeper1.Update();
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
DHT.read(dht11_data);
temp=DHT.temperature * 1.8 + 32;
hum=DHT.humidity;
lcd.clear(); //clear display
lcd.print("Hum=%"); //display "Hum=%"
lcd.print(hum);
lcd.setCursor(10,0) ;
lcd.print("DHT11"); //display "Smraza"
lcd.setCursor(0,1) ; //Display position
lcd.print("Temp="); //display"Temp="
lcd.print(temp);
lcd.write(0xDF); //Display custom characters ''
lcd.print("F");

}
// read the sensor value:
int sensorReading = 20;
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);
}
}

...obviously the timing doesn't match for the steps. But, my main problem is that the servo and motor
are rotating slower than they should...(mainly the servo). Whenever, I adjust the speed of one, it affects
both motor and servo speed.

Again, I'm new to arduino so please comment easy to understand stuff.

FCjosh

Newbie
Posts: 6
Karma: 0 [add]

Re: Help with programming servo and stepper motor at the same time

#1

Jan 06, 2017, 06:44 pm


By the way, I forgot to say that you can ignore the DHT11, LCD, and potentimeter stuff.

wg0z

Full Member
Posts: 150
Karma: 18 [add]

Re: Help with programming servo and stepper motor at the same time
#2

Jan 06, 2017, 06:50 pm


try running with just the servo or the stepper motor;
if performance improves, then your problem is probably the power supply for the servo and stepper

note also that changing the servo's commanded position by only one degree / 200ms is slow regardless
of any power problems.

Delta_G

Shannon Member
Posts: 11,334
Karma: 1116 [add]

Re: Help with programming servo and stepper motor at the same time

#3

Jan 06, 2017, 06:52 pm


In your specifications you link the movement of the stepper and the servo and make it seem like the
stepper should step one step once in between the forward and reverse servo sweeps.

But in your code (which is awfully complex for someone as new to coding as you claim to be) you have
the two things completely separated. Why don't you put the code to step your stepper one step in with
the code that sweeps the servo so you know it will happen at the right time. Then the only speed issue
you have to worry about is the servo sweep speed and that looks trivial to adjust.

If at first you don't succeed, up - home - sudo - enter.

FCjosh

Newbie
Posts: 6
Karma: 0 [add]

Re: Help with programming servo and stepper motor at the same time

#4

Jan 06, 2017, 07:01 pm


Alright, I tested the program without the motor. The servo ran much faster and smoother. So, does
anybody have any recommendations on how to keep enough power flowing?

Delta_G

Shannon Member
Posts: 11,334
Karma: 1116 [add]

Re: Help with programming servo and stepper motor at the same time

#5

Jan 06, 2017, 07:22 pm


Use a big enough power supply. How are you powering the motor and servo now? What type of motor
and servo? How big? Can you see how those types of details might be important?

If at first you don't succeed, up - home - sudo - enter.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Help with programming servo and stepper motor at the same time

#6

Jan 06, 2017, 07:30 pm


Please modify your post and use the code button </>

so your code looks like this

Simple Stepper Program

Nov 08, 2014, 01:54 pm Last Edit: Jul 23, 2016, 09:43 am by Robin2
I wrote a very simple program to demonstrate stepper control using a Polulu A4988 stepper driver. It
should also work with any stepper driver that just needs step and direction signals from an Arduino.

I have included it in response to several queries and it seemed it would be easier to create this Thread and
then just add a link to it.

Edit 10 Dec 2014 - readers may also be interested in this note about Stepper Motor Basics
If all you want to do is demonstrate that a motor can work this code is ideal.
Edit 23 Jul 2016 - increased millisBetweenSteps to 250 for slower running
// testing a stepper motor with a Pololu A4988 driver board or equivalent
// on an Uno the onboard led will flash with each step
// this version uses delay() to manage timing

byte directionPin = 9;
byte stepPin = 8;
int numberOfSteps = 100;
byte ledPin = 13;
int pulseWidthMicros = 20; // microseconds
int millisbetweenSteps = 250; // milliseconds - or try 1000 for slower steps

void setup() {

Serial.begin(9600);
Serial.println("Starting StepperTest");
digitalWrite(ledPin, LOW);

delay(2000);

pinMode(directionPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(ledPin, OUTPUT);

digitalWrite(directionPin, HIGH);
for(int n = 0; n < numberOfSteps; n++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(pulseWidthMicros); // this line is probably unnecessary
digitalWrite(stepPin, LOW);

delay(millisbetweenSteps);

digitalWrite(ledPin, !digitalRead(ledPin));
}

delay(3000);

digitalWrite(directionPin, LOW);
for(int n = 0; n < numberOfSteps; n++) {
digitalWrite(stepPin, HIGH);
// delayMicroseconds(pulseWidthMicros); // probably not needed
digitalWrite(stepPin, LOW);
delay(millisbetweenSteps);

digitalWrite(ledPin, !digitalRead(ledPin));
}
}

void loop() {
}

More recently there has been a request for a more complete example using buttons to control a stepper
motor and I have now created a new version which also uses millis() rather than delay() for timing.
Following is the code for this version

EDIT (13 Nov 2014) to correct serious error. Humble apologies. Instead of 2 separate programs I had
accidentally repeated the first program. The correct second program is now here

// testing a stepper motor with a Pololu A4988 driver board or equivalent

// this version uses millis() to manage timing rather than delay()


// and the movement is determined by a pair of momentary push switches
// press one and it turns CW, press the other and it turns CCW

byte directionPin = 9;
byte stepPin = 8;

byte buttonCWpin = 10;


byte buttonCCWpin = 11;

boolean buttonCWpressed = false;


boolean buttonCCWpressed = false;

byte ledPin = 13;

unsigned long curMillis;


unsigned long prevStepMillis = 0;
unsigned long millisBetweenSteps = 25; // milliseconds

void setup() {

Serial.begin(9600);
Serial.println("Starting Stepper Demo with millis()");

pinMode(directionPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(ledPin, OUTPUT);

pinMode(buttonCWpin, INPUT_PULLUP);
pinMode(buttonCCWpin, INPUT_PULLUP);
}

void loop() {

curMillis = millis();
readButtons();
actOnButtons();

void readButtons() {

buttonCCWpressed = false;
buttonCWpressed = false;

if (digitalRead(buttonCWpin) == LOW) {
buttonCWpressed = true;
}
if (digitalRead(buttonCCWpin) == LOW) {
buttonCCWpressed = true;
}
}

void actOnButtons() {
if (buttonCWpressed == true) {
digitalWrite(directionPin, LOW);
singleStep();
}
if (buttonCCWpressed == true) {
digitalWrite(directionPin, HIGH);
singleStep();
}
}

void singleStep() {
if (curMillis - prevStepMillis >= millisBetweenSteps) {
prevStepMillis += millisBetweenSteps;
digitalWrite(stepPin, HIGH);
digitalWrite(stepPin, LOW);
}
}

Re: Simple Stepper Program

#1
Nov 10, 2014, 09:24 pm
Hi Robin2,
But why is the whole program in the SETUP loop?? I did some work with steppers years ago
using the old Philips SAA1027 (I think), way before Arduinos and the like. But I have just ordered a
couple of cheap Chinese A4899 modules (about 3 the pair) so will be playing with them again soon (3
weeks from China), and will give your code a try, I have a few old steppers from printers, etc.

I would like a robot that goes where you tell it, and not just somewhere near!

Regards

Mel.

Open your mind! But not too far, your brains might fall out.
Also like Photography, model building and my 300+ Cacti and Succs.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#2

Nov 10, 2014, 10:40 pm


Quote from: Cactusface on Nov 10, 2014, 09:24 pm

But why is the whole program in the SETUP loop??

It is just a very basic test program to prove that the motor works. Move it one way. Move it the other way.
Stop.

The second program is more typical of normal use.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

daniellyall

Full Member
Posts: 148
Karma: 12 [add]

Re: Simple Stepper Program

#3

Nov 11, 2014, 12:00 am


very nice and simple will be very good for testing all the stepper I have laying around

richblus
Guest

Re: Simple Stepper Program

#4

Nov 26, 2014, 11:53 pm


Thanks for posting! I'm waiting for components but excited to try this!

dptdpt

Full Member
Posts: 137
Karma: 1 [add]

Re: Simple Stepper Program


#5

Nov 30, 2014, 04:08 pm


I do have another question. Robin - how did you come up with the 20 microsecond second pulse duration
and 25 milliseconds between pulses? Can it be done any faster? One of my steppers has 100 steps, so it
would be good if I could step it more quickly.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#6

Nov 30, 2014, 09:13 pm Last Edit: Nov 30, 2014, 09:15 pm by Robin2
Quote from: dptdpt on Nov 30, 2014, 04:08 pm

I do have another question. Robin - how did you come up with the 20 microsecond second pulse duration and 25
milliseconds between pulses? Can it be done any faster? One of my steppers has 100 steps, so it would be good if I
could step it more quickly.

This a THIRD thread where you have asked questions about your project. Why not keep all your own info
and questions in one place?

The 20 microseconds is not really needed - most stepper drivers just need a pulse of a few microseconds
and there is enough delay within the digitalWrite() function for that. Initially I tried it at 20 usecs just
being cautious.

The 25 millisecs is just trial and error. Experiment with any values you like - but only AFTER you have it
working with 25 msecs. Stepper motors will generally work at higher speeds if they are supplied with
higher voltages.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
dptdpt

Full Member
Posts: 137
Karma: 1 [add]

Re: Simple Stepper Program

#7

Nov 30, 2014, 10:27 pm


Sorry Robin! I thought about putting my question in my other thread, but thought it might be of interest
to anyone who used your program. I'd be happy to delete it if you disagree. On most forums, people
prefer for you to break up questions into different topics/threads based on relevance. It makes the forum
more useful as a knowledgebase if threads stick to a single topic as much as possible. It would make it a
lot easier for me, though, if I just put everything in a single "me" thread!

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#8

Nov 30, 2014, 11:18 pm Last Edit: Nov 30, 2014, 11:19 pm by Robin2
Leave things where they are now, but for the future I suggest you keep things in your main Thread.

I appreciate your consideration of other Forum users, but it does make it difficult to help you because
somebody trying to answer a question in one Thread may not be aware that relevant background info is
already in another Thread. You can easily include links in your Thread if you want to cross-reference
other Threads.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

marco1990
Guest

Re: Simple Stepper Program

#9

Feb 10, 2015, 11:23 am


Hi Robin,
I am a student and I am doing a part of the final project of master thesis. I have Arduino UNO, stepper
motor Skidproof Nema17, and stepper motor driver A4988. I tried to run my motor and it is ok. Now I
want to change and vary the speed. I know that the speed is linked with the frequency of the pulse signal.
Can you give some advice on how to do? Need I others components in addition to the ones I have?
Thank you so much for your availabilty

Marco

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#10

Feb 10, 2015, 11:48 am Last Edit: Feb 10, 2015, 11:49 am by Robin2
Quote from: marco1990 on Feb 10, 2015, 11:23 am

Now I want to change and vary the speed.


Just change the value of millisBetweenSteps in my demo programs

You may also be interested in stepper motor basics

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

daxasd

Newbie
Posts: 13
Karma: 1 [add]

Re: Simple Stepper Program

#11

Jul 09, 2015, 02:45 pm


@Robin2

Thank you for this useful thread.


Let me know, Can we use the code with driver CWD556 and stepper motor 57HS22 ?
daxasd

Newbie
Posts: 13
Karma: 1 [add]

Re: Simple Stepper Program

#12

Jul 09, 2015, 03:15 pm


Could you explain to me please why we use always pulse HIGH then delay and then LOW
and what if we use just HIGH
and what is the difference between the first delay and the second delay?
Re: Simple Stepper Program

#13

Jul 09, 2015, 04:30 pm


Hi daxasd,
Pluse HIGH on it's own will do nothing, it's the LOW to HIGH transition that steps the motor.
The time between this, controls how fast the motor moves.

Regards

Mel.
Open your mind! But not too far, your brains might fall out.
Also like Photography, model building and my 300+ Cacti and Succs.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#14

Jul 09, 2015, 05:33 pm

Quote from: Cactusface on Jul 09, 2015, 04:30 pm

it's the LOW to HIGH transition that steps the motor. The time between this, controls how fast the motor moves.

This may be a little confusing.

It is the time between successive pulses that controls the speed.

In the example code in Reply #12 the short delayMicroseconds(pulseWidthMicros); determines the width
of the HIGH pulse. With many stepper drivers this line can be omitted because the digitalWrite() is slow
enough to produce a satisfactory pulse.

The delay(millisBetweenSteps); determines the speed of the motor by setting the number of milliseconds
between successinge step pulses.

I'm nearly sure I answered a similar question involving a "driver CWD556 and stepper motor 57HS22"
yesterday or the day before.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

PRINT
Go Up

Pages: [1] 2

Jump to:

Newbie
Posts: 13
Karma: 1 [add]

Re: Simple Stepper Program

#15

Jul 09, 2015, 08:35 pm Last Edit: Jul 09, 2015, 08:39 pm by daxasd
thanks guys for reply

then what is the difference between using this high and low pulses and using the
Stepper.h library

for example

#include <Stepper.h>
Stepper myStepper(StepsPerRevolution, 8,9,10,11);
Stepper myStepper(StepsPerRevolution, 9,10);
setSpeed(rpms);
step(steps);

also I have seen AccelStepper.h library is it useful?

thanks

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#16

Jul 09, 2015, 09:46 pm


They are just 3 different ways of doing much the same thing. Ultimately the libraries have to do what my
code does. They just wrap it up in fancy clothes.

The libraries do have a value if you are using a h-bridge to drive a stepper because they take care of the
complex series of pulses. But it is much more sensible IMHO to leave that task to a specialized stepper
driver and take the load off the Arduino.

As its name implies the AccelStepper library is intended to apply acceleration and deceleration to the
motor. If you don't need acceleration and if you have a specilized stepper driver it does not really offer
much value IMHO.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
daxasd

Newbie
Posts: 13
Karma: 1 [add]

Re: Simple Stepper Program

#17

Jul 10, 2015, 11:11 am


@Robin2

Thank a lot

then in the case of the stepper.h library is it convenient to use these functions when we use a
specialized stepper driver that adjust the pulses and the microsteps manually
or using direct pulses without any library is better in this case.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#18

Jul 10, 2015, 05:55 pm


Quote from: daxasd on Jul 10, 2015, 11:11 am

then in the case of the stepper.h library is it convenient to use these functions when we use a specialized stepper
driver that adjust the pulses and the microsteps manually
or using direct pulses without any library is better in this case.

Your question is a bit confusing - especially the bit I have highlighed

And what do you mean by "these functions" ?

I have never used the Stepper library and I am not sure whether it is suitable for controlling a specialized
stepper driver. I think the options are DIY or the AccelStepper library.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

segg3060

Newbie
Posts: 23
Karma: 2 [add]

Re: Simple Stepper Program

#19

Jul 10, 2015, 09:55 pm


Be carefull to set the amps on the A4988 as we burned up 3 of them befor we caught on
MaxDan

Newbie
Posts: 2
Karma: 0 [add]

Re: Simple Stepper Program

#20

Jan 10, 2016, 04:19 am


Hello,

Anyone have a pic for the wiring on this code for Old Burt Brains?

First Project new job.

Thank you,

Dan

MaxDan

Newbie
Posts: 2
Karma: 0 [add]

Re: Simple Stepper Program

#21
Jan 10, 2016, 04:50 am
Hello,

Anyone have a pic for the wiring on this code for Old Burt Brains?

First Project new job.

Thank you,

Dan

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#22

Jan 10, 2016, 11:04 am Last Edit: Jan 10, 2016, 11:06 am by Robin2
The Pololu web pages for their A4988 and DRV8825 stepper driver boards have good wiring diagrams -
and lots of other useful info.

If you need more specific advice about your own project please start your own Thread so that your
details do not distract readers of my little Tutorial.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

paul_larner


Newbie
Posts: 14
Karma: 3 [add]

Re: Simple Stepper Program

#23

Aug 19, 2016, 12:05 am


will this work with an arduino and the addafruit motor shield?

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#24

Aug 19, 2016, 09:27 am


Quote from: paul_larner on Aug 19, 2016, 12:05 am

will this work with an arduino and the addafruit motor shield?

AFAIK the Adafruit motor shield has a simple h-bridge motor driver (rather than a specialized stepper
driver) and if I am correct the answer is NO.

It is important to read this Thread in the context of Stepper Motor Basics

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
paul_larner

Newbie
Posts: 14
Karma: 3 [add]

Re: Simple Stepper Program

#25

Aug 20, 2016, 07:34 am


Is there any chance you could write the code to make this work with the addafruit motor shield?,im sure
a lot more people would find that usefull!,cheers Paul.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#26

Aug 20, 2016, 10:26 am


Quote from: paul_larner on Aug 20, 2016, 07:34 am

Is there any chance you could write the code to make this work with the addafruit motor shield?,im sure a lot more
people would find that usefull!,cheers Paul.

Sorry. None.

I don't consider that shield to be a suitable device for controlling stepper motors. Did you not
read Stepper Motor Basics
Feel free to write your own code but please don't add it to this Tutorial Thread.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

paul_larner

Newbie
Posts: 14
Karma: 3 [add]

Re: Simple Stepper Program

#27

Aug 20, 2016, 03:20 pm


if its not a suitable device,why is it sold as such?,it works and delivers enough umpf for my needs,sounds
like an excuse to me!

rpt007


Dipl.-Ing.
Edison Member
Posts: 1,585
Karma: 319 [add]

Re: Simple Stepper Program

#28

Aug 20, 2016, 06:06 pm


Try to dig a bit deeper into the stuff and you might understand why @Robin2 denied to modify/ extend
the code.
It has nothing to do with the popularity of the shield.

Go with a "normal" bipolar stepper and the popular A4988 or DRV8825 and you will be happy.

Before you ask:


Did you really read and understand How to use this forum ?
AND:
Do you have already some solution or is a part of the problem sitting in front of the screen?

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Simple Stepper Program

#29

Aug 20, 2016, 07:09 pm


Quote from: paul_larner on Aug 20, 2016, 03:20 pm

if its not a suitable device,why is it sold as such?,

You need to address that question to the people who sell it. I have nothing to do with the sale or
marketing of any Arduino related products.
...R

Two or three hours spent thinking and reading documentation solves most programming problems.

PRINT

Go Up

Pages: 1 [2]

Jump to:

NEWSLETTER
SUBSCRIBE

Copyright Notice

Contact Us

About Us

Careers

2017 Arduino


Brattain Member
Posts: 40,256
Karma: 1843 [add]

Demonstration code for several things at the same time

Mar 04, 2014, 01:28 pm Last Edit: Sep 25, 2014, 10:14 am by Robin2 Reason: 1
NOTE for newcomers. The demo is entirely contained in this Post and Reply #1. There is no need to read
further unless you are interested. ...added 25Sep2014

There have been a few occasions recently where newcomers seemed to have difficulty applying the "blink
without delay" and "state" concepts to a sketch that is intended to manage a number of concurrent actions.

Its very time consuming to respond with suitable code examples - particularly as every case is a little
different.

I have prepared the attached example sketch in the hope that it will be a suitable model. I have tested it on
an Uno and a Mega. I have called it "SeveralThingsAtTheSameTime.ino". (It seems to be too long to
show the code directly in this post)

My sketch uses the concept in "blink without delay" to cause three LEDs to blink at different intervals, a
fourth LED is controlled by a button and a servo sweeps back and forth at two different speeds. The idea
is to demonstrate how different processes can be accommodated in the same general framework.

It also uses the "state machine" concept to manage the various activities and enable the different functions
to determine what to do.

I have deliberately designed the sketch as a series of short functions. Short pieces of code are much easier
to understand and debug and it will be an easy matter for a user to delete functions that they don't need or
to duplicate and modify functions if they need more of the same (for example to flash 5 LEDS at different
intervals).

There is a case for saying there is too much in the sketch but I concluded that the larger number of
activities is a better demonstration of the capabilities of this approach.

Comments are welcome.

...R
Edit ... the attached sketch has been revised to take account of comments below about improving the
timekeeping ...R

SeveralThingsAtTheSameTimeRev1.ino
9.37 KB
downloaded 12420 times

Two or three hours spent thinking and reading documentation solves most programming problems.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#1

Mar 04, 2014, 10:20 pm Last Edit: M

// SeveralThingsAtTheSameTimeRev1.ino

// An expansion of the BlinkWithoutDelay concept to illustrate how a script


// can appear to do several things at the same time

// this sketch does the following


// it blinks the onboard LED (as in the blinkWithoutDelay sketch)
// it blinks two external LEDs (LedA and LedB) that are connected to pins 12 and
11.
// it turns another Led (buttonLed connected to pin 10) on or off whenever a
button
// connected to pin 7 is pressed
// it sweeps a servo (connected to pin 5) back and forth at different speeds

// One leg of each LED should be connected to the relevant pin and the other leg
should be connected to a
// resistor of 470 ohms or more and the other end of the resistor to the Arduino
GND.
// If the LED doesn't light its probably connected the wrong way round.
// On my Uno and Mega the "button" is just a piece of wire inserted into pin 7.
// Touching the end of the wire with a moist finger is sufficient to cause the
switching action
// Of course a proper press-on-release-off button switch could also be used!

// The Arduino is not capable of supplying enough 5v power to operate a servo


// The servo should have it's own power supply and the power supply Ground should
// be connected to the Arduino Ground.

// The sketch is written to illustrate a few different programming features.


// The use of many functions with short pieces of code.
// Short pieces of code are much easier to follow and debug
// The use of variables to record the state of something (e.g. onBoardLedState) as
a means to
// enable the different functions to determine what to do.
// The use of millis() to manage the timing of activities
// The definition of all numbers used by the program at the top of the sketch
where
// they can easily be found if they need to be changed

//=======

// -----LIBRARIES

#include <Servo.h>

// ----CONSTANTS (won't change)

const int onBoardLedPin = 13; // the pin numbers for the LEDs
const int led_A_Pin = 12;
const int led_B_Pin = 11;
const int buttonLed_Pin = 10;

const int buttonPin = 7; // the pin number for the button

const int servoPin = 5; // the pin number for the servo signal

const int onBoardLedInterval = 500; // number of millisecs between blinks


const int led_A_Interval = 2500;
const int led_B_Interval = 4500;

const int blinkDuration = 500; // number of millisecs that Led's are on - all three
leds use this

const int buttonInterval = 300; // number of millisecs between button readings

const int servoMinDegrees = 20; // the limits to servo movement


const int servoMaxDegrees = 150;
//------- VARIABLES (will change)

byte onBoardLedState = LOW; // used to record whether the LEDs are on or


off
byte led_A_State = LOW; // LOW = off
byte led_B_State = LOW;
byte buttonLed_State = LOW;

Servo myservo; // create servo object to control a servo

int servoPosition = 90; // the current angle of the servo - starting at 90.
int servoSlowInterval = 80; // millisecs between servo moves
int servoFastInterval = 10;
int servoInterval = servoSlowInterval; // initial millisecs between servo moves
int servoDegrees = 2; // amount servo moves at each step
// will be changed to negative value for movement in
the other direction

unsigned long currentMillis = 0; // stores the value of millis() in each iteration


of loop()
unsigned long previousOnBoardLedMillis = 0; // will store last time the LED was
updated
unsigned long previousLed_A_Millis = 0;
unsigned long previousLed_B_Millis = 0;

unsigned long previousButtonMillis = 0; // time when button press last checked

unsigned long previousServoMillis = 0; // the time when the servo was last moved

//========

void setup() {

Serial.begin(9600);
Serial.println("Starting SeveralThingsAtTheSameTimeRev1.ino"); // so we know what
sketch is running

// set the Led pins as output:


pinMode(onBoardLedPin, OUTPUT);
pinMode(led_A_Pin, OUTPUT);
pinMode(led_B_Pin, OUTPUT);
pinMode(buttonLed_Pin, OUTPUT);

// set the button pin as input with a pullup resistor to ensure it defaults to
HIGH
pinMode(buttonPin, INPUT_PULLUP);
myservo.write(servoPosition); // sets the initial position
myservo.attach(servoPin);

//=======

void loop() {

// Notice that none of the action happens in loop() apart from reading millis()
// it just calls the functions that have the action code

currentMillis = millis(); // capture the latest value of millis()


// this is equivalent to noting the time from a clock
// use the same time for all LED flashes to keep them
synchronized

readButton(); // call the functions that do the work


updateOnBoardLedState();
updateLed_A_State();
updateLed_B_State();
switchLeds();
servoSweep();

//========

void updateOnBoardLedState() {

if (onBoardLedState == LOW) {
// if the Led is off, we must wait for the interval to expire before turning
it on
if (currentMillis - previousOnBoardLedMillis >= onBoardLedInterval) {
// time is up, so change the state to HIGH
onBoardLedState = HIGH;
// and save the time when we made the change
previousOnBoardLedMillis += onBoardLedInterval;
// NOTE: The previous line could alternatively be
// previousOnBoardLedMillis = currentMillis
// which is the style used in the BlinkWithoutDelay example sketch
// Adding on the interval is a better way to ensure that succesive
periods are identical

}
}
else { // i.e. if onBoardLedState is HIGH
// if the Led is on, we must wait for the duration to expire before turning
it off
if (currentMillis - previousOnBoardLedMillis >= blinkDuration) {
// time is up, so change the state to LOW
onBoardLedState = LOW;
// and save the time when we made the change
previousOnBoardLedMillis += blinkDuration;
}
}
}

//=======

void updateLed_A_State() {

if (led_A_State == LOW) {
if (currentMillis - previousLed_A_Millis >= led_A_Interval) {
led_A_State = HIGH;
previousLed_A_Millis += led_A_Interval;
}
}
else {
if (currentMillis - previousLed_A_Millis >= blinkDuration) {
led_A_State = LOW;
previousLed_A_Millis += blinkDuration;
}
}
}

//=======

void updateLed_B_State() {

if (led_B_State == LOW) {
if (currentMillis - previousLed_B_Millis >= led_B_Interval) {
led_B_State = HIGH;
previousLed_B_Millis += led_B_Interval;
}
}
else {
if (currentMillis - previousLed_B_Millis >= blinkDuration) {
led_B_State = LOW;
previousLed_B_Millis += blinkDuration;
}
}
}
//========

void switchLeds() {
// this is the code that actually switches the LEDs on and off

digitalWrite(onBoardLedPin, onBoardLedState);
digitalWrite(led_A_Pin, led_A_State);
digitalWrite(led_B_Pin, led_B_State);
digitalWrite(buttonLed_Pin, buttonLed_State);
}

//=======

void readButton() {

// this only reads the button state after the button interval has elapsed
// this avoids multiple flashes if the button bounces
// every time the button is pressed it changes buttonLed_State causing the Led
to go on or off
// Notice that there is no need to synchronize this use of millis() with the
flashing Leds

if (millis() - previousButtonMillis >= buttonInterval) {

if (digitalRead(buttonPin) == LOW) {
buttonLed_State = ! buttonLed_State; // this changes it to LOW if it was HIGH
// and to HIGH if it was LOW
previousButtonMillis += buttonInterval;
}
}

//========

void servoSweep() {

// this is similar to the servo sweep example except that it uses millis()
rather than delay()

// nothing happens unless the interval has expired


// the value of currentMillis was set in loop()

if (currentMillis - previousServoMillis >= servoInterval) {


// its time for another move
previousServoMillis += servoInterval;

servoPosition = servoPosition + servoDegrees; // servoDegrees might be negative


if (servoPosition <= servoMinDegrees) {
// when the servo gets to its minimum position change the interval to change
the speed
if (servoInterval == servoSlowInterval) {
servoInterval = servoFastInterval;
}
else {
servoInterval = servoSlowInterval;
}
}
if ((servoPosition >= servoMaxDegrees) || (servoPosition <= servoMinDegrees)) {
// if the servo is at either extreme change the sign of the degrees to make
it move the other way
servoDegrees = - servoDegrees; // reverse direction
// and update the position to ensure it is within range
servoPosition = servoPosition + servoDegrees;
}
// make the servo move to the next position
myservo.write(servoPosition);
// and record the time when the move happened
}
}

//=====END

Guest

Re: Demonstration code for several things at the same time

#2

Mar 04, 2014, 10:23 pm


Darn good idea :-)
Jiggy-Ninja

Faraday Member
Posts: 2,743
Karma: 317 [add]

Re: Demonstration code for several things at the same time

#3

Mar 10, 2014, 12:34 am


I prefer using switch statements for may state variables rather than ifs, even if there's only two states
something can be in. I find it easier to follow than trying to match an else with the right if to find out
what's going on, especially if they're nested.

So instead of:
void updateLed_A_State() {

if (led_A_State == LOW) {
if (currentMillis - previousLed_A_Millis >= led_A_Interval) {
led_A_State = HIGH;
previousLed_A_Millis = currentMillis;
}
}
else {
if (currentMillis - previousLed_A_Millis >= blinkDuration) {
led_A_State = LOW;
previousLed_A_Millis = currentMillis;
}
}
}

void updateLed_A_State()
{
switch( led_A_State )
{
case LOW:
if (currentMillis - previousLed_A_Millis >= led_A_Interval)
{
led_A_State = HIGH;
previousLed_A_Millis = currentMillis;
}

case HIGH:
if (currentMillis - previousLed_A_Millis >= blinkDuration)
{
led_A_State = LOW;
previousLed_A_Millis = currentMillis;
}
default:
;
}
}

I also prefer a different bracketing style to yours, but that's neither here nor there.

Hackaday: https://hackaday.io/MarkRD
Advanced C++ Techniques: https://forum.arduino.cc/index.php?topic=493075.0
Paul__B

Shannon Member
Posts: 10,862
Karma: 740 [add]

Re: Demonstration code for several things at the same time

#4

Mar 10, 2014, 01:25 am


Quote from: Jiggy-Ninja on Mar 10, 2014, 12:34 am

I also prefer a different bracketing style to yours, but that's neither here nor there.

Ah, but if you use "Auto Format", it arranges things in a certain way for you.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#5

Mar 10, 2014, 08:11 am


I debated using switch statements (even just using them in one function to illustrate how they are an
alternative to if statements). In the end I decided that it would just add to the learning burden for new
users. It would be an unusual program that could avoid if statements but switch statements are always
optional - even if convenient when you know them.

I like my bracketing system. The formatting was done manually in Gedit. If I have not been consistent
everywhere I apologize.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#6

Mar 10, 2014, 09:12 am


...
if (currentMillis - previousOnBoardLedMillis >= onBoardLedInterval) {
...
previousOnBoardLedMillis = currentMillis;
}

The average interval will be slightly to significantly more than onBoardLedInterval. For most uses (like
blinking an LED) the longer interval is insignificant. For some uses the longer interval is a failure.

previousOnBoardLedMillis += onBoardLedInterval;

...produces a bit more code but keeps the average interval at exactly onBoardLedInterval.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#7

Mar 10, 2014, 11:52 am


@CodingBadly, I'm interested but I don't understand exactly what you mean by "The average interval
will be slightly to significantly more than onBoardLedInterval"

My plan was/is to use a single instant in time (as captured in currentMillis) as the reference point for the
flashing of all of the leds so that their timing can't drift apart.

I can't figure out what effect your code would have.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

3dprinter


Edison Member
Posts: 1,336
Karma: 136 [add]
Have you testrun your INO file today?

Re: Demonstration code for several things at the same time

#8

Mar 10, 2014, 12:23 pm


Nice long example (not all examples can be 1<10 lines).

I wondered what the difference was between the attached file in the first and reply#1 with the code inline.
My editor only shows comments lines are shorter

I would do it slightly different (which means neither better nor worse) ^_^

I do not quite get the educational value of having update_LED_state() and switchLEDs() as
seperate functions - it means you have to carry LED-desired-state as global variables, when they could be
nicely encapsulated. Place most variables as static inside the function where they are exclusivly used -
this way you can not inadvertently modify a timer variable elsewhere.

CodingBadly's comment is that if your loop takes - say - 5 millisec to execute (because of some not-yet-
written heavy calculation code), then the LEDs will blink at the interval+5ms. By adding "interval" to the
"timer" (not the measured millis() value) you get it to run at the "interval" rate. For a "real" project it may
be desirable to include the loop overhead/jitter, for some you want a steady rate.

PeterH
previousOnBoardLedMillis += onBoardLedInterval;

That is my preferred approach too.

When your things are each implemented in separate self-contained functions s in the original example, I
also like to define the state data as local static variables rather than globals. Reducing the scope is
beneficial in its own right but in particular this makes copy/paste much safer, and that's something that I
would expect novice coders to be doing a lot when starting from examples like this. For example:

void blinkLed()
{
static const int LED_PIN = 13;
static const unsigned long BLINK_INTERVAL = 500; // duration of each blink
phase
static unsigned long lastBlinkTime = 0;

if(millis() - lastBlinkTime >= BLINK_INTERVAL)


{
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
lastBlinkTime += BLINK_INTERVAL
}
}

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#10

Mar 10, 2014, 06:20 pm Last Edit: Mar 10, 2014, 06:22 pm by Robin2 Reason: 1
Quote from: PeterH on Mar 10, 2014, 01:28 pm

That is my preferred approach too.

I'm hoping you or @GodingBadly will explain why.

I did consider static local variables but personally I prefer the simplicity and visibility of globals when I'm
working with such a small memory space. (I wouldn't do that with PC code). Also I was trying to limit the
amount of new stuff that a newbie has to take in.

I understand what you say about copy/paste, but I guess I'm old fashioned enough to prefer users to
understand what's going on.
There is an opportunity for someone to use my code as a starting point for a separate lesson on the use of
static local variables

And thanks very much for all the comments.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#11

Mar 10, 2014, 06:57 pm

Two hints...
1. You assume the delta is always 1. It is not.
2. You assume the time to execute loop is <= 1 millisecond. In your example that may be true but that
will not be true for every application.

Assume millis returns values evenly divisible by seven (0, 7, 14, etcetera) and work through the code by
hand.
el_supremo

Faraday Member
Posts: 3,700
Karma: 621 [add]

Re: Demonstration code for several things at the same time

#12

Mar 10, 2014, 07:16 pm


@jiggy-ninja:
I also prefer the switch statement but you need break statements in there to make it equivalent to the
original code. I would write it like this:

void updateLed_A_State()
{
switch( led_A_State )
{
case LOW:
if (currentMillis - previousLed_A_Millis >= led_A_Interval)
{
led_A_State = HIGH;
previousLed_A_Millis = currentMillis;
}
break;

case HIGH:
if (currentMillis - previousLed_A_Millis >= blinkDuration)
{
led_A_State = LOW;
previousLed_A_Millis = currentMillis;
}
break;

default:
break;
}
}

Don't send me technical questions via Private Message.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#13

Mar 10, 2014, 08:24 pm

Quote from: Msquare on Mar 10, 2014, 12:23 pm

I wondered what the difference was between the attached file in the first and reply#1 with the code inline. My editor only shows
comments lines are shorter

Sorry, I meant to mention this earlier ...

You are quite right, I was just trying to save enough bytes to get within the upload limit. I actually haven't
tested the visible version

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

Jiggy-Ninja

Faraday Member
Posts: 2,743
Karma: 317 [add]

Re: Demonstration code for several things at the same time

#14

Mar 10, 2014, 09:17 pm

Quote from: el_supremo on Mar 10, 2014, 07:16 pm

@jiggy-ninja:
I also prefer the switch statement but you need break statements in there to make it equivalent to the original code. I would write
it like this:

Pete

>.< Doh!

And that, ladies and gentlemen, is one argument against using switches.
Hackaday: https://hackaday.io/MarkRD
Advanced C++ Techniques: https://forum.arduino.cc/index.php?topic=493075.0

PRINT

Go Up

Newbie
Posts: 9
Karma: 0 [add]

Having problems in code

May 15, 2017, 08:08 pm Last Edit: May 15, 2017, 09:20 pm by trode
Hi there , im new on arduino and i did some projects by myself, but now im having some troubles on
my new project.
Im trying to make a kennel with arduino, like im trying to make the handler job easier, if they press a
push button they can open the food container and the food falls on to the dog bowl and if they push the
other push button associated to the servo motor they close the container, and they can see the temperature
and the humidity of the room on a 16x4 LCD.

Im using a arduino mega 2560, a DHT11 sensor, 2 LCD's 16x4, 4 push buttons and 2 servo motor HS-
422.

I made the codes separated and then joined them, the codes were working fine alone, but then when i
joined them the servo motors didnt work, i can ear the servo motor working, but if i push the button they
dont move, i cant find the problem i searched the internet i cant find nothing.

My code:

#include <stdio.h>
#include <dht.h>
#include <LiquidCrystal.h>
#include<Servo.h>
#define DHTPIN A0
#define DHTPIN1 A1

int pos = 0;

Servo servo;
Servo servo2;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);


LiquidCrystal lcd2(12, 10, 5, 4, 3, 2);

dht DHT;

void setup(){

lcd.begin(20, 4);
lcd2.begin(16, 2);

pinMode(52, INPUT);
pinMode(50, INPUT);
pinMode(53, INPUT);
pinMode(51, INPUT);

servo.attach(22);
servo2.attach(24);
}

void loop()
{
DHT.read11(DHTPIN);
lcd.setCursor(0,0);
lcd.print("Temp= ");
lcd.print(DHT.temperature);
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Hum= ");
lcd.print(DHT.humidity);
lcd.print("% ");
delay(2000);
DHT.read11(DHTPIN1);
lcd2.setCursor(0,0);
lcd2.print("Temp= ");
lcd2.print(DHT.temperature);
lcd2.print("C");
lcd2.setCursor(0,1);
lcd2.print("Hum= ");
lcd2.print(DHT.humidity);
lcd2.print("% ");
delay(2000);

if (digitalRead(52) == HIGH && pos < 180) {


pos++;
servo.write(pos);
delay(15);
}
if (digitalRead(50) == HIGH && pos > 0) {
pos--;
servo.write(pos);
delay(15);
}
if (digitalRead(53) == HIGH && pos < 180) {
pos++;
servo2.write(pos);
delay(15);
}
if (digitalRead(51) == HIGH && pos > 0) {
pos--;
servo2.write(pos);
delay(15);
}
}

I did the images on circuits.io and doesnt exist arduino mega so i have 1 image for the 2 LCD's and sensor
and the other for the push buttons, on the second image the white lines represent the wires that will conect
on the arduino ( first wire on the 52 pin, second wire on the 50 pin, third wire on the 53 pin and fourth
wire on the 51 pin), two of the servo motors pins will conect on the GND and 5V, and the other will
conect on the 22 pin, the other servo motor pin will not conect on 22 pin but on the 24 pin.

If someone could help me i would be very happy.

Capturar.PNG
66.28 KB
downloaded 12 times
1.PNG
27.37 KB
downloaded 12 times

sterretje

Faraday Member
Posts: 5,666
Karma: 909 [add]
Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years absence.

Re: Having problems in code

#1

May 15, 2017, 08:23 pm


Please add code tags around your code. Todo so, edit your post and
type [code] before your code and
type[/code] after your code.

Also, please provide a wiring diagram how everything is connected. A photo / scan of a handdrawn one is
fine.

How are you powering the servos?

If you understand an example, use it.


If you don't understand an example, don't use it.

Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years
absence.
cattledog

Faraday Member
Posts: 3,825
Karma: 806 [add]

Re: Having problems in code

#2

May 15, 2017, 09:00 pm Last Edit: May 15, 2017, 09:02 pm by cattledog
You have two significant delays in the lcd section which are blocking the button reading. It looks like you
will move 1 degree every 4 seconds. Without the display code you were moving 1 degree every 15 ms.

Take a look at the "blink without delay" example in the


ide,(File>Examples>02Digital>BlinkWithoutDelay) and place the dht readings and their display on a
millis() timer.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]
Re: Having problems in code

#3

May 16, 2017, 08:54 am


The demo Several Things at a Time is an extended example of BWoD and illustrates the use of millis() to
manage timing. It may help with understanding the technique.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

trode

Newbie
Posts: 9
Karma: 0 [add]

Re: Having problems in code

#4

May 16, 2017, 07:43 pm


Im feeding my servo with 5 V from the arduino.
I still dont get the delay part, could you tell me more specific whats the problem with the delay,
please .

septillion

Faraday Member
Posts: 5,739
Karma: 658 [add]
Re: Having problems in code

#5

May 16, 2017, 08:01 pm


In a delay, the Arduino does NOTHING, absolute nothing. It just waits and waits. It does not read
buttons, it updates nothing, it just sits there. Not very great if you want to detect a button press

Use fricking code tags!!!!


I want x => I would like x, I need help => I would like help, Need fast => Go and pay someone to do the job...

NEW Library to make fading leds a piece of cake


https://github.com/septillion-git/FadeLed

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Having problems in code

#6

May 16, 2017, 08:13 pm

Quote from: trode on May 16, 2017, 07:43 pm

Im feeding my servo with 5 V from the arduino.

The usual advice is NOT to do that as Servos can draw more power than the 5v pin can provide. That can
damage the Arduino or at least cause it to behave erratically.

Give the servo a separate power supply and connect the servo GND to the Arduino GND.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
trode

Newbie
Posts: 9
Karma: 0 [add]

Re: Having problems in code

#7

May 16, 2017, 08:31 pm


So i take out the delay from the servos?

cattledog

Faraday Member
Posts: 3,825
Karma: 806 [add]

Re: Having problems in code

#8
May 16, 2017, 08:36 pm Last Edit: May 16, 2017, 08:38 pm by cattledog

Quote

So i take out the delay from the servos?

Start by taking the two delay(2000) calls out of the dht/lcd routines.

You may want to place that section of code on a "blink without delay" millis() timer.

trode

Newbie
Posts: 9
Karma: 0 [add]

Re: Having problems in code

#9

May 27, 2017, 09:33 pm


Ive been trying tounderstand the blink without dealy code but i cant understand how do i put it on my
code.
Can someone help me pls?
cattledog

Faraday Member
Posts: 3,825
Karma: 806 [add]

Re: Having problems in code

#10

May 27, 2017, 10:15 pm

Quote

Ive been trying to understand the blink without delay code but i cant understand how do i put it on my code.

What have you tried? Give us your best effort to remove the two delay(2000) calls from temperature and
humidity reading and display section.

You can place that whole block of code within a millis() timer.

if(millis() -lastTime >= someInterval)


{
lastTime = millis(); //alternatively you can use lastTime += someInterval
//read and display temperature and humidity
}

PRINT
Go Up

Pages: [1]

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Stepper Motor Basics

Dec 10, 2014, 09:46 pm Last Edit: Feb 17, 2015, 05:03 pm by Robin2

Introduction
===========
I find myself repeatedly typing similar replies to similar questions about the basics of stepper motors and
I thought it would be useful to write this note as it will be a little more comprehensive than any individual
reply.

The information is presented under several different headings and there is quite a bit of overlap and cross-
referencing of ideas so I suggest that you should read all of the note at least once. I think it would be
possible to miss some important info if you only read the bit that immediately interests you.

Throughout this note I have referenced Pololu products. I have no connection with the company apart
from being a satisfied user of their A4988 stepper driver boards.

This note is intended to provide guidance for the Arduino user who is new to stepper motors. It is not
intended to be an expert dissertation on the subject.

Please be aware that this text continues into the next Post

Types of stepper motor


======================
Broadly speaking there are two types of stepper motor - unipolar and bipolar.

Bipolar motors have 4 wires connecting to the two separate coils inside the motor - one pair for each coil.
There are also two types of unipolar motor - those with 5 wires and those with 6 wires.

The 6-wire motors can also be referred to as hybrid motors. They are similar to the 4-wire bipolar motors
and just have an extra wire connected to the centre of each of the coils. If you want to use a 6-wire motor
in bipolar mode just ignore the wires that connect to the centres of the coils.

The 5-wire motors cannot be driven by a driver designed for a bipolar motor. An example of a 5-wire
motor is the small 28BYJ-48 motor which can be seen in many Arduino projects and usually uses a
ULN2003 chip as its driver.

This note only relates to bipolar motors and does NOT apply to 5-wire motors or the ULN2003 driver.

Motor Specifications
====================
Datasheets normally quote the coil current, coil resistance, nominal voltage and holding torque and steps
per revolution. For example, for this motor the values are 1 Amp, 2.7 Ohms, 2.7volts, 1.4Kg-cm and 200
steps/rev.

The nominal voltage is irrelevant for all practical purposes. The important figure is the rated current.

The rated current is normally the current per-coil and when currents are quoted for stepper motor driver
boards that is normally also a per-coil figure.

The holding torque is the torque available to resist rotation while the motor is stationary. The available
torque will decline as speed increases.

Some manufactures provide graphs showing how the torque varies with speed.

Operating Voltage
=================
Stepper motors are very different from regular DC motors.

With a DC motor you control the current in order to control the speed of the motor. The usual way to
control the current is to vary the voltage - perhaps using the Arduino analogWrite() function to control a
Pulse Width Modulated power supply to the motor.
Stepper motors pretty much draw their full current all the time, even when they are stationary - that is
how they resist being moved from their present position. This means they are very inefficient.

For all practical purposes the nominal voltage of a stepper motor is irrelevant. It is the voltage which
would drive the rated current through the coil when the motor is stationary based on Ohms law e.g. 2.7v =
1A * 2.7 Ohms. However, as soon as the motor starts moving the combination of the inductance of the
coils and the back-emf generated by the movement will prevent the nominal voltage from producing the
rated current.

For this reason stepper motors are normally driven with a much higher voltage. This, in turn, means that a
specialized stepper motor driver board is needed which can limit the current to whatever the motor can
take. If the current is not limited the high voltage would quickly destroy the motor.

Stepper Motor Driver Boards


===========================
These are specialized components designed to control stepper motors conveniently and efficiently.
The Pololu A4988 is a typical example that is often used with Arduinos.

Generally speaking specialized stepper motor driver boards only require two connections (plus GND) to
the Arduino for step and direction signals.

Normally specialized stepper motor driver boards have the ability to limit the current in the motor which
allows them to drive the motor with a high voltage (up to 35v for the Pololu A4988) for better high speed
performance.

And they all usually have the ability to do microstepping. The Pololu A4988 can do 1/2, 1/4, 1/8 and 1/16
microsteps. It defaults to full steps. I believe the BigEasydriver which uses the same A4988 chip defaults
to 1/16 microstepping mode.

H-bridge driver - e.g. LN298


============================
These can be made to control a stepper motor but they are a very poor choice - mainly because they have
no method for limiting the current and therefore cannot use high voltages. They are also more trouble to
connect to an Arduino (they require more pins) and more trouble to control with an Arduino (more
calculations for the Arduino to do).
Choosing a motor and motor driver
=================================
First choose the motor

The important specification is the torque of the motor. Generally speaking the holding torque is quoted.
For the motor I linked to above it is 1.4Kg-cm. The available useful torque will decline as the speed
increases and at no-load maximum speed it will be zero. Some (probably the more expensive) motor
manufactures provide graphs showing how the torque varies with speed.

To figure out what motor you need you will have to measure or estimate the torque required. It would be
a good idea to choose a motor with a good margin of surplus torque.

It is not too difficult to make a rough measurement of the torque required but it is beyond the scope of this
note.
Edit 17 Feb 2015 See Reply #29 for a suggestion

Then choose the stepper motor driver

When you have selected a motor and know what current it requires you can choose a stepper motor driver
that can comfortably supply the required current.

You should be aware that the economical single-chip stepper drivers (such as the A4988 and the
DRV8825) can only supply about 2 amps. If your motor requires more than that, you will need to get one
of the more expensive commercial stepper drivers. However the working principle will be practically
identical to the A4988.

NEMA 17 and 23
==============
These standards only define the size of the front face of the motor and the location and size of the
mounting screw holes. They say nothing about the power of the motor. The 17 is an abbreviation of 1.7
inches.

...... continued in next Post

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#1

Dec 10, 2014, 09:47 pm Last Edit: Jan 01, 2015, 10:11 pm by Robin2
continued from previous Post ....

Microsteps
==========
Most (but certainly not all) stepper motors do 200 full steps per revolution. By appropriately managing
the current in the coils it is possible to make the motor move in smaller steps. The Pololu A4988 can
make the motor move in 1/16th steps - or 3,200 steps per revolution.

The main advantage of microstepping is to reduce the roughness of the motion. The only fully accurate
positions are the full-step positions. The motor will not be able to hold a stationary position at one of the
intermediate positions with the same position accuracy or with the same holding torque as at the full step
positions.

Generally speaking when high speeds are required full steps should be used.

It is possible with most drivers including the Pololu A4988 to use the Arduino program to change the
microstep setting. This would require additional connections between the driver and the Arduino.

Stepper Motor Speed


===================
By comparison with regular DC motors stepper motors are very slow devices.

Typical speeds might be 1000 to 4000 steps per second and for a 200 step motor that would represent 5 to
20 rps (300 to 1200 rpm).

Generally speaking the motors with low coil resistance and high currents (and low nominal voltages) will
be most suitable for higher speeds. A high voltage will also be needed for high speed.

Acceleration
============
If the stepper motor is required to move a heavy load it will normally be necessary to start the movement
slowly (as with any motor) and accelerate to the desired speed and, equally, to decelerate when it is
necessary to stop.

This is quite different from a DC motor which will accelerate and decelerate automatically.

If you try to start or stop a stepper motor too quickly it will simply skip steps with no damage to motor.
However The Arduino has no means to know whether or how many steps have been missed and all of the
position control will be lost.

For this reason, in particular, it is essential to choose a motor with sufficient torque for the job and to use
acceleration and deceleration when necessary.

Position Feedback
=================
Stepper motors do not have the ability to tell the Arduino what position they are at, nor do they have the
ability (like a servo) to go to a particular position. All they can do is move N steps from where they are
now.

If it is essential to have position feedback a rotary encoder can be attached to the motor shaft - but that is
beyond the scope of this essay.

Initial Position
================
When it starts up the Arduino has no means of knowing where the stepper motor is positioned - for
example somebody might have moved it manually when the power was off.

The usual way to establish a datum for counting steps is with a limit switch. At startup the Arduino will
move the motor until it triggers the switch. The Arduino will then regard that step position as step zero for
the purpose of future position keeping.

Arduino Libraries
=================
When using an Arduino with a specialized stepper motor driver board such as the Pololu A4988 there is
little to be gained from using an Arduino library unless you need the acceleration feature of
the AccelStepper library.

Demonstration Arduino code


==========================
The code in my simple stepper demo is intended as a first step to getting your motor working. It also
shows how easy it is to control a motor without a library when a specialized stepper motor driver such as
the Pololu A4988 i8s used.

Wiring connections for a stepper motor


======================================
The code in my simple stepper demo assumes that the motor is connected as shown in the wiring
diagrams on the Pololu A4988 web page.

Arduino Pulse Width Modulation (PWM)


====================================
Arduino PWM using analogWrite() has nothing to do with controlling stepper motors. To control a
stepper motor though a specialized stepper motor driver the Arduino just needs to provide step and
direction signals using digitalWrite().

PWM may be used within the stepper motor driver to limit the current in the motor coils but this process
is invisible to the Arduino user.

....END

...R

Edit 01 Jan 2014 to change "proper" to "specialized"


Two or three hours spent thinking and reading documentation solves most programming problems.

daniellyall

Full Member
Posts: 148
Karma: 12 [add]

Re: Stepper Motor Basics

#2

Dec 11, 2014, 11:37 am Last Edit: Dec 11, 2014, 11:38 am by daniellyall
bang on

good start for nobs

Cactusface

God Member
Posts: 601

1.
Karma: 133 [add]
Half intelligent old fart.....
www.melsaunders.co.uk

Re: Stepper Motor Basics

#3

Dec 11, 2014, 12:25 pm


Hi Robin,
Thanks that was very useful! I have had a little play with some old salveged steppers (EX
printer, etc) and hope one day to build a bot using them for accurate movement and perhaps drawing, etc
or as I suggested to someone the other day a Pantagraph? or drawing machine!! I have used the good old
ULN28003, but the new A4988 type of modules make it a lot easier with only two signals STEP & DIR.
Fixing wheels on a 5mm shaft can be tricky....

Regards

Mel.

Open your mind! But not too far, your brains might fall out.
Also like Photography, model building and my 300+ Cacti and Succs.

dave-in-nj

Faraday Member
Posts: 5,065
Karma: 424 [add]

Re: Stepper Motor Basics

#4

Dec 11, 2014, 01:22 pm


"The nominal voltage is irrelevant for all practical purposes. The important figure is the rated current. "

I disagree with this statement. the manufacture offers data for the end user to use for calculations.
this statement is akin to saying that resistor wattage is irrelevant for all practical purposes in data circuits.
the stepper motor is a coil, the coil has inductance. what you can do with a coil is very much based on
manufacture. ergo the manufacture offers test data. the motor power supply calculation requires you
know the motor voltage, then allows for the inductive reactance.

a motor has two major causes of heating, copper losses and iron losses. copper losses are from power
flowing through the motor. iron losses are from the eddy currents and hysteresis heating.

every motor has a maximum voltage rating. it is a disservice to dismiss a part of the calculations without
describing why.

I offer white papers from a stepper motor designer. probably one of the foremost authorities on stepper
motors.

You would do well to read and understand how a stepper motor uses voltage and power and why they are
so important to understand, especially if you want to post as a source of teaching for others.

http://www.geckodrive.com/app-notes.html

he has a simple writing style and except for a few spelling errors (ration instead of ratio) he is very
readable.

JimFlounders
Guest

Re: Stepper Motor Basics

#5
Dec 11, 2014, 02:13 pm
Good stuff.
Thanks

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#6

Dec 11, 2014, 02:26 pm

Quote from: dave-in-nj on Dec 11, 2014, 01:22 pm

every motor has a maximum voltage rating. it is a disservice to dismiss a part of the calculations without describing why.

I make no apology for keeping my material simple. And I did say "for all practical purposes" - meaning
for all practical purposes for the people for whom the note is written.

The important point is that when the datasheet says 2.7v it does not mean that is the maximum you can
use, nor even that it is close to ideal.

If you can give me one or two sentences that will enhance the text without confusing newcomers I will
certainly consider including them. That is the purpose of asking for comments.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

nilton61


Edison Member
Posts: 1,356

1.
Karma: 63 [add]

Re: Stepper Motor Basics

#7

Dec 11, 2014, 05:12 pm


What is of interest in motor voltage is that it leads to a maximum value of the power supply

Quote

32 * VL = VMAX

The reason for this is iron losses (eddy currents) heating up the motor. But, this is almost academical
since most stepper motors i encountered have motor voltages over 1,5V and supplies over 45V are seldom
used. Also most drivers set the upper voltage limit at 35V which is safe for almost all motors.

Ecellent text, and really needed. What could be added is that power supplies should be unregulated with a
filter/reservoir capacitor with a value of:

Quote

(80,000 * I) / V = C(uF)

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#8
Dec 11, 2014, 06:15 pm

Quote from: nilton61 on Dec 11, 2014, 05:12 pm

Ecellent text, and really needed. What could be added is that power supplies should be unregulated with a filter/reservoir
capacitor with a value of:

Thank you (and everyone else) for the kind words.

I have noted your very useful views about power supplies elsewhere but I don't feel competent to write a
text about it myself. Perhaps you could find the time to write a few sentences which can either stand here
as a separate post or I might incorporate it into my text.

My own experience is that a computer power supply (18v or so) and a large 12v lead-acid battery work
fine. I haven't tried an unregulated supply myself to see if it would be better.

And I don't want to discourage or prevent newcomers from using a satisfactory power supply that they
happen to have, even if it is sub-optimal.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

nilton61

Edison Member
Posts: 1,356

1.
Karma: 63 [add]

Re: Stepper Motor Basics

#9
Dec 11, 2014, 07:36 pm Last Edit: Dec 11, 2014, 07:37 pm by nilton61
The reason for advocating unregulated supplies is that regulated ones more often than not have quite
small reservoir/filter caps. This has two negative effects

1. The small caps cannot absorb the returning energy when deaccelarating
2. The very transient currents can interfere with the voltage regulator

So the main issue is having large enough caps which should be stated.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#10

Dec 11, 2014, 08:22 pm

Quote from: nilton61 on Dec 11, 2014, 07:36 pm

So the main issue is having large enough caps which should be stated.

I've been thinking some more about the possibility of a text about power supplies and the problem is that I
keep running into more questions which leads me to think that it needs an entire Thread of its own.

For example does the piece I have quoted mean that it is a good idea to attach a very large capacitor to a
regulated power supply as well as to an unregulated supply?

And, to confirm my understanding, I have 3 motors that each have a coil current of 0.33 A. That would
mean 0.99A for all 3 - say 1.5A to give a margin. And, supposing they are powered at 20v your formula
would be
80,000 * 1.5 / 20 which gives a capacitor value of 6,000 microFarads.

And without intending the least disrespect to your knowledge I have not yet got any sense of how much
difference it would make to have an unregulated rather than a regulated power supply with the same
voltage assuming both can deliver enough amps.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

daniellyall

Full Member
Posts: 148
Karma: 12 [add]

Re: Stepper Motor Basics

#11

Dec 12, 2014, 12:45 am Last Edit: Dec 12, 2014, 04:39 am by daniellyall
just a note on my router I have 1400w 16 amp 80vdc power supply's the motors don't get hot at all I can
push them to 150vdc then they will get hot.

having a decent stepper driver takes care of its motors.

robin it would be a good idea to add in the steeps need to work out what size stepper a person would need
to get

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#12
Dec 12, 2014, 11:13 am

Quote from: daniellyall on Dec 12, 2014, 12:45 am

robin it would be a good idea to add in the steeps need to work out what size stepper a person would need to get

I thought about that. But it can get very complex - especially if you try to keep it simple. So much
depends on the reader's level of knowledge. That's why I just left it at "To figure out what motor you need
you will have to measure or estimate the torque required ..... It is not too difficult to make a rough
measurement of the torque required but it is beyond the scope of this note.".

If you have time to submit a suggested text I would really appreciate it.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

dave-in-nj

Faraday Member
Posts: 5,065
Karma: 424 [add]

Re: Stepper Motor Basics

#13
Dec 12, 2014, 12:46 pm

Quote from: daniellyall on Dec 12, 2014, 12:45 am

just a note on my router I have 1400w 16 amp 80vdc power supply's the motors don't get hot at all I can push them to 150vdc
then they will get hot.

having a decent stepper driver takes care of its motors.

robin it would be a good idea to add in the steeps need to work out what size stepper a person would need to get

I believe that the purpose of this thread is to hand-hold a newbie and get them past the common problems.
As Robin2 stated, this thread addresses the repeated problems newbies encounter.
It is a superficial introduction, touching only on the needed parts, but considering the limited space and
the capacity of the newbie to grasp the concepts, it is at exactly the right level. a good idea and pretty
well executed.

dave-in-nj

Faraday Member
Posts: 5,065
Karma: 424 [add]

Re: Stepper Motor Basics

#14
Dec 12, 2014, 01:04 pm

Quote from: Robin2 on Dec 11, 2014, 08:22 pm

And without intending the least disrespect to your knowledge I have not yet got any sense of how much difference it would make
to have an unregulated rather than a regulated power supply with the same voltage assuming both can deliver enough amps.

...R

I believe the whole concept of this thread is to get the NEWBIE to connect a stepper and make it move.
that said, almost any power supply will work for this purpose. and old brick that has the current, an old
PC power supply. whatever. I am content on building my own, but IMHO building a power supply is
about 5 steps down the road, and does not belong at this level.
suffice it to say that to get started, a power supply that has enough current should be good enough to use
to get the motors moving and it is is an old PC power supply with 12 volts or one from an old laptop, it
does not matter in order to get that motor spinning. once you have gotten the motor to spin and step
forward and back and things look good, it would be desirable to try to improve the performance by either
building or buying a power supply that is selected for the application.
as a note, the back EMF being delivered to the power supply from coil-A will be immediately send to
coil-B and not stored. for that reason, the regulated power supply will often work fine. in addition, many
regulated power supplies are designed to handle the higher voltage. lastly, I sincerely believe that AT
THIS LEVEL, no newbie will be running high power, high current motors under a load with sufficient
deceleration as to create enough back EMF to be of any concern.
PRINT

Go Up

Pages: [1] 2 3 4

Jump to:
NEWSLETTER

Newbie
Posts: 12
Karma: 0 [add]

Combining codes

Aug 13, 2017, 10:20 am


I am trying to combine 5 bits of code for an environmental monitor

I have a
DHT11 Sensor
LCD Screen
Utrasonic sensor
LDR
Servo

I am trying to have a breadboard and UNO board powering these sensors so when the temperature in a
room goes above 25 degrees celcius the window will open. My code I have for this so far is in seperate
parts these are

#include <dht.h>

dht DHT;

#define DHT11_PIN 7

void setup(){
Serial.begin(9600);
}

void loop()
{
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(1000);
}

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
lcd.begin(16, 2);
}

void loop() {
lcd.print("hello, world!");
delay(500);
lcd.clear();
delay(500);
}

/*
Adafruit Arduino - Lesson 14. Sweep
*/

#include <Servo.h>

int servoPin = 9;

Servo servo;

int angle = 0; // servo position in degrees

void setup()
{
servo.attach(servoPin);
}

void loop()
{
// scan from 0 to 180 degrees
for(angle = 0; angle < 180; angle++)
{
servo.write(angle);
delay(15);
}
// now scan back from 180 to 0 degrees
for(angle = 180; angle > 0; angle--)
{
servo.write(angle);
delay(15);
}
}

#include "NewPing.h"

#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters).
Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and


maximum distance.

void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
delay(500); // Wait 500ms between pings (about 2 pings/sec). 29ms should be the
shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance and print
result (0 = outside set distance range, no ping echo)
Serial.println("cm");
}

and I also am wondering what code I would need to incorporate LDR into this?

Any help is much appreciated!

J-M-L


Tesla Member
Posts: 8,160
Karma: 679 [add]

Re: Combining codes

#1

Aug 13, 2017, 10:32 am


what have you tried?

Please do not PM me for help, others will benefit as well if you post your question publicly on the
forums
Pas de messages privs SVP

arowe4610

Newbie
Posts: 12
Karma: 0 [add]

Re: Combining codes

#2

Aug 13, 2017, 10:34 am


I don't know much about coding. I tried to combine them by seperating the setups and the void loops and
uploading them to my board but it didn't work.

J-M-L

Tesla Member
Posts: 8,160
Karma: 679 [add]

Re: Combining codes

#3

Aug 13, 2017, 10:45 am Last Edit: Aug 13, 2017, 10:46 am by J-M-L
you need to merge the relevant parts of the setup() into one setup() and then redesign the loop to do
everything that is needed

do you understand each of the codes? if not this is where to start (possibly do some of the tutorials - if
you don't learn to program you'll go nowhere and it will be a miserable experience trying to do things you
don't understand)

Please do not PM me for help, others will benefit as well if you post your question publicly on the
forums
Pas de messages privs SVP

arowe4610

Newbie
Posts: 12
Karma: 0 [add]

Re: Combining codes

#4

Aug 13, 2017, 11:49 am


If anybody knows how to combine these codes could you post the completed code below please
PaulRB

Faraday Member
Posts: 5,870
Karma: 546 [add]

Re: Combining codes

#5

Aug 13, 2017, 12:03 pm


Many people on this forum know how to merge your codes. But they won't just do it for you. There is the
"Gigs and Collaborations" section of the forum where you can offer to pay someone to do this. But in this
section of the forum, they are here to help you learn and understand. That won't happen if you do not put
any effort in.

J-M-L

Tesla Member
Posts: 8,160
Karma: 679 [add]
Re: Combining codes

#6

Aug 13, 2017, 01:16 pm


and we don't know how you want to combine them anyway...

Combining does not mean anything. You need to define exactly what your program needs to do.

From your initial explanation you need to read the temperature, test the temperature and based on the test
(and window status) open or close the window. But we have not clue what is the LCD for? what is the
Utrasonic sensor for ? what's the LDR for ?

I suggest you try to put together a small code that reads the temperature, test against 25C and if you just
crossed the threshold print on the Serial Monitor "Opening the window" and if you crossed below 25
then print on the Serial Monitor "Closing the window"

Please do not PM me for help, others will benefit as well if you post your question publicly on the
forums
Pas de messages privs SVP

terryking228

Chrome App Beta


Faraday Member
Posts: 3,121

1.
Karma: 400 [add]
Terry has designed broadcast stations, recording studios, broadcast equipment, intelligent machines and special
computer languages for IBM, and has worked as a broadcast journalist covering elections, fires, riots and
Woodstock. He has taught electronics
http://yourduino.com

Re: Combining codes

#7
Aug 14, 2017, 02:28 am Last Edit: Aug 14, 2017, 02:29 am by terryking228
Hi,
There is a suggested approach to combining code On This Page:
http://arduino-info.wikispaces.com/CombiningArduinoSketches

Regards, Terry King terry@yourduino.com - Check great prices, devices and Arduino-related boards at
http://YourDuino.com
HOW-TO: http://ArduinoInfo.Info

Dec 12, 2014, 01:24 pm


I think that generally speaking, this is a good start. It is apparent that the writer does not like the L298
boards that so many newbies have and ask about. I would offer that more technical discussion would be
called for. It appears to me that the section about them is dismissive.

the L298 does have sense resistors to limit current, check the data sheet.

IMHO, it would be appropriate to remove the writers (negative) evaluation of the board and be more
technical.

the L298 is a full or half step driver that can power a stepper. it takes 4 pins from the Arduino and is used
on a bi-polar motor. running a full step at slow speed will have the motor appear to jump and shake. a
half step will remove much of the apparent motor movement. The cost of the L298 is comparable to the
A4988. in the opinion of the writer the A4988 is a much better choice.

a micro-stepper breaks each step by sending each of the two coils some energy. if you think of it as
taking the power and one coil gets 90% and the other gets 10%, then 80/20, 70/30... and so on, you can
see that the movement will be much more fluid. this is most apparent at reduced speeds.

at higher speeds the micro-stepping actually takes more time and can become a problem. at this
introductory level, we do not need to address these things, but only bring them to your attention. This is
mentioned because you will find both the jumpy movement at low speeds with a full step driver and a
limit to high speed when using a high number of micro-steps,.
dave-in-nj

Faraday Member
Posts: 5,065
Karma: 424 [add]

Re: Stepper Motor Basics

#16

Dec 12, 2014, 01:27 pm


motor speed :

a DC motor delivers full power and full torque at high speeds. as the speed is reduced, the power drops
off.
a stepper delivers maximum power at it's lowest speeds and as speed increases, power drops off.
each type of motor has applications that they are best suited for.

nilton61

Edison Member
Posts: 1,356

1.
Karma: 63 [add]

Re: Stepper Motor Basics

#17

Dec 12, 2014, 02:43 pm Last Edit: Dec 12, 2014, 02:47 pm by nilton61

Quote from: dave-in-nj on Dec 12, 2014, 01:27 pm

motor speed :

a DC motor delivers full power and full torque at high speeds. as the speed is reduced, the power drops off.
a stepper delivers maximum power at it's lowest speeds and as speed increases, power drops off.
each type of motor has applications that they are best suited for.

Not quite correct.

A brushed Dc motor delivers a torque that is almost proportional to its current and hence at maximum for
a stalled motor and zero for a free running motor (assuming constant voltage). The output power
(N(rpm)*M(Nm)/9,55) is zero at these two points and at its maximum at about half the free running
speed. The efficiency is at its maximum at about 70%-80% of the free running speed.
A stepper motor (as all ac motors driven with variable frequency) delivers aproximately a constant torque
up to its corner speed which depends on the supply voltage and after that aproximately constant power,
that is above the corner speed torque decreases inversely with speed

It seems that a similar text on rotating machinery is also needed

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#18
Dec 12, 2014, 02:50 pm

Quote from: dave-in-nj on Dec 12, 2014, 12:46 pm

but considering the limited space and the capacity of the newbie to grasp the concepts, it is at exactly the right level. a good idea
and pretty well executed.

Quote from: dave-in-nj on Dec 12, 2014, 01:24 pm

It is apparent that the writer does not like the L298 boards that so many newbies have and ask about. I would offer that more
technical discussion would be called for. It appears to me that the section about them is dismissive.
....SNIP....
IMHO, it would be appropriate to remove the writers (negative) evaluation of the board and be more technical.

I find it very difficult to reconcile these quotes from 2 different posts?

I agree I am dismissive about L298 drivers. Compared to using a proper stepper motor driver board they
are the equivalent of painting the outside of a house with a 25mm paint brush.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

daniellyall

Full Member
Posts: 148
Karma: 12 [add]

Re: Stepper Motor Basics

#19

Dec 13, 2014, 02:34 am


L298 are only good for new bees who don't know any better they are a pain

to drive a stepper so it does not over heat it and do stupid things it needs a proper stepper driver like a
A4988 or equivalent, steppers are holding torque to its curve drop off nothing else
1. working out what size stepper to get is what's the amount of torque will it need for the load it needs to
move.

2. what is the amount of current needed to drive said stepper for load being moved.

3. what is the max current that the said stepper be needing to be driven at the speed required up to the top
of its curve

4. then you get a stepper driver that can handle said amount of current plus a bit extra for back emf.

5. A power supply that can produce the amount of current needed under its max load.

also some one say what a stepper they are using gets, it`s is a good thing to have in any discussion as if
someone work out they need a power supply and driver of simmaler size they can ask that person what is
there set up, I use big and small steppers.

in a discussion I have had I asked people who have the same size stepper as the machine I have (was
meant to have) what there set up was people with same size machine and smaller said they had no
problems with there steppers what where the same as mine so what was wrong with my set up. simple
answer miss labled steppers.

if I did not ask what peoples set ups where I probley would not have worked out the stepper where miss
labled.
so anything in a discussion about correct set ups of stepper, power supply's and drives can`t be bad if a
person does not under stand they can just ask.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#20
Dec 13, 2014, 08:56 am
@daniellall, I'm not sure if your Reply #19 is partly a response to my Reply #12.

I think I have covered your points 1-4 in my original text.

I haven't covered power supplies (point 5) - apart from the question of voltage. I assume the user is
sensible enough to use a power supply with sufficient amps. That aspect is not specific to stepper motors.

@nilton61 and others have added useful posts about power supplies.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

daniellyall

Full Member
Posts: 148
Karma: 12 [add]

Re: Stepper Motor Basics

#21

Dec 13, 2014, 11:21 am


yes it is, its as simple as I can put it.

its the way I work it out

its in 5 lines with all the correct words that anyone can find with Google or I could have just said read this
http://www.geckodrive.com/app-notes.html

that has all what is need to know


neksmerj

Full Member
Posts: 103
Karma: 6 [add]

Re: Stepper Motor Basics

#22

Dec 13, 2014, 11:53 am


Robin2,

A really well written, concise tutorial for the benefit of all us novices.

Ken

weldsmith

Full Member
Posts: 160
Karma: 39 [add]
Live life to it's fullest

Re: Stepper Motor Basics

#23

Dec 13, 2014, 09:36 pm Last Edit: Dec 13, 2014, 09:38 pm by weldsmith
Robin2,

Very nice, I am not a newbie to stepper motors, and you pulled me in. I read the whole thing!

A person certainly would not get the performance they need in many cases if they stuck to the rated
voltages. The availability and price of stepper drives have drastically improved in the recent years. These
new cheaper drives control the amps by your setting and then chops the voltages as needed. This
generally gives you more speed and torque. The newbie has a lot less to worry about these days.

David Smith

o_lampe
Guest

Re: Stepper Motor Basics

#24

Dec 16, 2014, 10:47 am


Well written tutorial Robin!

I'm just missing a more detailed description, how to connect a unknown stepper to a driver board.

Describe how a ohm-meter can be used to find out which are the ends/centers of a coil and if it makes a
difference which way you connect a coil to the driver. A newbee might be confused which coil is A or B
and which end of the coil is A1 or A2.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#25

Dec 16, 2014, 09:14 pm

Quote from: o_lampe on Dec 16, 2014, 10:47 am

I'm just missing a more detailed description, how to connect a unknown stepper to a driver board.

I guess that's why I didn't write it


Quote

Describe how a ohm-meter can be used to find out which are the ends/centers of a coil and if it makes a difference which way you
connect a coil to the driver. A newbee might be confused which coil is A or B and which end of the coil is A1 or A2,

Can you post a few sentences that may be suitable to incorporate in the text?

I don't actually know if it matters which end is A1 - I don't think it does.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

daniellyall

Full Member
Posts: 148
Karma: 12 [add]

Re: Stepper Motor Basics

#26

Dec 17, 2014, 09:51 am


as far as what I have done it does not matter what end is A+ or A- as long As B+ and B- are the same
order as A+ and A- flipping A+ A- B+ B- just changes direction.
dave-in-nj

Faraday Member
Posts: 5,065
Karma: 424 [add]

Re: Stepper Motor Basics

#27

Dec 26, 2014, 02:19 pm

Quote

These can be made to control a stepper motor but they are a very poor choice - mainly because they have no method for limiting
the current and therefore cannot use high voltages.

reading the data sheet is in order.


the L298 certainly does have limiting resistors and many of the available boards on the market have them
out to pins. the vast majority of the super-cheap e-bay ones are set for full power,

.
daniellyall

Full Member
Posts: 148
Karma: 12 [add]

Re: Stepper Motor Basics

#28

Dec 27, 2014, 02:27 am

Quote from: dave-in-nj on Dec 26, 2014, 02:19 pm

reading the data sheet is in order.


the L298 certainly does have limiting resistors and many of the available boards on the market have them out to pins. the vast
majority of the super-cheap e-bay ones are set for full power,

you have all ready said most of that

the l298 are a poor choice for controlling stepper 4 wires, proper stepper driver 2 wires which one is
better 4 wires or 2

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]
Re: Stepper Motor Basics

#29

Feb 17, 2015, 04:57 pm Last Edit: Feb 17, 2015, 05:00 pm by Robin2
A simple method to get a rough measurement of the required torque.

Attach some sort of wheel or drum to the shaft that the stepper motor will be required to turn. Wrap some
strong thread or fine string around the drum and suspend a small plastic beaker from it. This will
obviously only work if the shaft is horizontal.

Add coins to the beaker until the weight is just sufficient to make the drum rotate. Weigh the beaker with
the coins in it.

Measure the diameter of the drum where the thread is wrapped and calculate the radius. Suppose the
radius in 2cm and the weight is 100grams. Then the torque is 200gm-cm.

Repeat the measurement several times and take an average. Choose a motor with perhaps twice that
amount of torque to provide a good safety margin.

...R

TorqueDrum.gif
6.02 KB
downloaded 1026 times

Two or three hours spent thinking and reading documentation solves most programming problems.

PRINT

Go Up

Pages: 1 [2] 3 4

Jump to:

Re: Stepper Motor Basics

#30

Feb 17, 2015, 09:09 pm


It might be more than twice I fear. This article might be helpful, explaining torque v. speed
curves: http://www.orientalmotor.com/technology/articles/article-speed-torque-curves-for-step-
motors.html

So with your load torque measurement taken, look at the graphs for the motor in question
and be prepared to also add in a safety margin on top of that...

[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#31

Feb 17, 2015, 10:28 pm


Thanks for adding that Mark. It looks like it has a lot of useful data.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

polymorph


Faraday Member
Posts: 4,087

1.
Karma: 560 [add]
Electronic Technician, Electronic Engineering Technician I love to build things. Test equipment, replica and original sci fi
props and costume pieces, and whatever else I feel like at the time. I have an Ultimaker and a 3D engraver. I rarely put a
kit tog
http://www.olymega.org

Re: Stepper Motor Basics

#32

Feb 18, 2015, 12:04 am

Quote

the L298 does have sense resistors to limit current, check the data sheet.

It is more correct to say that the L298 has a place to add sense resistors to enable external ICs to measure
and limit current. The L298 has no mechanism to limit current.

In fact, it can be used with the L297 to make a chopper stepper driver.
The advantage to this over the A4988 is slightly increased current (rated at 2A, but you can fit a big heat
sink), and increased working voltage at 46V max. The saturation voltage is rather high, due to the use of
bipolar transistors. On the order of up to 4.9V total (both opposite legs of an H bridge) at 2A. Plus the
voltage drop across the sense resistor.

So I don't recommend it.

Steve Greenfield AE7HD


Drawing Schematics: tinyurl.com/23mo9pf - tinyurl.com/o97ysyx - tinyurl.com/q7uqnvn
Multitasking: forum.arduino.cc/index.php?topic=223286.0
gammon.com.au/blink - gammon.com.au/serial - gammon.com.au/interrupts
1:1

Sr. Member
Posts: 468
Karma: 87 [add]

Re: Stepper Motor Basics

#33

Feb 18, 2015, 03:08 pm

Quote from: Robin2 on Feb 17, 2015, 04:57 pm

A simple method to get a rough measurement of the required torque.

Attach some sort of wheel or drum to the shaft that the stepper motor will be required to turn. Wrap some strong thread or fine
string around the drum and suspend a small plastic beaker from it. This will obviously only work if the shaft is horizontal.

Add coins to the beaker until the weight is just sufficient to make the drum rotate. Weigh the beaker with the coins in it.

Measure the diameter of the drum where the thread is wrapped and calculate the radius. Suppose the radius in 2cm and the
weight is 100grams. Then the torque is 200gm-cm.

Repeat the measurement several times and take an average. Choose a motor with perhaps twice that amount of torque to provide
a good safety margin.

...R

I know it's meant for newbies - but maybe supply a link to more text that describes rotational inertia and
static/dynamic friction?

Non-linearities such as static friction and backlash/dead zones for that matter can give you all sorts of
headaches if you're not aware of them.

Rotational inertia also, ponderous (massive, but well lubricated) equipment will eventually get going with
twice the torque rating of whatever it took to break the static friction, but you're still left with a very slow
system. You might want 100 times more... I guess steppers are by their nature speed restricted at the
lower end (compared to DC/AC servos which have different limiting characteristics) - maybe the
discussion is outside of your defined context.

The XY problem: "the over-use of one line responses that simply link though to websites that describe the XY
problem"

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#34

Feb 18, 2015, 06:49 pm

Quote from: 1:1 on Feb 18, 2015, 03:08 pm

I know it's meant for newbies - but maybe supply a link to more text that describes rotational inertia and static/dynamic friction?

I would be happy to do so. Have you any suggestions, or perhaps you could write a few lines yourself?

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

1:1

Sr. Member
Posts: 468
Karma: 87 [add]

Re: Stepper Motor Basics


#35

Feb 19, 2015, 12:12 am Last Edit: Feb 19, 2015, 11:44 pm by 1:1

Quote from: Robin2 on Feb 18, 2015, 06:49 pm

I would be happy to do so. Have you any suggestions, or perhaps you could write a few lines yourself?

...R

heh - a few lines! Sheesh, once I started I couldn't stop ...

I thought it would be useful to provide some additional advice for getting a reasonable estimate of the
torque required to get something moving.

A torque is a force applied with a lever arm. In the example in Reply #29 the "lever arm" is the radius of
the drum and the force is the weight hanging from the thread. The system will feel exactly the same effect
with a stepper at the same rating.

Don't skip the step of using a drum or something round, using a ruler might seem like a nice idea but it
will give you erroneous results as it creates it's own torque and the torque will decrease as it rotates past
horizontal - by using round lever arm with string it cancels out its own effects and keeps the force vertical
at all times (you can point this out once you've attracting interest in your peers and people will think
you're very clever).

By doubling the rating you're going to be sure you can get the system at least moving. However there are
some effects and considerations that might mean you want to go a lot higher than this, and a small chance
lower.

Firstly, there are non-linearaties such as backlash, and 'stiction' (static friction). Might sound technical,
but they're things you're no doubt aware of from using everyday mechanical objects. Notice how
sometimes things are hard to move initially but once you get them going, they're good? Or sometimes
when you turn a knob in the other direction the system doesn't change directions immediately because
there is some slack in the mechanism? Well that's stiction and backlash respectively. Why mention them?
Well, if you measure your torque and don't take account of them, you could under or over-estimate your
rating, although it's not perfect try to make sure your system is in the state that it will be under normal
operation, sometimes if a something sits for a long time, dry lubrication, thermal expansion/contraction
can cause stiction effects, maybe you want to predict that it'll be there under normal operation and
account for it, maybe you know that your system will be warmed up and can ignore it. Backlash is harder
to account for, but know that in 99%+ cases it'll only get worse. If you cant eliminate it before measuring
torque at least consider the implications, there is a small possibility you could underestimate the torque
required.

Another effect that isn't so related to the initial torque measurement but certainly effects your system, is
the rotational inertia of the mechanism. Twice the torque might get something moving - i.e. you will get
your velocity eventually - but did you get that velocity fast enough? i.e. acceleration Especially
relevant if you're wanting to change directions quickly. Think of a bicycle wheel, ever changed a tyre and
spun the wheels in your hands to play with the gyro effect? Well, it's not quite the gyro effect I'm talking
about (although that certainly is interesting stuff), but what you may have noticed is that the effect is
larger when the tyre is on compared to off, that is because the wheel has a higher 'moment of inertia'.

There is more mass, 'at a distance' - sound familiar?

Yes, just like torque!

You may have also noticed it was harder to start and stop spinning? (i.e. it took longer). This is the effect
a stepper will have to deal with also. Double rating might not cut it

That being said, for many applications in the world of hobby/arduino/desktop robotics, inertia analysis is
overkill as the parts you're moving will likely be mated with over-spec steppers from word go and friction
might be the over-ruling factor anyway. But it's nice to get an initial appreciation of it's effects.

As a final word, keep in mind you experience torque, inertia, friction and backlash in the world around
you often (steering wheels, can openers, bicycles, door handles etc.) - if all this sounded too technical
then just let your intuition guide you.

(edited after a few suggestions from Robin)

The XY problem: "the over-use of one line responses that simply link though to websites that describe the XY
problem"

marco1990
Guest

Re: Stepper Motor Basics

#36
Feb 19, 2015, 12:29 pm
Hi Robin,
I use your code for driving my stepper motor. I attached here:

byte directionPin = 2;
byte stepPin = 3;
int numberOfSteps = 2000;
//int pulseWidthMicros = 20; // microseconds
int millisbetweenSteps = 25; // milliseconds

void setup() {

Serial.begin(9600);
Serial.println("Starting StepperTest");

delay(2000);

pinMode(directionPin, OUTPUT);
pinMode(stepPin, OUTPUT);

digitalWrite(directionPin, HIGH);
for(int n = 0; n < numberOfSteps; n++) {
digitalWrite(stepPin, HIGH);
// delayMicroseconds(pulseWidthMicros);
digitalWrite(stepPin, LOW);

delay(millisbetweenSteps);

delay(3000);

digitalWrite(directionPin, LOW);
for(int n = 0; n < numberOfSteps; n++) {
digitalWrite(stepPin, HIGH);
// delayMicroseconds(pulseWidthMicros);
digitalWrite(stepPin, LOW); delay(millisbetweenSteps);
}
}

void loop() {
}

My problem is to obtain the angular velocity of the shaft. If my millisbetweenSteps are 25 is correct to
take the frequency equal to: f = 1/0.0025 Hz?

Thank you so much Robin

ShapeShifter

Edison Member
Posts: 2,447
Karma: 313 [add]

Re: Stepper Motor Basics

#37

Feb 19, 2015, 01:42 pm

Quote from: marco1990 on Feb 19, 2015, 12:29 pm

If my millisbetweenSteps are 25 is correct to take the frequency equal to: f = 1/0.0025 Hz?

You've slipped the decimal point one place f = 1 / 0.025 or 40 Hz.

That's the step frequency. The revolutions per second is the steps per second, divided by the steps per
revolution: Assuming 200 steps per revolution, that is 40 / 200 or 0.2 revolutions per second. Divide that
by 60 and you get revolutions per minute or 0.00333 RPM.

To get angular velocity (degrees per second) take revolutions per second, and multiply by 360 degrees per
revolution. So, with 25 ms between steps, and 200 steps per revolution, that gives 72 degrees per second.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#38

Feb 19, 2015, 02:22 pm

Quote from: marco1990 on Feb 19, 2015, 12:29 pm

Thank you so much Robin

Don't waste time double posting. I already answered your question here.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#39

Feb 19, 2015, 03:10 pm

Quote from: 1:1 on Feb 19, 2015, 12:12 am


Sheesh, once I started I couldn't stop ...

Thanks very much. I sent you a couple of PMs so as not to confuse stuff here

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

1:1

Sr. Member
Posts: 468
Karma: 87 [add]

Re: Stepper Motor Basics

#40

Feb 19, 2015, 11:49 pm

Quote from: Robin2 on Feb 19, 2015, 03:10 pm

Thanks very much. I sent you a couple of PMs so as not to confuse stuff here

...R

Maybe once it's all settled - start a new post, than ask a mod to lock and sticky it ?

The XY problem: "the over-use of one line responses that simply link though to websites that describe the XY
problem"

CoffeeMan
Guest

Re: Stepper Motor Basics

#41
Feb 20, 2015, 10:51 pm
Hi everyone,

First of all thank you for being such a community. I started working on a project that will need an
arduino and so i thought i would try to figure it out myself. Seeing how much is posted here, I don't feel
entirely alone on this quest.

To make this project work I bought:


- Arduino Uno
- a 5.5A/4.6Nm stepper motor
- a Power Microstep Driver (with a range of 3.8 - 8.0A)
- and finally a PSu with a max output of 24VDC & 6.25A

I keep running into the same problem - every time i run a script and initiate it on the hardware, the stepper
makes a single step, then the red Alert light on the Driver pops on.

I have tried a number of skripts, redoing the wire configuration, & messing with the SW switches. I can't
think of how to tackle this problem - has anybody else ran into this?

Any advice will be EXTREMELY appreciated.

Thanks Again!

polymorph

Faraday Member
Posts: 4,087

1.
Karma: 560 [add]
Electronic Technician, Electronic Engineering Technician I love to build things. Test equipment, replica and original sci fi
props and costume pieces, and whatever else I feel like at the time. I have an Ultimaker and a 3D engraver. I rarely put a
kit tog
http://www.olymega.org

Re: Stepper Motor Basics

#42

Feb 20, 2015, 11:07 pm


Coffeeman, you need to start your own thread.

Steve Greenfield AE7HD


Drawing Schematics: tinyurl.com/23mo9pf - tinyurl.com/o97ysyx - tinyurl.com/q7uqnvn
Multitasking: forum.arduino.cc/index.php?topic=223286.0
gammon.com.au/blink - gammon.com.au/serial - gammon.com.au/interrupts

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#43

Feb 21, 2015, 11:35 am


Agree with @polymorph.
It would be a big help if others would NOT respond to @Coffeeman here as it will just confuse the
purpose of this Thread.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
CoffeeMan
Guest

Re: Stepper Motor Basics

#44

Feb 22, 2015, 10:49 am


Will do. thanks
PRINT

Go Up

Pages: 1 2 [3] 4

Jump to:

NEWSLETTER
Re: Stepper Motor Basics

#45

Mar 03, 2015, 02:09 am


Slight correction needed:

Quote

With a DC motor you control the current in order to control the speed of the motor. The usual way to control the current is to
vary the voltage - perhaps using the Arduino analogWrite() function to control a Pulse Width Modulated power supply to the
motor.

For PMDC (permanent magnet DC) motors the _voltage_ controls the speed, the current
is proportional to the torque. You can use voltage control or current control, for speed and
torque drive respectively. This is true of BLDCs too.

[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]
18omkar

Newbie
Posts: 1
Karma: 0 [add]

avrdude error

#46

Jun 22, 2015, 11:05 pm


Hey Hi
I used your given code for checking stepper but repeatedly getting this error:

avrdude: verification error, first mismatch at byte 0x016c


0x00 != 0x80
avrdude: verification error; content mismatch

I have checked my board as Mega 2560, serial communication port, drivers, connections etc.
All looks perfect.

I have connected via reprap Pololu Shield RAMPS 1.4

Please help me how to resolve this error.


Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#47

Jun 23, 2015, 09:00 am Last Edit: Jun 23, 2015, 09:00 am by Robin2
This is the first time anyone has reported that sort of problem. I think it is an uploading problem rather
than a problem with compiling my code - but I am not an expert on AVRDUDE.

Post the actual code you are trying to use

Are you able to upload other programs to your Mega ?

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

ShapeShifter

Edison Member
Posts: 2,447
Karma: 313 [add]

Re: Stepper Motor Basics

#48
Jun 23, 2015, 04:27 pm
I agree, it sounds like a problem with the development environment, not the sketch. Try loading a
different sketch: if that also has a problem, then it's definitely an environment problem. A better place to
find an answer would be in the Installation & Troubleshooting forum.

nilton61

Edison Member
Posts: 1,356

1.
Karma: 63 [add]

Re: Stepper Motor Basics

#49

Aug 26, 2015, 11:10 am


The Leadshine drives are very competent drivers but they are quite costly, several 100$ depending on
model. The question is if you not are better off getting a servo drive instead when spending that kind of
money.

Isabelle_VP

Newbie
Posts: 43
Karma: 12 [add]

Re: Stepper Motor Basics

#50
Oct 02, 2015, 10:41 am
Hello Robin2,

Thank a lot to have written those both wonderful posts ! It explains very well and easily!
Thanks also to have answered yesterday to my posts !

Marciokoko

Edison Member
Posts: 1,222
Karma: 175 [add]

Re: Stepper Motor Basics

#51

Feb 07, 2016, 02:36 pm


Great thread. I'm a newbie. I would suggest 2 things:

1. Get rid of the power talk posts and include it as links (as you did with measuring torque). As
mentioned, we are interested in making the stepper move.

2. Can you make this and many other topics in this forum into stickies? I feel there are lots of common
n00b issues that could be dealt with if stickies were available.

Thanks robin2!
Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Stepper Motor Basics

#52

Feb 07, 2016, 06:05 pm Last Edit: Feb 07, 2016, 06:06 pm by Robin2

Quote from: Marciokoko on Feb 07, 2016, 02:36 pm

Great thread. I'm a newbie. I would suggest 2 things:

1. Get rid of the power talk posts and include it as links (as you did with measuring torque). As mentioned, we are interested in
making the stepper move.

2. Can you make this and many other topics in this forum into stickies? I feel there are lots of common n00b issues that could be
dealt with if stickies were available.

Thank you for your kind words.

I don't know which Posts you refer to in 1.


The only reason the Torque stuff is in a link is because it was an afterthought

Item 2 is not a matter for me. There are already stickies in some Forum sections - but not this Thread. Too
many stickies can be as big a problem as too few.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

PRINT

Go Up

Pages: 1 2 3 [4]
Jump to:

Re: Demonstration code for several things at the same time

#15

Mar 10, 2014, 11:10 pm


Hey, no, don't give up on switches!
'if' statements can go haywire too if you forget an 'else'!

Pete

Don't send me technical questions via Private Message.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#16

Mar 10, 2014, 11:55 pm


@CodingBadly and @PeterH,

I think I now see the point you are making. I wrote a couple of spreadsheets to experiment with numbers.

I then set out to modify my sketch but I've run into a very strange problem. All of the functions work fine
your way ( += interval) EXCEPT the servo function. After a short period it goes haywire, yet it works
perfectly using " = currentMillis".

I think the problem may be due to the much shorter interval (or may be showing up sooner because of the
shorter interval). And I think the problem arises because at some stage prevMillis exceeds currentMillis
so that currentMillis - prevMillis gives a "negative" number or, since it is an unsigned long, a very large
positive number which always satisfies the if statement.
I've had enough for today. I will experiment more tomorrow.

I suspect that the error associated with doing it the "wrong" way (i.e. "= currentMillis") depends on the
ratio between the interval between successive values of millis() and the size of interval for the blinks (or
whatever). If the blink interval is relatively large the error may not matter. I haven't explored this with my
spreadsheet yet.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

PeterH
Guest

Re: Demonstration code for several things at the same time

#17

Mar 11, 2014, 12:16 am


Quote from: Robin2 on Mar 10, 2014, 11:55 pm

I suspect that the error associated with doing it the "wrong" way (i.e. "= currentMillis") depends on the ratio
between the interval between successive values of millis() and the size of interval for the blinks (or whatever). If the
blink interval is relatively large the error may not matter. I haven't explored this with my spreadsheet yet.

The basic problem is that the code may not evaluate the condition at the precise instant that the interval
has elapsed. Suppose for the sake of argument that you were trying to take some action every 100ms and
your loop took 5ms to execute. The original code would take up to 5ms to notice that the interval had
elapsed. Since the next interval is calculated based on the value of millis() at the point where we notice
the interval elapsed, this means the next interval will be delayed by up to 5ms too. In effect, any latency
noticing that the condition is true will cause all subsequent processing to slip.

The preferred approach always schedules the next event based on when the current event became due, not
when the code noticed that it had occurred. This avoids slippage when there is any latency noticing the
event.
Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#18

Mar 11, 2014, 08:34 am


I eventually figured out the problem while lying in bed.

The problem arises in the servo function because I change the interval after every sweep. As initially
written "prevMillis = currentMillis" is at the bottom of the function after the interval has been changed.
And when the revised version "prevMillis += interval" is used at the same location it erroneously adds the
revised interval. When there is a switch from a short to a long interval that means the prevMillis is
actually greater than the next version of currentMillis which gives a "negative" answer to the subtraction
(actually a large +ve number) which always evaluates to true.

The solution to that problem is to move "prevMillis += interval" to a position before the interval is
changed.

HOWEVER .... (and I'm delighted that this problem gave me time to look at the bigger picture)

FIRST ... @CodingBadly said in Reply #11 that I was assuming that delta (the difference between
successive values of millis()) was 1. Of course, as he suspected, I hadn't thought about that at all. BUT ...
millis() does in fact increment by 1.

SECOND ... (though, I had forgotten) The code in "BlinkWithouDelay" uses "previousMillis =
currentMillis; "

MY CONCLUSION ... is that this is a discussion about angels on the head of a pin. So, in the absence of
evidence of a real problem I will not post an updated version of my demo sketch. The present version
works and is consistent with BlinkWithoutDelay.
I am wondering if I might write a short accompanying essay that covers the points raised here (this one,
the use of Switch and the maintaining State in static local variables).

As always, comments are welcome.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#19

Mar 11, 2014, 08:45 am Last Edit: Mar 11, 2014, 08:49 am by Coding Badly Reason: 1
Quote from: Robin2 on Mar 11, 2014, 08:34 am

BUT ... millis() does in fact increment by 1.

There you go again making assumptions. This time you assume I made a mistake (and failed to test your
assumption).

What about when the processor is running at 8 MHz? What about when the fractional part reaches a
whole number?
Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#20

Mar 11, 2014, 08:48 am


Quote from: Robin2 on Mar 11, 2014, 08:34 am

MY CONCLUSION ... is that this is a discussion about angels on the head of a pin.

Uh huh. Except, of course, when a drifting clock is undesirable.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#21
Mar 11, 2014, 09:18 am
Quote from: Coding Badly on Mar 11, 2014, 08:45 am

Quote from: Robin2 on Mar 11, 2014, 08:34 am

BUT ... millis() does in fact increment by 1.

There you go again making assumptions. This time you assume I made a mistake (and failed to test your
assumption).

What about when the processor is running at 8 MHz? What about when the fractional part reaches a whole
number?

I made no assumptions, certainly not about your coding ability. I wrote a short sketch to test millis() on
my Uno. I have another 328 which I could (maybe already have) set up for 8MHz but I haven't tested that.
I also have some Attiny 45's that I could set up for 1MHz. Most beginners for whom my demo may be
useful are likely to be using an Uno at 16MHz.

If you know what different increments of millis() are possible in different circumstances I would
appreciate it if you would tell me, rather than teasing with questions.

As regards the drifting clock - I started this to produce a more extensive example of "BlinkWithoutDelay"
- nothing more. I expect that someone who needs better performance will also know how to get it, or will
start a new Thread about it. I don't see any need to complicate matters for newbies. It would be another
thing entirely if my code did not do what it claims (and I believe it does).

None of this means that I have not been interested in your comments - I will certainly bear them in mind
for my own projects.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
PeterH
Guest

Re: Demonstration code for several things at the same time

#22

Mar 11, 2014, 03:57 pm


Quote from: Robin2 on Mar 11, 2014, 08:34 am

MY CONCLUSION ... is that this is a discussion about angels on the head of a pin. So, in the absence of evidence of
a real problem I will not post an updated version of my demo sketch. The present version works and is consistent
with BlinkWithoutDelay.

I disagree completely - your conclusion is wrong. The technique used in your example is flawed and is
vulnerable to slip. The classic 'blink without delay' makes the same mistake (as well as others). It is quite
a common mistake, and the fact that it's taking so long to explain it to you demonstrates that it's quite a
subtle problem - but it is still a problem.

The problem is that the timing will be subject to cumulative slip when there is any latency between the
timed condition becoming true, and the code to detect that executing. As soon as that latency exceeds
1ms, the time of the next scheduled event will be wrong, and so on for all subsequent events. The timing
will have slipped by a small amount. It will keep doing this every time there is any latency. There may be
some situations where that doesn't matter, and it's even possible to design a sketch that relies on that
behaviour, but as a general approach for making something happen at regular intervals this is a problem.

Fortunately the solution is easy: schedule the next event based on when the current event was due, not
when it was detected.

Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#23

Mar 11, 2014, 06:23 pm Last Edit: Mar 11, 2014, 06:26 pm by Coding Badly Reason: 1
Quote from: Robin2 on Mar 11, 2014, 09:18 am

If you know what different increments of millis() are possible in different circumstances I would appreciate it if you
would tell me, rather than teasing with questions.

Uno running at 16 MHz...

void setup()
{
Serial.begin( 115200 );
Serial.println( F( "Five seconds to lift off..." ) );
}

static unsigned long Mark;


static unsigned long Previous;
static unsigned short Histogram[256];

void loop()
{
unsigned long Current;
unsigned long Delta;

Current = millis();

Delta = Current - Previous;

if ( Delta != 0 )
{
Previous = Current;

if ( Delta < 256 )


{
++Histogram[(unsigned char)Delta];
}
else
{
++Histogram[255];
}

return;
}

if ( Current - Mark >= 5000ul )


{
for ( int i = 0; i < 256; ++i )
{
Serial.print( i );
Serial.write( '\t' );
Serial.println( Histogram[i] );
}
Serial.println();
while ( true );
}
}

Five seconds to lift off...


0 0
1 4766
2 117
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 0
24 0
25 0
26 0
27 0
28 0
29 0
30 0
31 0
32 0
33 0
34 0
35 0
36 0
37 0
38 0
39 0
40 0
41 0
42 0
43 0
44 0
45 0
46 0
47 0
48 0
49 0
50 0
51 0
52 0
53 0
54 0
55 0
56 0
57 0
58 0
59 0
60 0
61 0
62 0
63 0
64 0
65 0
66 0
67 0
68 0
69 0
70 0
71 0
72 0
73 0
74 0
75 0
76 0
77 0
78 0
79 0
80 0
81 0
82 0
83 0
84 0
85 0
86 0
87 0
88 0
89 0
90 0
91 0
92 0
93 0
94 0
95 0
96 0
97 0
98 0
99 0
100 0
101 0
102 0
103 0
104 0
105 0
106 0
107 0
108 0
109 0
110 0
111 0
112 0
113 0
114 0
115 0
116 0
117 0
118 0
119 0
120 0
121 0
122 0
123 0
124 0
125 0
126 0
127 0
128 0
129 0
130 0
131 0
132 0
133 0
134 0
135 0
136 0
137 0
138 0
139 0
140 0
141 0
142 0
143 0
144 0
145 0
146 0
147 0
148 0
149 0
150 0
151 0
152 0
153 0
154 0
155 0
156 0
157 0
158 0
159 0
160 0
161 0
162 0
163 0
164 0
165 0
166 0
167 0
168 0
169 0
170 0
171 0
172 0
173 0
174 0
175 0
176 0
177 0
178 0
179 0
180 0
181 0
182 0
183 0
184 0
185 0
186 0
187 0
188 0
189 0
190 0
191 0
192 0
193 0
194 0
195 0
196 0
197 0
198 0
199 0
200 0
201 0
202 0
203 0
204 0
205 0
206 0
207 0
208 0
209 0
210 0
211 0
212 0
213 0
214 0
215 0
216 0
217 0
218 0
219 0
220 0
221 0
222 0
223 0
224 0
225 0
226 0
227 0
228 0
229 0
230 0
231 0
232 0
233 0
234 0
235 0
236 0
237 0
238 0
239 0
240 0
241 0
242 0
243 0
244 0
245 0
246 0
247 0
248 0
249 0
250 0
251 0
252 0
253 0
254 0
255

2.4% of the time a two was returned otherwise a one is returned. Which passes a basic stink test: 4766
+ 2*117 = 5000.
Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#24

Mar 11, 2014, 06:29 pm


Quote from: Robin2 on Mar 11, 2014, 09:18 am

As regards the drifting clock - I started this to produce a more extensive example of "BlinkWithoutDelay" - nothing
more. I expect that someone who needs better performance will also know how to get it, or will start a new Thread
about it. I don't see any need to complicate matters for newbies. It would be another thing entirely if my code did
not do what it claims (and I believe it does).

Perfect. My only concern was that your audience knows what they are getting and, with that, they do.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time


#25

Mar 11, 2014, 06:30 pm


Thanks for your code @CodingBadly. I will try it and then I also want to reply to @PeterH.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

3dprinter

Edison Member
Posts: 1,336
Karma: 136 [add]
Have you testrun your INO file today?

Re: Demonstration code for several things at the same time

#26

Mar 11, 2014, 08:03 pm


Me sits here feeling slightly miffed that my explanation (reply#8)
of the reason why timer += increment is the better way is quietly ignored by Robin2
-- only to be repeated by PeterH (reply#17) (and I am sure PeterH invented his own).

Robin2

void loop() {
delay(12) ;
Serial.println(millis()) ;
}

millis() now increases by 12 in each loop ! Eh?! And sometimes by 13. Eh eh!?!?

Quote

SECOND ... (though, I had forgotten) The code in "BlinkWithouDelay" uses "previousMillis = currentMillis; "
Unfortunatly there are several things missing, misleading and sometimes plain wrong in the
reference/tutorials.
These have been pointed out, but the Arduino team has choosen not to use advice from this forum on that
matter.

Quote

MY CONCLUSION ... is that this is a discussion about angels on the head of a pin

You're entitled to your point of view. However, this is not a religous point - it is mathematically
deterministically provable true.
It may be for some applications the slippage/jittery is of no consequence, but it is there.

PeterH said it succinctly "the fact that it's taking so long to explain it to you demonstrates that it's quite a
subtle problem - but it is still a problem."

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#27

Mar 11, 2014, 08:07 pm


11 Mar 2012

@CodingBadly, I modified your code a bit to explore the phenomenon further. It seems that millis()
increments by 2 every 41 or 42 steps. My code is below. Let me know if I have misrepresented your
ideas. It could be interesting to try to figure out what give rise to the 2 step, and whether the frequency
varies.

@PeterH, Based on the data from that sketch I think I can see the problem you refer to. For example,
suppose the required interval is 41 millisecs. Let's also assume that on the previous iteration millis() was
40 (so the event did not happen). On the next iteration millis() will be 42 (because it jumped 2 places) and
then the event will be triggered a millisecond late. If I use that new value of millis() as the base for the
next event it should happen when millis() becomes 83. Whereas if I calculated from the originally
intended event time (41) I would schedule the next event for 82. On the other hand if the required interval
doesn't coincide with the millis() jump there won't be any error.

I think what has been confusing me (maybe still does) is your phrase "when there is any latency between
the timed condition becoming true, and the code to detect that executing". I believe that by "saving"
millis() at the start of each iteration of loop() it doesn't matter when the code actually gets around to
executing the event. And the timing of the subsequent event is not linked to the actual time of execution
of the previous event. Instead it is linked to the value of millis() at the time the loop() began its iteration.

Bearing in mind the limited purpose of my sketch and its intended audience I still think the problem is
small enough that the balance of advantage lies with being consistent with the usage in Blink-Without-
Delay rather than trying to explain this problem to newbies.

As I said earlier, I am thinking of writing a short additional note to cover this point and the two others that
have been raised. Your comment has helped to clarify my understanding, and may make a description
easier to write. Do feel free to write a few explanatory sentences/paragraphs on the subject yourself to
save me the bother.

@Msquare, your post just came in as I finished this. Sorry if I was too thick to see your point. You, also,
are invited to write a suitable explanation for newbies.

...R

static unsigned long Mark;


static unsigned long Previous;
static unsigned short Histogram[256];
static unsigned short OverOne[256];

void setup()
{
Serial.begin( 115200 );
Serial.println( F( "Five seconds to lift off..." ) );

unsigned long Current;


unsigned long Delta;
int count = 0;

while (count < 256) {


Current = millis();
Delta = Current - Previous;
if (Delta > 0) {
Previous = Current;
Histogram[count] = (unsigned char)Delta;
if (Delta > 1) {
OverOne[count] = count;
}

count++;
}
}
for ( int i = 1; i < 256; ++i )
{
Serial.print( i );
Serial.write( '\t' );
Serial.print( Histogram[i] );
Serial.write( '\t' );
Serial.println( OverOne[i] );
}
Serial.println();
}

void loop()
{

Two or three hours spent thinking and reading documentation solves most programming problems.
CrossRoads

Global Moderator
Unlimited Eagle board sizes available.
Brattain Member
Posts: 41,715

1.
Karma: 1740 [add]
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board
sizes!
http://www.crossroadsfencing.com/BobuinoRev17/

Re: Demonstration code for several things at the same time

#28

Mar 11, 2014, 08:28 pm


Robin2,
This was how AWOL or CodingBadly or PaulStoffregen or maybe PaulS explained accurate time keeping
to me:

void loop(){
currentMicros = micros(); // I have found micros to keep more accurate time
// likely because 16 clocks is 1uS, and millis has some "fudge factor" in it.
elapsedMicros = currentMicros - nextMicros;
// I had trouble with this evaluation in an if early on, so now I do it outside
if (elapsedMicros >= duration){
// here's the key:
nextMicros = nextMicros + duration; // set up time for next comparison
/* nextMicros is kept independent of currentMicros -
so if currentMicros capture was delayed for any reason,
the delay does not impact when the next time comparison will happen.
the comparison will still be at a multiple of "duration".
the actual real-world time between comparisons may then wiggle some, this will be
independent of that wiggle. */

// do the timed event


} // end time check
} // end loop

Guest

Re: Demonstration code for several things at the same time

#30

Mar 11, 2014, 11:01 pm


Quote from: Robin2 on Mar 11, 2014, 08:07 pm

I think what has been confusing me (maybe still does) is your phrase "when there is any latency between the timed
condition becoming true, and the code to detect that executing". I believe that by "saving" millis() at the start of
each iteration of loop() it doesn't matter when the code actually gets around to executing the event. And the timing
of the subsequent event is not linked to the actual time of execution of the previous event. Instead it is linked to the
value of millis() at the time the loop() began its iteration.

I think you have understood the problem correctly.

The scope for latency within a specific sketch can be affected by the placement of the call to millis()
relative to the call checking whether the time has elapsed, and by how frequently the loop executes, but
the latency can never be reduced to zero.

This is a problem that has varying severity and varying impact. Arguably, in many cases it can be
ignored. However, the issue of how to control multiple things independently, including controlling
independently timed things, crops up so frequently, and is so fundamentally important for newcomers to
understand, that I think having a really good example of 'best practice', together with an explanation of
why that is the best practice, would be extremely useful. It's a great shame, and a lost opportunity, that the
'blink without delay' example is so poorly explained and so mediocre in implementation. This is why I'm
so keen for you to develop your example to the point where it really does represent best practice, and not
just 'good enough for simple examples'.

Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#31

Mar 12, 2014, 03:10 am

A word of caution about the basic "mile marker" approach: an overrun will wreak havoc. A while loop
overcomes the problem.

An example from CrossRoads' snippet...


void setup()
{
Serial.begin( 115200 );
}

void loop()
{
unsigned long currentMicros;
unsigned long elapsedMicros;
static unsigned long nextMicros;
const unsigned long duration = 1000000ul;

currentMicros = micros();
elapsedMicros = currentMicros - nextMicros;
if ( elapsedMicros >= duration )
{
nextMicros = nextMicros + duration;
Serial.println( currentMicros );
}
// Pretend loop takes too long to execute
delay( 1001 );
}

Change the if to a while.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#32

Mar 12, 2014, 08:12 am Last Edit: Mar 12, 2014, 10:45 am by Robin2 Reason: 1
This is all provin' very stimulatin' to the few remaining grey cells ...

@CrossRoads, thank you, but I am not concerned with accuracy greater than you get from millis(). This is
just intended as a simple learning device for newbies.

@PeterH and @CodingBadly, I hope you will have realized that my only objection to doing it "properly"
was the risk that explaining the change would so confuse a newbie that all value from the demo code
would be lost. I think I have now figured out a simple way to link the "+= interval" version to the "=
currentMillis" version that's in Blink-Without-Delay without the need for a complex explanation.

I will modify my example and maybe post the updated version later today if I feel the change will be
sufficiently unobtrusive. Edit to add ... I have now updated the code attached to the original post and the
code in Reply #1.

@CrossRoads, I don't understand your use of the term "mile marker".


...R

Two or three hours spent thinking and reading documentation solves most programming problems.

CrossRoads

Global Moderator
Unlimited Eagle board sizes available.
Brattain Member
Posts: 41,715

1.
Karma: 1740 [add]
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board
sizes!
http://www.crossroadsfencing.com/BobuinoRev17/

Re: Demonstration code for several things at the same time

#33

Mar 13, 2014, 05:35 am


"mile marker" refers to the event happening at regular intervals:

Code: [Select]
the comparison will still be at a multiple of "duration".
as I indicated in my code comments.

Designing & building electrical circuits for over 25 years. Screw Shield for Mega/Due/Uno, Bobuino
with ATMega1284P, & other '328P & '1284P creations & offerings at my website.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#34

Mar 13, 2014, 08:48 am


Sorry @Crossroads, but I still don't see how your comments (or @CodingBadly's comments on your
comments) to relate to my demo sketch. I thought you were recommending using micros instead of millis
for more accurate timing.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

cootcraig

Newbie
Posts: 8
Karma: 6 [add]

Re: Demonstration code for several things at the same time


#35

Mar 13, 2014, 09:08 pm


Quote from: Robin2 on Mar 04, 2014, 01:28 pm

I have prepared the attached example sketch in the hope that it will be a
suitable model. I have tested it on an Uno and a Mega. I have called it
"SeveralThingsAtTheSameTime.ino". (It seems to be too long to show the
code directly in this post)
...
It also uses the "state machine" concept to manage the various activities
and enable the different functions to determine what to do.
...
Comments are welcome.

Thank you for this, I will be studying it.

I'm new to Arduino coding and learning what and how can be fit in Arduino
IDE code. My starting approach was to leverage this SimpleTimer code:

http://playground.arduino.cc/Code/SimpleTimer#.UyIPih_f9ic

Here is a code fragment where I do periodic Serial writes. This not


really equivalent to what your code is doing, but this is my starting
point.

...
#include <SimpleTimer.h>
...
SimpleTimer timer;
...
void setup()
{
...
timer.setInterval((5*1000), timerWrite);
...
}
void loop()
{
...
timer.run();
...
}
// Periodic write to Serial to test RPi <-> Arduino
void timerWrite()
{
// Code here that queues up some text to write on Serial
}

Re: Demonstration code for several things at the same time

#36

Mar 13, 2014, 09:58 pm


@cootcraig, thank you for your kind words.

If you want get advice about the SimpleTimer library (about which I know nothing) I would appreciate it
if you would start a new Thread as I would like to keep this thread to the one subject so as not to confuse
newcomers.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

cootcraig

Newbie
Posts: 8
Karma: 6 [add]

Re: Demonstration code for several things at the same time

#37

Mar 13, 2014, 11:43 pm


Quote from: Robin2 on Mar 13, 2014, 09:58 pm
If you want get advice about the SimpleTimer library (about which I know nothing) I would appreciate it if you
would start a new Thread as I would like to keep this thread to the one subject so as not to confuse newcomers.

...R

I'm not looking for help with SimpleTimer, sorry. I'm learning how to multiple things on an Arduino
myself., just not starting with the same demo. I will continue watching this thread.

evancleary

Newbie
Posts: 28
Karma: 9 [add]

Re: Demonstration code for several things at the same time

#38

Mar 14, 2014, 03:42 am Last Edit: Mar 14, 2014, 06:07 am by Coding Badly Reason: 1
hey guys,

i took your example and tried to apply it to a binary thermometer that i had already done
i got it to comply but it dosnt function like it should

Moderator edit: offensive phrase remove

any ideas?
cr0sh

Tesla Member
Posts: 6,497

1.
Karma: 442 [add]
Where's the beer?

Re: Demonstration code for several things at the same time

#39

Mar 14, 2014, 04:18 am


Quote from: evancleary on Mar 14, 2014, 03:42 am

any ideas?

I don't know about the code, but you have a serial.print() line in the loop() function that I would like to
encourage you to edit, or the moderators may do it for you.

/remember, this forum caters to many age groups and such; let's try to keep it somewhat in line with that...

I will not respond to Arduino help PM's from random forum users; if you have such a question, start a
new topic thread.

Coding Badly


Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#40

Mar 14, 2014, 06:09 am


Quote from: cr0sh on Mar 14, 2014, 04:18 am

...or the moderators may do it for you.

Too late.

Quote

/remember, this forum caters to many age groups and such; let's try to keep it somewhat in line with that...

Well stated @cr0sh. Thank you for your post.

@evancleary, I make you this promise: I will not waste my time again cleaning up your mess.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time


#41

Mar 14, 2014, 08:17 am


I take it that no input is required from me until there is some code to look at?

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

evancleary

Newbie
Posts: 28
Karma: 9 [add]

Re: Demonstration code for several things at the same time

#42

Mar 14, 2014, 06:12 pm


apologies for the bad language in the last post guys
was messing about with the print function and forgot to remove the phrase before post
const int ledPin1= 13;
const int ledPin2= 12;
const int ledPin3= 11;
const int ledPin4= 10;
const int ledPin5= 9;
int sensorValue = 0;

// ==================variables====================================

int degrees_21 = LOW;


int degrees_22 = LOW;
int degrees_23 = LOW; // these are my seperate functions
int degrees_24 = LOW; // kept the rang of temp around room temp for
int degrees_25 = LOW; // trial run
int degrees_26 = LOW;

//===================================================================
void setup()

{
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);

Serial.begin(9600);
}

//========================================================================

void loop()

{
sensorValue = analogRead(A0);
Serial.println(sensorValue);

updatedegrees_21();
updatedegrees_22();
updatedegrees_23();
updatedegrees_24();
updatedegrees_25();
updatedegrees_26();

//=====================================================================

void updatedegrees_21()
{
if (degrees_21 == LOW) // was thinking about putting an else (degrees_21 = LOW)
{ // but didnt think it was required
if (sensorValue <= 43)//21
degrees_21 = HIGH;
}
if (degrees_21 == HIGH)
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, HIGH);
}

//==================================================================

void updatedegrees_22()
{
if (degrees_22 == LOW)
{
if (sensorValue > 43 && sensorValue <= 45)//22
degrees_22 = HIGH;
}
if (degrees_22 == HIGH)
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, HIGH);
digitalWrite(ledPin5, LOW);
}

//======================================================================

void updatedegrees_23()
{
if (degrees_23 == LOW)
{
if (sensorValue > 45 && sensorValue <= 47)
degrees_23 = HIGH;
}
if (degrees_23 == HIGH);
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, HIGH);
digitalWrite(ledPin5, HIGH);
}

//==========================================================================

void updatedegrees_24()
{
if (degrees_24 == LOW)
{
if (sensorValue > 45 && sensorValue <= 47)
degrees_24 = HIGH;
}
if (degrees_24 == HIGH);
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, LOW);
}

//========================================================================

void updatedegrees_25()
{
if (degrees_25 == LOW)
{
if (sensorValue > 49 && sensorValue <= 52)//25
degrees_25 == HIGH;
}
if (degrees_25 == HIGH)
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, HIGH);
}

//===========================================================================

void updatedegrees_26()
{
if (degrees_26 == LOW)
{
if (sensorValue > 52 && sensorValue <= 54)
degrees_26 = HIGH;
}
if (degrees_26 == HIGH)
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, HIGH);
digitalWrite(ledPin5, LOW);
}

in the version of this code that i have working i basically have a load of if and else function on a delayed
loop which constantly checks sensorValue, thought applying it with non-blocked architecture would be a
good training exercise

@CodingBadly Im not looking for anyone to clean up my mess just looking for some advice or point in
the right direction because i have a breathalyzer with multiple inputs/outputs and functions to have
completed in the next 2 weeks

yet again folks my apologies

CrossRoads

Global Moderator
Unlimited Eagle board sizes available.
Brattain Member
Posts: 41,715

1.
Karma: 1740 [add]
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board sizes!
http://www.crossroadsfencing.com/BobuinoRev17/
Re: Demonstration code for several things at the same time

#43

Mar 14, 2014, 08:06 pm


For all these, you could simplify some:

void updatedegrees_25()
{
if (degrees_25 == LOW)
{
if (sensorValue > 49 && sensorValue <= 52)//25
degrees_25 == HIGH;
}
if (degrees_25 == HIGH)
{ digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, HIGH);
}

What makes degrees_25 and the others Low again to allow another reading?

Designing & building electrical circuits for over 25 years. Screw Shield for Mega/Due/Uno, Bobuino with
ATMega1284P, & other '328P & '1284P creations & offerings at my website.
CrossRoads

Global Moderator
Unlimited Eagle board sizes available.
Brattain Member
Posts: 41,715

1.
Karma: 1740 [add]
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board sizes!
http://www.crossroadsfencing.com/BobuinoRev17/

Re: Demonstration code for several things at the same time

#44

Mar 14, 2014, 08:07 pm


(apparently strikeout does not work within code tags)

Designing & building electrical circuits for over 25 years. Screw Shield for Mega/Due/Uno, Bobuino with
ATMega1284P, & other '328P & '1284P creations & offerings at my website.

PRINT

Go Up

Pages: 1 2 [3] 4 5 ... 7

Jump to:
NEWSLETTER

Global Moderator
Unlimited Eagle board sizes available.
Brattain Member
Posts: 41,715

1.
Karma: 1740 [add]
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board sizes!
http://www.crossroadsfencing.com/BobuinoRev17/

Re: Demonstration code for several things at the same time

#45

Mar 14, 2014, 08:10 pm


Do you also find this update really fast so the outputs seem to be the same all the time?
I think I would add a time check and only update every 1/10 or 1/5 second or so.

Designing & building electrical circuits for over 25 years. Screw Shield for Mega/Due/Uno, Bobuino with
ATMega1284P, & other '328P & '1284P creations & offerings at my website.
evancleary

Newbie
Posts: 28
Karma: 9 [add]

Re: Demonstration code for several things at the same time

#46

Mar 14, 2014, 08:27 pm


was thinking that falling out of the stated sensorValue range would set the function back to when checked
and found not to be

may use an else function stating that when not within range = LOW

im gona be looking into some tutorials posted up by GrumpyMike to try get my head more around the
logic required

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#47

Mar 14, 2014, 09:19 pm


What is all the digitalWrite(ledPinX, HiGH/LOW) stuff?

If these were put in named functions it would make the code much clearer.
It may also be possible to do them all in one function to reduce duplication of code.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

evancleary

Newbie
Posts: 28
Karma: 9 [add]

Re: Demonstration code for several things at the same time

#48

Mar 14, 2014, 09:31 pm


its representing the degrees celcius in a 5 bit binary led setup

ie 26 degrees = 1 1 0 1 0

thus led 1 HIGH and so on

got some advice from GrumpyMike earlier saying that they can be given an array function which this
page shows how to

http://www.thebox.myzen.co.uk/Tutorial/Arrays.html

it would seem ive got a lot of ground to cover and not a whole lot of time to do it considering i have 2
exams in the next couple of weeks to boot, so it all systems are non stop. This is why Ive been looking
for a bit of direction, gona run through as much of Mikes tutorials as I can and hopefully Ill be able to
work out this project
Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#49

Mar 15, 2014, 08:52 am


I think we could help you much better if you give us a clear description (in english, not code) of what you
want to do.

You have jumped into the middle of this Thread (which is fine) but you might have been better starting
your own Thread. I suspect you are assuming we know a great deal more about your project than we
actually do. Assume we know nothing!

It's not even clear to me how you are thinking of making use of my demo sketch (which, I assume, is the
reason you have asked your question here).

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

Coding Badly

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/
Re: Demonstration code for several things at the same time

#50

Mar 15, 2014, 09:00 am Last Edit: Mar 27, 2014, 06:58 am by Coding Badly Reason: 1

Quote from: Robin2 on Mar 15, 2014, 08:52 am

...but you might have been better starting your own Thread.

He has. Twice...
http://forum.arduino.cc/index.php?topic=225213.0
http://forum.arduino.cc/index.php?topic=224682.0

Quote

@CodingBadly Im not looking for anyone to clean up my mess...

Then stop posting obscenities, stop cross-posting, and stop hijacking.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#51

Mar 15, 2014, 12:09 pm

Quote from: Coding Badly on Mar 15, 2014, 09:00 am

He has. Twice...
Thanks, I hadn't spotted those.

@evancleary, over to you to sort things out ....

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

evancleary

Newbie
Posts: 28
Karma: 9 [add]

Re: Demonstration code for several things at the same time

#52

Mar 15, 2014, 02:13 pm


ok so i made a post first time round which is the second link

after doing that i came across your post here which seemed extremely helpful because im going to have to
integrate multiple functions into the one code , so i made a reply then explaining fully what it was i hoped
to achieve and how i was planning to use your code in helping me learn what it was i needed to know,
however that reply that i made to this post ended up being its own post? with its own new title,a title
which i didnt give it. Dont know how or why?

Apologies if my code dosnt seem neat or logical, yet again im very new to this and am just trying to find
me feet with it

also yet again apologies for the obscenities but as already stated it was an absolute mistake

didnt know that i was hijacking or that posting on multiple links was a bad thing, i dont really use forums
how and ever thanks for the post it has given me an idea of how to go about getting a main loop to
reference function loops, between this and GrumpyMikes stuff i should be on the right track

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#53

Mar 15, 2014, 02:46 pm


The problem with multiple Threads on the same subject is that none of them has the full picture. And
someone may waste his/her time giving advice on one Thread which has already been given on another.

From your own point of view the problem is that contributors will only have part of the picture and won't
be able to give you the best advice.

Hijacking a Thread is slightly different - it usually means causing the Thread to wander off into a
discussion that the person who started the Thread hadn't intended. In this case your interest seems to have
been to adapt my code to your project. I think you lose most from using this Thread for that because
readers won't expect your problem to appear here.

I suggest you ask the moderator to merge your other two threads and then continue your enquiries there,
and not here.

And, as I said earlier, you need to provide a very clear description of what you are trying to do before you
tell us howyou are trying to do it.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#54

Mar 25, 2014, 12:41 am


Robin,

Keith here, you referred me to this thread a couple of days ago. Thanks again for doing something like
this for irritating beginners like myself

It's a bit brain frying for me at present but with a bit of repetitive studying I'm sure it will start coming
together for me. One of the earlier responses was about the bracketing positioning. As a beginner the first
thing that made it difficult for me to read through the code, was the positioning of the curly brackets.

I modified the bracket positioning to make the functions more graphically visible (if that's a way to put it).
Now I can clearly see a function inside a function inside a function, so to speak, and it leaves my
beginners brain more free to learn the coding.

Example:

void updateLed_A_State()
{
if (led_A_State == LOW)
{
if (currentMillis - previousLed_A_Millis >= led_A_Interval)
{
led_A_State = HIGH;
previousLed_A_Millis += led_A_Interval;
}
}
else
{
if (currentMillis - previousLed_A_Millis >= blinkDuration)
{
led_A_State = LOW;
previousLed_A_Millis += blinkDuration;
}
}
}

I hope I did all that correctly LOL.

Opening and closing brackets of each function line up vertically. Brackets of "inner" functions have good
distance on indentation. I realise as a proficient experienced programmer you may detest this for your
own use, but seeing as your sketch is for beginners I thought I'd mention this.

Keith.

PeterH
Guest

Re: Demonstration code for several things at the same time

#55

Mar 25, 2014, 02:52 am

Quote from: beefy23 on Mar 25, 2014, 12:41 am

I modified the bracket positioning to make the functions more graphically visible (if that's a way to put it). Now I can clearly see
a function inside a function inside a function, so to speak, and it leaves my beginners brain more free to learn the coding.

That indentation is horrible. I recommend you use Tools / Autoformat to put it right.
Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#56

Mar 25, 2014, 09:39 am


Indentation is a personal choice. Do it any way you like.

I like my way.

It is a good idea to use a system that is similar to what autoformat produces for stuff that you propose to
post here. People find it easier to get a quick understanding if the format is familiar.

MUCH more important, @beefy23, ALWAYS enclose code in CODE tags so that it displays properly.
Read the stickies at the top of the Forum for instructions.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#57
Mar 25, 2014, 09:17 pm Last Edit: Mar 26, 2014, 03:43 am by beefy23 Reason: 1

Quote from: PeterH on Mar 25, 2014, 02:52 am

Quote from: beefy23 on Mar 25, 2014, 12:41 am

I modified the bracket positioning to make the functions more graphically visible (if that's a way to put it). Now I can clearly see
a function inside a function inside a function, so to speak, and it leaves my beginners brain more free to learn the coding.

That indentation is horrible. I recommend you use Tools / Autoformat to put it right.

Wow Pete,

that's highly constructive and educational. I love the explanation you give of why it's horrible. I was
speaking as a beginner, saying what I personally find makes the code much easier to read for me. Robin
started this for beginners so I simply said what aided me as a beginner to follow the code. I wasn't saying
Robin or anyone else should coding should code like this themselves. I even said to Robin that he may
detest that method himself.

I'll take note of your recommendation and see what results I get when I use the auto feature. For a
beginner I may personally find that result horrible. Then I can come back to you and say it's horrible and
not say why.

As for my recommendation to you, don't comment if all you can say is something is horrible without
giving any explanation as to why. Should I start being just as "constructive" as you and we can both start
throwing rubbish at each other. Forums becomes a great place when that starts.

Edit:
I've just went at took a look at the way Jiggy Ninja (the one who said he prefers a different bracketing
arrangement) does his code and remarkably it's very similar to what I did. Looks like there's 2 of us have
a "horrible" arrangement. To me it's very clear and easy on the eyes. Functions stand out so clearly,
perfect for a beginners eyes. I suspect I will find your personal method of bracketing much more horrible.

Keith.
beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#58

Mar 25, 2014, 09:20 pm


Hi Robin,

thanks for the explanation on why to use the autoformat, and I'll read the stickies about putting code in the
threads.

Keith.

altimmons
Guest

Re: Demonstration code for several things at the same time

#59

Mar 26, 2014, 03:17 am


I was just struggling with this myself (doing several things at once). I will pick through the code tonight.
I appreciate it.

PRINT

Go Up

Pages: 1 2 3 [4] 5 6 7

Jump to:

Re: Demonstration code for several things at the same time


#60

Mar 26, 2014, 10:15 am


Quote from: beefy23 on Mar 25, 2014, 09:17 pm

that's highly constructive and educational. I love the explanation you give of why it's horrible.

You need to develop a thick skin here. @PeterH is by no means the most critical. Interpret "is horrible"
as "I don't like it" and get over it.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#61

Mar 27, 2014, 01:16 am Last Edit: Mar 27, 2014, 04:50 am by beefy23 Reason: 1
Quote from: Robin2 on Mar 26, 2014, 10:15 am

Quote from: beefy23 on Mar 25, 2014, 09:17 pm

that's highly constructive and educational. I love the explanation you give of why it's horrible.
You need to develop a thick skin here. @PeterH is by no means the most critical. Interpret "is horrible" as "I don't
like it" and get over it.

...R

Completely disagree Robin.

First of all I am "over it", but I wouldn't be over it if I hadn't responded to that irritating comment.

How is it supposed to work here ??. Someone says something bordering on insulting, and definitely not
constructive or educational, and the one he's telling it to just has to "get over it" and say nothing. I don't
work that way, if someone talks pointless rubbish to me, I let them know I don't accept it and I give
something back. Talk constructively to me, and as you have seen from my other posts I express thanks
and talk with respect to others.

It's interesting that you aren't saying to Pete that if he doesn't like my bracketing style then HE should
get over it and not post pointless aggressive comments. C'mon think about who is the one that initiated
this rubbish, and give him the talking to, not me.

I've been a member of quite a few forums for a few years now, and comments like Pete made do
nothing except irritate others & start a crap fight. And working on "interpretation" is the worst thing you
can do when all there is to go on is written words, so when commenting, that should be taken into
account.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#62
Mar 27, 2014, 08:13 am
I complain about unhelpful and offensive comments too, including recently.

I don't happen to think that saying the appearance of something is "horrible" is insulting or offensive. It
is certainly not unusual and is not confined to the sphere of programming.

Different people like different things and I believe they should be allowed to express their opinions even
if we don't like them.

And I doubt if 0.0001% of human statements are ever supported by a justification.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#63

Mar 27, 2014, 10:30 am


Well, it's all a matter of opinion and it looks like you and me disagree.

So my advice to you is right back at you what you said to me. Why don't you get over it, get a thicker
skin, and stop being bothered by my opinion about a comment made to me. I'm sure you could devote
your time to some other beginners.

I've just been on the AVR Freaks forum today, and they are having a problem with certain responses.
The basic request over there is that is you don't have anything decent to say then don't say it.
Keith.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#64

Mar 27, 2014, 01:47 pm


Quote from: beefy23 on Mar 27, 2014, 10:30 am

and stop being bothered by my opinion about a comment made to me

My original comment in response to your opinion post was intended as a friendly assistance to
somebody new to this Forum. I'm sorry you haven't seen it like that.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

beefy23

Jr. Member
Posts: 57
Karma: 0 [add]
Re: Demonstration code for several things at the same time

#65

Mar 28, 2014, 01:26 am


Quote from: Robin2 on Mar 27, 2014, 01:47 pm

Quote from: beefy23 on Mar 27, 2014, 10:30 am

and stop being bothered by my opinion about a comment made to me

My original comment in response to your opinion post was intended as a friendly assistance to somebody new to
this Forum. I'm sorry you haven't seen it like that.

...R

Robin,

thank you for your good intentions with your friendly advice. You could however, choose better words
than "get over it".

The problem is I find your advice very one sided, unfair, and not conducive to helping this forum become
a better one. You are totally condoning how Pete can talk to a beginner on the forum, and telling the
beginner to just get over it. Further you are saying people should be allowed to express their opinions,
so it's OK for Pete to post a worthless knockdown comment to a beginner, but it seems like I should not
be expressing my opinion about that comment, and I should get a thick skin and get over it. So where is
my freedom to express my opinion. Seems like different rules for me and Pete.

I've been busting my guts the last few days learning this coding because it's all fairly new to me. As a
beginner I come to ask questions with a little nervousness, and a feeling that I may ask irritating
questions. I've clearly stated I am a beginner so when a more established member has nothing more to
say than, "That's horrible" without explaining why, it gets my back up a bit, and as you say member
should be free to do, I express my opinion back. I'm rather shocked that your opinion is not more along
the lines of "let's keep comments constructive", especially when beginners are the target.
Just because your advice is supposed to be friendly does not mean I will lie down and take it if I feel it's
completely wrong and unfair. As you said people should be free to express their opinion and looks like
I'm following your advice and doing exactly that. Seems when I give the same advice to you (my last
post) that you originally gave to me, then you say I'm not seeing your advice as friendly. Seems to me
like you can dish out your friendly advice but you don't like it when someone disagrees.

Don't try and make me out to be the bad one. Sparks (Petes' comment) create fires. The answer lies in
not letting the sparks start.

Keith.

Jack Christensen

Faraday Member
Posts: 4,208

1.
Karma: 244 [add]
CODE is a mass noun and should not be used in the plural or with an indefinite article.
Adventures in Arduinoland

Re: Demonstration code for several things at the same time

#66

Mar 28, 2014, 02:14 am Last Edit: Mar 28, 2014, 02:17 am by Jack Christensen Reason: 1
Hi Keith,

Welcome to the forum Here's my $0.02 on the indentation/style business (guaranteed to be worth
every penny )

As you can well imagine, no two people do it exactly the same way. And people get very invested (I
might say overly so) in the particular way they do it (yes, me too, absolutely). Some companies write
extensive rules that specify how every tiny syntax feature should be written. But without going that far,
there are certain norms or patterns or conventions that are common. It's in a programmer's best
interest to adopt something fairly close because others will be able to read their code easier and vice-
versa.

I'm sure I can't do a decent job here of explaining typical norms or conventions. Best to study several
texts to get a feel for it. The autoformat tool does do a good job so a person can't go too far wrong with
that. Most folks, once they've been at it for a while and have interacted with enough other
programmers, probably adopt a style that is 90%-95% like that of others.

I know programmers far better than I, who, while they have a very good style, do one or two little things
that just make me absolutely crazy. But in the end they are little things, so I figure that's just their bit of
artistic flair, and we all can indulge in some small amount of that.

No doubt quite a few newcomers here feel very puzzled when they're the object of a derisive response,
because they don't have the first clue as to how they caused such a reaction. The compiler didn't
complain (assuming their code compiles) so what could possibly be the problem. That's unfortunate, but
it happens, I guess, because it's just the fast and easy way out. Truly there is some horrible looking code
around the forum, but folks usually want to focus on more immediate issues than style, like fixing a
problem and getting the code working.

PS: On the lighter side, there are a good number of people out there with a sense of humor about the
whole business: http://www.ioccc.org/

beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#67
Mar 28, 2014, 09:58 am
Hi Jack,

thanks very much for those pointers. I had a quick look at that contest you gave the link to and can't
believe those code examples, complete gobbledegook to me. Great to see some humour in the matter.

After reading your post I went and played with autoformat and expected it to move my curly bracket
positions all over the place but surprisingly it didn't. I then went and Googled the matter and came across
a writeup on different methods of indentation. The differences seem legion, but like you say I'll probably
start to see a general pattern used by most coders. I was relieved to see one method was along the lines of
what I suggested Robin could use for teaching beginners and in fact in the writeup it said that method is
one of the easiest for beginners to understand, although it does take up more line for the same amount of
code. It also said it is very common for C.

Here's a part of that writeup (italics):

Allman / "East Coast" / Horstmann

Example: GNU-example in Allman style

int f(int x, int y, int z)


{
if (x < foo(y, z))
{
haha = bar[4] + 5;
}
else
{
while (z)
{
haha += foo(z, z);
z--;
}
return ++x + bar();
}
}

This style is named after Eric Allman, who wrote a lot of utilities for the BSD family of operating systems,
which also is a reason why this style is sometimes incorrectly referred to as the BSD style. Please note
that this style might sometimes be called BSD style, but that this is wrong. For BSD itself, just as for
UNIX and Linux, 1TBS is used. You can read about this in the man pages of the different BSD derivates
e.g. for ?FreeBSD and ?OpenBSD.

This style is usually preferred by newbes to C-derived programming languages for being the easiest.
Despite the fact that the inventors of C, UNIX and BSD use 1TBS, this style is very common for C.

The main disadvantage of this style is the waste of precious screen lines. Per block at least one additional
line is needed compared to 1TBS. In C, C++ and similar languages with comparable preprocessors there
is one single situation where this style shows an advantage over 1TBS.

I accept that is not the norm, but I am surprised by that too. It is so easy to read and I equate it to looking
at the graphical representation of a computer folder system, where you can see a folder inside a folder
inside a folder with great ease, but in this case it's functions. I'm guessing as I get more proficient at C
then I'll see functions and nested functions easier without my preferred bracketing method. Right now
though some of the code I've looked at is incredibly confusing to my beginner eyes. I see an opening
curly bracket, then in the same line another opening one. My eyes continue scanning serially along the
lines and oh my God another opening bracket. Somewhere each of these opening brackets have a closing
bracket and a lot of my effort is spent identifying individual functions and the nested functions inside
them. Welcome to the world of C I tell myself LOL.

As per your suggestion I'll keep an eye out for what seems to be the norm in coding style. Even if I don't
use it personally, my sketches are fairly simple at present and I can change it to the general method if I
post it on the forum.

Cheers,

Keith.

Jack Christensen

Faraday Member
Posts: 4,208

1.
Karma: 244 [add]
CODE is a mass noun and should not be used in the plural or with an indefinite article.
Adventures in Arduinoland

Re: Demonstration code for several things at the same time

#68
Mar 28, 2014, 01:34 pm
Ha, well that'll learn me, I had no idea the topic was so thoroughly documented with names for styles and
so forth. I should have known

Quote from: beefy23 on Mar 28, 2014, 09:58 am

I was relieved to see one method was along the lines of what I suggested Robin could use for teaching beginners and
in fact in the writeup it said that method is one of the easiest for beginners to understand, although it does take up
more line for the same amount of code. It also said it is very common for C.

Yeah I couldn't complain too much about that one. At least some thought went into it. If the worst thing is
that it wastes some space, but makes things easier for beginners to understand, then I can live with it.

Quote

I'm guessing as I get more proficient at C then I'll see functions and nested functions easier without my preferred
bracketing method.

In C and C++, while blocks of code can be nested, functions cannot be nested inside other functions.

Quote

Right now though some of the code I've looked at is incredibly confusing to my beginner eyes. I see an opening curly
bracket, then in the same line another opening one. My eyes continue scanning serially along the lines and oh my
God another opening bracket. Somewhere each of these opening brackets have a closing bracket and a lot of my
effort is spent identifying individual functions and the nested functions inside them. Welcome to the world of C I tell
myself LOL.

Actually that sounds like really bad style. That's where I'd just hit the Autoformat button before even
attempting to read it.
Jack Christensen

Faraday Member
Posts: 4,208

1.
Karma: 244 [add]
CODE is a mass noun and should not be used in the plural or with an indefinite article.
Adventures in Arduinoland

Re: Demonstration code for several things at the same time

#69

Mar 28, 2014, 01:45 pm


Keith, if you don't already have one, an editor that recognizes the language can really help by providing
"ident guides" (the vertical lines) and the ability to collapse or expand blocks of code. The Arduino IDE
can be rigged to work with an external editor via Preferences.

npp1.png
21.19 KB
downloaded 242 times

npp2.png
18.44 KB
downloaded 187 times

beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time


#70

Mar 29, 2014, 12:25 am Last Edit: Mar 29, 2014, 12:31 am by beefy23 Reason: 1
Quote from: Jack Christensen on Mar 28, 2014, 01:34 pm

In C and C++, while blocks of code can be nested, functions cannot be nested inside other functions.

Cheers Jack,

ha ha, there's the beginner in me coming out.


int f(int x, int y, int z)
{
if (x < foo(y, z))
{
haha = bar[4] + 5;
}
else
{
while (z)
{
haha += foo(z, z);
z--;
}
return ++x + bar();
}
}

I'm obviously describing things very wrong, time to re-educate myself. In the above example for instance
you've got "while(z)" inside "else". I've been calling both of those functions. I thought anything between
and open & closing curly bracket was a function.

You are completely correct about just trying to get things working and not focussing on learning C
properly. I'm impatient (and excited LOL) to get the end result. I've built a CNC plasma cutting table and
this project I've been working on is to make my table do something the standard software cannot do. I've
got so much on my plate I've just done what's necessary to get it working. I hadn't touched C before I got
an Arduino for this project. Then in addition I've been learning PCB making using the UV exposure
method, and Diptrace PCB design software (love it). So yeah, rush rush, cram into my head what I can as
quick as I can, etc. This is the result of my very first Arduino project so I'm quite elated
https://www.youtube.com/watch?v=yg-s-EAqMfI

The Arduino is controlling the plasma cutter directly instead of the computer. I'm just working on the
"Mark II" version now with some additions to the PCB hardware and improved features in the code. The
ease of use the Arduino provides made it possible.

Thanks as well for that pointer about the external editor, good information.

Edit:
Ha ha, just looked at the two images you supplied, and it's Notepad++. I just downloaded and installed it
two days ago, as well as another one called Programmers Notepad. I was Googling for a way to print my
code in colour (make it easy for the beginner again). Wow so now I can link to it from the Arduino IDE,
awesome. Time to look at Preferences.

Keith.

Jack Christensen

Faraday Member
Posts: 4,208

1.
Karma: 244 [add]
CODE is a mass noun and should not be used in the plural or with an indefinite article.
Adventures in Arduinoland

Re: Demonstration code for several things at the same time

#71

Mar 29, 2014, 01:28 am


Mighty impressive project there!

Curly braces enclose a block of one or more statements. The block of statements could be the body of a
function. So in the example, the function is named "f" (very original) and the outermost pair of braces
enclose the function body.
The function f() expects three integers as its input arguments and its return value is likewise an integer.

Within the function we have an if statement, which if the condition (x < foo(y, z)) is true, executes a
block that consists of one statement, haha = bar[4] + 5;

If the condition is false, then the else block gets executed. Within the else block is a while statement that
executes a block of two statements as long as the condition (z) is true.

Sounds worse than it is when it's written out like that. Don't analyze it too much because it's just an
example and a lousy one. For one thing, the function only returns a value if the else branch is taken.
That's at least bad form, and likely to cause a problem, because the caller would expect the function to
return an integer regardless. Another function foo() is called in two places within f(), but we don't know
what it does. So again just an example.

beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#72

Mar 29, 2014, 02:06 am


Thanks Jack,

I'll have to sit down with that one a bit and let it sink in.

Got the external editor working. Now there's no more copying and pasting just so I can print in colour,
and all the coding is done in a much better editor. Thanks a million, that's helped a lot.

Keith.
mrburnette

Faraday Member
Posts: 3,566

1.
Karma: 475 [add]
AKA: Ray Burne

Re: Demonstration code for several things at the same time

#73

Mar 29, 2014, 02:21 am


@Keith,

Welcome. Many of our most experienced members believe in tough-love. You do not have to like it, or
dislike it but you should take away that they spend countless hours a week in these forums attempting to
help answer questions; all non-paid and often thankless work. Formatting before posting (as requested in
the stickies at the top of the topics) is my and your easy of making their job a bit easier. After all, we
came in with the question/need.

I personally spend from 1 to 2 hours daily, often more if available. It is hard work, often frustrating. I
don't like being rude, but I am certain I have been sometimes. Unlike writing a project column (I do)
there is no draft review before publishing, "Post" click and move on to the next needy person. Very few
members give back from experience, so as you acquire knowledge and experience, consider taking on a
few newbie questions... It is a gratifying experience and you will grow from the research you do on their
behalf.

Best Arduino wishes,

Ray
beefy23

Jr. Member
Posts: 57
Karma: 0 [add]

Re: Demonstration code for several things at the same time

#74

Mar 31, 2014, 08:44 am


Hi Ray,

reading what you say has only gave me further disappointment.

A comment such as "that's horrible" is not tough love. It does nothing to help / educate the person it's
aimed at. Tough love applied in this situation should be helping someone, not just putting something
down with no explanation why. So far not one member has said Pete could have refrained from putting in
a criticising & pointless comment, yet seems I'm getting a gentle talking to from more than one member
because I reacted to that comment. I think that is completely screwed up.

I have been a member of a cnc forum for several years, and am at the stage where I help more than ask
questions. I have never gave a comment like what I got here, because of the hard thankless work I put into
answering newbies questions. I understand all too well the lack of thanks for answering questions and as
you'll see from my posts, I try to make of point of expressing thanks when someone helps me. I've been
pretty resentful on many occasions because of zero thanks or response when I've put time into a detailed
answer, but that has never led me to make the type of comment that I reacted to on here. If someone is
getting hot and bothered with all the hard work of being a charity to others, and they resort to pointless
irritating comments then maybe they need to take a break from the forum, and ask why they are doing it
in the first place.

And based on what has been said to me so far, why would I want to help others on this forum. The very
first time I suggest something with the good intention of helping beginners read code easier (whether my
suggestion is right or wrong, I was trying to help), I get a crap comment fired at me. I react to that
comment then I'm the one getting the talking to (however gentle). The message I keep getting, put
bluntly, is that on this forum, derisive comments are completely acceptable, and the person giving them
has justification for giving those comments.

Don't count on me to give help if this is the risk I put myself at on this forum. It will not be a gratifying
experience when I have to eat dirt because someone does not like what I said.

Keith.
PRINT

Go Up

Pages: 1 ... 3 4 [5] 6 7

Jump to:

NEWSLETTER

Old And In The Way


Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#75

Apr 03, 2014, 10:08 am


Quote from: Paul__B on Mar 10, 2014, 01:25 am
Quote from: Jiggy-Ninja on Mar 10, 2014, 12:34 am

I also prefer a different bracketing style to yours, but that's neither here nor there.

Ah, but if you use "Auto Format", it arranges things in a certain way for you.

Not completely at all. If you put the open brace on its own line, it will stay on its own line easier to see
and balance.

Nick Gammon on multitasking Arduinos:


1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

polymorph

Faraday Member
Posts: 4,087

1.
Karma: 560 [add]
Electronic Technician, Electronic Engineering Technician I love to build things. Test equipment, replica and
original sci fi props and costume pieces, and whatever else I feel like at the time. I have an Ultimaker and a 3D
engraver. I rarely put a kit tog
http://www.olymega.org

Re: Demonstration code for several things at the same time

#76

Jun 04, 2014, 09:05 pm


Quote from: Coding Badly on Mar 10, 2014, 09:12 am

Code: [Select]

...
if (currentMillis - previousOnBoardLedMillis >= onBoardLedInterval) {
...
previousOnBoardLedMillis = currentMillis;
}

The average interval will be slightly to significantly more than onBoardLedInterval. For most uses (like blinking an
LED) the longer interval is insignificant. For some uses the longer interval is a failure.

Code: [Select]

previousOnBoardLedMillis += onBoardLedInterval;

...produces a bit more code but keeps the average interval at exactly onBoardLedInterval.

Oh, I get it, maybe. If you make previousOnBoardLedMillis equal to currentMillis, then errors due to the
time it takes to step through the program are cumulative. But if you merely add onBoardLedInterval to
previousOnBoardLedMillis, while each time around will have a little error in timing, it is not cumulative.

Is that right?
Steve Greenfield AE7HD
Drawing Schematics: tinyurl.com/23mo9pf - tinyurl.com/o97ysyx - tinyurl.com/q7uqnvn
Multitasking: forum.arduino.cc/index.php?topic=223286.0
gammon.com.au/blink - gammon.com.au/serial - gammon.com.au/interrupts

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#77

Jun 04, 2014, 09:12 pm Last Edit: Jun 04, 2014, 09:16 pm by Robin2 Reason: 1
Quote from: polymorph on Jun 04, 2014, 09:05 pm

Is that right?

Very close.

The errors that creep in and could accumulate happen because currMillis = millis() may happen a tiny bit
late. Remember that the test is if (currMillis - prevMillis >= interval) so it may be a little greater, but it
will never be a little less.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

GoForSmoke


Old And In The Way
Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#78

Jun 05, 2014, 12:20 am


When you read millis() into currMillis, you set a time point.

The math (currMillis - prevMillis >= interval) evaluates the time point as TRUE or FALSE

When that is TRUE, you can eliminate slippage to less than 1 ms.
First, calculate millis past interval it took to run the check.
lateMillis = (currMillis - prevMillis) - interval; // partly to keep the compiler from rearranging terms
Then set your start time to the time point plus the overage at the time point.
prevMillis = curMillis + lateMillis
Slippage will be less than 1 ms, unless you time micros.

Nick Gammon on multitasking Arduinos:


1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#79
Jun 05, 2014, 08:07 am
Quote from: GoForSmoke on Jun 05, 2014, 12:20 am

Slippage will be less than 1 ms, unless you time micros.

prevMillis += interval has NO slippage and is much simpler.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

GoForSmoke

Old And In The Way


Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#80

Jun 05, 2014, 01:37 pm


Oh. Right.
Tired lately. Crash after caffeine burnout.

Nick Gammon on multitasking Arduinos:


1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts
Paul Beaudet

Full Member
Posts: 178
Karma: 6 [add]
Like to build typing devices, and heard unicorns

Re: Demonstration code for several things at the same time

#81

Jun 13, 2014, 08:15 pm


First of all, I commend Robbin's effort of showing newbies how to manage time.

Going to point out something a little less technical though. Sometimes people need to step in poo before
really understanding it smells. Even after countless people have told them how much it smells. In the
figurative sense my feet have a lot of lingering smell, probably the worst offender of this.

Tried to show a bunch of kids how to set robot motors without delays. Even basically built the functions
for them. Long story short, gave up and told them to use delays. After that, they started making progress
as opposed to being confused. The quality of my explanation mattered very little.

A smart person knows when they are right. A wise person knows when being right matters.
Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#82

Jun 13, 2014, 08:52 pm


@Paul Beaudet, I completely understand what you are saying.

And I am a great believer in learning by doing - the theory often makes complete sense later.

From reading a lot of stuff here it is obvious that some people grasp concepts quickly and others never do.
It is always difficult to know where to pitch advice when you don't get the instant feedback that you get in
a face-to-face situation.

One of the difficulties about the delay() vs BWoD choice is that it can be very difficult to convert a
complex piece of code from using delay()s to using BWoD. For that reason I am inclined to encourage the
early use of BWoD even when, technically, it doesn't make a lot of difference.

Conversion is not helped by the understandable "decision" by many newbies to bundle all their code into
loop(). I put the word decision in quotes, because, of course it is an absence of a decision to be more
organized - usually for want of experience.

Another complication is that you never know how long a newbie is going to stick with Arduino - if s/he is
going to lose interest after the first project almost all teaching will be a waste of time. I think the only
practical approach is to treat everyone as a long term prospect.

Following from that, my perception is that it is not helpful to propose (as opposed to assist with) second
rate solutions.

And, of course, the reader is always free to reject the advice. I hope that people who use my example do
so because they themselves think it is appropriate.
Thanks for your comments.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

polymorph

Faraday Member
Posts: 4,087

1.
Karma: 560 [add]
Electronic Technician, Electronic Engineering Technician I love to build things. Test equipment, replica and
original sci fi props and costume pieces, and whatever else I feel like at the time. I have an Ultimaker and a 3D
engraver. I rarely put a kit tog
http://www.olymega.org

Re: Demonstration code for several things at the same time

#83

Jun 13, 2014, 09:16 pm


Quote
One of the difficulties about the delay() vs BWoD choice is that it can be very difficult to convert a complex piece of
code from using delay()s to using BWoD. For that reason I am inclined to encourage the early use of BWoD even
when, technically, it doesn't make a lot of difference.

Yes! Agree 100%!

Steve Greenfield AE7HD


Drawing Schematics: tinyurl.com/23mo9pf - tinyurl.com/o97ysyx - tinyurl.com/q7uqnvn
Multitasking: forum.arduino.cc/index.php?topic=223286.0
gammon.com.au/blink - gammon.com.au/serial - gammon.com.au/interrupts

GoForSmoke

Old And In The Way


Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#84

Jun 13, 2014, 09:28 pm


The more time and money invested in a mistake, the harder it is to walk away.

Never time to do it right, always time to do it over.

Nick Gammon on multitasking Arduinos:


1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts
polymorph

Faraday Member
Posts: 4,087

1.
Karma: 560 [add]
Electronic Technician, Electronic Engineering Technician I love to build things. Test equipment, replica and
original sci fi props and costume pieces, and whatever else I feel like at the time. I have an Ultimaker and a 3D
engraver. I rarely put a kit tog
http://www.olymega.org

Re: Demonstration code for several things at the same time

#85

Jun 13, 2014, 09:58 pm


Yeah... a friend of mine has the unenviable job of cleaning up sloppy quick-fixes in other people's
programming.

And this is why I'm on kind of a tear, criticizing the over-use of delay() to time things. It really annoys me
how just about every book, class, website, and video that purports to be for beginners to Arduino, use
delay() for everything.

Steve Greenfield AE7HD


Drawing Schematics: tinyurl.com/23mo9pf - tinyurl.com/o97ysyx - tinyurl.com/q7uqnvn
Multitasking: forum.arduino.cc/index.php?topic=223286.0
gammon.com.au/blink - gammon.com.au/serial - gammon.com.au/interrupts

JimboZA

Tesla Member
Posts: 8,723
Karma: 838 [add]

Re: Demonstration code for several things at the same time

#86

Jun 15, 2014, 09:02 am


At last I got round to looking at this thread, although I've seen Robin2 link to it numerous times.

The esoteric discussion on latency and slippage aside- most if not all of which went splat on the wall
behind me- it's an excellent piece of work and a good look at the whole bwod thing. Well done and karma
to you Robin2.

I'm going to use this approach in some stuff I intend to do today- probably get really advanced and have
different durations on the LEDs , and include some other stuff I'm fiddling with.

[whisper]It's such a pity that this thread went off the rails a number of times but that's life I guess.[/whisper]
Johannesburg hams call me: ZS6JMB on Highveld rep 145.7875 (-600 & 88.5 tone)
Dr Perry Cox: "Help me to help you, help me to help you...."
Your answer may already be here: https://forum.arduino.cc/index.php?topic=384198.0

spruce_m00se

Sr. Member
Posts: 437
Karma: 3 [add]

Re: Demonstration code for several things at the same time

#87

Jun 23, 2014, 01:09 pm


Well, i just stumbled across this example after starting this thread:
http://forum.arduino.cc/index.php?topic=248643.0

I had already written a higgledy piggledy code that more or less did what I want it to do, but some things
are just seemingly messed up by timing during other events using delay()

I had already taken each part of the code into individual functions as in your example before reading it
and was looking into how to use millis in various functions at the same time,

this was very useful having stepped in the previously mentioned poo and looking for a way to clean my
foot,

Thanks,
polymorph

Faraday Member
Posts: 4,087

1.
Karma: 560 [add]
Electronic Technician, Electronic Engineering Technician I love to build things. Test equipment, replica and
original sci fi props and costume pieces, and whatever else I feel like at the time. I have an Ultimaker and a 3D
engraver. I rarely put a kit tog
http://www.olymega.org

Re: Demonstration code for several things at the same time

#88

Jun 23, 2014, 08:27 pm


And if you need finer grained timing, there is also micros(). Although it counts in microseconds, you
should know that the granularity is 4us.

Steve Greenfield AE7HD


Drawing Schematics: tinyurl.com/23mo9pf - tinyurl.com/o97ysyx - tinyurl.com/q7uqnvn
Multitasking: forum.arduino.cc/index.php?topic=223286.0
gammon.com.au/blink - gammon.com.au/serial - gammon.com.au/interrupts
GoForSmoke

Old And In The Way


Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#89

Jun 23, 2014, 11:50 pm Last Edit: Jun 24, 2014, 12:01 am by GoForSmoke Reason: 1
Months ago I saw this thread but since the principle is the same as what Nick Gammon covers very will
in his blog (that explains blocking code and other basic concepts in a slow-pitch way), I just linked people
to that.

If you haven't seen, this is Nock's (edit, errr Nick's) tutorial:


http://www.gammon.com.au/forum/?id=11411
Note to self: start using the new keyboard that doesn't have half the letters rubbed off.

Not long ago I got back and learned one very good lesson from Robin2 (karma to you, Robin) of not
updating start time to millis() in a time check that may be late but rather adding the interval to the start
which is ALWAYS right.

So this time I actually looked the code over and I see something that I have done very often before,
especially when under the gun, but that does not make it good practice at all. In fact, even as beginners we
are reminded to not do this thing.
And what is that?
Copy&paste then modify to suit code multiplication. Because it works and what works is good, right?
Wrong.

Do I want to add a block of code for every led I add? No. That's why there's arrays, etc.
I had a pretty good day today, healthwise, so I dug out the breadboard, parts boxes and magnifier to do
something.

Here is Blink Multiple Leds Without Delay in 2 versions.


1st is the short version that I count as 24 lines of actual code (not counting braces).
2nd is a longer teaching version with loads of comments and serial report options. 1st is the short version
that I count as 24 lines of actual code (not counting braces).

Mess with it. Ask questions. I had all that addressed then the forum timed me out and poof, all that is
gone!
Add leds. If you want more than 8 then change ledState to unsigned int or long.

Short version:

// Blink Multiple leds With Uneven Delays, Short Version

const byte LEDS = 4;


const byte ledPin[ LEDS ] = // I use Autoformat. It won't let this be 1 line.
{
13, 3, 5, 7
};

byte ledState = 0; // this will handle 8 led states as bits


byte led = 0; // this example processes 1 led per pass through loop()

unsigned int millisNow; // fill with the lower 16 bits of millis()


unsigned int startBlink[ LEDS ]; // these all default to zero
unsigned int waitBlink[ LEDS ][ 2 ]; // one for OFF time, one for ON time

void setup()
{
for ( led = 0; led < LEDS; led++ )
{
waitBlink[ led ][ 0 ] = 250U * ((unsigned int) led + 1U ); // OFF millis
waitBlink[ led ][ 1 ] = 10U * ((unsigned int) led + 1U ); // ON millis

pinMode( ledPin[ led ], OUTPUT ); // default output is LOW


digitalWrite( ledPin[ led ], bitRead( ledState, led ));
}

led = 0;
}
void loop()
{
millisNow = (unsigned int)( millis() & 0xFFFF ); // lower 16 bits roll over just
fine

if ( millisNow - startBlink[ led ] >= waitBlink[ led ][ bitRead( ledState, led ) ] )

{
startBlink[ led ] += waitBlink[ led ][ bitRead( ledState, led ) ]; // update start
time

bitWrite( ledState, led, ( bitRead( ledState, led ) == 0 )); // change led state
bit
digitalWrite( ledPin[ led ], bitRead( ledState, led ) ); // change the led pin
}

led++;
if ( led >= LEDS )
{
led = 0;
}
}

// Blink Multiple leds With Uneven Delays, Serial reporting optional

/*
The hardest part of this was getting the debug/report prints to not screw the timing
by more than 1 milli. I even left in some commented-out lines just for comparison.
Serial is not free, it blocks execution!
*/

// make SERPRINT 1 to enable serial preorti


#define SERPRINT 1

// #if SERPRINT ---- if I leave this in, the sketch won't compile
byte runBeforeStop = 199; // to limit serial print lines set this to < 200
//#endif

const byte LEDS = 4;


const byte ledPin[ LEDS ] = // I use Autoformat. It won't let this be 1 line.
{
13, 3, 5, 7
};

byte ledState = 0; // this will handle 8 led states as bits


// to track more than 8 leds, use larger unsigned integers than byte
byte led = 0; // this example processes 1 led per pass through loop()

unsigned int millisNow; // fill with the lower 16 bits of millis()


unsigned int startBlink[ LEDS ]; // these all default to zero
unsigned int waitBlink[ LEDS ][ 2 ]; // one for OFF time, one for ON time
// using the low 16 bits of millis allows 65.535 second blink
// however if you need longer, change these to unsigned long
// you can initialize this array as const or use PROGMEM to store it
// I chose to use a formula. With a different formula I could get rid
// of the whole array and use one or more variables to run the formula.

// This is code. Make your own way all you *can*! More you do, better you get.
// And note, this mess just begs to be turned into a Class Objects example.

void setup()
{
#if SERPRINT
Serial.flush();
Serial.begin( 9600 );
Serial.println( "\nMulti-led blink test\n" );
#endif

for ( led = 0; led < LEDS; led++ )


{
#if SERPRINT
Serial.print( " Led " );
Serial.print( led, DEC );
Serial.print( " >> " );
#endif

// setting the blink delays by formula here


// YES for this the array is not needed, the code below could use the formula
// however this example can also use a pre-compiled array
// and if User I/O or other dynamic change method is added, the array may serve
that
// But Please, change it all to suit your ideas as they occur!

waitBlink[ led ][ 0 ] = 250U * ((unsigned int) led + 1U ); // OFF millis


waitBlink[ led ][ 1 ] = 10U * ((unsigned int) led + 1U ); // ON millis

#if SERPRINT
Serial.print( " OFF millis = " );
Serial.print( waitBlink[ led ][ 0 ] );
Serial.print( " ON millis = " );
Serial.println( waitBlink[ led ][ 1 ] );
#endif

pinMode( ledPin[ led ], OUTPUT ); // default output is LOW


digitalWrite( ledPin[ led ], bitRead( ledState, led ));
}
#if SERPRINT
Serial.println( );

Serial.println( "Led <led> t <millisNow> x <pin state> n <next change>" );


#endif

led = 0;
}

void loop()
{

millisNow = (unsigned int)( millis() & 0xFFFF ); // lower 16 bits roll over just
fine

if ( millisNow - startBlink[ led ] >= waitBlink[ led ][ bitRead( ledState, led ) ] )

{
#if SERPRINT
Serial.print( led, DEC );
Serial.print( " t " );
Serial.print( millisNow );
/*
Serial.print( " states " );
Serial.print( ledState, BIN );
*/
#endif

startBlink[ led ] += waitBlink[ led ][ bitRead( ledState, led ) ]; // update start


time
// Thank You Robin2, this really does take care of late updates

bitWrite( ledState, led, ( bitRead( ledState, led ) == 0 )); // change led state
bit
digitalWrite( ledPin[ led ], bitRead( ledState, led ) ); // change the led pin

#if SERPRINT
/* put these in and see what it does occasionally to timing. then add more serial
Serial.print( " change " );
Serial.print( ledState, BIN );
Serial.print( " start " );
Serial.print( startBlink[ led ] );
Serial.print( " wait " );
Serial.print( waitBlink[ led ][ bitRead( ledState, led ) ] );
*/
Serial.print( " x " );
Serial.print( bitRead( ledState, led ) );
Serial.print( " n " );
Serial.print( startBlink[ led ] + waitBlink[ led ][ bitRead( ledState, led ) ] );
Serial.println();

if ( runBeforeStop < 200 )


{
if ( !runBeforeStop-- )
{
while( 1 );
}
}
#endif

led++;
if ( led >= LEDS )
{
led = 0;
}
}----

Global Moderator
Brattain Member
Posts: 18,603

1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/

Re: Demonstration code for several things at the same time

#90

Jun 23, 2014, 11:55 pm

Quote from: GoForSmoke on Jun 23, 2014, 11:50 pm


If you haven't seen, this is Nock's tutorial:
http://www.gammon.com.au/forum/?id=11411

In case you don't want to / can't remember a five digit number...


http://gammon.com.au/blink

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#91

Sep 20, 2014, 04:31 pm Last Edit: Oct 02, 2014, 08:35 am by Robin2 Reason: 1

Quote from: casemod on Sep 20, 2014, 03:07 pm

Since this is a sticky it's worth to post this method here as well:

Added 02 Oct 2014 --- @casemod seems to have moved his posts out of this Thread (as was suggested in
the next Post) hence this and some of the following posts are in a bit of a vacuum.

Most of the posts in this Thread are about the cumulative error associated with

Code: [Select]

previousmillis = currentmillis;
and how it is better to use

Code: [Select]

previousmillis += time;
or (in your second method)
Code: [Select]

since += time

Please don't confuse newcomers by recommending the deprecated approach in this Thread.

It would probably also be very useful for newcomers if you would modify your Post and add an
explanation about how &since works. Most of them will find that concept very confusing without a clear
explanation.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#92

Sep 20, 2014, 07:46 pm

Quote from: casemod on Sep 20, 2014, 06:54 pm

I changed that bit and added a brief description

I posted the code with the intent of helping those trying to "multitask" or do things at the same time, not exactly the issue you
mentioned, however if it is not suitable let me know so I can remove it or make further corrections

Thanks.

You don't seem to have changed the line with since = currentmillis.
And I can't see your explanation of the way &since works

Your concept might be better placed in its own Thread titled "A non-blocking alternative to delay()". If
you move your code you could keep a link to the other Thread here.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

GoForSmoke

Old And In The Way


Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#93

Sep 24, 2014, 08:49 am

Quote from: casemod on Sep 20, 2014, 08:31 pm

Quote from: Robin2 on Sep 20, 2014, 07:46 pm

You don't seem to have changed the line with since = currentmillis.

I changed this line


Code: [Select]

if (currentmillis - previousmillis >= time) {

previousmillis = currentmillis

with

Code: [Select]

if (currentmillis - previousmillis >= time) {

previousmillis += time;

If you're using the blinking led as a status light then the first way will let accumulated "late errors"
actually show.
What code is "right" is a matter of what your output is for. As an indicator, self-correction is not the best
goal.

Nick Gammon on multitasking Arduinos:


1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#94

Sep 24, 2014, 08:56 am

Quote from: GoForSmoke on Sep 24, 2014, 08:49 am


If you're using the blinking led as a status light then the first way will let accumulated "late errors" actually show.
What code is "right" is a matter of what your output is for. As an indicator, self-correction is not the best goal.

Please don't reopen this discussion. It has all been extensively covered in earlier posts and the demo in the
first Post in the Thread has taken all the discussion into account. My only concern is that @Casemod's
contribution might confuse newcomers. He has said he will move it to another Thread.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

nickgammon

Global Moderator
Nick Gammon
Brattain Member
Posts: 28,093

1.
Karma: 1345 [add]
Lua rocks!
http://www.gammon.com.au

Re: Demonstration code for several things at the same time


#95

Sep 24, 2014, 10:03 am

Quote from: Coding Badly on Jun 23, 2014, 11:55 pm

Quote from: GoForSmoke on Jun 23, 2014, 11:50 pm

If you haven't seen, this is Nock's tutorial:


http://www.gammon.com.au/forum/?id=11411

Nick's tutorial.

My examples there actually do have the creep which is mentioned earlier. Putting aside coding issues, this
creep is based on the fact that you reset the timer when the event is noticed, not a fixed interval from
when it should have been noticed.

In the case of flashing an LED, this isn't an issue.

Let me give you an example in real-life terms. Say you get a credit card statement in the mail, and you
have 30 days to pay. The 30 days is from when the statement was sent, not from when you receive it
(which might be a few days later). The creep is in the delivery time (or maybe in the time it takes you to
notice the mail).

To have the statements come every 30 days, the sender simply adds 30 days to when they sent the last
one. To have the creep, they would add 30 days to when you received the mail.

Please post technical questions on the forum, not by personal message. Thanks!

More info: http://www.gammon.com.au/electronics

GoForSmoke


Old And In The Way
Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#96

Sep 24, 2014, 10:24 am


Sorry about that Mr. Gammon, Sir! One quoted mistype that's never going to die, is it? IIRC, I did fix the
original.

In the bills case it is desired to keep the billing cycle regular. Apps should fit needs. Been there, wrote the
packages.

I want a status light to tell me more about the running of the software, not less. I've got one now that
doesn't so much creep as leap whenever the GSM element runs. It's for someone else and free work so I'm
not going to fix that library but wow does it need unblocking!

I thank you again for your great tutorials that put words to what I never put words to. My right-brain
thinking ways don't do that and I end up with poor explanations for thoughts that are more like working
pictures. What can I say? Literally! It's been great to be able to link people to your full, coherent
explanations instead of my poor attempts.

Nick Gammon on multitasking Arduinos:


1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts
larryd

Shannon Member
Posts: 12,488
Karma: 1163 [add]
The last thing you did is where you should start looking.

Re: Demonstration code for several things at the same time

#97

Sep 25, 2014, 02:25 am


Robin2
I am sure people new to programming will find your work very beneficial.
One comment, if a newcomer reads through the whole thread I think they may a bit confused with all the
discussions.
IMHO it would be best to chop everything after your example which incorporates the the discussed creep
code modification.
Thanks for your time on this.
Thanks to the software guys for there explanations also.

No technical PMs.
The last thing you did is where you should start looking.
Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#98

Sep 25, 2014, 10:17 am

Quote from: LarryD on Sep 25, 2014, 02:25 am

One comment, if a newcomer reads through the whole thread I think they may a bit confused with all the discussions.

I have been wondering about this as well, but I am concerned that I may be too close to the subject to take
an objective view.

I have added a note for newcomers at the top of the first Post.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

GoForSmoke

Old And In The Way


Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.
Re: Demonstration code for several things at the same time

#99

Sep 25, 2014, 01:14 pm


I just wish that you had explained the central problem of blocking code explicitly.
That is why I still link to Nick's blog. He does a good job of doing that.

Nick Gammon on multitasking Arduinos:


1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#100

Sep 25, 2014, 10:42 pm

Quote from: GoForSmoke on Sep 25, 2014, 01:14 pm

I just wish that you had explained the central problem of blocking code explicitly.
That is why I still link to Nick's blog. He does a good job of doing that.

As I say in the opening post (the only one that really matters for a newcomer) I just set out to give an
extended example of the BWoD concept. I was not trying to monopolize the subject.
I like Nick's stuff - I have bookmarked several items.

But I also think it is a good idea to be able to direct people to material within the Arduino website.

It is always difficult to know how to pitch a teaching item. Some people like to read the theory. Others
just want to get stuck in.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.

GoForSmoke

Old And In The Way


Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.

Re: Demonstration code for several things at the same time

#101

Sep 26, 2014, 01:47 am


I agree with your goals very much.

But to some of this I liken it to teaching the 2 + 2 = 4 and 3 + 3 = 6 without teaching what 2 and 3 are. I
want beginners to be able to say 2 + 3 = 5 without having to memorize it, look it up or get a library to do
it for them.

If you don't have your fundamentals down then you make fundamental mistakes. Bits, bytes and logic are
the ABC's, 123's and +-x/ operators of computing. Arrays are the spelling words and structure is
grammar. Everyone with a solid grounding in those will be able to make easier sense of the rest. The how
and why is more important than the what and that gets demonstrated every day here which is why I try to
hand out fundamentals where I find a lack.
Nick Gammon on multitasking Arduinos:
1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

Robin2

Brattain Member
Posts: 40,256
Karma: 1843 [add]

Re: Demonstration code for several things at the same time

#102

Sep 26, 2014, 09:37 am

Quote from: GoForSmoke on Sep 26, 2014, 01:47 am

But to some of this I liken it to teaching the 2 + 2 = 4 and 3 + 3 = 6 without teaching what 2 and 3 are.

I see that.

I guess I started from the assumption that the reason WHY would have been explained in whatever Reply
told the OP not to use delay() and to look at this as an example of how to get by without it.

It seems to me that the newcomers have no difficulty understanding that delay() gets in the the way of
concurrency - but they don't immediately grasp how to use millis() to replace it.

If you can suggest 2 or 3 lines (not more!) for insertion into my original post I will certainly consider it.

...R

Two or three hours spent thinking and reading documentation solves most programming problems.
robtillaart

Global Moderator
Brattain Member
Posts: 18,352
Karma: 1035 [add]
In theory there is no difference between theory and practice, however in practice there are many...

Re: Demonstration code for several things at the same time

#103

Dec 20, 2014, 12:52 pm

Why is the usage of break an argument against switch()? That is the same as saying the use of else is an
argument against if... It are code constructs to make an algorithm easier to maintain and give the compiler
means to optimize the code.

For a switch statement there are at least 2 ways to compile to machine code while an if then else ladder
(expressed functionally equivalent) cannot. One reason is that for a switch statement the compiler knows
immediately that there is one element in an "is equal" compare, which is every time the same (e.g.
optimize in a register). For an if then else ladder every comparison is a new one for the parse tree, which
might be optimized later. In switch statements every case must be disjunct, semantics forces that. In an if
then else ladder you can do the same comparison multiple times.

A switch statements allows a fall through which can be used for simple OR or for reducing double code.
An if then else ladder has no (straightforward) equivalent for that.

For me the only drawback of the switch statement is that it does only support simple integer types and not
complex or aggregate like strings and structs. BUt that is by design so I can (have to) live with that.

Rob Tillaart
Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

PRINT

Go Up

Pages: 1 ... 5 6 [7]

Jump to:

servo motore

Mar 07, 2016, 07:56 pm


salve avrei un problema in quanto vorrei attivare il servomotore quando si attivano le ventole e farlo
ruotare di 90 gradi mentre quando si spengono vorrei tornasse nella posizione iniziale.posto il mio codice:
#include <dht11.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C
address
dht11 DHT11;

#define DHT11PIN 9
//#define tempPin 0
int sensorvalue;
float umiditaterra;
//int tempC ;
int relepompaacqua=7;
int releventole=5;
int relephon=6;
Servo motor;
int pos = 0;
void setup() {
pinMode(relepompaacqua ,OUTPUT);
digitalWrite(relepompaacqua, HIGH);
digitalWrite(releventole, HIGH);
pinMode(releventole ,OUTPUT);
digitalWrite(relephon, HIGH);
pinMode(relephon ,OUTPUT);
motor.attach(4);
//pinMode(tempPin,INPUT);
lcd.begin(20,4); // initialize the lcd for 20 chars 4 lines, turn on
backlight
lcd.backlight();
Serial.begin(9600);
}

void loop()
{

int ciao= DHT11.read(DHT11PIN);

lcd.setCursor(0,0);
lcd.print("-tempdht11= ");
lcd.print((float)DHT11.temperature,0);
lcd.print("C");

lcd.setCursor(0,1);
lcd.print("-umidita'= ");
lcd.print((float)DHT11.humidity,0);
lcd.print("%");

sensorvalue=analogRead(2);
umiditaterra =map(sensorvalue,365,1023,100,0);
lcd.setCursor(0,2);
lcd.print("-um terreno= ");
lcd.print(umiditaterra);

// lcd.setCursor(0,3);
//tempC = analogRead(tempPin); //lettura valore del sensore
//tempC =tempC*500/1024; //conversione del dato analogico in
temperatura(tempc/1024.0)*5000
//lcd.print(" -templm35=");
//lcd.print(tempC);
//lcd.print("C");
//delay(500);
if(umiditaterra < 60)
{
digitalWrite(relepompaacqua,LOW);
}
else
{
digitalWrite(relepompaacqua,HIGH);
}
if(DHT11.humidity > 50)
{
digitalWrite(releventole,LOW);
}
else
{
digitalWrite(releventole,HIGH);
}
if(DHT11.temperature <15)
{
digitalWrite(relephon,LOW);
}
else
{
digitalWrite(relephon,HIGH);
}

if(releventole==LOW)
{
for(pos = 0; pos <= 90; pos += 1)
{
motor.write(pos); // indirizza il perno alla posizione desiderata,
memorizzata in 'pos'
delay(15); // attende 15ms per consentire al servomotore di raggiungere la
posizione
}
}
else{
}

delay(1000);
}

else{
}
========

"The S2000 is nothing so much as a legend in its own time. If you don't like it, you probably haven't
driven it hard enough." - Car culture
Colzadanicola

Full Member
Posts: 153
Karma: 5 [add]

Re: servo motore

#2

Mar 08, 2016, 08:53 am


se non si mette l'else non funziona? era solo una prova per vedere quando sono attive le ventole si apre il
portellone.

c0rsa1r

Awesome
Full Member
Posts: 172
Karma: 41 [add]

Re: servo motore


#3

Mar 08, 2016, 09:18 am


Non che non funziona, semplicemente non fa nulla.

if = se questa condizione vera allora fai questo;


else = se la precedente condizione falsa invece fai quest'altro;

Quindi se dici che il relay delle ventole attivo e le ventole girano (if) allora fa il giro di 90, mentre se il
relay delle ventole inattivo, il servo torna in posizione zero (else);

"The S2000 is nothing so much as a legend in its own time. If you don't like it, you probably haven't
driven it hard enough." - Car culture

Colzadanicola

Full Member
Posts: 153
Karma: 5 [add]

Re: servo motore

#4

Mar 08, 2016, 09:29 am


si ma io l'ho fatto senza else solo per provarlo,ho fatto in modo che il rel 2 fosse attivo,quindi il motore
doveva fare qualcosa,invece non si mosso.
o sbaglio?
c0rsa1r

Awesome
Full Member
Posts: 172
Karma: 41 [add]

Re: servo motore

#5

Mar 08, 2016, 09:41 am Last Edit: Mar 08, 2016, 09:47 am by c0rsa1r
Lo sketch esempio "Sweep" funziona correttamente? Stai alimentando il servo esternamente o stai
utilizzando la 5V di Arduino?

Edit: in void setup sarebbe meglio prima dichiarare i relay come OUTPUT e POI metterli rispettivamente
in HIGH o in LOW a seconda della necessit in avvio;

"The S2000 is nothing so much as a legend in its own time. If you don't like it, you probably haven't
driven it hard enough." - Car culture

Colzadanicola


Full Member
Posts: 153
Karma: 5 [add]

Re: servo motore

#6

Mar 08, 2016, 10:04 am


mi sembra quello che ho fatto.no?comunque ho provato sia a alimentarli esternamente che internamente e
funzionano;ho provato senza un if solo per una prova.

Colzadanicola

Full Member
Posts: 153
Karma: 5 [add]

Re: servo motore

#7

Mar 08, 2016, 12:33 pm


Mi correggo,senza else

brunello22

Faraday Member
Posts: 5,138
Karma: 444 [add]

Re: servo motore


#8

Mar 08, 2016, 12:58 pm


Quando fai questo
if ( releventole == LOW )
come se facessi if ( 5 == LOW )
5 e non lettura del pin 5

Code: [Select]

if (digitalRead (releventole) == LOW )

e abbassa quel delay(15);

"C' chi legge Guerra & Pace e non ci capisce un tubo vuoto; c' chi legge l'etichetta delle patatine fritte e
ci trova la spiegazione del mondo"

Colzadanicola

Full Member
Posts: 153
Karma: 5 [add]

Re: servo motore

#9

Mar 08, 2016, 01:14 pm


Ok b infatti che stupido.quando sono a casa provo .grazie

Colzadanicola


Full Member
Posts: 153
Karma: 5 [add]

Re: servo motore

#10

Mar 08, 2016, 08:04 pm


quando faccio partire il programma il servo compie una rotazione di 30 gradi e poi torna nella pos
iniziale,poi funziona correttamente come l'ho impostato nel programma.
codice:

#include <dht11.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C
address
dht11 DHT11;

#define DHT11PIN 9
//#define tempPin 0
int sensorvalue;
float umiditaterra;
//int tempC ;
int relepompaacqua=7;
int releventole=5;
int relephon=6;
Servo motor;
int pos ;
void setup() {
pinMode(relepompaacqua ,OUTPUT);
digitalWrite(relepompaacqua, HIGH);
digitalWrite(releventole, HIGH);
pinMode(releventole ,OUTPUT);
digitalWrite(relephon, HIGH);
pinMode(relephon ,OUTPUT);
motor.attach(4);
//pinMode(tempPin,INPUT);
lcd.begin(20,4); // initialize the lcd for 20 chars 4 lines, turn on
backlight
lcd.backlight();
Serial.begin(9600);
}

void loop()
{

int ciao= DHT11.read(DHT11PIN);

lcd.setCursor(0,0);
lcd.print("-tempdht11= ");
lcd.print((float)DHT11.temperature,0);
lcd.print("C");

lcd.setCursor(0,1);
lcd.print("-umidita'= ");
lcd.print((float)DHT11.humidity,0);
lcd.print("%");

sensorvalue=analogRead(2);
umiditaterra =map(sensorvalue,365,1023,100,0);
lcd.setCursor(0,2);
lcd.print("-um terreno= ");
lcd.print(umiditaterra);

// lcd.setCursor(0,3);
//tempC = analogRead(tempPin); //lettura valore del sensore
//tempC =tempC*500/1024; //conversione del dato analogico in
temperatura(tempc/1024.0)*5000
//lcd.print(" -templm35=");
//lcd.print(tempC);
//lcd.print("C");
//delay(500);
if(umiditaterra < 60)
{
digitalWrite(relepompaacqua,LOW);
}
else
{
digitalWrite(relepompaacqua,HIGH);
}
if(DHT11.humidity > 50)
{
digitalWrite(releventole,LOW);
}
else
{
digitalWrite(releventole,HIGH);
}
if(DHT11.temperature <15)
{
digitalWrite(relephon,LOW);
}
else
{
digitalWrite(relephon,HIGH);
}

if(digitalRead(releventole)==LOW)
{
for(pos = 0; pos <= 90; pos += 1)
{
motor.write(pos=90); // indirizza il perno alla posizione desiderata,
memorizzata in 'pos'
delay(10); // attende 15ms per consentire al servomotore di raggiungere la
posizione
}
}
else{ for(pos = 0; pos <= 0; pos += 1)
{
motor.write(pos=1); // indirizza il perno alla posizione desiderata,
memorizzata in 'pos'
delay(10); // attende 15ms per consentire al servomotore di raggiungere la
posizione
}
}

delay(2000);
}

Re: servo motore

#11

Mar 08, 2016, 08:09 pm


come faccio a eliminare la rotazione che fa il servo a inizio programma?
brunello22

Faraday Member
Posts: 5,138
Karma: 444 [add]

Re: servo motore

#12

Mar 08, 2016, 10:06 pm


se tu che ce lo mandi
else{ for(pos = 0; pos <= 0; pos += 1)
{
motor.write(pos=1); // indirizza il perno alla posizione desiderata,
memorizzata in 'pos'
delay(10); // attende 15ms per consentire al servomotore di raggiungere la
posizione
}
}

if (digitalRead(releventole) == LOW)
{
motor.write(90);
}
else {
motor.write(1);
}

#include <dht11.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C
address
dht11 DHT11;

#define DHT11PIN 9
//#define tempPin 0
int sensorvalue;
float umiditaterra;
//int tempC ;
int relepompaacqua=7;
int releventole=5;
int relephon=6;
Servo motor;
int pos ;
void setup() {
pinMode(relepompaacqua ,OUTPUT);
digitalWrite(relepompaacqua, HIGH);
digitalWrite(releventole, HIGH);
pinMode(releventole ,OUTPUT);
digitalWrite(relephon, HIGH);
pinMode(relephon ,OUTPUT);

motor.attach(4);
//pinMode(tempPin,INPUT);
lcd.begin(20,4); // initialize the lcd for 20 chars 4 lines, turn on
backlight
lcd.backlight();
Serial.begin(9600);
}

void loop()
{

int ciao= DHT11.read(DHT11PIN);

lcd.setCursor(0,0);
lcd.print("-tempdht11= ");
lcd.print((float)DHT11.temperature,0);
lcd.print("C");

lcd.setCursor(0,1);
lcd.print("-umidita'= ");
lcd.print((float)DHT11.humidity,0);
lcd.print("%");

sensorvalue=analogRead(2);
umiditaterra =map(sensorvalue,365,1023,100,0);
lcd.setCursor(0,2);
lcd.print("-um terreno= ");
lcd.print(umiditaterra);
// lcd.setCursor(0,3);
//tempC = analogRead(tempPin); //lettura valore del sensore
//tempC =tempC*500/1024; //conversione del dato analogico in
temperatura(tempc/1024.0)*5000
//lcd.print(" -templm35=");
//lcd.print(tempC);
//lcd.print("C");
//delay(500);
if(umiditaterra < 60)
{
digitalWrite(relepompaacqua,LOW);
}
else
{
digitalWrite(relepompaacqua,HIGH);
}
if(DHT11.humidity > 50)
{
digitalWrite(releventole,LOW);
}
else
{
digitalWrite(releventole,HIGH);
}
if(DHT11.temperature <15)
{
digitalWrite(relephon,LOW);
}
else
{
digitalWrite(relephon,HIGH);
}

if(digitalRead(releventole)==HIGH)
{

motor.write(pos=0); // indirizza il perno alla posizione desiderata,


memorizzata in 'pos'
delay(10); // attende 15ms per consentire al servomotore di raggiungere la
posizione
}

else{

motor.write(pos=90); // indirizza il perno alla posizione desiderata,


memorizzata in 'pos'
delay(10);

delay(2000);
}========

#include <dht11.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C
address
dht11 DHT11;

#define DHT11PIN 9
//#define tempPin 0
int sensorvalue;
float umiditaterra;
//int tempC ;
int relepompaacqua=7;
int releventole=5;
int relephon=6;
Servo motor;
int pos=4 ;
void setup() {
pinMode(relepompaacqua ,OUTPUT);
digitalWrite(relepompaacqua, HIGH);
digitalWrite(releventole, HIGH);
pinMode(releventole ,OUTPUT);
digitalWrite(relephon, HIGH);
pinMode(relephon ,OUTPUT);

motor.attach(4);
//pinMode(tempPin,INPUT);
lcd.begin(20,4); // initialize the lcd for 20 chars 4 lines, turn on
backlight
lcd.backlight();
Serial.begin(9600);
}

void loop()
{
int ciao= DHT11.read(DHT11PIN);

lcd.setCursor(0,0);
lcd.print("-tempdht11= ");
lcd.print((float)DHT11.temperature,0);
lcd.print("C");

lcd.setCursor(0,1);
lcd.print("-umidita'= ");
lcd.print((float)DHT11.humidity,0);
lcd.print("%");

sensorvalue=analogRead(2);
umiditaterra =map(sensorvalue,365,1023,100,0);
lcd.setCursor(0,2);
lcd.print("-um terreno= ");
lcd.print(umiditaterra);

// lcd.setCursor(0,3);
//tempC = analogRead(tempPin); //lettura valore del sensore
//tempC =tempC*500/1024; //conversione del dato analogico in
temperatura(tempc/1024.0)*5000
//lcd.print(" -templm35=");
//lcd.print(tempC);
//lcd.print("C");
//delay(500);
if(umiditaterra < 60)
{
digitalWrite(relepompaacqua,LOW);
}
else
{
digitalWrite(relepompaacqua,HIGH);
}
if(DHT11.humidity > 50)
{
digitalWrite(releventole,LOW);
}
else
{
digitalWrite(releventole,HIGH);
}
if(DHT11.temperature <15)
{
digitalWrite(relephon,LOW);
}
else
{
digitalWrite(relephon,HIGH);
}

if(DHT11.humidity <= 50)


{

motor.write(pos=4); // indirizza il perno alla posizione desiderata,


memorizzata in 'pos'

else{

motor.write(pos=90); // indirizza il perno alla posizione desiderata,


memorizzata in 'pos'

delay(2000);
}

te l'ho gia' detto, metti

motor.write(4) prima di
motor.attach(4)

e alla fine e' inutile scrivere


motor.write(pos=4) o motor.write(pos=90)

scrivi semplicemente
motor.write(4) e motor.write(90)
"C' chi legge Guerra & Pace e non ci capisce un tubo vuoto; c' chi legge l'etichetta delle patatine fritte e ci trova la
spiegazione del mondo"

Newbie
Posts: 2
Karma: 0 [add]

Issues combining two codes that work independently for a simple thermostat

May 09, 2017, 10:44 pm


This is my first project with Arduino, and my first true attempt at some programming. My current project
is a thermostat consisting of an Arduino Uno, a servo motor, a DHT11 temperature and humidity sensor,
a 16x2 LCD Display with 4 Pin Adapter (I2C LCD1602), and a button. Currently, I have a code that
properly works to control the servo motor with the button (one click of the button turns the motor to
position 90/ON and another click turns the motor back to position 0/OFF), and I have a code that is
properly working to display the time and temperature on the LCD display; however, I am encountering
numerous errors when attempting to compile the two.

Ideally, I would also like to set an alarm for 10 PM for the program to check the position of the servo
motor and turn it to position 0 if it is at position 90. Currently, there is alarm set for 1:25:10 PM to print
"ALARM: TURN OFF HEAT" in the serial monitor.

This is also my first post on a forum such as this. I have read the rules and guidelines, but would
appreciate any further guidance for improvements or changes. Thank you!

Faulty Frankensteined Attempt at Com


//Credit to codebender_cc at instructables.com for the groundwork of the button
coding for the button control.
//http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/

#include <Servo.h>

Servo myservo; // create servo object to control a servo


// a maximum of eight servo objects can be created
// include the library code
#include <dht.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

dht DHT;
#define DHT11_PIN 5

#include <Time.h>
#include <TimeAlarms.h>

//Constants
const int buttonPin = 7;

//Variables
int buttonState = 0;
int flag = 0;
int pos = 0;

/**********************************************************/
//char array1[]="Temperature"; //the string to print on the LCD
//char array2[]="Humidity";
//int tim = 500; //the value of delay time
// initialize the library with the numbers of the interface pins
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2
line display
/*********************************************************/

void setup()
{
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(pos, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite (buttonPin, LOW);
}
{
lcd.init(); //initialize the lcd
lcd.backlight(); //open the backlight
}
{
Serial.begin(9600);
setTime(13,25,0,5,6,17); // set time to Saturday 1:25:00pm May 6 2017
// create the alarms
{
void EveningAlarm();
Serial.println("ALARM: TURN HEAT OFF");
}
Alarm.alarmRepeat(13,25,10,EveningAlarm); // 1:25:10pm every day
}
}

void loop()
//Read button state (pressed or not pressed?)
{
buttonState = digitalRead(buttonPin);

//If button pressed...


if (buttonState == HIGH) {
//...once, turn thermostat on!
if ( flag == 0){
myservo.write(90); // tell servo to go to position
flag=1; //change flag variable
}
//...twice, turn thermostat off!
else if ( flag == 1){
myservo.write(0); // tell servo to go to position
flag=0; //change flag variable again
}
}
delay(200); //Small delay
{
int chk = DHT.read11(DHT11_PIN);
lcd.setCursor(0,0);
lcd.print("Temp: ~ ");
lcd.print(DHT.temperature);
lcd.print((char)223);
lcd.print("C");

lcd.setCursor(0,1);
lcd.print("Time: ~ ");
digitalClockDisplay();
Alarm.delay(1000); // wait one second between clock display
}

void EveningAlarm()
{
Serial.println("ALARM: TURN HEAT OFF");
}

void digitalClockDisplay()
{
// digital clock display of the time
lcd.print(hour());
printDigits(minute());
printDigits(second());
lcd.println();
}

void printDigits(int digits)


{
lcd.print(":");
if(digits < 10)
lcd.print('0');
lcd.print(digits);
}
}

I realize there are likely several beginner errors and sloppy syntax. Any constructive criticism and
guidance is apppreciated.

Errors

CumulativeAttempt2.ino: In function 'void setup()':


CumulativeAttempt2:56: error: 'EveningAlarm' was not declared in this scope
CumulativeAttempt2.ino: In function 'void loop()':
CumulativeAttempt2:89: error: 'digitalClockDisplay' was not declared in this scope
CumulativeAttempt2:94: error: a function-definition is not allowed here before '{'
token
CumulativeAttempt2:99: error: a function-definition is not allowed here before '{'
token
CumulativeAttempt2:108: error: a function-definition is not allowed here before '{'
token
'EveningAlarm' was not declared in this scope

//Credit to codebender_cc at instructables.com for the groundwork of the button


coding for the button control.
//http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/

#include <Servo.h>

Servo myservo; // create servo object to control a servo


// a maximum of eight servo objects can be created

//Constants
const int buttonPin = 7;

//Variables
int buttonState = 0;
int flag = 0;
int pos = 0;
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(pos, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite (buttonPin, LOW);
}

void loop(){
//Read button state (pressed or not pressed?)
buttonState = digitalRead(buttonPin);

//If button pressed...


if (buttonState == HIGH) {
//...once, turn thermostat on!
if ( flag == 0){
myservo.write(90); // tell servo to go to position
flag=1; //change flag variable
}
//...twice, turn thermostat off!
else if ( flag == 1){
myservo.write(0); // tell servo to go to position
flag=0; //change flag variable again
}
}
delay(200); //Small delay

--------

Code for LCD

// include the library code


#include <dht.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

dht DHT;
#define DHT11_PIN 5

#include <Time.h>
#include <TimeAlarms.h>

/**********************************************************/
//char array1[]="Temperature"; //the string to print on the LCD
//char array2[]="Humidity";
//int tim = 500; //the value of delay time
// initialize the library with the numbers of the interface pins
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2
line display
/*********************************************************/
void setup()
{
//Serial.begin(9600);
lcd.init(); //initialize the lcd
lcd.backlight(); //open the backlight

/************************TIMER*********************************/
Serial.begin(9600);
setTime(13,25,0,5,9,17); // set time to Saturday 1:25:00pm May 9 2017
// create the alarms
Alarm.alarmRepeat(13,25,10,EveningAlarm); // 1:25:10pm every day
}
/*********************************************************/
void loop()
{
int chk = DHT.read11(DHT11_PIN);
lcd.setCursor(0,0);
lcd.print("Temp: ~ ");
lcd.print(DHT.temperature);
lcd.print((char)223);
lcd.print("C");

lcd.setCursor(0,1);
lcd.print("Time: ~ ");
digitalClockDisplay();
Alarm.delay(1000); // wait one second between clock display
}

void EveningAlarm(){
Serial.println("ALARM: TURN HEAT OFF");

void digitalClockDisplay()
{
// digital clock display of the time
lcd.print(hour());
printDigits(minute());
printDigits(second());
lcd.println();
}

void printDigits(int digits)


{
lcd.print(":");
if(digits < 10)
lcd.print('0');
lcd.print(digits);
}

Hi,
Combining sketches can be difficult. There are some suggestions about how to approach this On THIS
Page

Regards, Terry King terry@yourduino.com - Check great prices, devices and Arduino-related boards at
http://YourDuino.com
HOW-TO: http://ArduinoInfo.Info

Newbie
Posts: 4
Karma: 0 [add]

Arduino Incubator

Sep 03, 2016, 08:36 am Last Edit: Sep 03, 2016, 08:41 am by Shoive
I am trying to make an Arduino Incubator... I am novice to Arduino and have little knowledge about
programing.

Although I have already made a blueprint of this project .


I have a lm35, a fan and a light is connected with the arduino and I have satisfactorily become able to run
it properly with coding...

But the problem arises when I try to control humidity and also the egg turner.

For humidity control I need to control a DC motor in both direction..

Egg turning has become most problematic as It needs timing. I need to move the egg turner motor after
each four hours. But my little knowledge is not allowing me to accomplish the task.

I hope the sophisticated members of this forum will help me with coding to bring my dream true..

Thanks in Advance.

PaulRB

Faraday Member
Posts: 5,870
Karma: 546 [add]

Re: Arduino Incubator

#1

Sep 03, 2016, 10:43 am Last Edit: Sep 03, 2016, 10:46 am by PaulRB
Quote from: Shoive on Sep 03, 2016, 08:36 am

I hope the sophisticated members of this forum will help me with coding

Not without a good deal more information from yourself!

We need links to all the components you are using, and this "blueprint" you made, pictures of what you
have so far and any code you have working so far.

Read the forum rules before you post them so you know how to post links, pictures and code properly.

And don't assume that experts will always know more than yourself and know what you are talking about.
I know a little about hatching hen's eggs, assuming that's what you are trying to hatch. But incubators can
also be for plants, baby mammals etc.

Paul

Shoive


Newbie
Posts: 4
Karma: 0 [add]

Re: Arduino Incubator

#2

Sep 04, 2016, 07:44 am Last Edit: Sep 04, 2016, 07:49 am by Shoive
Ok.. This Incubator is intended to hatch eggs.

I have Used LM35 sensor for temperature and DHT11 to observe humidity.

My purpose is to keep temperature in 102 degree Fahrenheit. For heater I will use a 100 watt bulb and for
cooling (it temperature exceeds) a AC Fan. Obviously these will be attached with relay module.

For bringing water in and out of the incubator to control humidity I need to drive a DC motor in both
directions.

And for turning the tray for each four hours I need to control a time controlled AC motor.

That's the main idea.


PaulRB

Faraday Member
Posts: 5,870
Karma: 546 [add]

Re: Arduino Incubator

#3

Sep 04, 2016, 10:45 am Last Edit: Sep 04, 2016, 11:15 am by PaulRB
I don't see why you need the lm35 when the dht11 will also give you temperature.

Without an internal fan to keep the temperature even, the 100W bulb will cook the nearest eggs and the
farther ones will not develop.

If the motor for the egg tray is time controlled, why do you need the Arduino to control it?

For the water pump, you could use two more relays. The COM connectors to the motor terminals, the NO
connectors to +V and the NC connectors to -V.

As you won't give the other information I asked for, and won't explain why you can't, that's all the help I
can give you.
Chagrin

Faraday Member
Posts: 3,542
Karma: 546 [add]

Re: Arduino Incubator

#4

Sep 06, 2016, 07:03 pm Last Edit: Sep 06, 2016, 07:05 pm by Chagrin
For the tray an RC servo would be much simpler. I assume you're describing this style of egg turner (not
the type that spins in a circle). Servos are designed to flop back and forth and have a lot of torque in doing
that, and of course with an servo all you need is the servo itself -- no additional motor driver needed.

With respect to the humidity control you'd have to tell us what you're doing to increase humidity. Is it a
sprayer or a water pad or ... ?

Also, you want to use *two* lightbulbs in parallel because if one burns out you're kinda hosed.

Shoive


Newbie
Posts: 4
Karma: 0 [add]

Re: Arduino Incubator

#5

Sep 06, 2016, 09:39 pm


Quote from: PaulRB on Sep 04, 2016, 10:45 am

I don't see why you need the lm35 when the dht11 will also give you temperature.

Actually DHT11 sensor is very cheap and does not give accurate reading so I decided to use LM35 for
temperature measurement.. As you can understand more than one degree deviation from actual
temperature can bring disaster but for humidity this is not big problem as desired humidity range is high.
So for getting thing cheap and accurate I have decided to use two sensors.

Now the question about Egg Turner. I have said that the motor will be used for turning tray should be
controlled through the Arduino and it's my great shortcoming.
I seek your help asking you a code that turns a MOTOR after each four hours.

My headache is how to make the Arduino run on the basis of a schedule. The schedule will order the
Arduino to do a certain thing after a definite period that I want.

Is it possible?

I want to co-operate you. Plz if You have further inquiry I will reply. Don't get bothered plz.

Here is code only for controlling the temperature....


Newbie
Posts: 4
Karma: 0 [add]

Re: Arduino Incubator

#6

Sep 06, 2016, 10:12 pm

Quote from: Chagrin on Sep 06, 2016, 07:03 pm

For the tray an RC servo would be much simpler. I assume you're describing this style of egg turner (not the type that spins in a
circle). Servos are designed to flop back and forth and have a lot of torque in doing that, and of course with an servo all you need
is the servo itself -- no additional motor driver needed.

With respect to the humidity control you'd have to tell us what you're doing to increase humidity. Is it a sprayer or a water pad or
... ?

Also, you want to use *two* lightbulbs in parallel because if one burns out you're kinda hosed.
Thanks for your helping hands.

For humidity I have thought to use a capped water container whose cap will be controlled with a servo
motor. When humidity will increase servo will bring the cap upon the container and humidity increment
will stop and at the same time a small dc motor pump will suck the water from inside to outside ...
whenever the humidity will go low then servo will open the cap and this same motor pump will suck
water from outside to inside.

Mostly I need help in egg turning.


These are the models that I wish to operate with a Motor.

https://www.youtube.com/results?search_query=Homemade+automatic+egg+turner+for+incubator

https://www.youtube.com/watch?v=ATvFdeIELc8

https://www.youtube.com/watch?v=B0uYGau-UcY

Thanks in advance...

Chagrin

Faraday Member
Posts: 3,542
Karma: 546 [add]

Re: Arduino Incubator

#7
Sep 07, 2016, 12:15 am
I can pretty much guarantee you will never have a situation where the humidity in your incubator is too
high. The net effect of heating air also lowers the (relative) humidity of that air and your incubator will be
much dryer than your ambient climate -- and if you're running this incubator indoors while the home's air
conditioning or furnace is active then you'll be seeing much dryer air to begin with. And of course the
incubator needs some ventilation so it's a problem you're constantly fighting.

I'd suggest looking at using an ultrasonic atomizer that would be set in a bowl of water. Granted it's up to
you to figure out how to keep the bowl full with the right amount of water...

Back to the "servo" thing, take a look at https://www.youtube.com/watch?v=QhkzTi8P84c. Right at the


start of the video you can see the black servo on the side that is connected to an arm that tilts the egg tray.
You can't get much simpler than that.

Lastly you should probably take a look at the PID libraryto control the humidity and temperature. While
you're probably thinking along the lines of "when the temperature is too low, turn on the light bulbs" what
will happen if you do that is you will get some weird temperature or humidity swings or the light will
flicker constantly or other things you haven't considered. PID control will manage the temperature and
humidity in a more predictive manner, and the PID library (once you understand it) makes everything
pretty foolproof.

PaulRB

Faraday Member
Posts: 5,870
Karma: 546 [add]
Re: Arduino Incubator

#8

Sep 07, 2016, 01:54 am


I can recommend sht21 sensors. These are pretty accurate for temp and humidity, and not too expensive
on eBay these days. They have an i2c interface so can share the same two Arduino pins as an LCD screen
to display current status and an RTC for reliable time measurement. The Arduino can probably measure
the time accurately enough for the 4 hour egg turning and the overall 21 day hatching, but of there is a
power failure, the Arduino will lose track of time whereas the RTC has battery back-up.

Fuzzoffury

Newbie
Posts: 1
Karma: 0 [add]

Re: Arduino Incubator

#9

Sep 17, 2016, 12:35 pm


When coding is not
Delay (1000). = One second delay ?
So therefore
Delay (14,400,000). = Four hours delay ?

Sorry if my math is out at this time of night.

Wawa

Tesla Member
Posts: 7,695
Karma: 848 [add]

Re: Arduino Incubator

#10

Sep 17, 2016, 01:17 pm

Quote from: Fuzzoffury on Sep 17, 2016, 12:35 pm

Delay (14,400,000). = Four hours delay ?

Can't do that.
Delay is blocking code.
The Arduino will do nothing while the delay is running.
If the heating is on or off, it will stay that way untill the delay has finished.
Delays are better done with millis().
Look at the BlinkWithoutDelay example in the IDE.
Leo..

PRINT

Go Up

Pages: [1]

#include <DS1307RTC.h>
#include <Time.h>
#include <dht11.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define DHT11PIN 9
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C
address
dht11 DHT11;
int relepompaacqua=7;
int releventole=5;
int relephon=6;
int releluce=8;
Servo motor;
void setup()
{
pinMode(releluce ,OUTPUT);
digitalWrite(releluce, HIGH);
pinMode(relepompaacqua ,OUTPUT);
digitalWrite(relepompaacqua, HIGH);
digitalWrite(releventole, HIGH);
pinMode(releventole ,OUTPUT);
digitalWrite(relephon, HIGH);
pinMode(relephon ,OUTPUT);

setSyncProvider(RTC.get); // the function to get the time from the RTC

motor.attach(4);
lcd.begin(20,4); // initialize the lcd for 20 chars 4 lines, turn on
backlight
lcd.backlight();
Serial.begin(9600);
}

void loop(){

int dht= DHT11.read(DHT11PIN);

lcd.setCursor(0,0);

lcd.print("-tempdht11= ");
lcd.print((float)DHT11.temperature,0);
lcd.print("C");

lcd.setCursor(0,1);
lcd.print("-umidita'= ");
lcd.print((float)DHT11.humidity,0);
lcd.print("%");
int sensorvalue;
int umiditaterra;
sensorvalue=analogRead(2);
umiditaterra =map(sensorvalue,486,842,100,0);
lcd.setCursor(0,2);
lcd.print("-hterr=");
lcd.print(umiditaterra);
lcd.print("-");
lcd.print(sensorvalue);

//mantiene umidit terreno a 60


if(umiditaterra < 60){
digitalWrite(relepompaacqua,LOW);
} else {
digitalWrite(relepompaacqua,HIGH);
}
//mantiene temperatura minima a 19 gradi
if(DHT11.temperature<16) {
digitalWrite(relephon,LOW);
} else {
if (DHT11.temperature >= 19){
digitalWrite(relephon,HIGH);
}
}

//umidit e/o temperatura al di sopra dei livelli, necessita accensione ventola


if((DHT11.humidity >68 && DHT11.temperature <= 24) ||
(DHT11.humidity > 68 && DHT11.temperature >= 24) ||
(DHT11.humidity <= 68 && DHT11.temperature >= 24) ||
(minute()>=10 && minute()<= 15)||
(minute()>=40 && minute()<= 45)
)
{
digitalWrite(releventole,LOW);
motor.write(-90);
}
else{
//umidit e temperatura enntrambe sotto la soglia, non necessita accensione ventola
if (DHT11.humidity < 60 && DHT11.temperature < 23)
{
motor.write(90);
digitalWrite(releventole,HIGH);
}
}
if((hour()>=19) ||( hour()<12))
{
digitalWrite(releluce,LOW);
}
else
{
digitalWrite(releluce,HIGH);
}

lcd.setCursor(0,3);
if(hour()<10) lcd.print('0');
lcd.print(hour());
lcd.print(":");
if(minute()<10) lcd.print('0');
lcd.print(minute());
// Serial.print(":");
// if(second()<10) Serial.print('0');
// Serial.print(second());
lcd.print(" ");
if(day()<10) lcd.print('0');
lcd.print(day());
lcd.print("/");
if(month()<10) lcd.print('0');
lcd.print(month());
lcd.print("/");
lcd.print(year());

delay(2000);
}

Re: Project Guidance for a website controlled Arduino greenhouse

#15

Jun 01, 2013, 02:06 am


Got my code and hardware running. Thanks for the help. Eventually I used the DHT11 library.
#include <DHT11.h>
#include <Wire.h>
#include <LiquidCrystal.h> // include the library code:

int dHTPin = A4;


DHT11 dht11(dHTPin);
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// named constant for the pin the sensor is connected to

const int waterPin = 2; // Pin for relay to solenoid valve


const int fanPin = 4; // Pin for relay to Fan / Ventialation
const int potTempPin =A2; // Pin for potmeter max Temp
const int potHumPin =A3; // Pin for potmeter min soilHum
const int soilLEDPin = 7; // choose the pin for the LED (turns on when the soil
is dry
const int soilSensorPin = A5; // Pin for soil humidity Sensor
int potTempVal; // value from potentiometer for temp (turn knob Max
temp)
int potHumVal; // value from potentiometer for soil Humidity (turn
knob min hum)
int minSoilHum = 0; // Minimal soil humidity level before turning
"watering" on.
int maxTempSet; // Max temperature setting
int minHumSet; // Min Soil humitdity setting
int pirState = LOW; // we start, assuming no motion detected
// variable for reading the pin status
int SoilSensorValue; // variable Soil Sensor
int var1; // variable while loop
int var2; // variable while loop

void setup(){

// set up the LCD's number of columns and rows:


lcd.begin(16, 2);
// Print a message to the LCD to see the power is connected.
lcd.print("Power is on");

// fan pinmode set begins low


pinMode(fanPin, OUTPUT);
digitalWrite(fanPin, LOW);

// irrigation pinmode set begins low


pinMode(waterPin, OUTPUT);
digitalWrite(waterPin, LOW);

//soil level pinmode set begins low


pinMode(soilLEDPin, OUTPUT); // declare LED as output
pinMode(soilSensorPin, INPUT); // declare soil humidity sensor as input

delay (3000);
lcd.clear();

void loop(){

// ten seconds to adjust Max temperature

var1 = 0;
while(var1< 50){// loops for ten seconds
potTempVal = analogRead(potTempPin); // read the value of the potentiometer
maxTempSet = map(potTempVal, 0, 1023, 0, 45); // formule voor maken 0 tot 45 graden
lcd.clear();
lcd.print("Set max temp now:");
lcd.setCursor(0,1);
lcd.print(maxTempSet, DEC);
lcd.print(" celcius");
delay (100);
var1++;
}
lcd.clear();
delay(500);

// ten seconds to adjust Min soil Humidity

var2 = 0;
while(var2 < 50){ // loops for ten seconds
potHumVal = analogRead(potHumPin); // read the value of the potentiometer
minHumSet = map(potHumVal, 0, 1023, 0, 100); // formule voor maken 0 tot 100 %
vochtigheid
lcd.clear();
lcd.print("Set min soil");
lcd.setCursor(0,1);
lcd.print("humidity:");
lcd.print(minHumSet, DEC);
lcd.print("%");
delay (100);
var2++;
}

// DHT PIN

int err;
float temp, humi;

if((err=dht11.read(humi, temp))==0)
{

// Turn on the display, and show the three sensor values in degrees or in percentage
than leave it on for three seconds

lcd.clear();
lcd.print("AirHum is:");
lcd.print(humi, DEC);
lcd.println("% ");

delay (2000);
lcd.clear();
delay (500);
lcd.print("Temp is: ");
lcd.print(temp, DEC);
lcd.println(" *C ");

delay (2000);
lcd.clear();
delay (500);

}
else
{
lcd.print("Error No :");
lcd.print(err);

}
delay(DHT11_RETRY_DELAY); //delay for reread

// Soil Hum Pin


int soilSensorValue = analogRead(soilSensorPin); // reads sensor soil hummidity pin
and makes value
int soilHumid = map(soilSensorValue, 0, 1023, 0, 100);
soilHumid = 100 - soilHumid;
lcd.print("SoilHum is: ");
lcd.print(soilHumid, DEC);
lcd.print(" % ");

delay (2000);
lcd.clear();

delay (500);

// controlling the WaterPump by reading the soil humidity

if (soilHumid < minSoilHum) { // check if the soil has low humidity

// vochtigheid laag
digitalWrite(soilLEDPin, HIGH); // turn LED ON
lcd.print("Soil too dry"); //
lcd.setCursor(0,1);
lcd.print("now watering"); //
digitalWrite(waterPin, HIGH); // turning solenoid valve open to start watering
delay (1000*60); // watering continuesly for 1 minute
lcd.clear();
}
else
{
// vochtigheid hoog
digitalWrite(soilLEDPin, LOW); // turn LED OFF
digitalWrite(waterPin, LOW); // turns or leaves solenoid water valve closed
}

// Controlling Fan / Window opening closing

if(temp > maxTempSet){


digitalWrite(fanPin, HIGH);
lcd.print("Max Temp reached");
lcd.setCursor(0,1);
lcd.print("ventilation on");
delay(2000);
lcd.clear();
}
else {
digitalWrite(fanPin, LOW);
}
delay(500);
}

Re: Project Guidance for a website controlled Arduino greenhouse

#16

Jun 01, 2013, 12:29 pm Last Edit: Jun 01, 2013, 12:33 pm by michiel1984 Reason: 1
There is something wrong with my if statement for the waterpump (See " // controlling the WaterPump
by reading the soil humidity" . It does not display: "now watering" it only changes the direction of the
servo but does not go back to initial value after a minute. Also I want my lcd screen to display the text
while watering. what am I doing wrong? (The code gave no errors compiling) Thanks in advance!
#include <DHT11.h>
#include <Wire.h>
#include <LiquidCrystal.h> // include the library code:
#include <Servo.h>
Servo waterServo;
int dHTPin = A4;
DHT11 dht11(dHTPin);
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// named constant for the pin the sensor is connected to

const int waterPin = 9; // Pin for relay to solenoid valve


const int fanPin = 4; // Pin for relay to Fan / Ventialation
const int potTempPin =A2; // Pin for potmeter max Temp
const int potHumPin =A3; // Pin for potmeter min soilHum
const int soilLEDPin = 7; // choose the pin for the LED (turns on when the soil
is dry
const int soilSensorPin = A5; // Pin for soil humidity Sensor
int potTempVal; // value from potentiometer for temp (turn knob Max
temp)
int potHumVal; // value from potentiometer for soil Humidity (turn
knob min hum)
int minSoilHum = 0; // Minimal soil humidity level before turning
"watering" on.
int maxTempSet; // Max temperature setting
int minHumSet; // Min Soil humitdity setting
int SoilSensorValue; // variable Soil Sensor
int var1; // variable while loop
int var2; // variable while loop

void setup(){

// set up the LCD's number of columns and rows:


lcd.begin(16, 2);
// Print a message to the LCD to see the power is connected.
lcd.print("Power is on");

// fan pinmode set begins low


pinMode(fanPin, OUTPUT);
digitalWrite(fanPin, LOW);

// irrigation pinmode set begins low


pinMode(waterPin, OUTPUT);
digitalWrite(waterPin, LOW);

//soil level pinmode set begins low


pinMode(soilLEDPin, OUTPUT); // declare LED as output
pinMode(soilSensorPin, INPUT); // declare soil humidity sensor as input

waterServo.attach(9);
waterServo.write(0);

delay (3000);
lcd.clear();

void loop(){
// ten seconds to adjust Max temperature

var1 = 0;
while(var1< 50){// loops for ten seconds
potTempVal = analogRead(potTempPin); // read the value of the potentiometer
maxTempSet = map(potTempVal, 0, 1023, 0, 45); // formule voor maken 0 tot 45 graden
lcd.clear();
lcd.print("Set max temp now:");
lcd.setCursor(0,1);
lcd.print(maxTempSet, DEC);
lcd.print(" celcius");
delay (100);
var1++;
}
lcd.clear();
delay(500);

// ten seconds to adjust Min soil Humidity

var2 = 0;
while(var2 < 50){ // loops for ten seconds
potHumVal = analogRead(potHumPin); // read the value of the potentiometer
minHumSet = map(potHumVal, 0, 1023, 0, 100); // formule voor maken 0 tot 100 %
vochtigheid
lcd.clear();
lcd.print("Set min soil");
lcd.setCursor(0,1);
lcd.print("humidity:");
lcd.print(minHumSet, DEC);
lcd.print("%");
delay (100);
var2++;
}

// DHT PIN

int err;
float temp, humi;

if((err=dht11.read(humi, temp))==0)
{
// Turn on the display, and show the three sensor values in degrees or in percentage
than leave it on for three seconds

lcd.clear();
lcd.print("AirHum is:");
lcd.print(humi, DEC);
lcd.println("% ");

delay (2000);
lcd.clear();
delay (500);

lcd.print("Temp is: ");


lcd.print(temp, DEC);
lcd.println(" *C ");

delay (2000);
lcd.clear();
delay (500);

}
else
{
lcd.print("Error No :");
lcd.print(err);

}
delay(DHT11_RETRY_DELAY); //delay for reread

// Soil Hum Pin


int soilSensorValue = analogRead(soilSensorPin); // reads sensor soil hummidity pin
and makes value
int soilHumid = map(soilSensorValue, 0, 1023, 0, 100);
soilHumid = 100 - soilHumid;
lcd.print("SoilHum is: ");
lcd.print(soilHumid, DEC);
lcd.print(" % ");

delay (2000);
lcd.clear();

delay (500);

// controlling the WaterPump by reading the soil humidity


if (soilHumid < minSoilHum) { // check if the soil has low humidity

// low soil humidity


digitalWrite(soilLEDPin, HIGH); // turn LED ON
waterServo.write(1023);
lcd.print("Soil too dry"); //
lcd.setCursor(0,1);
lcd.print("now watering"); //
// turning solenoid valve open to start watering
delay (1000*60); // watering continuesly for 1 minute
lcd.clear();
waterServo.write(0);
}
else
{
// vochtigheid hoog
digitalWrite(soilLEDPin, LOW); // turn LED OFF
waterServo.write(0); // turns or leaves solenoid water valve closed
}

// Controlling Fan / Window opening closing

if(temp > maxTempSet){


digitalWrite(fanPin, HIGH);
lcd.print("Max Temp reached");
lcd.setCursor(0,1);
lcd.print("ventilation on");
delay(2000);
lcd.clear();
}
else {
digitalWrite(fanPin, LOW);
}
delay(500);
}

Re: Project Guidance for a website controlled Arduino greenhouse

#17

Jun 01, 2013, 01:31 pm


This is a possible problem:

Code: [Select]
delay (1000*60); // watering continuesly for 1 minute

Those constants are treated by the compiler as 16 bit signed integers. The result of the calculation will
overflow. Try this instead:

Code: [Select]

delay (1000UL*60UL); // watering continuesly for 1 minute

Generally, servo.Write takes a value in degrees. 1023 seems unusually high.


Re: Project Guidance for a website controlled Arduino greenhouse

#11

May 31, 2013, 10:39 pm


Okee, I have been programming something really simple with an lcd screen just to get started with the
basics, becuase I have some problems with obaining the touch screen. This is a basic sketch without the
server and all, just functioning on an arduino uno and with an lcd screen to adjust minhum and max temp
level before watering / ventilating.

Sketch is below.

Problem: I cant get the DHT 11 working when I compile it gives an error. Can someone help? thanks

Code: [Select]

#include <Wire.h>
#include <LiquidCrystal.h> // include the library code:
#define dht_dpin A1 //pin for DHT11
#define DHTTYPE DHT11

byte dht_dat[4]; //Array to hold the bytes sent from sensor.


// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// named constant for the pin the sensor is connected to


const int waterPin = 2; // Pin for relay to solenoid valve
const int fanPin = 4; // Pin for relay to Fan / Ventialation
const int potTempPin =A2; // Pin for potmeter max Temp
const int potHumPin =A3; // Pin for potmeter min soilHum
const int soilLEDPin = 7; // choose the pin for the LED (turns on when the soil
is dry
const int soilSensorPin = A5; // Pin for soil humidity Sensor
int potTempVal; // value from potentiometer for temp (turn knob Max
temp)
int potHumVal; // value from potentiometer for soil Humidity (turn
knob min hum)
int maxTemp = 40; // Maximal temperature is 40 degrees (" ")
int minSoilHum = 0; // Minimal soil humidity level before turning
"watering" on.
int maxTempSet; // Max temperature setting
int minHumSet; // Min Soil humitdity setting
int pirState = LOW; // we start, assuming no motion detected
// variable for reading the pin status
int SoilSensorValue; // variable Soil Sensor
int var1; // variable while loop
int var2; // variable while loop

void setup(){

// set up the LCD's number of columns and rows:


lcd.begin(16, 2);
// Print a message to the LCD to see the power is connected.
lcd.print("Power is on");

// fan pinmode set begins low


pinMode(fanPin, OUTPUT);
digitalWrite(fanPin, LOW);

// irrigation pinmode set begins low


pinMode(waterPin, OUTPUT);
digitalWrite(waterPin, LOW);

//soil level pinmode set begins low


pinMode(soilLEDPin, OUTPUT); // declare LED as output
pinMode(soilSensorPin, INPUT); // declare soil humidity sensor as input

// potmeters adjustment and modification


maxTempSet = map(potTempVal, 0, 1023, 0, 45); // formule voor maken 0 tot 45 graden
minHumSet = map(potHumVal, 0, 1023, 0, 100); // formule voor maken 0 tot 100 %
vochtigheid

InitDHT(); //Initializing for reading DHT


delay (3000);
lcd.clear();

void loop(){

lcd.print("Set max Temp");


delay(3000);

// ten seconds to adjust Max temperature

var1 = 0;
while(var1< 100){// loops for ten seconds
potTempVal = analogRead(potTempPin); // read the value of the potentiometer
lcd.clear();
lcd.print("Max Temp:");
lcd.print(maxTempSet, DEC);
delay (100);
var1++;
}

lcd.print("Set min Hum");


delay(3000);

// ten seconds to adjust Min soil Humidity

var2 = 0;
while(var2 < 100){ // loops for ten seconds
potHumVal = analogRead(potHumPin); // read the value of the potentiometer
lcd.clear();
lcd.print("Min Hum:");
lcd.print(minHumSet, DEC);
delay (100);
var2++;
}

// DHT PIN
ReadDHT(); //Read from DHT chip
temp = dht_dat[0]; // giving variable a name
airHum = dht_dat[2]; // giving variable a name

// Soil Hum Pin


soilSensorValue = analogRead(analogPin); // reads sensor soil hummidity pin and
makes value

// Turn on the display, and show the three sensor values in degrees or in percentage
than leave it on for three seconds

lcd.display();

lcd.print("AirHum is:");
lcd.print(airHum, DEC);
lcd.println("% ");

delay (3000);
lcd.clear();
delay (500);

lcd.print("Temp is: ");


lcd.print(temp, DEC);
lcd.println(" *C ");

delay (3000);
lcd.clear();
delay (500);

lcd.print("SoilHum is: ");


lcd.print(soilSensorValue, DEC);
lcd.println(" % ");

delay (3000);
lcd.clear();

delay (500);

// controlling the WaterPump by reading the soil humidity

if (soilSensorValue < minSoilHum) { // check if the soil has low


humidity

// vochtigheid laag
digitalWrite(ledPin, HIGH); // turn LED ON
lcd.print("Soil dry"); //
lcd.println ("Now Watering");
digitalWrite(waterPin, High); // turning solenoid valve open to start watering
delay (1000*60); // watering continuesly for 1 minute
lcd.clear();
}
else
{
// vochtigheid hoog
digitalWrite(ledPin, LOW); // turn LED OFF
digitalWrite(waterPin, LOW); // turns or leaves solenoid water valve closed
}

// Controlling Fan / Window opening closing

if(temp > maxTemp){


digitalWrite(fanPin, HIGH);
lcd.print("Max Temp!");
lcd.println("Fan is on");
delay(3000);
lcd.clear();
}
else {
digitalWrite(fanPin, LOW);
}

Text only | Text with Images

Arduino Forum
Using Arduino => Project Guidance => Topic started by: ChrisPSR on
Oct 05, 2014, 11:09 am

Title: 2 dht11's into 1 microcontroller


Post by: ChrisPSR on Oct 05, 2014, 11:09 am

I am struggling to find the route code for reading two DHT11 temperature sensors
in to 1 microcontroller board so as to provide for the user the temperature
underground of a 'Heat Pump' and the temperature of the area to be heated in this
case a 'Green House'.

I have tried to modify Adafruits program that uses a number of #Includes but
most importantly DHT.h, and all as the following code. Although the code is
suggested as altered the code provided herewith is the bare bones Adafruit working
code:
// atempt to produce a sketch for DHT humidity/temperature sensors
// & LCD temp & humidity readouts
// Originally aurhored by Adafruit Industries.
#include "DHT.h"
#include <LiquidCrystal.h>
#include <Wire.h> // Wire header file for I2C and 2 wire
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT11 //#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
// Connect pin 1 (on the left) of the sensor to +5V. Connect pin 2 of the sensor to
whatever your DHTPIN is. Connect pin 4 (on the right) of the sensor to GROUND.
Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
// SerialDegC += char(176); // Setup a Degrees C Serial symbol
// SerialDegC += "C ";

dht.begin();
}

void loop() {
dht.readHumidity() = digital.read(DHTPIN 2);
// 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();
float t = dht.readTemperature();

// check if returns are valid, if they are NaN (not a number) then something went
wrong!
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT");
} else {
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
// Serial.println(SerialDegC);
// Serial.println(" *C");
}
}

The above code is supported by way of the #include DHT.h all as follows:

#ifndef DHT_H
#define DHT_H
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

/* DHT library

MIT license
written by Adafruit Industries
*/

// how many timing transitions we need to keep track of. 2 * number bits + extra
#define MAXTIMINGS 85

#define DHT11 11
#define DHT22 22
#define DHT21 21
#define AM2301 21

class DHT {
private:
uint8_t data[6];
uint8_t _pin, _type, _count;
boolean read(void);
unsigned long _lastreadtime;
boolean firstreading;

public:
DHT(uint8_t pin, uint8_t type, uint8_t count=6);
void begin(void);
float readTemperature(bool S=false);
float convertCtoF(float);
float readHumidity(void);
};
#endif

Any help or lead would be greatly appreciated.


Cheers,
Chris S.

Title: Re: 2 dht11's into 1 microcontroller


Post by: JimboZA on Oct 05, 2014, 11:14 am
Going by the way one adds servos say, I'd guess that you dupe this line:

Code: [Select]
DHT dht(DHTPIN, DHTTYPE);

and have

Code: [Select]

#define DHTPIN2 3 // added later, see rogerClark's reply#2

DHT dht1(DHTPIN, DHTTYPE);


DHT dht2(DHTPIN2, DHTTYPE); //changed to DHTPIN2, see rogerClark's reply#2

Then have

Code: [Select]
dht1.begin();
dht2.begin();

.... and later on:

Code: [Select]
float h2 = dht2.readHumidity();

Total flier, though.

Title: Re: 2 dht11's into 1 microcontroller


Post by: rogerClark on Oct 05, 2014, 11:16 am
@JimboZA,

I think you mean


Code: [Select]

#define DHTPIN2 3

DHT dht1(DHTPIN, DHTTYPE);


DHT dht2(DHTPIN2, DHTTYPE);

Title: Re: 2 dht11's into 1 microcontroller


Post by: JimboZA on Oct 05, 2014, 11:18 am

Quote from: rogerClark on Oct 05, 2014, 11:16 am

@JimboZA,
I think you mean....

Probably 8)

That makes sense yes......

Title: Re: 2 dht11's into 1 microcontroller


Post by: ChrisPSR on Oct 05, 2014, 12:32 pm

Hi,

Many thanks for your help, I have rewritten it all as follows with some starting
#includes not so far in use. One thing I can not find in any example of this sensor is
the retrieval of the insignificants or fractions but reading the somewhat scant
descriptions by the manufacturers they show I think that this information is
available. Would you guys know how to achieve their discovery? Cheers, Chris:

// atempt to produce a sketch for DHT humidity/temperature sensors


// & LCD temp & humidity Green House readouts
// Author H C Spreckley.

#include "DHT.h"
#include <LiquidCrystal.h>
#include <Wire.h>
#define DHTPIN1 2
#define DHTPIN2 3
#define DHTTYPE DHT11
DHT dht1(DHTPIN1, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);

void setup() {
Serial.begin(9600);
dht1.begin();
dht2.begin(); // This is one of the prime parts I failed to write in my first
"dream".
}

void loop() {
float h1 = dht1.readHumidity();
float t1 = dht1.readTemperature(); // Ditto the above
float h2 = dht2.readHumidity();
float t2 = dht2.readTemperature();

if (isnan(t1) || isnan(h1)) {
Serial.println("Failed to read from DHT");
}
else {
Serial.print("Temp ");
Serial.print(t1,0);
Serial.println(" degC");
}
}

Title: Re: 2 dht11's into 1 microcontroller


Post by: JimboZA on Oct 05, 2014, 12:37 pm

I can't advise- never used one.

You didn't actually say so, but assuming my stab in the dark worked Chris?

Title: Re: 2 dht11's into 1 microcontroller


Post by: ChrisPSR on Oct 05, 2014, 01:53 pm

Jimbo,

Yes I thought I had I even put a "Quote" into the heading but some how or other It
went missing. Yep It did work exactly as I h ad said it was not too far in front of my
own derisory coding though it didn't parse. So I am very grateful for your input,
thanks!

Do you know by any chance how to read the fractions of degrees t hat I am unable
to.

Cheers,
Chris.

Title: Re: 2 dht11's into 1 microcontroller


Post by: robtillaart on Oct 05, 2014, 02:21 pm

Quote

One thing I can not find in any example of this sensor is the retrieval of the insignificants or
fraction

The DHT11 has no fraction part, it only return whole numbers. It also does no
negative temperature.

If you want that you need to check the DHT22.

Title: Re: 2 dht11's into 1 microcontroller


Post by: ChrisPSR on Oct 05, 2014, 07:28 pm

Quote from: JimboZA on Oct 05, 2014, 12:37 pm

I can't advise- never used one.

You didn't actually say so, but assuming my stab in the dark worked Chris?

Jimbo,

Is it possible you could explain to me just how you new how to index the variables
in the way you did; the pin numbers were obvious but how to use them elsewhere,
was not. You see I guessed at something similar although as I said it wouldn't
parse and I didn't know just what I was doing. Due to them being in a long
statement as they were I din't know what each of the syllables was or was doing as
this form of programming is still hard fr me to follow. Simple statements I
understand but when they are compound my brain shrinks to an even smaller size
than it really is and drops out.

I would be very much obliged if you could spare me the a few minutes of your time
in explanation.
Cheers, and many thanks.
Chris S., Manchester, UK.

Title: Re: 2 dht11's into 1 microcontroller


Post by: ChrisPSR on Oct 05, 2014, 07:57 pm

Quote from: robtillaart on Oct 05, 2014, 02:21 pm

Quote

One thing I can not find in any example of this sensor is the retrieval of the insignificants or
fraction

The DHT11 has no fraction part, it only return whole numbers. It also does no negative
temperature.

If you want that you need to check the DHT22.

Dear Rob,

Many thanks for the help. I looked at your DHT11 program and ran it. It is very,
very good but all the ducking and diving that the program takes (I say with
admiration) and the amount of information it portrays are well beyond my brief
from the neighbour for whom I am building this package. I also like to build these
programs my self and even the disseminating useful information from your program
was just not on as I couldn't understand very much of it and I would hate to be
thought of as a parasite.

As a young man I could write fluently in MS., Basic and later used quite a lot of
ASP., but much time has passed and so I am now attempting to learn, C# and the
Arduino syntax differs.

So very many thanks for your advise; I will look into DHT22 as soon as I can.

Cheers and very many thanks,


Chris Spreckley

Title: Re: 2 dht11's into 1 microcontroller


Post by: JimboZA on Oct 05, 2014, 08:06 pm
Chris I kinda went off how the servo code works- standard example in the IDE. I
knew from having more than one servo in there, to double upon every thing that
set a servo up, obviously giving them unique names. Then when you want to use
each servo, you can them individually by their names.

I think the key is understanding that you need 2 of these.....

Code: [Select]
DHT dht1(DHTPIN1, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);

Each of these fashions a new instance of the DHT class, here named dht1 and dht2.
They could have course been named bill and ben, and Roger spotted that I hadn't
put the 2nd one on its own pin.

Once you have dht1 and dht2 setup like that, you merely treat them each the same
as the original dht you already had.

I can't say much more than that!

Title: Re: 2 dht11's into 1 microcontroller


Post by: ChrisPSR on Oct 05, 2014, 10:21 pm

Thanks for your help. I'm sure you can't explain it any more. I think its my
ignorance in not really understanding properly or fully just what a class is and
exactly how an *.h file works as when I write my own stuff I try not not produce a
class *,h file unless I really can't seem to do without it.

I'm not too sure of what I am about to say so I hope it's understandable, however:
The DHT.h file used here presumably carries the necessary code to extract the
Temperature and Humidity from the code issued by the DHT11 however I can't see
this in the DHT.h file. I have also come across a lot of dht/DHT11.h files by way of
Google that do not work with this program; now that I do not understand, as
presumably all users wish to extract the very same information from the DHT11. It
is this sort of coding with which I get very confused.

Anyway, cheers and thanks,


Chris

Title: Re: 2 dht11's into 1 microcontroller


Post by: rogerClark on Oct 06, 2014, 01:00 am

Quote
The DHT.h file used here presumably carries the necessary code to extract the Temperature
and Humidity from the code issued by the DHT11

Normally the header files (.h) don't contain the code. In basic terms they contain a
list of the feature available in the library, i.e the functions within the library as well
as any variables that are part of the library

However in some cases, people put the actual functions inside the .h file

Depending on which DHT library you are using, the .h may be this one

Code: [Select]
class DHT {
private:
uint8_t data[6];
uint8_t _pin, _type, _count;
unsigned long _lastreadtime;
boolean firstreading;
public:
DHT(uint8_t pin, uint8_t type, uint8_t count=6);
void begin(void);
float readTemperature(bool S=false);
float convertCtoF(float);
float convertFtoC(float);
float computeHeatIndex(float tempFahrenheit, float percentHumidity);
float readHumidity(void);
boolean read(void);
};

which lists the functions at the bottom. e.g. readTemperature

The cpp file contains all the actual programming code for the library

You don't need to know the internals of how this (or any) library works, you only
need to know what functions are in the library and how to use them
Title: Re: 2 dht11's into 1 microcontroller
Post by: ChrisPSR on Oct 06, 2014, 10:37 am
Quote from: rogerClark on Oct 06, 2014, 01:00 am

Quote

The DHT.h file used here presumably carries the necessary code to extract the Temperature
and Humidity from the code issued by the DHT11

Normally the header files (.h) don't contain the code. In basic terms they contain a list of
the feature available in the library, i.e the functions within the library as well as any
variables that are part of the library

However in some cases, people put the actual functions inside the .h file

Depending on which DHT library you are using, the .h may be this one

[font=Verdana]Roger many thanks; may I try to tell you what I think your lines of code
mean and may I dare to ask you whether you could comment on my misunderstandings:
[/font][/i][/size][/size]
( ?) = Don't know
what it means

Code: [Select]

class DHT {
private:
uint8_t data[6];
[i]8 bit integer array of 6 pockets[/i]
uint8_t _pin, _type, _count; [i]8
bit integer _t, (?) _type, (?) _count; (?)[/i]
unsigned long _lastreadtime; [i]
+or- variable number _lastreadtime (does underscore mean its a

pointer)[/i]
boolean firstreading;
[i]boolean variable of firstreading of sensor[/i]
public:
[i]public (?) Guess as the following: can be read in any
part of the document
rather like
'Global'[/i]
DHT(uint8_t pin, uint8_t type, uint8_t count=6); [i]Not sure of anything
here excepting the 8bit . Can guess of course as t o

what the pin is etc but what of the _t of which I


cannot even guess.[/i]
void begin(void);
[i] Obviously the actuating code starts here and does not provide a
value.[/i]
float readTemperature(bool S=false);
float convertCtoF(float);
float convertFtoC(float);
float computeHeatIndex(float tempFahrenheit, float percentHumidity);
float readHumidity(void);
boolean read(void);
};

which lists the functions at the bottom. e.g. readTemperature

The cpp file contains all the actual programming code for the library

You don't need to know the internals of how this (or any) library works, you only need to
know what functions are in the library and how to use them. OK but I would like to
understand as I think that this is the only true way you can write the content of the cpp or
ino file.

Hope that I am not asking too much. (?)

Text only | Text with Images


SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images


Arduino Forum
International => Italiano => Software => Topic started by:
giulioparisini on Apr 16, 2017, 10:03 pm

Title: Progetto Incrocio semaforico


Post by: giulioparisini on Apr 16, 2017, 10:03 pm

Salve, ho creato un progetto di un incrocio semaforico per la scuola. I semafori di


per se funzionano bene, ho voluto implementare anche un sistema di rilevamento di
luminosit che, appena rileva il buio, fa accendere 8 luci bianche e fa lampeggiare i
semafori sul giallo. Anche questo funziona alla grande. Infine volevo implementare
il suono di una sirena con luci rosse, blu e un buzzer cliccando un pulsante quando
"notte". Per appena premo il pulsante arduino se ne frega e continua il suo
codice...
Ecco lo sketch

Code: [Select]

#include <LCD.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <dht11.h>
#include <Servo.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);


dht11 DHT;
Servo mioservo;
int fotoresistenza = A2;
int fotovalore;
int pos = 0;
int luci=A0;
int servo=A3;
int buzzer=6;
int rosso=A4;
int blu=A5;
int buttonState;
int cont=1;
int buttonPin=7;
void polizia()
{
if(cont%2==0)
{
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,HIGH);
tone(6, 440, 1000);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,LOW);
digitalWrite(4,HIGH);

delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(4,LOW);
digitalWrite(2,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,LOW);
digitalWrite(4,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(4,LOW);
digitalWrite(2,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,LOW);
digitalWrite(4,HIGH);
delay(100);
tone(6, 494, 1000);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(4,LOW);
digitalWrite(2,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,LOW);
digitalWrite(4,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(4,LOW);
digitalWrite(2,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,LOW);
digitalWrite(2,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,LOW);
digitalWrite(4,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(4,LOW);
digitalWrite(2,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(2,LOW);
digitalWrite(4,HIGH);
delay(100);
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
}
digitalWrite(4,LOW);

}
}

void luce()
{
lcd.clear();
lcd.setCursor(4,0);
lcd.print("MODALITA'");
lcd.setCursor(5,1);
lcd.print("NOTTE!");

mioservo.write(0);
digitalWrite(13,LOW);
digitalWrite(8,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);
digitalWrite(12,HIGH);
digitalWrite(9,HIGH);
digitalWrite(luci,HIGH);
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
digitalWrite(12,LOW);
digitalWrite(9,LOW);
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
delay(100);
buttonState=analogRead(buttonPin);
if(buttonState==HIGH)
{
cont++;
delay(500);
polizia();
}
fotovalore = analogRead(fotoresistenza);
}

void setup() {
pinMode(luci, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,INPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
lcd.begin(16,2);
lcd.backlight();
mioservo.attach(servo);
digitalWrite(4, LOW);
}

Il void loop non l'ho messo perch troppo lungo, per il problema tra il void luce
e void polizia

Title: Re: Progetto Incrocio semaforico


Post by: uwefed on Apr 17, 2017, 12:03 am

Cosa fa il servo?
Dacci lo sketch completo.

Non puoi fare le temporizzazioni con delay() perch sono bloccanti.

La funzione luce controlla lo stato del buttonpin ma incrementa solo la variabile


cont. Per eseguire la funzione passano 2 secondi (senza sapere cosa fa la funzione
polizia) mentre se il pulsante premuto di continuo dura 12 secondi. La funzione
polizia un simile ammasso di delay().

Usa dei cicli for per fare le ripetizioni e impara a usare i millis() e la statemachine
per fare i ritardi e le differenti giochi di luce.

Ciao Uwe

Title: Re: Progetto Incrocio semaforico


Post by: giulioparisini on Apr 17, 2017, 12:10 am
Il servo non fa altro che alzare e abbassare con un'asta di legno un'insegna.
Non ho capito molto bene cosa hai detto e purtroppo non posso mettere il codice
perch supera i 9000 caratteri, ti lascio per in allegato il file .ino dello sketch

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Programming Questions => Topic started by:
walterkim on Dec 14, 2014, 01:17 pm

Title: incubator help


Post by: walterkim on Dec 14, 2014, 01:17 pm

Hello everyone,

Am building chicken egg incubator using arduino codes but I come up to stuck
somewhere for the weeks now, my issue is how to combine arduino sketches to
come up with one code.

I have three separate arduino sketches (codes) that I need to combine them
together to come up with one code. The three codes are:

1st Code : this contains codes for temperature sensor, fan, and LCD

2nd Code: this contains codes for counting that is seven segment display
3rd Code: this contains codes for DC motor

I will be glad if I get assistance on how I can combine them especially if i start
putting them together one by one. The codes might not be on its best but just
understand that am new in programming and am trying to learn so quickly. Please
find my three sketches.

Note: don't bother about the temperature values I put in my codes, those one are
just for testing

Please have a clue of what am doing in incubator project before you assist me. In
my project I have the following
1. Arduino Board
2. Temperature sensor(LM35)
3. FAN(for cooling incubator)
4. LCD(Liquid Crystal Display)
5. Seven segment display(Common Cathode)
6. DC Motor(for turning eggs)-this will rotate clockwise and anticlockwise
7. Shift registers (74HC595)
This is chicken egg incubator will hatch for 21 days, I want to control temperature
at 37.5 degree centigrade for the whole 21 days as well as humidity at 75% for 18
days, 90% for last 3 days of hatching.
Liquid crystal display for showing temperature and humidity that will be sensed by
temperature and humidity sensor
Eggs are suppose to be turned for the for 18 days and stop turning them for the
remaining 3 days, so here motor will help me to do this task. Motor will be turned
clockwise and anticlockwise for 3 times per day.
For the Seven segment display, I want it to display number of days from day 0 to
day 21. So this will increment by one after every 24hrs
Shift register: 74hc595 will help me to reduce number of output from arduino, this
is serial in parallel out (SIPO). For example two seven segment display needs 16
pins from arduino so with help of 74HC 595 I will take only three pins from arduino
to 74hc595. 74HC595 will give out 16 outputs to seven segment display

first code:

Code: [Select]

#include <ShiftLCD.h>
ShiftLCD lcd(2, 4, 3);
int tempPin = A0; // the output pin of LM35
int fan = 11; // the pin where fan is
int led = 8; // led pin
int temp;
int tempMin = 30; // the temperature to start the fan
int tempMax = 70; // the maximum temperature when fan is at 100%
int fanSpeed;
int fanLCD;

void setup() {

pinMode(fan, OUTPUT);
pinMode(led, OUTPUT);
pinMode(tempPin, INPUT);
lcd.begin(16, 2);

int readTemp() { // get the temperature and convert it to celsius


temp = analogRead(tempPin);
return temp * 0.48828125;
}

void loop() {
temp = readTemp(); // get the temperature

if(temp < tempMin){ // if temp is lower than minimum temp


fanSpeed = 0; // fan is not spinning
digitalWrite(fan, LOW);
}

if((temp >= tempMin) && (temp <= tempMax)) { // if temperature is higher


than minimum temp
fanSpeed = map(temp, tempMin, tempMax, 32, 255); // the actual speed
of fan
fanLCD = map(temp, tempMin, tempMax, 0, 100); // speed of fan to
display on LCD
analogWrite(fan, fanSpeed); // spin the fan at the fanSpeed speed
}

if(temp > tempMax) { // if temp is higher than tempMax


digitalWrite(led, HIGH); // turn on led
} else { // else turn of led
digitalWrite(led, LOW);
}

lcd.print("TEMP: ");
lcd.print(temp); // display the temperature
lcd.print("C ");
lcd.setCursor(0,1); // move cursor to next line
lcd.print("FANS: ");
lcd.print(fanLCD); // display the fan speed
lcd.print("%");
delay(50);
lcd.clear();
}

second code:

Code: [Select]

#define LATCH 12
#define CLK 13
#define DATA 11

//This is the dec value of each number stored in an array by index num

int i,j;
int digitOne[10]= {192,249,164,176,153,146,130,248,128,24};
int digitTwo[10]= {192,249,164,176,153,146,130,248,128,24};

unsigned long interval=500;

void setup(){
pinMode(LATCH, OUTPUT);
pinMode(CLK, OUTPUT);
pinMode(DATA, OUTPUT);
}

void loop(){
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
digitalWrite(LATCH, LOW);
shiftOut(DATA, CLK, MSBFIRST, ~digitTwo[j]); // digitTwo
shiftOut(DATA, CLK, MSBFIRST, ~digitOne[i]); // digitOne
digitalWrite(LATCH, HIGH);
unsigned long startTime = millis();
while (millis() - startTime < interval); //wait 1 minute
//i will change later from 1 minute to 24hrs
}
}
}

third code:

Code: [Select]

int PinOne = 9;
int PinTwo = 10;

int PinOneState = LOW;


int PinTwoState = LOW;

unsigned long previousTime1=0;


unsigned long previousTime2 = 0;

unsigned long intervalON = 6000;


unsigned long long intervalOFF = 2000;
unsigned long stopTurning=20000;

void setup() {
pinMode(PinOne, OUTPUT);
pinMode(PinTwo, OUTPUT);
digitalWrite(PinOne, PinOneState);
digitalWrite(PinTwo, PinTwoState);
}

void loop() {

unsigned long currentTime1=millis();

if (currentTime1 - previousTime1 < stopTurning){

unsigned long currentTime2 = millis();

if ((PinOneState == LOW) && (PinTwoState == LOW)){


if (currentTime2 - previousTime2 > intervalOFF){//and enough time has
passed
digitalWrite(PinOne, LOW);//CLOCKWISE
digitalWrite(PinTwo, HIGH);
PinOneState = LOW;//store its current state
PinTwoState = HIGH;
previousTime2 = currentTime2;//update the time of this new event
}
} else if((PinOneState == LOW) && (PinTwoState == HIGH)){
if (currentTime2 - previousTime2 > intervalON){
digitalWrite(PinOne,HIGH);//STOP
digitalWrite(PinTwo, HIGH);
PinOneState = HIGH;
PinTwoState = HIGH;
previousTime2 = currentTime2;
}
}

else if((PinOneState == HIGH) && (PinTwoState == HIGH)){


if (currentTime2 - previousTime2 > intervalOFF){
digitalWrite(PinOne,HIGH);//ANTCLOCKWISE
digitalWrite(PinTwo, LOW);
PinOneState = HIGH;
PinTwoState = LOW;
previousTime2 = currentTime2;
}
}

else if((PinOneState == HIGH) && (PinTwoState == LOW)){


if (currentTime2 - previousTime2 > intervalON){
digitalWrite(PinOne,LOW);//STOP
digitalWrite(PinTwo, LOW);
PinOneState = LOW;
PinTwoState = LOW;
previousTime2 = currentTime2;
}
}
} else{

digitalWrite(PinOne ,LOW);
digitalWrite(PinTwo ,LOW);
}
}

thanks
walter

Title: Re: incubator help


Post by: PaulS on Dec 14, 2014, 01:59 pm

Where is the 4th code, where you tried to put them together? What did that code
actually do? What was it supposed to do?

In other words, what are the requirements for the final sketch?

Obviously, you have some pin conflicts. The first thing you should do is modify the
individual sketches to resolve them.

Title: Re: incubator help


Post by: KenF on Dec 14, 2014, 02:09 pm

Quite some time ago I built an incubator for chicken eggs. Unfortunately I don't
have my final sketch available any more.

From what I recall though, your humidity settings look way too high. This could
lead to sticky chicks and probably reduce your hatch rate.

Title: Re: incubator help


Post by: walterkim on Dec 14, 2014, 03:38 pm

i started combining first code and the third code,which works very oky. Just to
remind you first code is the code for temperature sensor, fan, and LCD in which
they all responding oky as well as third code is the code for DC motor which is also
working very well.....so generall the combination of first code and third code has no
problem and there is no pin conflicts.

combination of first and third code:

Code: [Select]

#include <ShiftLCD.h>
ShiftLCD lcd(2, 4, 3);

int tempPin = A0; // the output pin of LM35


int fan = 7; // the pin where fan is
int led = 8; // led pin
int temp;
int tempMin = 30; // the temperature to start the fan
int tempMax = 70; // the maximum temperature when fan is at 100%
int fanSpeed;
int fanLCD;

int PinOne = 9;
int PinTwo = 10;

int PinOneState = LOW;


int PinTwoState = LOW;

unsigned long previousTime1=0;


unsigned long previousTime2 = 0;

unsigned long intervalON = 6000;


unsigned long long intervalOFF = 2000;
unsigned long stopTurning=20000;

void setup(){
setupFirstCode();
setupThirdCode();

}
int readTemp() { // get the temperature and convert it to celsius
temp = analogRead(tempPin);
return temp * 0.48828125;
}

void loop(){

loopFirstCode();
loopThirdCode();

void setupFirstCode() {

pinMode(fan, OUTPUT);
pinMode(led, OUTPUT);
pinMode(tempPin, INPUT);
lcd.begin(16, 2);

void loopFirstCode() {
temp = readTemp(); // get the temperature
if(temp < tempMin) { // if temp is lower than minimum temp
fanSpeed = 0; // fan is not spinning
digitalWrite(fan, LOW);
}
if((temp >= tempMin) && (temp <= tempMax)) { // if temperature is higher
than minimum temp
fanSpeed = map(temp, tempMin, tempMax, 32, 255); // the actual speed
of fan
fanLCD = map(temp, tempMin, tempMax, 0, 100); // speed of fan to
display on LCD
analogWrite(fan, fanSpeed); // spin the fan at the fanSpeed speed
}

if(temp > tempMax) { // if temp is higher than tempMax


digitalWrite(led, HIGH); // turn on led
} else { // else turn of led
digitalWrite(led, LOW);
}

lcd.print("TEMP: ");
lcd.print(temp); // display the temperature
lcd.print("C ");
lcd.setCursor(0,1); // move cursor to next line
lcd.print("FANS: ");
lcd.print(fanLCD); // display the fan speed
lcd.print("%");
delay(50);
lcd.clear();
}

void setupThirdCode() {
pinMode(PinOne, OUTPUT);
pinMode(PinTwo, OUTPUT);
digitalWrite(PinOne, PinOneState);
digitalWrite(PinTwo, PinTwoState);

void loopThirdCode() {

unsigned long currentTime1=millis();

if (currentTime1 - previousTime1 < stopTurning){

unsigned long currentTime2 = millis();

if ((PinOneState == LOW) && (PinTwoState == LOW)){


if (currentTime2 - previousTime2 > intervalOFF){//and enough time has
passed
digitalWrite(PinOne, LOW);//CLOCKWISE
digitalWrite(PinTwo, HIGH);
PinOneState = LOW;//store its current state
PinTwoState = HIGH;
previousTime2 = currentTime2;//update the time of this new event
}
} else if((PinOneState == LOW) && (PinTwoState == HIGH)){
if (currentTime2 - previousTime2 > intervalON){
digitalWrite(PinOne,HIGH);//STOP
digitalWrite(PinTwo, HIGH);
PinOneState = HIGH;
PinTwoState = HIGH;
previousTime2 = currentTime2;
}
}

else if((PinOneState == HIGH) && (PinTwoState == HIGH)){


if (currentTime2 - previousTime2 > intervalOFF){
digitalWrite(PinOne,HIGH);//ANTCLOCKWISE
digitalWrite(PinTwo, LOW);
PinOneState = HIGH;
PinTwoState = LOW;
previousTime2 = currentTime2;
}
}

else if((PinOneState == HIGH) && (PinTwoState == LOW)){


if (currentTime2 - previousTime2 > intervalON){
digitalWrite(PinOne,LOW);//STOP
digitalWrite(PinTwo, LOW);
PinOneState = LOW;
PinTwoState = LOW;
previousTime2 = currentTime2;
}
}
} else{

digitalWrite(PinOne ,LOW);
digitalWrite(PinTwo ,LOW);
}
}

the issue is to add the second code to come up with the whole program, i tried to
its i think the main problem is the "good coding"
however individually,second count exactly what i wanted.but one introducing other
programs it refuses....
just to remind:second code is the one with seven segment display which i want it to
count.

Title: Re: incubator help


Post by: walterkim on Dec 14, 2014, 03:39 pm

here is the combination of all three sketch which brings no response

Code: [Select]

#define LATCH 12
#define CLK 13
#define DATA 11
#include <ShiftLCD.h>
ShiftLCD lcd(2, 4, 3);

int tempPin = A0; // the output pin of LM35


int fan = 7; // the pin where fan is
int led = 8; // led pin
int temp;
int tempMin = 30; // the temperature to start the fan
int tempMax = 70; // the maximum temperature when fan is at 100%
int fanSpeed;
int fanLCD;

//This is the dec value of each number stored in an array by index num

int i,j;
int digitOne[10]= {192,249,164,176,153,146,130,248,128,24};
int digitTwo[10]= {192,249,164,176,153,146,130,248,128,24};
unsigned long interval=500;

int PinOne = 9;
int PinTwo = 10;

int PinOneState = LOW;


int PinTwoState = LOW;
unsigned long previousTime1=0;
unsigned long previousTime2 = 0;

unsigned long intervalON = 6000;


unsigned long long intervalOFF = 2000;
unsigned long stopTurning=20000;

void setup(){

setupFirstCode();
setupSecondCode();
setupThirdCode();
}

int readTemp() { // get the temperature and convert it to celsius


temp = analogRead(tempPin);
return temp * 0.48828125;
}

void loop(){

loopFirstCode();
loopSecondCode();
loopThirdCode();

void setupFirstCode() {

pinMode(fan, OUTPUT);
pinMode(led, OUTPUT);
pinMode(tempPin, INPUT);
lcd.begin(16, 2);

}
void loopFirstCode() {
temp = readTemp(); // get the temperature
if(temp < tempMin) { // if temp is lower than minimum temp
fanSpeed = 0; // fan is not spinning
digitalWrite(fan, LOW);
}
if((temp >= tempMin) && (temp <= tempMax)) { // if temperature is higher
than minimum temp
fanSpeed = map(temp, tempMin, tempMax, 32, 255); // the actual speed
of fan
fanLCD = map(temp, tempMin, tempMax, 0, 100); // speed of fan to
display on LCD
analogWrite(fan, fanSpeed); // spin the fan at the fanSpeed speed
}

if(temp > tempMax) { // if temp is higher than tempMax


digitalWrite(led, HIGH); // turn on led
} else { // else turn of led
digitalWrite(led, LOW);
}

lcd.print("TEMP: ");
lcd.print(temp); // display the temperature
lcd.print("C ");
lcd.setCursor(0,1); // move cursor to next line
lcd.print("FANS: ");
lcd.print(fanLCD); // display the fan speed
lcd.print("%");
delay(50);
lcd.clear();
}

void setupSecondCode() {
pinMode(PinOne, OUTPUT);
pinMode(PinTwo, OUTPUT);
digitalWrite(PinOne, PinOneState);
digitalWrite(PinTwo, PinTwoState);

void loopSecondCode() {
unsigned long currentTime1=millis();

if (currentTime1 - previousTime1 < stopTurning){

unsigned long currentTime2 = millis();

if ((PinOneState == LOW) && (PinTwoState == LOW)){


if (currentTime2 - previousTime2 > intervalOFF){//and enough time has
passed
digitalWrite(PinOne, LOW);//CLOCKWISE
digitalWrite(PinTwo, HIGH);
PinOneState = LOW;//store its current state
PinTwoState = HIGH;
previousTime2 = currentTime2;//update the time of this new event
}
} else if((PinOneState == LOW) && (PinTwoState == HIGH)){
if (currentTime2 - previousTime2 > intervalON){
digitalWrite(PinOne,HIGH);//STOP
digitalWrite(PinTwo, HIGH);
PinOneState = HIGH;
PinTwoState = HIGH;
previousTime2 = currentTime2;
}
}

else if((PinOneState == HIGH) && (PinTwoState == HIGH)){


if (currentTime2 - previousTime2 > intervalOFF){
digitalWrite(PinOne,HIGH);//ANTCLOCKWISE
digitalWrite(PinTwo, LOW);
PinOneState = HIGH;
PinTwoState = LOW;
previousTime2 = currentTime2;
}
}

else if((PinOneState == HIGH) && (PinTwoState == LOW)){


if (currentTime2 - previousTime2 > intervalON){
digitalWrite(PinOne,LOW);//STOP
digitalWrite(PinTwo, LOW);
PinOneState = LOW;
PinTwoState = LOW;
previousTime2 = currentTime2;
}
}
} else{

digitalWrite(PinOne ,LOW);
digitalWrite(PinTwo ,LOW);
}
}

void setupThirdCode(){
pinMode(LATCH, OUTPUT);
pinMode(CLK, OUTPUT);
pinMode(DATA, OUTPUT);
}

void loopThirdCode(){
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
digitalWrite(LATCH, LOW);
shiftOut(DATA, CLK, MSBFIRST, ~digitTwo[j]); // digitTwo
shiftOut(DATA, CLK, MSBFIRST, ~digitOne[i]); // digitOne
digitalWrite(LATCH, HIGH);
unsigned long startTime = millis();
while (millis() - startTime < interval); //wait 1 minute days
}
}
}

thanks KenF and PaulS for your quick response


Title: Re: incubator help
Post by: PaulS on Dec 14, 2014, 04:31 pm

None of your setup functions has Serial.begin(). None of your loop functions has
any Serial.print() statements. How do you know what the code is doing, or where it
is going wrong?

Title: Re: incubator help


Post by: walterkim on Dec 14, 2014, 05:01 pm

am loading my arduino sketches in Proteus ISIS7 professional as simulator for my


incubator project

Title: Re: incubator help


Post by: PaulS on Dec 14, 2014, 05:56 pm

Quote

am loading my arduino sketches in Proteus ISIS7 professional as simulator for my incubator


project

Down the road, the Chevy dealer might be able to help you with your Ford.

Title: Re: incubator help


Post by: walterkim on Dec 14, 2014, 06:13 pm

who are chevy dealer?

Title: Re: incubator help


Post by: khorshidalam on Nov 11, 2016, 04:09 pm

walterkim, can u fulfill your incubator code?

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images


Arduino Forum
Using Arduino => Project Guidance => Topic started by: nzioka on
Oct 27, 2015, 10:21 am

Title: egg incubator


Post by: nzioka on Oct 27, 2015, 10:21 am

hi, i am trying to write a program for an incubator that can be set to incubate
different types of eggs at a time . can someone help me how to do it? here is a
sample code ii had written but it is not working as expected..

Code: [Select]

#include "DHT.h"
#include <Password.h>
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#define DHTPIN 22 //arduino pin where the data pin of the sensor is
connected to.
#define DHTTYPE DHT22 //define the DHT22 sensor.
DHT dht (DHTPIN,DHTTYPE); // initialize sensor.

LiquidCrystal lcd (8,9,10,11,12,13); // initialize the LCD.


const byte ROWS = 4; // Four rows
const byte COLS = 3; // Four columns

char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};

// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = {26,27,28,29}; //connect to row pinouts

// Connect keypad COL0, COL1, COL2 and COL3 to these Arduino pins.
byte colPins[COLS] = {30,31,32}; //connect to column pinouts
// Create the Keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int relay1=23;
int relay2=24;
int relay3=25;
float temperature,humidity;
char tempF[6];
char humF[6];
void setup() {
pinMode (relay1,OUTPUT);
pinMode (relay2,OUTPUT);
pinMode (relay3,OUTPUT);
lcd.begin(20,4);
welcome();
dht.begin();

void loop() {
lcd.clear();
char y= getkey();

switch (y){

case '1':
humidity= dht.readHumidity();
temperature=dht.readTemperature();
lcd.clear();

dtostrf (temperature,3,1,tempF); // functions to convert


sensor readings to string variables for display.
dtostrf (humidity,3,1,humF);

lcd.setCursor(0,0);
lcd.print ("Tempeture: ");
lcd.print (tempF);
lcd.setCursor(0,1);
lcd.print ("humidity: ");
lcd.print (humF);
lcd.print ("%");

if (humidity >60)
{
digitalWrite(relay3,LOW);
}
else
{
digitalWrite (relay3,HIGH);
}

if (humidity <50)
{
digitalWrite(relay2,LOW);
}

else
{
digitalWrite (relay2,HIGH);
}

delay (500);
break;

case '2':

humidity= dht.readHumidity();
temperature=dht.readTemperature();

dtostrf (temperature,3,1,tempF); // functions to convert


sensor readings to string variables for display.
dtostrf (humidity,3,1,humF);

lcd.setCursor(0,0);
lcd.print ("Tempeture: ");
lcd.print (tempF);

lcd.setCursor(0,1);
lcd.print ("humidity: ");
lcd.print (humF);
lcd.print ("%");
if (humidity >48.5)
{
digitalWrite(relay3,LOW);
}
else
{
digitalWrite (relay3,HIGH);
}

if (humidity <40)
{
digitalWrite(relay2,LOW);
}

else
{
digitalWrite (relay2,HIGH);
}

break;

case '3':

humidity= dht.readHumidity();
temperature=dht.readTemperature();

dtostrf (temperature,3,1,tempF); // functions to convert


sensor readings to string variables for display.
dtostrf (humidity,3,1,humF);

lcd.setCursor(0,0);
lcd.print ("Tempeture: ");
lcd.print (tempF);

lcd.setCursor(0,1);
lcd.print ("humidity: ");
lcd.print (humF);
lcd.print ("%");

if (humidity >55)
{
digitalWrite(relay3,LOW);
}
else
{
digitalWrite (relay3,HIGH);
}

if (humidity <50)
{
digitalWrite(relay2,LOW);
}

else
{
digitalWrite (relay2,HIGH);
}

break;

default:
lcd.print("WRONG CHOOICE");

break;

void welcome(){
lcd.clear();
lcd.print("****WELCOME*****");
lcd.setCursor(0,1);
lcd.print("SELECT TYPE OF EGG");
delay(5000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("1: CHICKEN");
lcd.setCursor(0,1);
lcd.print("2: DUCKK");
lcd.setCursor(0,2);
lcd.print("3: QUAIL");
delay(500);
}

char getkey()
{
lcd.clear();
char key=keypad.getKey();
keypad.setDebounceTime(250);
if (key!=NO_KEY)
return key;
else
lcd.print("NO KEY PRESSED");

Title: Re: egg incubator


Post by: weedpharma on Oct 27, 2015, 10:39 am

At least let us know what it does and does not do. As well as what you want it to
do.

Two lines and code to work out is not a lot of help.

Weedpharma

Title: Re: egg incubator


Post by: PaulS on Oct 27, 2015, 11:33 am
Code: [Select]

digitalWrite (relay2,HIGH);
}

delay (500);
break;

case '2':
Fix your piss-poor indenting by using Tools + Auto Format.

Why do you read the temperature (THAT is the correct spelling) and humidity in
every case? Reading the temperature and humidity, and displaying that data on the
LCD is NOT case dependent.
Why is the Password library included? It is not used.

Many of your global variables should NOT be global.

Title: Re: egg incubator


Post by: dave-in-nj on Oct 27, 2015, 11:37 am

Quote from: PaulS on Oct 27, 2015, 11:33 am

Why is the Password library included? It is not used.

future probably... you know those pesky racoons... set the temp to chicken and get
hard boiled quail eggs.

Title: Re: egg incubator


Post by: Robin2 on Oct 27, 2015, 12:00 pm

@nzioka,

If you monitor the Forum and respond to questions quickly it stops people
wandering off with idle (if humourous) speculations.

...R

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Programming Questions => Topic started by:
theslayer20099 on Jul 07, 2016, 01:13 pm

Title: Help in Incubator


Post by: theslayer20099 on Jul 07, 2016, 01:13 pm

hello guys, ....!

I am making an egg incubator I found on the internet a very good code but I
modified it to suite my requirement but there is a problem in coding the egg turner
I am using a satellite motor for turning egg in big incubators so I use switching
relays I want it to do the turning ever 3 hours but I mad the test on the minutes
but doesn't worked .

need help in fixing the problem as it annoying me and making me mad :) :) .

Code: [Select]
// Incubator code
// ---------------------------------------------
#include <LiquidCrystal.h>
#include "DHT.h"
#include <Servo.h>
#define DHTPIN 1 // Define the temp sensor data
pin
#define DHTTYPE DHT21 // define the temp/hum sensor
type
#define RELAY 0 // define the relay control
pin
#define STEPS_PER_MOTOR_REVOLUTION 32 //define the number of steps
per motor revolution
Servo myservo; // create servo object to
control a servo
DHT dht(DHTPIN, DHTTYPE); //initialize the temp sensor
// LCD Connections:
// rs (LCD pin 4) to Arduino pin 12
// rw (LCD pin 5) to Arduino pin 11
// enable (LCD pin 6) to Arduino pin 10
// LCD pin 15 to Arduino pin 13
// LCD pins d4, d5, d6, d7 to Arduino pins 5, 4, 3, 1
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //set up what port the LCD will use
int backLight = 13; // pin 13 will control the
backlight
int is, im, ih, id, ida; // variables for time
float time, s1, m1, h1, d1; // Set up variables to
calculate time
int ic, ip, ik;
byte thermo[8] = {B00100, B01010, B01010, B01110, B01110, B11111, B11111,
B01110}; //thermometer icon
byte drop[8] = {B00100, B00100, B01010, B01010, B10001, B10001, B10001,
B01110}; //drop icon
byte smile[8] = {B00000, B10001, B00000, B00000, B10001, B01110, B00000}; //
smile icon
byte tim[8] = {B00000, B01110, B10101, B10101, B10011, B10001, B01110,}; //
clock icon
// done with initial parameters
// turner test
#define led1 15
#define led2 14

void setup()
{
dht.begin(); //start the temp sensor
pinMode(RELAY, OUTPUT);
pinMode(backLight, OUTPUT);
digitalWrite(backLight, LOW); // turn backlight on. Replace
'HIGH' with 'LOW' to turn it off.
lcd.begin(20, 4); // columns, rows. use 16,2
for a 16x2 LCD, etc.
lcd.clear(); // start with a blank screen
lcd.setCursor(4, 1); // set cursor to column 0, row
0 (the first row)
lcd.print("Incubator 1.0"); // opening line
lcd.setCursor(4, 2); // set cursor to column 0, row
1
lcd.print("Hatch Them!");
delay(2000);
// Uncomment if you want more text on the 4 line LCD (not used in 2 line
LCDs)
// lcd.setCursor(0,2); // set cursor to column 0,
row 2
// lcd.print("Row 3"); //Text for line 3
//lcd.setCursor(0,3); // set cursor to column 0,
row 3
//lcd.print("Row 4"); // Text for line 4
lcd.createChar(0, thermo);
lcd.createChar(1, drop);
lcd.createChar(2, smile);
lcd.createChar(3, tim);
myservo.attach(9); // servo control is set to pin 9 (usually yellow wire
is control, black goes to ground red goes to +5V)
myservo.write(16); //put the servo at intitial posistion of 16 degrees
// led test as motor setup
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
//timer for test led
}
//loop to read the sensor and display
void loop() {
float h = dht.readHumidity(); // Read the humidity
float t = dht.readTemperature(); // Read temperature in
celsius
float f = dht.readTemperature(true); // get the temperature in
Fahreheit
// uncomment to compute heat index in Fahrenheit (the default)
//float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
//float hic = dht.computeHeatIndex(t, h, false);
time = millis(); // Get time in milliseconds
since tunit turn on
s1 = time / 1000; // Convert time to seconds,
minutes, hours, days
m1 = s1 / 60;
h1 = m1 / 60;
d1 = h1 / 24;
id = int(d1); // Strip out remainder to
leave Days:Hours:Minutes:Seconds
ih = int((d1 - int(d1)) * 24);
im = int((h1 - int(h1)) * 60);
is = int((m1 - int(m1)) * 60);
// Calculate approximate days till hatch (assume 21 days to hatch)
ida = 18 - id;
if (isnan(h) || isnan(t) || isnan(f)) {
// if sensor can't be read
lcd.clear();
lcd.setCursor(7, 0);
lcd.print("failed");
lcd.setCursor(7, 1);
lcd.print("to read");
lcd.setCursor(7, 2);
lcd.print("Sensor!");
delay(10000);
return;
}
else {
//sensor was read succesfully so print values to LCD
lcd.clear(); // Clear the LCD
//Print temperature and humidity in first two lines
lcd.setCursor(0, 0);
// lcd.print("Temperature:");
lcd.print(" ");
lcd.write(byte(0)); // Write the Thhermometer icon
lcd.print(" ");
lcd.print(t, 1);
lcd.print(" C ");
//lcd.setCursor(0,1);
lcd.write(byte(1)); // Write the drop icon
// lcd.print("Humidity:");
lcd.print(" ");
lcd.print(h, 0);
lcd.print(" %");
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.write(byte(3));
lcd.print(" ");
// Print time in format Time: xxd:xxh:xxm:xxs
lcd.print(id);
lcd.print("d:");
lcd.print(ih);
lcd.print("h:");
lcd.print(im);
lcd.print("m:");
lcd.print(is);
lcd.print("s");
lcd.setCursor(0, 2);
lcd.print("_-_-_-_-_-_-_-_-_-_-");
lcd.setCursor(0, 3);
// Print days left till hatch
lcd.print("Days left:");
lcd.print(18 - id);
lcd.print(" ");
lcd.write(byte(2));
//Temperature controller
if (t > 37.0) { // Set the temperature for the
relay to come on (somewhere around 90-101F to get eggs to hatch)
digitalWrite(RELAY, LOW); // Turns ON Relay
}
else {
digitalWrite(RELAY, HIGH); // Turns Relay Off
}
int value = ( 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);
if(im == value){
digitalWrite(led1,HIGH);
digitalWrite(led2,LOW);
lcd.setCursor(18,3);
lcd.print("RT");
}
else {
digitalWrite(led1,LOW);
digitalWrite(led2,HIGH);
lcd.setCursor(16,3);
lcd.print("LT");
}

}
delay(1000);
}

/* --------------------------------------------------------------------------
----- */
Title: Re: Help in Incubator
Post by: septillion on Jul 07, 2016, 01:22 pm

Quote from: theslayer20099 on Jul 07, 2016, 01:13 pm

but doesn't worked .

That's like the worst explanation... What does not work? What do you expect to
happen? What does actually happen? Which part did you modify? Etc...

Title: Re: Help in Incubator


Post by: UKHeliBob on Jul 07, 2016, 01:25 pm

Quote

but doesn't worked .

What does it do that it shouldn't or what doesn't it do that it should ?

More detail please.

Title: Re: Help in Incubator


Post by: UKHeliBob on Jul 07, 2016, 01:28 pm

Code: [Select]

int value = ( 1, 3, 5, 7, 9, 11, 13, 15, 17, 19); What do you think this line of
code does ?
What do you want it to do ?
Have you tried printing the value of value after that line ?

Title: Re: Help in Incubator


Post by: theslayer20099 on Jul 07, 2016, 03:33 pm

Code: [Select]

int value = ( 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);


if(im == value){
digitalWrite(led1,HIGH);
digitalWrite(led2,LOW);
lcd.setCursor(18,3);
lcd.print("RT");
}
else {
digitalWrite(led1,LOW);
digitalWrite(led2,HIGH);
lcd.setCursor(16,3);
lcd.print("LT");
}

this code lines should let the egg turner go to right position when the minute equal
these variables .
sorry I know I didn't clear the Idea for you

Title: Re: Help in Incubator


Post by: UKHeliBob on Jul 07, 2016, 03:52 pm

Quote

this code lines should let the egg turner go to right position when the minute equal these
variables .

I thought that was what you were trying to do but this code won't do it.

As I asked before

Quote

Have you tried printing the value of value after that line ?

It sounds to me as though you need value to be an array and to examine each


value in it to see whether it is time to turn the eggs. A smarter way to do it is to
use an array and save the index to the last value used. That way you only have to
check the next value and when it matches increment the index ready for the next
check.

Title: Re: Help in Incubator


Post by: septillion on Jul 07, 2016, 03:56 pm

Nope, it does not. value is an int, so it can only hold one single value, not 10.
That's why we have arrays!

Code: [Select]

const byte EggTurnMinuts[] = {1, 3, 5, 7}; //more but to lazy


//See how I gave it a usefull name?
//Also made it const because you don't want to change them
//and byte because it's smaller but all numbers fit in a byte

//now loop over every entery to see if it matches


//Also gave im a better name, im is ridiculous
for(byte i = 0; i < sizeof(EggTurnMinutes); i++){
if(currentMinute == EggTurnMinutes[i])[
turnTheEggs();
}
}

Or, because it boils down to every two minutes between 0 and 20...

Code: [Select]

if(currentMinute >= 0 && currentMinute < 20){


if(currentMinute % 2 == 1){
turnTheEggs();
}
}

But keep in mind, both have a problem. The micro will execute that code many
many times in the single minute and I think you only want to do it once in that
minute. So you have to check when you enter a new minute and only do it then.

Code: [Select]

static byte lastMinute = 0;


if(currentMinute != lastMinute){
lastMinute = currentMinute; //save we have seen the change
if(currentMinute >= 0 && currentMinute < 20){
if(currentMinute % 2 == 1){
turnTheEggs();
}
}
}

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images


Arduino Forum
Using Arduino => Programming Questions => Topic started by:
hackertom on Mar 23, 2016, 12:58 pm

Title: Egg incubator menu arduino!


Post by: hackertom on Mar 23, 2016, 12:58 pm

hi! I need to work a function menu for my egg incubator, i want

root menu choose


|
|
|

chicken > 21 days, 37.7c, 45-50h,

turkey > 28days,37.7, 60-75h,

goose >30days,37,6,60-80h

e.g. > if i choose chicken avoid all options for turkey and goose and run machine in
21days 37.7c,45-50h

Title: Re: Egg incubator menu arduino!


Post by: UKHeliBob on Mar 23, 2016, 01:11 pm

Display the 3 options and prompt the user to enter 1, 2 or 3


Call a function that takes 3 parameters to do what you want based on the option
chosen.

Where are you stuck ?

Title: Re: Egg incubator menu arduino!


Post by: hackertom on Mar 23, 2016, 01:22 pm

Quote from: UKHeliBob on Mar 23, 2016, 01:11 pm

Display the 3 options and prompt the user to enter 1, 2 or 3


Call a function that takes 3 parameters to do what you want based on the option chosen.

Where are you stuck ?


i display the 3 options, my problem is the function . . look the example code can
you help me? i have 5 buttons

Code: [Select]

#include <LiquidCrystal.h>
#include "DHT.h"
#define DHTPIN 2 // Define the temp sensor data
pin
#define DHTTYPE DHT22 // define the temp/hum sensor
type
#define RELAY 0 // define the relay control pin
DHT dht(DHTPIN, DHTTYPE); //initialize the temp sensor
// LCD Connections:
// rs (LCD pin 4) to Arduino pin 12
// rw (LCD pin 5) to Arduino pin 11
// enable (LCD pin 6) to Arduino pin 10
// LCD pin 15 to Arduino pin 13
// LCD pins d4, d5, d6, d7 to Arduino pins 5, 4, 3, 1
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 1); //set up what port the LCD will
use
int backLight = 13; // pin 13 will control the
backlight
void setup()
{
dht.begin(); //start the temp sensor
pinMode(RELAY, OUTPUT);
pinMode(backLight, OUTPUT);
digitalWrite(backLight, HIGH); // turn backlight on. Replace
'HIGH' with 'LOW' to turn it off.
lcd.begin(20,4); // columns, rows. use 16,2 for
a 16x2 LCD, etc.
lcd.clear(); // start with a blank screen
lcd.setCursor(0,0); // set cursor to column 0, row
0 (the first row)
lcd.print("Incubator 1.0"); // opening line
lcd.setCursor(0,1); // set cursor to column 0, row
1
lcd.print("Hatch Them!");
delay(2000);
// Uncomment if you want more text on the 4 line LCD (not used in 2 line
LCDs)
// lcd.setCursor(0,2); // set cursor to column 0, row
2
// lcd.print("Row 3"); //Text for line 3
//lcd.setCursor(0,3); // set cursor to column 0, row
3
//lcd.print("Row 4"); // Text for line 4
}
//loop to read the sensor and display
void loop(){
float h = dht.readHumidity(); // Read the humidity
float t = dht.readTemperature(); // Read temperature in celsius
float f = dht.readTemperature(true); // get the temperature in
Fahreheit
// uncomment to compute heat index in Fahrenheit (the default)
//float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
//float hic = dht.computeHeatIndex(t, h, false);
int is,im,ih,id,ida; // variables for time
float time,s1,m1,h1,d1; // Set up variables to
calculate time
time=millis(); // Get time in milliseconds
since tunit turn on
s1=time/1000; // Convert time to seconds,
minutes, hours, days
m1=s1/60;
h1=m1/60;
d1=h1/24;
id=int(d1); // Strip out remainder to
leave Days:Hours:Minutes:Seconds
ih=int((d1-int(d1))*24);
im=int((h1-int(h1))*60);
is=int((m1-int(m1))*60);
// Calculate approximate days till hatch (assume 21 days to hatch)
ida=21-id;
if (isnan(h) || isnan(t) || isnan(f)){
// if sensor can't be read
lcd.clear();
lcd.setCursor(0,0);
lcd.print("failed to read");
delay(50000);
return;
}
else {
//sensor was read succesfully so print values to LCD
lcd.clear(); // Clear the LCD
//Print temperature and humidity in first two lines
lcd.setCursor(0,0);
lcd.print("Temperature:");
lcd.print(f,1);
lcd.print(" F");
lcd.setCursor(0,1);
lcd.print("Humidity:");
lcd.print(h,0);
lcd.print(" %");
lcd.setCursor(0,2);
lcd.print("Time:");
// Print time in format Time: xxd:xxh:xxm:xxs
lcd.print(id);
lcd.print("d:");
lcd.print(ih);
lcd.print("h:");
lcd.print(im);
lcd.print("m:");
lcd.print(is);
lcd.print("s");
lcd.setCursor(0,3);
// Print days left till hatch
lcd.print("Days left:");
lcd.print(21-id);
//Temperature controller
if(f<91){ // Set the temperature for the relay to
come on (somewhere around 90-101F to get eggs to hatch)
digitalWrite(RELAY,LOW); // Turns ON Relay
}
else{
digitalWrite(RELAY,HIGH); // Turns Relay Off
}
// Puase for 5 seconds
delay(5000);
}
}
Title: Re: Egg incubator menu arduino!
Post by: chipwitch on Mar 23, 2016, 05:08 pm

I don't see any functions in your code. Do you know how to use them?

BTW... I've hatched a few broods of chickens in my homemade arduino incubator.


The DHT temperature probe will work, but it has a slow response time which can
cause problems if you don't compensate for it. The BMP temp sensors are much
faster and don't require any compensation for the lag time.

Title: Re: Egg incubator menu arduino!


Post by: chipwitch on Mar 23, 2016, 07:00 pm

I had another thought to share...

You MUST have an understanding of functions in order to program your Arduino.


Read and understand this: Functions
(https://www.arduino.cc/en/Reference/FunctionDeclaration)

A function is a little snippet of code that is only executed on an as-needed basis. In


fact, it may never be executed at all. Typically, something in the body of your
sketch (in the loop()) will "call" that snippet after an "if/then" statement (or similar)
determines that function is necessary.

What I suggest is that you design your loop() with as little code as possible.
Something like:

void loop(){
check temperature
if temperature is < 99 then call the function to add heat
if temperature is > 100 then call function to turn off heat
// next, add similar calls to functions as needed
if button x is pressed call function But1pressed()
if button y is pressed... call function But2pressed()
if time to turn the eggs call function eggTurn()
.
.
.
etc
delay(2000);
}

It's absolutely imperative that you structure your code something like that to avoid
problems down the road and make your code easy to follow for editing. I wrote the
above loop() in a pseudo-code style for clarity since the code you posted shows no
kind of logical flow. I hope it's easier to understand.

Also, I want to point out that trying to time your incubator to turn on, execute a
particular temperature protocal and then turn off on day 21 for chickens, is
dangerous. More complex code must be included in the sketch to accommodate the
very real possibility that you will lose power, a wire will get damaged/pulled out or
that your board simply freezes. In that event, you must have some process by
which you can restart the arduino board and set the remaining days again to pick
up the temperature protocol where it left off before the failure. Personally, I
avoided that aspect in my design. If you're just using the day count down for
display on the lcd, of course that's okay :) I suggest you have an alarm for if the
temperature is out of the expected range, a beeper goes off. I lost my first batch
of eggs for some unanticipated over-heating.

Title: Re: Egg incubator menu arduino!


Post by: ltore123 on Jul 26, 2017, 03:30 pm
here is my code

https://drive.google.com/open?id=0B0eWzIn-plF2SVNHR3BGTTBOY1E

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Programming Questions => Topic started by:
Cromp on Mar 26, 2012, 07:44 pm

Title: Arduino based incubator - hangs - SOLVED - power supply issues


Post by: Cromp on Mar 26, 2012, 07:44 pm
Hello all,
This is my first post to the forum, so greetings all.
For my first Arduino project, I tried automating the chicken egg incubator I built
last year. Since the humidity level was hard to control, I used the PID library and a
relay to control an ultrasonic fogger. Relative humidity is very accurately measured
using a Sensirion SHT15 sensor with the Sensirion library. Most importantly,
temperature is (and was) controlled by a commercial PID controller.

Some pictures:
I had no previous experience with C, only limited knowledge of Turbopascal.
I use an LCD screen from Wulfden to display information about temperature and
humidity. Temperature and humidity values are stored as arrays of bytes, from
which I calculate average, minimum and maximum values.
It's been a lot of work, reading and debugging to get to this point, where my
incubator is up and running, with 120 (180 max) chicken eggs inside.
Setpoint for humidity is now 58%, the PID algorithm manages to stay within 1% of
that value.

One problem remains: my Arduino Uno keeps freezing, and I don't know why. My
arrays are global variables, so my code should be able to perform calculations on
them right?

Then I thought it was maybe a RAM issue, so I now store my text strings in flash
memory. Didn't help.

Then I moved most of my functions to the main loop, didn't help ether.

The only "solution" I have found so far, is to make watchdog timer automatically
reset my Arduino if it hangs after 8 s. But I'd like to dig to the root of the problem,
because my min/max values of the last 24 hours are worthless, and because I'd like
to automate the turning of the trays.

Any hints what the source of those crashes could be? Or tips for a debugging
strategy? The crashes seem to occur randomly, after a few hours. The longest time
the incubator ran was 6 hours. I'll post my code below.
Thanks for your help,

Wouter

Title: code
Post by: Cromp on Mar 26, 2012, 07:47 pm

Code: [Select]

#include <PID_v1.h>
#include <Sensirion.h>
#include <avr/wdt.h>
#include <MemoryFree.h>

const byte RELAYPIN = 6; //fog machine


const byte DATAPIN = 2; // SHTxx serial data
const byte SCLKPIN = 3; // SHTxx serial clock
const byte LCDPIN = 1;
const byte AUTOTURNPIN = 7; //switch to choose RH setpoint

const unsigned long TRHSTEP = 10000; // measure RH every 10 s


const unsigned long LCDTEMP1 = 0; //8s temp display
const unsigned long LCDTEMP2 = 8000;
const unsigned long LCDHUM1 = 16000; //8s RH display
const unsigned long LCDHUM2 = 24000; //8s RH display
const unsigned long LCDTURN = 32000; //8s
const unsigned long LCDPID = 40000; //8s pidinfo
const unsigned long LCDSTOP = 48000;

float PTERM = 2.00;


float ITERM = 0.50;
float DTERM = 1.00;

double Setpoint, Input, Output;

unsigned int rawData;


float temperature;
float humidity = 90.0;
byte measActive = false;
byte measType = TEMP;

unsigned long windowSize = 120000; //in milliseconds, pid


windowsize 2 minutes, so pid output ranges from 0 s to 120 s
unsigned long windowStartTime;
unsigned long rhMillis = 0;
unsigned long curMillis=0;
unsigned long lcdMillis=0;
unsigned long timevalue=0;

Sensirion sht = Sensirion(DATAPIN, SCLKPIN);


PID mijnPID(&Input, &Output, &Setpoint,PTERM,ITERM,DTERM, DIRECT);

float humidity1Minute[6] = {
50.0,50.0,50.0,50.0,50.0,50.0};
byte hum1MinIndex = 0;
float averageHum1Min = 50.0;
byte humidity1Hour[60] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte hum1HourIndex = 0;
byte humidity24Hours[24] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte hum24HourIndex = 0;
byte temperature1Minute[6] = {
0,0,0,0,0,0};
byte temp1MinIndex = 0;
byte temperature1Hour[60] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte temp1HourIndex = 0;
byte lcdState = 5;
boolean fillUpArray = true;

byte averageTemp1Minute = 0;
byte maxTemp1Minute = 0;
byte minTemp1Minute = 0;
byte averageTemp1Hour = 0;
byte maxTemp1Hour = 0;
byte minTemp1Hour = 0;
byte averageHum1Hour = 0;
byte minHum1Hour = 0;
byte maxHum1Hour = 0;
byte averageHum24Hours = 0;
byte minHum24Hours = 0;
byte maxHum24Hours = 0;

void setup()
{
wdt_enable(WDTO_8S);
averageHum1Min=constrain(averageHum1Min,0.0,100.0);

Serial.begin(19200);
delay(20);
byte stat;
byte error = 0;
mijnPID.SetOutputLimits(0,windowSize); //minimum 0 seconde
fog machine on
mijnPID.SetSampleTime(10000);
windowStartTime = 0;
mijnPID.SetMode(AUTOMATIC);
pinMode(RELAYPIN, OUTPUT);
digitalWrite(RELAYPIN, LOW);

pinMode(8, OUTPUT); //no autoturn yet


pinMode(9, OUTPUT);
digitalWrite(8, LOW);
digitalWrite(9, LOW);

pinMode(13, OUTPUT);
digitalWrite(13, LOW);
wdt_reset();
showString(PSTR("?f?n"));
showString(PSTR("***tok**tok**tok****"));
delay(2000);
showString(PSTR("********************"));
showString(PSTR("Bezig met opstarten "));
showString(PSTR("********************"));
showString(PSTR("You toking to me??"));
delay(3000);
lcdMillis = millis();
}

void loop()
{
wdt_reset();
curMillis = millis(); // Get current time
if (digitalRead(AUTOTURNPIN) == HIGH) Setpoint = 600; //538 = 55%, 614 =
60%, change humidity setpoint according to switch position
else Setpoint = 700; //70% RH

pidparameterchange(); //set pid aggressiveness


according to distance from setpoint

if (curMillis - rhMillis >= TRHSTEP) // Time for new


measurements?
{
digitalWrite(13, HIGH); //LED lights up
measActive = true;
measType = TEMP;
sht.meas(TEMP, &rawData, NONBLOCK); // Start temp measurement
rhMillis = curMillis;
}
if (measActive && sht.measRdy())
{ // Check measurement status
if (measType == TEMP)
{ // Process temp or humi?
measType = HUMI;
temperature = sht.calcTemp(rawData); // Convert raw sensor data
temperature = temperature - 0.9;
sht.meas(HUMI, &rawData, NONBLOCK); // Start humi measurement
}
else
{
measActive = false;
humidity = sht.calcHumi(rawData, temperature); // Convert raw sensor
data
digitalWrite(13, LOW); //led off
wdt_reset();
humcalc(); //calculate humidity
tempcalc(); //calculate temperature
}

wdt_reset();
Input = map(humidity,0.0,100.0,0,1023); // input pid rescaled from 0 to
1023
mijnPID.Compute(); //run PID algorithm
if(curMillis - windowStartTime>=windowSize) windowStartTime = curMillis;
if(Output > curMillis - windowStartTime) digitalWrite(RELAYPIN,HIGH);
//should the fogger be on
else digitalWrite(RELAYPIN,LOW);
//or off?
lcdprint(); //display one of the 6
different screens

wdt_reset();
}
}

void pidparameterchange()
{
if (Setpoint-map(humidity,0.0,100.0,0,1023)>100)
{
PTERM = 10.0;
ITERM = 1.00;
}
else
{
if (Setpoint-map(humidity,0.0,100.0,0,1023)>50)
{
PTERM = 2.0;
ITERM = 0.0;
}
else
{
PTERM = 0.10;
ITERM = 0;
}
}
}

void humcalc() //calculate humidity values


{
humidity1Minute[hum1MinIndex] = floor(humidity+0.5);
averageHum1Min = 0.0;
for (int i=0;i<=5;i++)
{
averageHum1Min += humidity1Minute[i];
}
averageHum1Min /= 6.0; //calculate average humidity in the last minute
if (hum1MinIndex==5)
{
hum1MinIndex=0; //reset index

humidity1Hour[hum1HourIndex] = floor(averageHum1Min + 0.5);

averageHum1Hour = averageValue (59, humidity1Hour);


minHum1Hour = minimumValue (59, humidity1Hour);
maxHum1Hour = maximumValue (59, humidity1Hour);
if (hum1HourIndex == 59) //fill next level
{
hum1HourIndex = 0; //reset index

humidity24Hours[hum24HourIndex] = averageHum1Hour;

averageHum24Hours = averageValue (23, humidity24Hours);


minHum24Hours = minimumValue (23, humidity24Hours);
maxHum24Hours = maximumValue (23, humidity24Hours);

if (hum24HourIndex == 23) hum24HourIndex = 0; //reset index


else hum24HourIndex++;
}
else hum1HourIndex++;
}
else hum1MinIndex++;
}

Title: Re: Arduino based incubator - hangs - help!


Post by: Cromp on Mar 26, 2012, 07:48 pm

Code: [Select]

byte averageValue (byte maxIndex, byte array[]) //calculate average value


from an array of bytes
{
float average = 0.0;
byte result;
for (int i=0;i<=maxIndex;i++)
{
average += array[i];
}
average/=(maxIndex+1);
result=constrain(result,0.0,100.0);
result = floor(average+0.5);
return result;
}

byte minimumValue (byte maxIndex, byte array[]) //calculate minimum value


from an array of bytes
{
byte result;
result = array[0];
for (int i=1;i<=maxIndex;i++)
{
if(array[i]<result) result=array[i];
}
return result;
}

byte maximumValue (byte maxIndex, byte array[]) //calculate maximum value


from an array of bytes
{
byte result;
result = array[0];
for (int i=1;i<=maxIndex;i++)
{
if(array[i]>result) result=array[i];
}
return result;
}

void tempcalc() //calculate temperature values


{
float temp = 0.0;
temp = floor(temperature*10.0+0.5);
temp = constrain(temp,166,421);
temperature1Minute[temp1MinIndex]=map(temp,166,421,0,255);
averageTemp1Minute = averageValue(5, temperature1Minute);
maxTemp1Minute = maximumValue(5, temperature1Minute);
minTemp1Minute = minimumValue(5, temperature1Minute);

if (temp1MinIndex == 5)
{
temp1MinIndex = 0; //reset
index
temperature1Hour[temp1HourIndex] = averageTemp1Minute;

if (fillUpArray) fillarrays();//fill arrays with values 1 min after


startup
averageTemp1Hour = averageValue(59, temperature1Hour);
maxTemp1Hour = maximumValue(59, temperature1Hour);
minTemp1Hour = minimumValue(59, temperature1Hour);

if (temp1HourIndex == 59) temp1HourIndex = 0;


else temp1HourIndex++;
}
else temp1MinIndex ++;
}

void fillarrays() //fills arrays with first measurement 1 min after boot-up,
run only once
{
for (int i=0;i<=59;i++)
{
humidity1Hour[i]=humidity1Hour[0];
}
for (int i=0;i<=23;i++)
{
humidity24Hours[i]=humidity1Hour[0];
}
averageHum24Hours = averageValue (23, humidity24Hours); //calculate 24 h
values right after boot-up
minHum24Hours = minimumValue (23, humidity24Hours);
maxHum24Hours = maximumValue (23, humidity24Hours);
for (int i=1;i<=59;i++)
{
temperature1Hour[i]=temperature1Hour[0];
}
fillUpArray = false;
}

void lcdprint() //display temperature, humidity and time online


{
timevalue = curMillis - lcdMillis;

if (timevalue > LCDTEMP1 && timevalue < LCDTEMP2 && lcdState!=0) //temp
display
{
showString(PSTR("?f"));
showString(PSTR("Temperatuur "));
float temp = 0.0;
temp = map(averageTemp1Minute,0,255,166,421)/10.0;
Serial.print(temp,1);
showString(PSTR("?0C** Nu "));
Serial.print(temperature);
showString(PSTR("?0C **"));
showString(PSTR("Max 1m: "));
temp = map(maxTemp1Minute,0,255,166,421)/10.0;
Serial.print(temp,1);
showString(PSTR("?0C?n"));
showString(PSTR("Min 1m: "));
temp = map(minTemp1Minute,0,255,166,421)/10.0;
Serial.print(temp,1);
showString(PSTR("?0C"));
lcdState=0;
}

if (timevalue > LCDTEMP2 && timevalue < LCDHUM1 && lcdState!=1)


{
float temp = 0.0;
showString(PSTR("?f"));
showString(PSTR("Gem temperatuur 1h: ** "));
temp = map(averageTemp1Hour,0,255,166,421)/10.0;
Serial.print(temp,1);
showString(PSTR("?0C **"));
showString(PSTR("Max: "));
temp = map(maxTemp1Hour,0,255,166,421)/10.0;
Serial.print(temp,1);
showString(PSTR("?0C?n"));
showString(PSTR("Min: "));
temp = map(minTemp1Hour,0,255,166,421)/10.0;
Serial.print(temp,1);
showString(PSTR("?0C"));
lcdState=1;
}

if (timevalue > LCDHUM1 && timevalue < LCDHUM2 && lcdState!=2)


{ //display
rh
float temp = 0.0;
showString(PSTR("?f"));
showString(PSTR("Rel Luchtvochtigheid"));
Serial.print(averageHum1Min);
showString(PSTR("%"));
showString(PSTR(" Nu "));
Serial.print(humidity);
showString(PSTR("%freeRAM "));
Serial.print(freeMemory());
showString(PSTR(" / 2048"));
//showString(PSTR("%Setpoint:?n"));
//showString(PSTR("** "));
//Serial.print(map(Setpoint,0,1023,0,100));
//showString(PSTR("% **"));
lcdState=2;
}

if(timevalue > LCDHUM2 && timevalue < LCDTURN && lcdState!=3)


{
byte temp = 0;
showString(PSTR("?f"));
showString(PSTR("1 uur: "));
temp = averageHum1Hour;
Serial.print(averageHum1Hour);
showString(PSTR("%?n"));
showString(PSTR("Min: "));
temp = minHum1Hour;
Serial.print(minHum1Hour);
showString(PSTR("% Max: "));
temp = maxHum1Hour;
Serial.print(temp);
showString(PSTR("%"));
showString(PSTR("24 uur: "));
temp = averageHum24Hours;
Serial.print(temp);
showString(PSTR("%?n"));
showString(PSTR("Min: "));
temp = minHum24Hours;
Serial.print(temp);
showString(PSTR("%"));
showString(PSTR(" Max: "));
temp = maxHum24Hours;
Serial.print(temp);
showString(PSTR("%"));
lcdState=3;
}

if(timevalue > LCDTURN && timevalue < LCDPID && lcdState!=4)


{
//display time incubator has been online
showString(PSTR("?f"));
showString(PSTR("freeRAM "));
Serial.print(freeMemory());
showString(PSTR(" / 2048"));
showString(PSTR("?n Kast staat al?n"));
//showString(PSTR(" "));
Serial.print(curMillis/86400000);
showString(PSTR("d "));
Serial.print((curMillis%86400000)/3600000);
showString(PSTR("h "));
Serial.print((curMillis%3600000)/60000);
showString(PSTR("m aan?n"));
//showString(PSTR("**** aan *****"));
showString(PSTR("freeRAM "));
Serial.print(freeRam());
showString(PSTR(" / 2048"));
lcdState=4;
}

if(timevalue > LCDPID && timevalue < LCDSTOP && lcdState!=5)


{
showString(PSTR("?f"));
showString(PSTR("Instellingen RL PID "));
showString(PSTR("P="));
float temp = 0.0;
temp = PTERM;
Serial.print(temp);
showString(PSTR(" I="));
temp = ITERM;
Serial.print(temp);
showString(PSTR("?n"));
showString(PSTR("D="));
temp = DTERM;
Serial.print(temp);
showString(PSTR("?n"));
showString(PSTR(" Mist aan "));
temp = Output*100.0/windowSize;
Serial.print(temp);
showString(PSTR(" %"));
lcdState=5;
}
if(curMillis - lcdMillis > LCDSTOP) lcdMillis = curMillis;
}

void showString (PGM_P s) //store strings in


flash memory
{
char c;
while ((c = pgm_read_byte(s++)) != 0)
Serial.print(c);
}

int freeRam () //returns free RAM


{
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

Title: Re: Arduino based incubator - hangs - help!


Post by: wildbill on Mar 26, 2012, 08:31 pm
One likely culprit is array bounds violations. It looks like you're using constrain
statements to defend against that, but your usage is not correct. Constrain returns
the contstrained number, it doesn't change the value it is passed. So this:

Code: [Select]

constrain(hum1MinIndex,0,6);

Should be this:

Code: [Select]

hum1MinIndex=constrain(hum1MinIndex,0,6);

You might want to grab one of the freemem functions regularly posted here to see
how much RAM you have left. Given that you've started moving strings to progmem
with no effect, it likely isn't an issue, but it might give you the necessary comfort to
consider moving code back into individual functions again.

Title: Re: Arduino based incubator - hangs - help!


Post by: Cromp on Mar 27, 2012, 10:01 am

wildbill, thank you for your suggestions, much appreciated.

I followed your suggestion and corrected my contrains:

Code: [Select]

hum1MinIndex=constrain(hum1MinIndex,0,5); //constrain indexes


hum1HourIndex=constrain(hum1HourIndex,0,59);
hum24HourIndex=constrain(hum24HourIndex,0,23);
temp1MinIndex=constrain(temp1MinIndex,0,5);
temp1HourIndex=constrain(temp1HourIndex,0,59);

lcdState=constrain(lcdState,0,5);
averageHum1Min=constrain(averageHum1Min,0.0,100.0);

This now reflects the actual sizes of all the arrays, so no more array bounds
violations I hope.
I updated my code above.

I also added two different freeRam functions I found online:

Code: [Select]
#include <MemoryFree.h>

Serial.print(freeMemory());

and

Code: [Select]
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);

Serial.print(freeRam());

I'll upload this afternoon, and report back here.


Fingers crossed and thanks again!

Title: Re: Arduino based incubator - hangs - help!


Post by: PaulS on Mar 27, 2012, 11:33 am

Quote

I followed your suggestion and corrected my contrains...This now reflects the actual sizes of
all the arrays, so no more array bounds violations I hope.

I really don't see how constraining what should be constants is going to help
anything. Personally, I think trying to just screams "clueless". Just assign the
variable the correct value in the first place.
It's not like you are constraining things in loop, where there might be value added
doing so.

Code: [Select]
if(curMillis - windowStartTime>windowSize) windowStartTime += windowSize;
Adding time variables is a bad idea.

Some comments in the code, on the other hand, would be a good idea, as would
using Tools + Auto Format to correct the inconsistent indenting.

A lot of the stuff in loop() should be put in functions.

Title: Re: Arduino based incubator - hangs - help!


Post by: Cromp on Mar 27, 2012, 05:58 pm

Hello,

correcting the constraints didn't work. When I came back from work, I noticed the
Arduino crashed after 4 hours and 40 minutes.

The free RAM functions tell me I have 1500 bytes of RAM available after startup, so
no problems there.

PaulS: Thank you for your comments. Maybe you're right about clueless. But
hopeless is maybe a better word. :D
I've checked my code so many times now, and I really don't see where I would
violate my array bounds. So I removed the constrains.

Quote
Adding time variables is a bad idea.

Aha! A bad idea I didn't code myself! That piece of code comes from the PID Library
Relay Output Example
(http://arduino.cc/playground/Code/PIDLibraryRelayOutputExample)

I've changed

Code: [Select]

if(curMillis - windowStartTime>windowSize) windowStartTime +=


windowSize;
if(Output >= curMillis - windowStartTime) digitalWrite(RELAYPIN,HIGH);
else digitalWrite(RELAYPIN,LOW);

to

Code: [Select]

if(curMillis - windowStartTime>=windowSize) windowStartTime = curMillis;


if(Output > curMillis - windowStartTime) digitalWrite(RELAYPIN,HIGH);
else digitalWrite(RELAYPIN,LOW);

Would that be allright?


I've updated my code above, formatted (thanks for the tip) and restored functions /
added more comment.

Wouter

Title: Re: Arduino based incubator - hangs - help!


Post by: wildbill on Mar 27, 2012, 08:37 pm

What do you see on the Serial monitor when it crashes? Can you put in some more
debugging strings to isolate the area that's causing it?

Title: Re: Arduino based incubator - hangs - help!


Post by: Cromp on Mar 27, 2012, 09:46 pm

Unfortunately I can only connect it to my netbook when I'm arround (it's at my


aunt's place).
Also, serial monitor displays only gibberish, since I'm using pin 1 to drive my LCD,
at 19200 baud (incompatible with serial monitor?).
So I can only display debug messages on the LCD. Like the amount of free RAM
you suggested, still around 1485 bytes after about an hour.

The strange thing is that it only happens after 4 to 6 hours. I really don't
understand why it never happens sooner? I did notice earlier, now that I divided my
code over a few functions, that loop takes longer to complete, causing timevalue to
miss one of the LCD screens (the fifth one, who shows the time the incubator has
been online). So I had to increase the time interval each screen is displayed from 8
to 12 seconds.

Thanks again for all the help,


Title: Re: Arduino based incubator - hangs - help!
Post by: MarkT on Mar 27, 2012, 09:56 pm

Quote from: PaulS on Mar 27, 2012, 11:33 am

Code: [Select]
if(curMillis - windowStartTime>windowSize) windowStartTime += windowSize;
Adding time variables is a bad idea.

But that's adding an interval to a timestamp to get a new later timestamp, nothing
wrong with that at all.
Title: Re: Arduino based incubator - hangs - help!
Post by: MarkT on Mar 27, 2012, 10:09 pm

Crashes can be caused by power supply glitches, or electrical noise, not just
software problems. Try monitoring the power source when the outputs switch and
check that the relay coil has a flyback diode fitted.

Title: Re: Arduino based incubator - hangs - help!


Post by: wildbill on Mar 27, 2012, 10:19 pm

Quote

So I had to increase the time interval each screen is displayed from 8 to 12 seconds

That's disturbing - could that be causing an issue with not resetting the watchdog
timer soon enough as well? Also, what on earth is consuming that time?

On the topic of missing screens of LCD data, I'd be inclined to just flip to the next
one every eight seconds, rather than using multiple measures such as LCDHUM2. I
don't believe it's causing a problem, but it would make the code a little simpler.

Can you use softwareserial for the LCD and reserve the serial port for debug?
Although it sounds like you're not going to be around to capture that data anyway.
Somehow you need to be able to indicate where you were when it crashed. Is the
watchdog masking your ability to tell?

Title: Re: Arduino based incubator - hangs - help!


Post by: Cromp on Mar 29, 2012, 09:05 pm
Well the last version of my code seems a bit more stable, runs for about 12 - 16
hours before it crashes.

Quote from: MarkT


Crashes can be caused by power supply glitches, or electrical noise, not just software
problems. Try monitoring the power source when the outputs switch and check that the
relay coil has a flyback diode fitted.

Hi Mark, the relay has all the bells and whistles (transistor, LED, diode), it's from a
kit I bought on ebay. Furthermore, I'm not switching the 220 V -> 24 V AC
transformer on and off that powers the ultrasonic fogger. The transformer is always
on, I switch the output (24 V AC ~ 1 amp). It also switches only once every two
minutes.

My Arduino is powered by a beefy 7805 voltage regulator, which gets 12 Volts at 5


A maximum from a switching power supply I bought, originally to power the motor
to turn the trays. It used to be on it's own 9 V PSU, it crashed back then as well.

Quote from: wildbill


That's disturbing - could that be causing an issue with not resetting the watchdog timer
soon enough as well? Also, what on earth is consuming that time?

I wonder as well. But untill the eggs hatch the dog is my best friend: before I
configured wdt, the Arduino froze, not regulating humidity for hours. Now it's just
an annoyance.

Quote
On the topic of missing screens of LCD data, I'd be inclined to just flip to the next one every
eight seconds, rather than using multiple measures such as LCDHUM2. I don't believe it's
causing a problem, but it would make the code a little simpler.

I'll write some switch case code to control the LCD, thanks for the tip.

Quote
Can you use softwareserial for the LCD and reserve the serial port for debug? Although it
sounds like you're not going to be around to capture that data anyway. Somehow you need
to be able to indicate where you were when it crashed. Is the watchdog masking your ability
to tell?
I'll put my code full off serial.prints, then run the incubator with my pc attached
untill it freezes. Hopefully, that way we can figure out what it was doing when it
crashed... This will have to wait untill hatch time I'm afraid.

Title: Re: Arduino based incubator - hangs - help!


Post by: MarkT on Mar 29, 2012, 11:05 pm
Good luck... BTW those eggs look smaller than the ones in Jurassic Park ;)

Title: Re: Arduino based incubator - hangs - help!


Post by: liuzengqiang on Mar 30, 2012, 01:05 am

Not as much of a fan of some constrain function as you are (maybe Paul is on my
side with this too). You need to be aware of what you set the array indices to
instead of constrain them in case of overflow. I'd get rid off all these constrain
function before asking again what's wrong with the code.

BTW, you constrained the hum1MinIndex to 0-6 but you only have 6 element in the
relevant array so once hum1MinIndex==6 you destroy the chicken world. Good
work giving the chicken the inevitable. They should chant iiagdtd ]:)

Title: Re: Arduino based incubator - hangs - help!


Post by: wildbill on Mar 30, 2012, 01:50 am

Before you rule out power issues completely, consider whether the mains power
you're getting is ok. I recall another troubleshooting thread where the eventual
problem turned out to be a very old fridge. When the compressor kicked in, it
caused all sorts of issues for the electronics plugged in on the same circuit.

Title: Re: Arduino based incubator - hangs - help!


Post by: Cromp on Apr 08, 2012, 10:06 am

Quote

Good luck... BTW those eggs look smaller than the ones in Jurassic Park smiley-wink

Yes, fortunately. When they are 5 months old they still need to fit in my homebuilt
plucker.

(http://www.youtube.com/watch?v=3Tcx60gNHWI)

Quote
Before you rule out power issues completely, consider whether the mains power you're
getting is ok. I recall another troubleshooting thread where the eventual problem turned out
to be a very old fridge. When the compressor kicked in, it caused all sorts of issues for the
electronics plugged in on the same circuit.

wildbill, thank you for that remark. Especially the part about the old fridge,
because:

One likely culprit is standing there! But I noticed before the lights flicker heavily
when inductive loads get switched on...
I placed a 2200 F capacitor parallel to the output of my power supply and voila.
No more reboots for the last 4 days.

Thank you so much!

Title: Re: Arduino based incubator - hangs - help!


Post by: sbolel on Oct 08, 2012, 08:32 pm
Quote from: Cromp on Apr 08, 2012, 10:06 am

I placed a 2200 F capacitor parallel to the output of my power supply and voila. No more
reboots for the last 4 days.

Hey. I have the same problem right now with a heavy load circuit causing my
arduino to hang. im using a usb adapter and a usb cable to power it. how would i
go about putting the capacitor parallel to the usb power output?

i'd appreciate any help. thanks!

Title: Re: Arduino based incubator - hangs - SOLVED - power supply issues
Post by: MarkT on Oct 08, 2012, 08:48 pm

Add it from the 5V pin to one of the ground pins. If its too big a capacitor its
conceivable the USB supply could trip out (more likely for an actual
computer/laptop than a wall-wart supply).

[BTW there is already 47uF on 5V rail on the standard Arduino]

Title: Re: Arduino based incubator - hangs - SOLVED - power supply issues
Post by: sbolel on Oct 08, 2012, 08:53 pm

Quote from: MarkT on Oct 08, 2012, 08:48 pm

Add it from the 5V pin to one of the ground pins. If its too big a capacitor its conceivable
the USB supply could trip out (more likely for an actual computer/laptop than a wall-wart
supply).

[BTW there is already 47uF on 5V rail on the standard Arduino]

thanks for your help. ill give it a shot later today and post results.
Here (http://arduino.cc/forum/index.php/topic,123613.15.html) is the original
thread with my issue for reference.
Title: Re: Arduino based incubator - hangs - SOLVED - power supply issues
Post by: Lowa1 on Oct 09, 2013, 06:54 pm

Hoi Cromp.

I want to make a incubator with Arduino.

Please can you post the arduino code.

Greetings Lowa1. (From Holland).

Title: Re: Arduino based incubator - hangs - SOLVED - power supply issues
Post by: TawandaSA on Oct 29, 2014, 11:48 am

I had the same problem then tried to put a 2200 F parallel to my Arduino (and
relay) power supply and now my Serial enabled LCD Display is no longer working.
It's on but not displaying what it's suppose to display.

I have also noticed that my Arduino no longer run the setup part of the code. When
I remove the capacitor, it runs the setup but the LCD is still not working. What
could have gone wrong?

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Project Guidance => Topic started by: rvannly on
Apr 23, 2012, 07:29 am

Title: Can someone go over my code please? 16ch chicken incubator


Post by: rvannly on Apr 23, 2012, 07:29 am

Hi everyone,

I'm fairly new to programming, and have this project I'm doing for my father. He
asked me to control a chicken Incubator, but 16 of them. I decided to use the
dht22 sensors being it reads temp. and humidity. To keep the internal temperature
at a constant 100 Deg F, I will be using a 100w 120/220v light bulb in each of the
16 incubators. All 16 relays are controlled by a SainSmart 16ch relay board. Along
with the climate control I also have a 24v Linear actuator in each incubator to tilt
the egg trays at a 45 deg each way. This actuator tilts the tray to 45 deg every
1hour. This is where I need help, so far I can log temp and humidity from two
sensors (the rest or in the mail) and the light bulbs are turning on and off according
to set temps. The millis function is still a little hard to grasp, I've just saw my first
arduino code or any type of code, just 3 weeks ago. Anyhow, here's my code so far.
OH, thanks in advance

PS. Saintsmart lcd display is also going to be integrated, but later.

(http://img24.imageshack.us/img24/2253/imag0510i.jpg)
(http://img23.imageshack.us/img23/6269/imag0513ad.jpg)

Code: [Select]
/* 16 channel Incubator
created/ modified apr 20 2012
by Roth Ly
Also bits of code has been used from "frostin" of Arduino forum:
http://arduino.cc/forum/index.php?topic=70742.0

This code is for a 16 channel chicken incubator, where a total of


16 seperate incubator will be controlled via one Arduino Mega.
16 Dht22 senor inputs will run in to digital I/O 23,25,27...37.
A 16 channel relay board from sain smart takes care of switching
the heating element(100watt bulb) needed in each of the 16 incubators to keep
an
internal temp of 100F. Along side the sensor data and relay switching
there is also a code for turning a separate DPDT relay on and off to activate
a linear actuator every hour.

Modified Blink without Delay


Turns on and off a DPDT relay connected to a digital pin (off for 1hr, on for
1hr)
without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code.

The Blink without Delay circuit:


* Relay pin connected at pin A15 and Ground, with a TIP102 tran and 1n4004
diode.
* This relay acts as a H-bridge to on/off a linear actuator every hour.

Blink without Delay


created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
//***************************************************************************

// constants won't change. Used here to


// set pin numbers:
const int relayPin = A15; // the number of the LED pin

// Variables will change:


int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,


// will quickly become a bigger number than can be stored in an int.
long interval = 19000; // interval at which to blink (milliseconds)

#include <DHT.h>

#define DHTPIN1 23 // sets Dht22 sensor #1 at pin digital 23


#define DHTPIN2 25 // sets Dht22 sensor #2 at pin digital 25

#define DHTTYPE DHT22

DHT dht1(DHTPIN1, DHTTYPE);


DHT dht2(DHTPIN2, DHTTYPE);

#define bulbPIN1 22 // pin number for relay/heater #1


#define bulbPIN2 24 // pin number for relay/heater #2

#define TEMP_HIGH 29 //at what temp (C*) to turn off relay/heater


#define TEMP_LOW 28 //at what temp to turn on relay/heater
//#define HUMID_HIGH 60
//#define HUMID_LOW 20

float minTemp = 100;


float maxTemp = 0;

//float minHumid = 100;


//float maxHumid = 0;

int bulbValue = 0;

void setup() {
// set the digital pin as output:
pinMode(relayPin, OUTPUT);
Serial.begin(9600);
Serial.println("Program Start");
dht1.begin();// starts sensor 1
dht2.begin(); // starts sensor 2

pinMode(bulbPIN1, OUTPUT); //sets bulbPin as OUTPUT


pinMode(bulbPIN2, OUTPUT);

void loop()
{

// READ DATA
float t1 = dht1.readTemperature();
float h1 = dht1.readHumidity();
//int temperatureF = (t1 * 9 / 5) +32.5; // converts to Farenhiet, not sure
how to use properly yet

// DO THE MIN/MAX
minTemp = min(minTemp, t1);
maxTemp = max(maxTemp , t1);

// DISPLAT DATA
if (isnan(t1) || isnan(h1)){ // sensor reading check
Serial.println("sensor 1");
} else {
Serial.print("#1 Temp:");
Serial.print(t1);
Serial.println("*C");
Serial.print("#1 Humid:");
Serial.print(h1);
Serial.println("%\t");
// relay/heater
if (t1 > TEMP_HIGH) bulbValue = 1;
else if (t1 < TEMP_LOW) bulbValue = 0;
digitalWrite(bulbPIN1, bulbValue);
delay(2000); // DHT's need a delay between readings ...
}
//****************************************************
{
// READ DATA
// READ DATA
float t2 = dht2.readTemperature();
float h2 = dht2.readHumidity();
//int temperatureF = (t2 * 9 / 5) +32.5;

// DO THE MIN/MAX
minTemp = min(minTemp, t2);
maxTemp = max(maxTemp , t2);

// DISPLAT DATA
if (isnan(t2) || isnan(h2)){
Serial.println("sensor 2");
} else {

Serial.print("#2 Temp:");
Serial.print(t2);
Serial.println("*c");
Serial.print("#2 Humid:");
Serial.print(h2);
Serial.println("%\t");
// CROCKPOT
if (t2 > TEMP_HIGH) bulbValue = 1;
else if (t2 < TEMP_LOW) bulbValue = 0;
digitalWrite(bulbPIN2, bulbValue);
delay(2000); // DHT's need a delay between readings ...
}
//*****************************************************************
}
// here is where you'd put code that needs to be running all the time.

// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();

if(currentMillis - previousMillis > interval) {


// save the last time you blinked the LED
previousMillis = currentMillis;

// if the LED is off turn it on and vice-versa:


if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;

// set the LED with the ledState of the variable:


digitalWrite(relayPin, ledState);
}
}

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: strykeroz on Apr 23, 2012, 09:37 am
Hi

I've not gone through it in detail, since you say it does log the temperature and
humidity correctly for you now. Just a couple of comments.

Rather than replicating your variables 16x times for the full scale version, consider
using an array for each of them.
http://arduino.cc/en/Reference/Array
Then you can use a loop to address each in turn, which will keep your sketch
organised and easier to read. And will allow you to expand further when the time
comes by only changing a few lines.

And, in this line you have a delay which will block your code from doing anything
else for 2sec. Not that this is a long time, but if you're using the non-blocking
method (with millis) for turning the relays off and on, you may consider that here
too.

Code: [Select]

delay(2000); // DHT's need a delay between readings ...


Love the build - looks impressive !
Geoff

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: wildbill on Apr 23, 2012, 01:25 pm

You're not doing anything with minTemp and maxTemp. If you intend to, you'll
probably need to keep separate readings for each incubator - another array. Do you
plan to use the humidity data to control anything or is it just a display item?

Consider using an SD shield so you can log your data. If you have a bug in your
code, it may help to detect what's happening. Also, some kind of alarm functionality
would be nice. When the bulb fails, you likely don't have much time to replace it
before a batch of eggs is lost.

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: PaulS on Apr 23, 2012, 01:39 pm

Code: [Select]

// if the LED is off turn it on and vice-versa:


if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
Can be written much more compactly:

Code: [Select]

ledState = !ledState;

You probably do not want to be banging the relay on and off as the temperature
gets above/below the set-point, when you get to that point. Let the temperature
vary a little before toggling the relay. If the set point is 25C, for instance, turn the
relay on when the temp gets down to 24.75 and off when the temp gets to 25.25,
rather than on and off exactly at 25.00. The amount of variation is something you
can control, but keep in mind the accuracy of the sensor you are using, and the
speed at which the temperature is changed by the heat source.

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: kf2qd on Apr 23, 2012, 04:54 pm

Also - Is your heat sensor where the light shines on it? if so you may get higher
than actual air temperature readings. Make sure your sensor is warmed by the air
and not the lamp.
Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: Nikarus on Apr 23, 2012, 05:51 pm

That is one of the most organized homebrew circuit boards I have ever seen. Props
to you man.

Though using arrays definitely will make your life and following your code a bit
easier. A for loop would probably help too.
Reads sensor, calculates temp. Switches relay if needed. Moves on to next pin. And
then just does this repeatedly.

For getting the actuator to tilt the egg trays a little though. One thing, is it
supposed to be like a sudden, over a minute it does the 45 degree shift, or does it
gently go back and forth over the course of the hour? And what kind of signal does
it take to operate the actuator?

As for the millis command.


Since you're already using the basic blink without delay to turn on and off the
incubator lights I think. Its probably good to mention that you can have other
intervals to do sections of code at. Each one will need its own previous millis (so
like prevmillisincubator, prevmillistilt) and then jsut have the different while loops
activate as needed at different times.

One thing though. I don't think you can have a Millis based timer with a 2000ms
delay within your code. I'm pretty sure thatd cause a problem. You could, for
example, make it so that that delay is a millis one. If you've noticed, does you LED
on your arduino only blink every 5 seconds or is it off and on every sec? (haven't
tried putting both a delay and a timer in the loop at the same time, always figured
it'd cause problems. If it doesn't, well then I learned something coming here
today).

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: PaulS on Apr 23, 2012, 06:16 pm

Quote

One thing though. I don't think you can have a Millis based timer with a 2000ms delay
within your code. I'm pretty sure thatd cause a problem. You could, for example, make it so
that that delay is a millis one.

Sure you can. millis() is a clock. delay() uses the clock to know when it is done
wasting time.
Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: Nikarus on Apr 23, 2012, 06:59 pm

Quote from: PaulS on Apr 23, 2012, 06:16 pm

Quote

One thing though. I don't think you can have a Millis based timer with a 2000ms delay
within your code. I'm pretty sure thatd cause a problem. You could, for example, make it so
that that delay is a millis one.

Sure you can. millis() is a clock. delay() uses the clock to know when it is done wasting
time.

Hmm I always figured that a delay stopped the loop from operating for that time
though. So, if he were to have something with the 2 sec delay, but then something
that should happen every second because of a millis timer, then the millis timer
would also end up working at the 2 second mark (since itd be past the 1000ms
interval anyways). Meh i guess ill try something out when i get to my dorm later.

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: wildbill on Apr 23, 2012, 07:50 pm

Quote

Hmm I always figured that a delay stopped the loop from operating for that time though.

That is true. The point is, you can mix and match delay and millis if you want to,
but as you correctly observe in this case, the delays may interfere with the timing
you're trying to control with millis. There is no reason to avoid delay altogther - it
can be useful for debouncing for example, but in this case, of course it would be
better to control the timing of the thermometer reads using millis too.

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images


Arduino Forum
Using Arduino => Project Guidance => Topic started by: PFH11 on
Mar 24, 2015, 05:58 pm

Title: Egg Incubation,a beginners advice needed


Post by: PFH11 on Mar 24, 2015, 05:58 pm

Greetings I am a complete novice , I have been studying the variables and what I
can research from others what I want to do is create another Arduino controlled
poultry egg incubator .My concept so far
-An Arduino uno as controller
-An ethernet /sd card shield and for data storage and communication to a server ,
either rasp Pi or a laptop connection to internet, the intent here is future
development of communication wirelessly through telephony to remote access and
data management. Cell phone
-16 x 2 LCD display and keypad shield for at source display and data management
would a serial based two wire be a better choice, I already ordered the shield , I
imagine it could be modified if I needed to go serial and have fewer pins employed.
Not sure if this is right or a 20 x4 would be better , need advice
-The temperature setting and sensing would primarily be a DS18B20 sensor
sending to the Arduino which I hope could run the PID library with auto tune. PWM
temp control through a ssr . I would like to have an upper and lower limit alarm
with this
-The humidity, I hope to use a AM2302 sensor . I want on off with set limits,
control through a EM relay module. I would like to have an upper and lower limit
alarm with this. The temp function of the sensor would be utilized as a read only
second temperature check in the chamber. I am not sure if PID is relevant here as
the nature of humidity and temperature is so difficult to sense and control
accurately as it is a relative read, as well as frequency of sampling and frequency of
response being slow I expect to only be able to get at best within 2%to 5% of set
value process value variance. I don't want to have a dehumidification exhaust
happening I think this would be counter productive causing heat hysteresis
-I would want to control a dc 12 volt fan with on off proportional control PWM for
circulation, like fan speed control. Ventilation would be one aperture that was
opened and closed by hand to maintain a positive pressure and stable temp, no
sensor or controller, a minimal opening.
-I want to use a timer set up with an interval interrupt loop to control the motion of
a 12 volt DC turner motor for back and forth side to side egg turning This would
likely be seconds on minutes off looping. Off between a variable of 200 to 800
minutes, through a EM relay module
-Last to use a DS3231 RTC for recording start date , time stamping functions,and
also to use its temperature sensing to record the ambient temperature outside of
the chamber .

The primary display on LCD would be SV and PV for temperature with the SV and
PV of relative humidity,
I want to basically use they keypad to scroll through the other displayed
information and have it return to temp and humidity values when basically
running
A key scroll to another screen for turner motor motion frequency and start ,finish
dates, interval value and interrupt value
A key scroll to fan circulation speed , ambient temperature , current operating
date,start date,elapsed date, target date to stop turning eggs and expected hatch
date.

I would have a dedicated power supply for the arduino . would like it to retain
settings if the power was disrupted and reset, Any advice would be appreciated I
think I have conceived it right, now is the task to learn how to find libraries and
integrate them in some logical sequence for the five functions that need be sensed
or controlled, time, temperature ,humidity,fan speed ,and motor motion control for
the egg turning. I am hoping to learn how to write and create a working sketch for
this. I looked at the PID temperature library and it was 17 k hopefully everything
else will fit or do I need a larger set up,more pins and memory. Am I way off with
this expectation.

Title: Re: Egg Incubation,a beginners advice needed


Post by: aditya3098 on Mar 24, 2015, 06:10 pm

No, sounds good.

You don't need an ethernet/sd shield. Just use a serial line to the RPi over the UART
or USB.

You might want to get an arduino mega instead of the uno.

Use cherrypy or similar framework on the pi to write the web part, using pyserial.

Avoid much logic on the arduino, mostly put the logic on the pi and make the
arduino act as a slave to the pi. As you are just begining, you might manage better
in python than C.

Dont use a shield, just wire the devices directly instead. Its a bit tougher, but more
versatile (and potentially leaves more io pins free)

20x4 sounds better, as you can use arduino menu library (there are a bunch of
them, google it) to do some tasks.

For the fan, you could use an L293D (recommended) or L298N based motor
controller, or if you have the time, just get the IC and wire it up.

No need of RTC, if your Pi is connected to the internet. Otherwise, it might be a


good idea.

Title: Re: Egg Incubation,a beginners advice needed


Post by: aditya3098 on Mar 24, 2015, 06:13 pm
Also, about the persistant data, just serial it over to the pi and have it store and
sync it. You could use logrotate, syslogng or many other log management tools.
You could also use some kind of SMS api from the Pi. Or maybe email will do.

UPDATE: By sync, I mean the "sync" command.

Also, you could power the Pi off a battery, and probably connect the most important
sensors to an arduino promini or nano. Then use another USB cable, or the GPIO
Uart, if you didn't use it up for the MEGA, to handle your most essential sensors.
The pi could log the data, and push it when the power returns. Again, I am
assuming you are doing this for scientific data, and would like a backup.

Title: Re: Egg Incubation,a beginners advice needed


Post by: Robin2 on Mar 24, 2015, 07:40 pm

I agree 100% with the idea of doing as much of the work as possible on a Pi or a
PC.
I agree also about not using a shield.

In my opinion the Python Bottle server (http://bottlepy.org/docs/dev/index.html) is


easier to use than CherryPy.

You have not said what experience you have of programming generally or of the
Arduino in particular. If you are not already a competent programmer what you
propose involves a very steep learning curve.

I suggest that you start by writing separate Arduino programs to control each of the
accessories on its own. When you know how to work with each of them it will be
time to build them into a single project.
Leave the LCD display until last. Just use the Arduino Serial Monitor for output while
you are developing the project. The LCD code tends to obscure other aspects of the
project. Also it is easier for people here to give advice for code without LCD stuff
because they can easily try it on their own Uno of Mega.

There are many useful examples in the Arduino IDE and you may find useful ideas
in planning and implementing a program
(http://forum.arduino.cc/index.php?topic=261445.0).

...R

Title: Re: Egg Incubation,a beginners advice needed


Post by: PFH11 on Mar 24, 2015, 09:25 pm

Thank you both,I appreciate your input.it gives a better insight into what I hope to
learn. I have no experience as a programmer, I am a retiree ,and have picked up
on this PLC stuff from employing separate devices like industrial PID temp control,
pwm motor control, plc stand alone humidity control and it seemed that to
integrate them and make it data based for records and analytics would be worthy .
I have seen these integrated applications in very expensive hardware proprietary
set ups. When I found the arduino my study of it seemed to promise that by using
the libraries and some time management with the the code you could put together
and sequence a device like this, I hope that in the final stages I can use the
intranet, internet, wireless facility to make it remote. I appreciate the advice
regards the learning curve.I will start with the arduino and once that becomes
familiar think about the greater logic and communication (PI) at the integration
phase.Your critique gives a better understanding of the depth here.

Title: Re: Egg Incubation,a beginners advice needed


Post by: Greensprings on Mar 24, 2015, 11:45 pm

use an arduino yun

Title: Re: Egg Incubation,a beginners advice needed


Post by: Robin2 on Mar 25, 2015, 09:00 am

Quote from: Greensprings on Mar 24, 2015, 11:45 pm

use an arduino yun

I have recently bought a Yun but have done very little with it because I am working
on another project which, I hope, will be runnable on the Yun as well as my PC. I
don't have an RPi. AFAIK an RPi plus an Uno is about the same price as a Yun.
I am genuinely interested to learn why you suggest a Yun for this job?
(I am not trying to dispute the issue).

...R

Title: Re: Egg Incubation,a beginners advice needed


Post by: Greensprings on Mar 25, 2015, 10:42 am

Quote from: Robin2 on Mar 25, 2015, 09:00 am

I have recently bought a Yun but have done very little with it because I am working on
another project which, I hope, will be runnable on the Yun as well as my PC. I don't have an
RPi. AFAIK an RPi plus an Uno is about the same price as a Yun.

I am genuinely interested to learn why you suggest a Yun for this job?
(I am not trying to dispute the issue).

...R

Yun means cloud, and while it is in its formitive stage, there are may projects which
have already been developed to data log to the cloud, and interact with the yun
from the internet via a cell phone or other device

the yun is not that much more expensive than the uno, esp by the time you add an
ethernet, wireless or sd card shield, which all take up space, pins and processikng
power on the uno.

unless you are just trying to reinvent the wheel for the fun of it, the yun was made
to make internet access easy
Title: Re: Egg Incubation,a beginners advice needed
Post by: wildbill on Mar 25, 2015, 12:00 pm

For learning and creating the mark one version of your incubator, I suggest using
an Uno and leaving out the LCD as Robin2 suggests. Pi and Yun will add
unnecessary complexity while you're learning the basics. You should be able to get
to a functional standalone device controlling everything, possibly then adding a
serial LCD (to save pins). You can use the EEPROM to retain settings through a
power outage, but be aware of the limits on how many times you can safely write
to it.

The Uno is cheap and so less painful to replace if you destroy/damage it with a
wiring mistake. Even cheaper to repair if you have one with a socketed Atmel chip.

Once you have a basic version going, you'll be in a much better place to decide
what the final version really needs.

Maybe search the forums a bit - there have been incubator projects done before -
may give you some ideas.

Title: Re: Egg Incubation,a beginners advice needed


Post by: Robin2 on Mar 25, 2015, 12:46 pm

Quote from: Greensprings on Mar 25, 2015, 10:42 am

unless you are just trying to reinvent the wheel for the fun of it, the yun was made to make
internet access easy

That does not really address the choice between the Yun and a combination of an
RPi + Uno ? The RPi is almost certainly more versatile than a Yun.

I am not a "cloud" fan. Generally I have no wish to make my data accessible to


people all over the world.

...R

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Project Guidance => Topic started by: rvannly on
Apr 23, 2012, 07:29 am

Title: Can someone go over my code please? 16ch chicken incubator


Post by: rvannly on Apr 23, 2012, 07:29 am

Hi everyone,

I'm fairly new to programming, and have this project I'm doing for my father. He
asked me to control a chicken Incubator, but 16 of them. I decided to use the
dht22 sensors being it reads temp. and humidity. To keep the internal temperature
at a constant 100 Deg F, I will be using a 100w 120/220v light bulb in each of the
16 incubators. All 16 relays are controlled by a SainSmart 16ch relay board. Along
with the climate control I also have a 24v Linear actuator in each incubator to tilt
the egg trays at a 45 deg each way. This actuator tilts the tray to 45 deg every
1hour. This is where I need help, so far I can log temp and humidity from two
sensors (the rest or in the mail) and the light bulbs are turning on and off according
to set temps. The millis function is still a little hard to grasp, I've just saw my first
arduino code or any type of code, just 3 weeks ago. Anyhow, here's my code so far.
OH, thanks in advance

PS. Saintsmart lcd display is also going to be integrated, but later.

(http://img24.imageshack.us/img24/2253/imag0510i.jpg)
(http://img23.imageshack.us/img23/6269/imag0513ad.jpg)

Code: [Select]
/* 16 channel Incubator
created/ modified apr 20 2012
by Roth Ly
Also bits of code has been used from "frostin" of Arduino forum:
http://arduino.cc/forum/index.php?topic=70742.0

This code is for a 16 channel chicken incubator, where a total of


16 seperate incubator will be controlled via one Arduino Mega.
16 Dht22 senor inputs will run in to digital I/O 23,25,27...37.
A 16 channel relay board from sain smart takes care of switching
the heating element(100watt bulb) needed in each of the 16 incubators to keep
an
internal temp of 100F. Along side the sensor data and relay switching
there is also a code for turning a separate DPDT relay on and off to activate
a linear actuator every hour.

Modified Blink without Delay


Turns on and off a DPDT relay connected to a digital pin (off for 1hr, on for
1hr)
without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code.

The Blink without Delay circuit:


* Relay pin connected at pin A15 and Ground, with a TIP102 tran and 1n4004
diode.
* This relay acts as a H-bridge to on/off a linear actuator every hour.
Blink without Delay
created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
//***************************************************************************

// constants won't change. Used here to


// set pin numbers:
const int relayPin = A15; // the number of the LED pin

// Variables will change:


int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,


// will quickly become a bigger number than can be stored in an int.
long interval = 19000; // interval at which to blink (milliseconds)

#include <DHT.h>

#define DHTPIN1 23 // sets Dht22 sensor #1 at pin digital 23


#define DHTPIN2 25 // sets Dht22 sensor #2 at pin digital 25

#define DHTTYPE DHT22

DHT dht1(DHTPIN1, DHTTYPE);


DHT dht2(DHTPIN2, DHTTYPE);

#define bulbPIN1 22 // pin number for relay/heater #1


#define bulbPIN2 24 // pin number for relay/heater #2

#define TEMP_HIGH 29 //at what temp (C*) to turn off relay/heater


#define TEMP_LOW 28 //at what temp to turn on relay/heater

//#define HUMID_HIGH 60
//#define HUMID_LOW 20

float minTemp = 100;


float maxTemp = 0;

//float minHumid = 100;


//float maxHumid = 0;

int bulbValue = 0;

void setup() {
// set the digital pin as output:
pinMode(relayPin, OUTPUT);
Serial.begin(9600);
Serial.println("Program Start");
dht1.begin();// starts sensor 1
dht2.begin(); // starts sensor 2

pinMode(bulbPIN1, OUTPUT); //sets bulbPin as OUTPUT


pinMode(bulbPIN2, OUTPUT);

void loop()
{

// READ DATA
float t1 = dht1.readTemperature();
float h1 = dht1.readHumidity();
//int temperatureF = (t1 * 9 / 5) +32.5; // converts to Farenhiet, not sure
how to use properly yet

// DO THE MIN/MAX
minTemp = min(minTemp, t1);
maxTemp = max(maxTemp , t1);

// DISPLAT DATA
if (isnan(t1) || isnan(h1)){ // sensor reading check
Serial.println("sensor 1");
} else {
Serial.print("#1 Temp:");
Serial.print(t1);
Serial.println("*C");
Serial.print("#1 Humid:");
Serial.print(h1);
Serial.println("%\t");
// relay/heater
if (t1 > TEMP_HIGH) bulbValue = 1;
else if (t1 < TEMP_LOW) bulbValue = 0;
digitalWrite(bulbPIN1, bulbValue);
delay(2000); // DHT's need a delay between readings ...
}
//****************************************************
{
// READ DATA
// READ DATA
float t2 = dht2.readTemperature();
float h2 = dht2.readHumidity();
//int temperatureF = (t2 * 9 / 5) +32.5;

// DO THE MIN/MAX
minTemp = min(minTemp, t2);
maxTemp = max(maxTemp , t2);

// DISPLAT DATA
if (isnan(t2) || isnan(h2)){
Serial.println("sensor 2");
} else {

Serial.print("#2 Temp:");
Serial.print(t2);
Serial.println("*c");
Serial.print("#2 Humid:");
Serial.print(h2);
Serial.println("%\t");
// CROCKPOT
if (t2 > TEMP_HIGH) bulbValue = 1;
else if (t2 < TEMP_LOW) bulbValue = 0;
digitalWrite(bulbPIN2, bulbValue);
delay(2000); // DHT's need a delay between readings ...
}
//*****************************************************************
}
// here is where you'd put code that needs to be running all the time.

// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();

if(currentMillis - previousMillis > interval) {


// save the last time you blinked the LED
previousMillis = currentMillis;

// if the LED is off turn it on and vice-versa:


if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;

// set the LED with the ledState of the variable:


digitalWrite(relayPin, ledState);
}
}

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: strykeroz on Apr 23, 2012, 09:37 am
Hi

I've not gone through it in detail, since you say it does log the temperature and
humidity correctly for you now. Just a couple of comments.

Rather than replicating your variables 16x times for the full scale version, consider
using an array for each of them.
http://arduino.cc/en/Reference/Array
Then you can use a loop to address each in turn, which will keep your sketch
organised and easier to read. And will allow you to expand further when the time
comes by only changing a few lines.

And, in this line you have a delay which will block your code from doing anything
else for 2sec. Not that this is a long time, but if you're using the non-blocking
method (with millis) for turning the relays off and on, you may consider that here
too.

Code: [Select]

delay(2000); // DHT's need a delay between readings ...


Love the build - looks impressive !
Geoff

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: wildbill on Apr 23, 2012, 01:25 pm

You're not doing anything with minTemp and maxTemp. If you intend to, you'll
probably need to keep separate readings for each incubator - another array. Do you
plan to use the humidity data to control anything or is it just a display item?

Consider using an SD shield so you can log your data. If you have a bug in your
code, it may help to detect what's happening. Also, some kind of alarm functionality
would be nice. When the bulb fails, you likely don't have much time to replace it
before a batch of eggs is lost.

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: PaulS on Apr 23, 2012, 01:39 pm

Code: [Select]

// if the LED is off turn it on and vice-versa:


if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
Can be written much more compactly:

Code: [Select]

ledState = !ledState;

You probably do not want to be banging the relay on and off as the temperature
gets above/below the set-point, when you get to that point. Let the temperature
vary a little before toggling the relay. If the set point is 25C, for instance, turn the
relay on when the temp gets down to 24.75 and off when the temp gets to 25.25,
rather than on and off exactly at 25.00. The amount of variation is something you
can control, but keep in mind the accuracy of the sensor you are using, and the
speed at which the temperature is changed by the heat source.

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: kf2qd on Apr 23, 2012, 04:54 pm

Also - Is your heat sensor where the light shines on it? if so you may get higher
than actual air temperature readings. Make sure your sensor is warmed by the air
and not the lamp.
Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: Nikarus on Apr 23, 2012, 05:51 pm

That is one of the most organized homebrew circuit boards I have ever seen. Props
to you man.

Though using arrays definitely will make your life and following your code a bit
easier. A for loop would probably help too.
Reads sensor, calculates temp. Switches relay if needed. Moves on to next pin. And
then just does this repeatedly.

For getting the actuator to tilt the egg trays a little though. One thing, is it
supposed to be like a sudden, over a minute it does the 45 degree shift, or does it
gently go back and forth over the course of the hour? And what kind of signal does
it take to operate the actuator?

As for the millis command.


Since you're already using the basic blink without delay to turn on and off the
incubator lights I think. Its probably good to mention that you can have other
intervals to do sections of code at. Each one will need its own previous millis (so
like prevmillisincubator, prevmillistilt) and then jsut have the different while loops
activate as needed at different times.

One thing though. I don't think you can have a Millis based timer with a 2000ms
delay within your code. I'm pretty sure thatd cause a problem. You could, for
example, make it so that that delay is a millis one. If you've noticed, does you LED
on your arduino only blink every 5 seconds or is it off and on every sec? (haven't
tried putting both a delay and a timer in the loop at the same time, always figured
it'd cause problems. If it doesn't, well then I learned something coming here
today).

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: PaulS on Apr 23, 2012, 06:16 pm

Quote

One thing though. I don't think you can have a Millis based timer with a 2000ms delay
within your code. I'm pretty sure thatd cause a problem. You could, for example, make it so
that that delay is a millis one.

Sure you can. millis() is a clock. delay() uses the clock to know when it is done
wasting time.
Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: Nikarus on Apr 23, 2012, 06:59 pm

Quote from: PaulS on Apr 23, 2012, 06:16 pm

Quote

One thing though. I don't think you can have a Millis based timer with a 2000ms delay
within your code. I'm pretty sure thatd cause a problem. You could, for example, make it so
that that delay is a millis one.

Sure you can. millis() is a clock. delay() uses the clock to know when it is done wasting
time.

Hmm I always figured that a delay stopped the loop from operating for that time
though. So, if he were to have something with the 2 sec delay, but then something
that should happen every second because of a millis timer, then the millis timer
would also end up working at the 2 second mark (since itd be past the 1000ms
interval anyways). Meh i guess ill try something out when i get to my dorm later.

Title: Re: Can someone go over my code please? 16ch chicken incubator
Post by: wildbill on Apr 23, 2012, 07:50 pm

Quote

Hmm I always figured that a delay stopped the loop from operating for that time though.

That is true. The point is, you can mix and match delay and millis if you want to,
but as you correctly observe in this case, the delays may interfere with the timing
you're trying to control with millis. There is no reason to avoid delay altogther - it
can be useful for debouncing for example, but in this case, of course it would be
better to control the timing of the thermometer reads using millis too.

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images


Arduino Forum
Using Arduino => Programming Questions => Topic started by:
ahmedlz on Apr 09, 2017, 04:59 pm

Title: programing problem


Post by: ahmedlz on Apr 09, 2017, 04:59 pm

hi guys i started making a full automatic egg incubator i use a dht11 temperature
and humidity sensor
for temperature everything are ok i will send a photo about the program i wrote
and scematic
but i have a problem with humidity
i need to make a servo motor turn from 0 degree to 180 and return to 0 if the
humidity level are less then 40% and i want it to repeat that until the humidity
reach 40% , then the servo motor stop in 0 degree

please can anyone help me in programming that because i'm noob in arduino world
thx

Note
the program in the photo work 100% i just need to add the servo motor part
the wiring in the schematic are not the same in the program

this is the code

Code: [Select]
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <dht.h>
#include <Servo.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4,5, 6, 7, 3, POSITIVE);


dht DHT;

#define DHT11_PIN 7
int pinOut = 8;
Servo myservo;
void setup()
{
lcd.begin(16, 2);
Serial.begin(9600);
pinMode(8, OUTPUT);
myservo.attach(9);
}

void loop()
{

int chk = DHT.read11(DHT11_PIN);


lcd.setCursor(0,0);
lcd.print("Temp: ");
lcd.print(DHT.temperature);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Humidity: ");
lcd.print(DHT.humidity);
lcd.print("%");
delay(1000);
if (DHT.temperature<=25){
digitalWrite(pinOut, HIGH);
}
else {
digitalWrite(pinOut, LOW);
}
delay(500);
}

Title: Re: programing problem


Post by: AWOL on Apr 09, 2017, 05:13 pm

Post your code.

Title: Re: programing problem


Post by: J-M-L on Apr 09, 2017, 05:13 pm

Why don't you post the code (within code tags) versus a picture we can't see...
Title: Re: programing problem
Post by: ahmedlz on Apr 09, 2017, 05:16 pm

Code: [Select]

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <dht.h>
#include <Servo.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4,5, 6, 7, 3, POSITIVE);


dht DHT;

#define DHT11_PIN 7
int pinOut = 8;
Servo myservo;

void setup()
{
lcd.begin(16, 2);
Serial.begin(9600);
pinMode(8, OUTPUT);
myservo.attach(9);
}

void loop()
{

int chk = DHT.read11(DHT11_PIN);


lcd.setCursor(0,0);
lcd.print("Temp: ");
lcd.print(DHT.temperature);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Humidity: ");
lcd.print(DHT.humidity);
lcd.print("%");
delay(1000);
if (DHT.temperature<=25){
digitalWrite(pinOut, HIGH);
}
else {
digitalWrite(pinOut, LOW);
}
delay(500);
}

Title: Re: programing problem


Post by: J-M-L on Apr 09, 2017, 05:24 pm

Quote

I just need to add the servo motor part

So where is your attempt? There are tons of on line egg incubator projects - did
you check any?

Title: Re: programing problem


Post by: ahmedlz on Apr 09, 2017, 05:34 pm

Quote from: J-M-L on Apr 09, 2017, 05:24 pm

So where is your attempt? There are tons of on line egg incubator projects - did you check
any?

i search for egg incubator projects but i didn't find anyone did it with arduino on
youtube or in projects hub or in a web site (i mean controlling humidity not all the
incubator)
so i wrote that code by collecting information from many places

Title: Re: programing problem


Post by: J-M-L on Apr 09, 2017, 05:57 pm

first hit on Google... (https://github.com/quantenschaum/egg-incubator)

Quote
Egg Incubator

Is an arduino controlled incubator for chicken's eggs. It's purpose is to keep temperature
and humidity at defined values, so that the eggs are incubated and the chicks finally hatch
after some days.

Does this help?

Title: Re: programing problem


Post by: ahmedlz on Apr 09, 2017, 07:46 pm
Quote from: J-M-L on Apr 09, 2017, 05:57 pm
first hit on Google... (https://github.com/quantenschaum/egg-incubator)

Does this help?

i know that i just want to make a servo motor turn when the humidity level are less
then 40% i need a code

if (DHT.humidity<40)
{

what i will wrote here that is the problem

}
read my topic again you will understand bro :)
Title: Re: programing problem
Post by: J-M-L on Apr 09, 2017, 08:02 pm

Ah - then it's the servo documentation


(https://www.arduino.cc/en/reference/servo) you need? Look at the sweep
example

video tutorial (https://www.youtube.com/watch?v=jVZJy6OlwcA)

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Programming Questions => Topic started by:
hackertom on Jul 21, 2015, 10:35 am

Title: Temperature Control of a Light Bulb [HELP]


Post by: hackertom on Jul 21, 2015, 10:35 am

I want to create this project >

(http://ctms.engin.umich.edu/CTMS/Content/Activities/figures/arduinoBulb.png)
if the temperature controller is
> 37.8 C then close the light
if the temperature controller is
< 37.7 open the Light

any help to programming this fuction?

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: UKHeliBob on Jul 21, 2015, 10:50 am

Start with something easy. Do you know how to read the value of the temperature
sensor ?
Do you already have a temperature sensor and, if so, which one ?
Have you done anything with the Arduino previously ?

Do you know what you are doing when it comes to mains voltage, it can be lethal.

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: Docedison on Jul 21, 2015, 11:07 am

Especially placing a switch or relay contact in the 240 VAC Return or Neutral Wire...
VERY BAD PRACTICE..

..

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: tammytam on Jul 21, 2015, 12:07 pm

Ensure your relay is opto isolated.

Change your relay to switch on the hot side as opposed to the neutral side.

Adding a small cap between Vin and GND for your sensor will most likely give you
better results, as this will help reduce RFI.

Then check this site out on how to convert your analog signal into tempterature,
premise is analog returns 0-1023, which is quantised 0-5v, your sensor gives you
values between 0-1.75v for its temperature range:

Using a temp sensor (https://learn.adafruit.com/tmp36-temperature-sensor/using-


a-temp-sensor)
Then the programming part should be straightforward, simple case of checking if
the return temperature is less than set amount and sending the signal to open the
relay.

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: ardnut on Jul 21, 2015, 12:23 pm

My advice would be don't play with mains electricity if you don't know what you're
doing ( which clearly you don't ).

Experiment with LEDs or 12v bulbs instead.

Anything powerful enough to create heat will probalby have enought power to be
fire risk. Learn about fuses.

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: ardnut on Jul 21, 2015, 12:35 pm

Are really trying to control the temp of the light bulb envelop ?

My guess from the temperature values is this is some kind of incubator so you
maybe need to be testing the air temp not the bulb temp.

Again, find out what you're doing before playing with potentially lethal equipment,
otherwise you'll end up frying the baby, the hatchlings or yourself.
:o

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: ardnut on Jul 21, 2015, 12:44 pm

Quote from: tammytam on Jul 21, 2015, 12:07 pm

Ensure your relay is opto isolated.

Change your relay to switch on the hot side as opposed to the neutral side.

Adding a small cap between Vin and GND for your sensor will most likely give you better
results, as this will help reduce RFI.

Then check this site out on how to convert your analog signal into tempterature, premise is
analog returns 0-1023, which is quantised 0-5v, your sensor gives you values between 0-
1.75v for its temperature range:

Using a temp sensor (https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-


sensor)
Then the programming part should be straightforward, simple case of checking if the return
temperature is less than set amount and sending the signal to open the relay.

The arduino has an internal temp sensor which is accessible via one of the ADC
inputs ( one not connected to an external pin) , so maybe strapping the arduino
close to the bulb would remove the need to interface with an external sensor.

If this is for incubating chicken eggs you want to make the bulb more distant and
sense the air temp. They don't want be irradiated from one side but cold on the
other.

If you're just looking for a fun project to learn about Ardiuino and electronics, don't
start by experimenting with living things.

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: hackertom on Jul 21, 2015, 06:42 pm

i use the RHT03 temperature and humility sensor, and the code to read temp +
humanity in serial monitor is :

Quote
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2 // what pin we're connected to

// Uncomment whatever type you're using!


//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V


// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.


// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");

dht.begin();
}

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);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Compute heat index in Fahrenheit (the default)


float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
}

now i need if / else function? if temperature is < = 27.5 C open lamp (gnd + pin 9
= 1 close ssr) else if temperature is > 27.8 open the ssr gnd + pin 9 = 0 ?

is that correct??

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: aarg on Jul 21, 2015, 07:50 pm

Quote from: hackertom on Jul 21, 2015, 06:42 pm

now i need if / else function? if temperature is < = 27.5 C open lamp (gnd + pin 9 = 1 close
ssr) else if temperature is > 27.8 open the ssr gnd + pin 9 = 0 ?
is that correct??

Yes.
But you should google hysteresis.

Title: Re: Temperature Control of a Light Bulb [HELP]


Post by: PaulS on Jul 21, 2015, 11:30 pm

Code: [Select]

// Read temperature as Celsius (the default)


float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);

Haven't figured out which system your country uses yet?

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines


Text only | Text with Images

Arduino Forum
Using Arduino => Programming Questions => Topic started by:
Rooster14250 on Mar 16, 2015, 05:12 pm

Title: Making Servo Move 30 Degrees and Stop


Post by: Rooster14250 on Mar 16, 2015, 05:12 pm

Hi. I am working on an incubator project, and am trying to get a servo to move 30


degrees (to open a vent) and stop based on humidity. Then if the humidity is still to
high, to open another 30 degrees and stop (doing this until it reaches 180 degrees
or the humidity regulates). I have a dht22 sensor attached to it right now to read
the humidity and temp. I am using the basic servo sweep to fill space right now. Is
there any way to have this function with a servo?
Here is the sketch:

// Example testing sketch for various DHT humidity/temperature sensors


// Written by ladyada, public domain
#include <Servo.h>

Servo myservo;
int pos = 0;

#include "DHT.h"

#define DHTPIN 2 // what pin we're connected to

// Uncomment whatever type you're using!


//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V


// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor for normal 16mhz Arduino


DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold. It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value. The default for a 16mhz AVR is a value of 6. For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

void setup(){
Serial.begin(9600);
Serial.println("Hello Future Incubator!");
dht.begin();
myservo.attach(4);

pinMode(3, OUTPUT);
}

void loop() {
// Wait a few seconds between measurements.
delay(200);

// 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
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

if ((f) < 80) {


digitalWrite(3, HIGH);
}
else
{
digitalWrite(3, LOW);
}

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(f);
Serial.print(" *F\t");

if ((h) > 55) {


for(pos = 0; pos <= 30; pos += 30) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 30; pos>=0; pos-=30) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
} else
{
}
}

Title: Re: Making Servo Move 30 Degrees and Stop


Post by: Robin2 on Mar 16, 2015, 07:34 pm

What would be wrong with something simple like

Code: [Select]
if (humid < lowVal) {
servo.write(0); // closed
}
else if (humid < medVal) {
servo.write(30);
}
else if (humid < highVal) {
servo.write(60);
}
else {
servo.write(90);
}

...R

Title: Re: Making Servo Move 30 Degrees and Stop


Post by: Rooster14250 on Mar 16, 2015, 08:57 pm

Thanks! That really cleared things up!

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines


Text only | Text with Images

Arduino Forum
Forum 2005-2010 (read only) => General => Exhibition => Topic
started by: sparkyt on Dec 12, 2010, 02:43 pm

Title: Egg Incubator


Post by: sparkyt on Dec 12, 2010, 02:43 pm

Hi all,
here is my project.
The atmega328 controls a 24v lamp (pwm), a 12v pc fan (pwm) and reads a SHT1x
temp/hum sensor. A standard laptop power supply is used.
One button and one potentiometer menu system (thanx tronixstuff) is used for user
input.
Internal logger for calculating average temp and hum (last hour, taking samples
every 10min)
User can set:
-temp levels
- lamp intensity (in digital steps)
- fan rpm (in digital steps)
- calculate avg temp
- calculate avg hum

here is the circuit

http://img213.imageshack.us/f/frontbhp.jpg/

and the box

http://img152.imageshack.us/f/boxf.jpg/

left to do:
- incorporate a step motor and control
- find a way (hardware) to produce humidity, and control

my software knowledge is limited so feel free to correct my sketch,


although it works fine, i am sure i have redundant code.
cant wait to here your thoughts

Title: Re: Egg Incubator


Post by: sparkyt on Dec 12, 2010, 02:53 pm

here is the sketch

Code: [Select]

// include the library code needed


#include <LiquidCrystal.h>
#include <SHT1x.h>

// initialize the lcd with the numbers of the interface pins


LiquidCrystal lcd(12, 13, 7, 4, 8, 19);

//initialize the SHT1x sensor


#define dataPin 1 //data connection to pin 1
#define clockPin 11 //clock connection to pin 11
SHT1x sht1x(dataPin, clockPin); //instantiate SHT1x sensor

// constants will not change


const int fanpin = 9; //fan connected to digital pin
9
const int lampin = 10; //lamp connected to pin 10
//const int buttonplus = 2; //button spare with interupt!
const int dialpin = A1; //potentiometer at analog 1
const int button_menu = 3; //button for menu at pin 3
//variables will change
int i=0; //used for taking samples,
logger
int fanval = 400; //to store the value of the
potentiometer
int tempval_min = 60; //to store the min value for the
lamp pwm
int tempval_max = 180; //to store the max value for the
lamp pwm
int tempval_avg = 100; //to store the avg value for the
lamp pwm
int tempval = 100; //to store the value for the
lamp pwm
int stepval = 0; //to store the value for
stepping lights
float fan_step; //to store the value for
stepping fan
float valplus = 35.7; //variable to store max allowed
temp
float valminus = 35.2; //variable to store min allowed
temp
float temp_c; //float number to measure
temperature with library
float humidity; //float number to measure
humidity with library
float new_temp_minus; //for calculation of min temp
after user input
float new_temp_plus; //for calculation of max temp
after user input
float diff; //for calculation of temp limits
after user input
float valplus_final; //for calculation of max temp
after user input
float valminus_final; //for calculation of min temp
after user input
float temp_data[] = {0,0,0,0,0,0}; //array to store temp samples,
logger
float hum_data[] = {0,0,0,0,0,0}; //array to store hum samples,
logger
float sum_temp = 0; //for calculation of all samples
taken, logger
float avg_temp = 0; //for calculation and display,
logger
float sum_hum = 0; //for calculation of all samples
taken, logger
float avg_hum = 0; //for calculation and display,
logger

// the following variables are long's because the time, measured in


miliseconds,
// will quickly become a bigger number than can be stored in an int.
long prevMils_1 = 0; //used for the delay loop, TO
NOT USE delay()
long prevMils_2 = 0; //used for the delay loop, TO
NOT USE delay()
long interval_1 = 5000; //delay for check and adjust
temp, 5sec
long interval_2 = 600000; //delay for taking samples,
10 min, display last hour avg

void setup()
{
pinMode(fanpin, OUTPUT); //set pin 9 as output
pinMode(lampin, OUTPUT); //set pin 10 as output
pinMode(button_menu, INPUT); //set pin 3 as input
//pinMode(buttonplus, INPUT); //set pin 2 as input

lcd.begin(16, 2); // set up the LCD's number of rows


and columns
lcd.clear();
lcd.print("ReklaDance"); // display a message to the LCD
delay(500);
lcd.setCursor(0, 1); // set the cursor to column 0, line
1
lcd.print(" Electronics"); // display a message to the LCD.
delay(3000);
lcd.clear();
lcd.print("Setting up..."); // display a message to the LCD
delay(1000);
lcd.setCursor(0, 1); // set the cursor to column 0, line
1
lcd.print("Ready Nikolas!"); // display a message to the LCD.
delay(500);
}

void loop()
{
//turn fan on
analogWrite(fanpin, fanval / 4); // analogRead value go from 0 to
1023, analogWrite value from 0 to 255

//turn lamp on
analogWrite(lampin, tempval); //about 45% duty cycle, at startup

// Read values from the sensor


temp_c = sht1x.readTemperatureC();
humidity = sht1x.readHumidity();

valplus_final = new_temp_plus + diff; //calculation of the final


value
valminus_final = new_temp_minus; //exageration

// read the state of the menu button


if (digitalRead(button_menu) == HIGH)
{
delay(200);
displaymenu(); //call to the menu routine
}

//use local variable for not using the delay() function


unsigned long curMils_1 = millis(); //check to see if the
difference between the current time and
if (curMils_1 - prevMils_1 > interval_1) { //last time you checked is
bigger than the interval set
prevMils_1 = curMils_1; //save the last time you
checked

//loop to set the temperature betweem user input


if (temp_c<valminus_final) //check if temp is lower
than,say 37.2
{
tempval=tempval_max; //set to about 100% duty
cycle for pwm lamp
}
else if(temp_c>valplus_final) //check if temp is higher
than, say 37.7
{
tempval=tempval_min; //set to about 50% duty
cycle for pwm lamp
}
else //temp is between, say 37.2
and 37.7
{
tempval=tempval_avg; //set to about 75% duty
cycle for pwm lamp
}
}

//use local variable for not using the delay() function


unsigned long curMils_2 = millis(); //check to see if the
difference between the current time and
if (curMils_2 - prevMils_2 > interval_2) { //last time you checked is
bigger than the interval set
prevMils_2 = curMils_2; //save the last time you
checked

//LOGGER, without the need of any external hardware


if (i<=5) //loop for taking samples
{
temp_data[i] = 0; //set all samples for
temperature to zero
hum_data[i] = 0; //set all samples for
humidity to zero
delay(100);
temp_data[i] = temp_c; //6 samples for temperature
hum_data[i] = humidity; //6 samples for humidity
i = i++;
}
if (i>5) //loop to make sure that we
wont
{ //write any sample outside
the specified array
i=0;
}
}

//display the values


lcd.clear();
lcd.setCursor(0, 0); // set the cursor to column
0, line 0
lcd.print("T:"); // display the temperature
to the lcd
lcd.print(temp_c, 1);
lcd.print("C");
lcd.print(" ");
lcd.print(valminus_final, 0); //display the user input temp
levels
lcd.print("-");
lcd.print(valplus_final, 0);
lcd.setCursor(0, 1); // set the cursor to column
0, line 1
lcd.print("H:"); // display the humidity to
the lcd
lcd.print(humidity);
lcd.print("%");
lcd.print(" L"); //display the user input
light step
lcd.print(stepval);
lcd.print("-F"); //display the user input fan
step
lcd.print(fan_step);
}

Title: Re: Egg Incubator


Post by: sparkyt on Dec 12, 2010, 02:54 pm

and the rest

Code: [Select]

// rangemax is the number of values in your range, e.g. if you want 0~9, set
rangemax to be '10'
// dialpin is the analog pin number connected to the potentiometer to read
int readdial(int rangemax, int dialpin)
{
int kv=0; //used for calculation
int kr=0; //used for calculation
int kb=0; //used for calculation
float a=0; //used for calculation
float rd=0; //used for calculation
rd=1023/rangemax;
kb=analogRead(dialpin); // read potentiometer
connected to analog pin 1
a=kb/rd;
kr=int(a);
if (kr>rangemax)
{
kr=rangemax;
}
return kr;
}

// display the menu options, selectable by using the knob


void displaymenu()
{
delay(300); // for debounce
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Turn knob slowly"); //print msg
lcd.setCursor(0,1);
lcd.print("to select option");
delay(2000);
while (digitalRead(button_menu)==LOW) //until user presses button
stay in this loop
{
if (readdial(7,1)==0) { //from readdial, we get 7
menu options
lcd.clear(); //option 1
lcd.setCursor(0,0);
lcd.print("Set Temperature");
}
else if (readdial(7,1)==1) { //option 2
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Set Fan RPM");
}
else if (readdial(7,1)==2) { //option 3
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Set Lamp PWM");
}
else if (readdial(7,1)==3) { //option 4
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Calc Average");
lcd.setCursor(0, 1);
lcd.print("Temperature?");
}
else if (readdial(7,1)==4) { //option 5
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Calc Average");
lcd.setCursor(0, 1);
lcd.print("Humidity?");
}
else if (readdial(7,1)==5) { //option 6
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Set Temperature");
lcd.setCursor(0, 1);
lcd.print("Difference");
}
else if (readdial(7,1)==6) { //option 7
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" exit menu ");
}
delay(100); // stop screen flicker
}
switch(readdial(7,1))
{
case 0:
set_temp(); //call the routine for setting
temperature levels
break;
case 1:
set_rpm(); //call the routine for setting
fan steps
break;
case 2:
set_step(); //call the routine for setting
light steps
break;
case 3:
calc_avg_temp(); //call the routine to calculate
average temp
break;
case 4:
calc_avg_hum(); //call the routine to calculate
average humidity
break;
case 5:
set_temp_dif(); //call the routine for setting
temp difference
break;
}
}

//All 7 routines for the menu system


//Setting temperature levels from 35-36 to 44-45 (10 menu options)
void set_temp()
{
delay(300);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Set Temp. Range");
while (digitalRead(button_menu)==LOW)
{
if (readdial(10,1)==0) //from readdial, we get 10 menu
options
{
new_temp_plus = valplus; //from 35-36
new_temp_minus = valminus;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==1) //from 36-37
{
new_temp_plus = valplus +1;
new_temp_minus = valminus + 1;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==2) //from 37-38
{
new_temp_plus = valplus + 2;
new_temp_minus = valminus + 2;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==3) //from 38-39
{
new_temp_plus = valplus + 3;
new_temp_minus = valminus + 3;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==4) //from 39-40
{
new_temp_plus = valplus + 4;
new_temp_minus = valminus + 4;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==5) //from 40-41
{
new_temp_plus = valplus + 5;
new_temp_minus = valminus + 5;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==6) //from 41-42
{
new_temp_plus = valplus + 6;
new_temp_minus = valminus + 6;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==7) //from 42-43
{
new_temp_plus = valplus + 7;
new_temp_minus = valminus + 7;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==8) //from 43-44
{
new_temp_plus = valplus + 8;
new_temp_minus = valminus + 8;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
else if (readdial(10,1)==9) //from 44-45
{
new_temp_plus = valplus + 9;
new_temp_minus = valminus + 9;
lcd.setCursor(0, 1);
lcd.print("From ");
lcd.print(new_temp_minus, 0);
lcd.print(" to ");
lcd.print(new_temp_plus, 0);
delay(100);
}
}
}
//Seting the difference for temperature levels
//ex. either 37-38 or 37-39
void set_temp_dif()
{
delay(300);
lcd.setCursor(0,0);
lcd.print("Set Temp. Diff.");
while (digitalRead(button_menu)==LOW)
{
if (readdial(5,1)==0) //from readdial, we get 5 menu
options
{ //1 degree celcius diff
diff = readdial(5,1);
lcd.setCursor(0, 1);
lcd.print("One(1) degree");
delay(100);
}
else if (readdial(5,1)==1) //2 degrees celcius diff
{
diff = readdial(5,1);
lcd.setCursor(0, 1);
lcd.print("Two(2) degrees");

delay(100);
}
else if (readdial(5,1)==2) //3 degrees celcius diff
{
diff = readdial(5,1);
lcd.setCursor(0, 1);
lcd.print("Three(3) degrees");
delay(100);
}
else if (readdial(5,1)==3) //4 degrees celcius diff
{
diff = readdial(5,1);
lcd.setCursor(0, 1);
lcd.print("Four(4) degrees");
delay(100);
}
else if (readdial(5,1)==4) //5 degrees celcius diff
{
diff = readdial(5,1);
lcd.setCursor(0, 1);
lcd.print("Five(5) degrees");
delay(100);
}
}
}

Title: Re: Egg Incubator


Post by: sparkyt on Dec 12, 2010, 02:56 pm

and the last bit

Code: [Select]

//Setting the Light Intensity, in 5 steps


void set_step()
{
delay(300);
lcd.setCursor(0,0);
lcd.print("Set Step Light");
while (digitalRead(button_menu)==LOW)
{
if (readdial(5,1)==0) //from readdial, we get 5 menu
options
{
stepval = readdial(5,1); //step 0, lowest values
tempval_min = 40;
tempval_max = 120;
tempval_avg = 60;
lcd.setCursor(0, 1);
lcd.print("Step 0");
delay(100);
}
else if (readdial(5,1)==1) //step 1
{
stepval = readdial(5,1);
tempval_min = 50;
tempval_max = 150;
tempval_avg = 80;
lcd.setCursor(0, 1);
lcd.print("Step 1");
delay(100);
}
else if (readdial(5,1)==2) //step 2
{
stepval = readdial(5,1);
tempval_min = 60;
tempval_max = 180;
tempval_avg = 100;
lcd.setCursor(0, 1);
lcd.print("Step 2");
delay(100);
}
else if (readdial(5,1)==3) //step 3
{
stepval = readdial(5,1);
tempval_min = 70;
tempval_max = 210;
tempval_avg = 120;
lcd.setCursor(0, 1);
lcd.print("Step 3");
delay(100);
}
else if (readdial(5,1)==4) //step 4
{
stepval = readdial(5,1);
tempval_min = 100;
tempval_max = 240;
tempval_avg = 180;
lcd.setCursor(0, 1);
lcd.print("Step 4");
delay(100);
}
}
}

//Setting the fan rpm, in 4 steps


void set_rpm()

{
delay(300);
lcd.setCursor(0,0);
lcd.print("Set Fan RPM");
while (digitalRead(button_menu)==LOW)
{
if (readdial(4,1)==0) //from readdial, we get 4 menu
options
{ //step 0
fanval = 200;
fan_step = readdial(4,1);
lcd.setCursor(0, 1);
lcd.print("Step 0");
delay(100);
}
else if (readdial(4,1)==1) //step 1
{
fanval = 350;
fan_step = readdial(4,1);
lcd.setCursor(0, 1);
lcd.print("Step 1");
delay(100);
}
else if (readdial(4,1)==2) //step 2
{
fanval = 500;
fan_step = readdial(4,1);
lcd.setCursor(0, 1);
lcd.print("Step 2");
delay(100);
}
else if (readdial(4,1)==3) //step 3
{
fanval = 700;
fan_step = readdial(4,1);
lcd.setCursor(0, 1);
lcd.print("Step 3");
delay(100);
}
}
}

//Calculating average temperature for LOGGER


void calc_avg_temp()
{
delay(300);
sum_temp = 0; //reset the sum
int c=0;
for (c=0; c<=5; c++)
{
sum_temp = sum_temp + temp_data[c]; //calculate sum of samples
taken
delay(10);
}
if (c>5) //loop to make sure that we
wont
{ //read any data outside the
specified array
c=0;
}
delay(500);
avg_temp = 0; //reset the average
temperature
delay(100);
avg_temp = sum_temp/6; //calculate average of
samples taken
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Last Hour"); //display info
lcd.setCursor(0, 1);
lcd.print("Avg Temp:");
lcd.print(avg_temp, 1);
lcd.print("C");
delay(3000);

//Calculate average humidity for LOGGER


void calc_avg_hum()
{
delay(300);
sum_hum = 0; //reset the sum
int d=0;
for (d=0; d<=5; d++)
{
sum_hum = sum_hum + hum_data[d]; //calculate sum of samples
taken
delay(10);
}
if (d>5)
{
d=0;
}
delay(500);
avg_hum = 0; //reset the average
temperature
delay(100);
avg_hum = sum_hum/6; //calculate average of
samples taken
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Last Hour"); //display info
lcd.setCursor(0, 1);
lcd.print("Avg Hum:");
lcd.print(avg_hum, 2);
lcd.print("%");
delay(3000);
}

/*if we get hardware for producing humidity...

void set_hum() {
}
void set_hum_dif() {
}
*/

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Project Guidance => Topic started by: AbdouRetro
on May 31, 2011, 10:11 pm

Title: Industrial Egg Incubator with Arduino.


Post by: AbdouRetro on May 31, 2011, 10:11 pm

Hello everyone,
I'd start by saying that I'm very amazed with community here, very helpful indeed.
I am only sharing ideas here, and getting contributions to make my project more
efficient.

The incubator I'll be building will host 19,200 eggs. This might sound like a lot, but
my family already owns a business and has the machines going. The only problem
is that they rely on boards made in 1980. which are now rusty and very high
maintenance, not to mention they are not debug-able and are very annoying to fix
(i.e testing about 20 shift registers, or something like that.)

enough with that long story...bottom line, machines available, I'm only replacing
the logic inside them to something more powerful and easier to maintain, also
cheaper(i.e 1980 models discontinued or very very expensive spare parts).

parameters for hatching eggs :


Temprature*C, 39/week1&2, 37/weeks3&4 correction : two heasting units
and one cooler
Humidity, 60RH w1&2, 70RH w3&4 correction : one humidifier and
one condenser
Turning, every 2 hours solution : special tray turning
motors
Ventilation, our machines allow air exchange at preset intervals, new machines use
co2 sensors to control that.
Important events:
Initial start --> there is a special starting routine (like oven preheat), that's
different from the main program.
Door Open/close --> lights are turned on , LED indicator, pulsator fan is
stopped(not to hurt the workers appraoching).

I am still in the flow chart phase, The reverse engineering phase is incomplete. so
here's how i plan to make this work:
- Going to use an RTC and a function to import the parameters from a table, that's
for automatically fixing parameters.
- might have to make some work arounds in the correcting function to prevent
over-correction.
- still have to find the acceptable deviations and when to start correcting them. (in
temp. its 0.3*F)
- going to use 6 interrupts: Temprature, Humidity, Co2, Open door, turner (time
since last turn)

questions:
-can 2 interrupts work at the same time? like if 2 values deviate at the same time,
is it possible to correct them at the same time?
-to use interrupts, do i have to use analog sensors?
-any brilliant ideas?

I am still learning to code BTW, I hope i provided people seeking to do the same
thing with useful information. feel free to ask anything, I'm more than willing to
help.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: Coding Badly on May 31, 2011, 10:19 pm

Quote

going to use 6 interrupts

Don't. There is nothing in what you've described so far that requires the use of
interrupts. Interrupts are typically appropriate when the time scale is short (e.g.
controller must respond within 1.2 milliseconds). Everything you've described is on
the scale of days and hours.

Interrupts add a great deal of complexity to an application and a large amount of


risk. Only tread down that path once you've determined nothing else will solve the
problem.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: AbdouRetro on May 31, 2011, 10:27 pm

for example,
if the temp exceeds set value by 0.4*F, the heater will stop and cooler will be
activated, then it will proceed to check all the other parameters and start all over
again...

so I should create a loop that takes no more than 3 seconds to complete, right?

can u tell me about accuracy, analog VS digital.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: AbdouRetro on May 31, 2011, 10:40 pm

Quote from: KE7GKP on May 31, 2011, 10:27 pm

Exactly what wires in the old machine do you need to interface to?
Presumably some sort of temperature sensor. What kind?
And some kind of humidity sensor. What kind?
And something to run the egg-turning motor, and something to run the ventilation fans.
And a switch to sense when the door is opened. And something to control the lights?

What controls were on it originally? What user-interface readouts, etc?


It would be almost trivial to add logging, and a graphic readout of current status and a log
of temp, humidity, egg turns, vent, door opens, etc. With microprocessor power, you can
do a lot more than back when the machine was designed.

yes temp/humidity sensors, but they will be changed to something of my liking. its
2011 who uses analog now?
egg turning is periodic. to clarify (internal vent. is by a pulsator fan, to cycle air
inside, ventilation is to allow air exchange)
yes, door sensor is available. lights relay, available.
I plan on using 4 digit LEDs for temp/humidity/vent(co2)/time since eggs went in
RTC, should rely on capacitors and a battery to retain their time

update : definitely replacing with modern equivalents. temperature accuracy is very


important, a deviation of a single degree could kill a whole batch. we use RTD temp
sensors, very very accurate.
update 2 : this is where i plan to pick a suitable sensor
http://www.sensorsportal.com/HTML/SENSORS/TempSens_Manufacturers.htm
provides a huge list, should be stickied in the scientific projects section.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: AbdouRetro on Jun 01, 2011, 05:07 pm

I am undecided in temperature sensors. as the machines currently use RTDs. but to


think, they didn't have digital ICs capable of doing such measurements back when
the machines were designed. RTDs were the only viable option. so maybe i'll go for
a good i2c digital sensor with the minimal deviation possible and see how it goes.
maybe RTD's 0.02 accuracy is not that necessary after all.

as for the RTCs, NVM storage sounds like a great idea.. since the plant is situated in
a rural area and experiences power outages a lot, we have a generator though. i
am also thinking about using a UPS, since the arduino and its sensors and relays
don't consume that much power. its the heating and cooling systems and motors
that drain electricity.

I think its time I go back and go over the 500 page manual to figure out some more
functions to implement.
I will be playing with the board to try to emulate different conditions and see how's
the board going to react, so that i can find out if i missed anything.

thanks ke7gkp for the great advice and link :) and thanks to coding badly as well :)

Title: Re: Industrial Egg Incubator with Arduino.


Post by: Korman on Jun 01, 2011, 07:58 pm

About the real time clock: It will make your life a lot easier, get one. The $20 spend
are worth it.

As your working period well over 1 seconds, use the Time library. It manages the
handling of the real time clock out of the box and you can work with Unix Time
Stamps (seconds since 1.1.1970) instead of millis() for long term periods. For the
scheduling of the next temperature measure, millis () is good enough.

For the internal EEPROM, you will find out that it's rated only for 100000 write
cycles on each byte. In your case, I would save on each cycle change the current
cycle and the date. I guess at maximum you'll save data every 30 minutes and the
EEPROM will last for the next millenia. This way, if your power fails or the Arduino
reboots, together with the RTC date it will pick up where it left.
Another gimmick you might consider is a cheap LCD display of the HD44780 type.
On ebay (for example this (http://cgi.ebay.com/HD44780-1602-16x2-LCM-
Character-LCD-Display-Module-New-/220788717420) a random hit when searching
for lcd and 44780) those cost $5 and interfacing with it easy with the LiquidCrystal
library. Add also a rotary encoder or 2 buttons and you have a user interface.
Programming this will be a bit more complicated, but this can be left for later when
the basics work.

If you need to replace the relay boards anyway, you probably will end up using shift
registers too. ShiftOut supports these kind of operation and there are many good
tutorials how to use it.

Consider adding to each relay a way of checking whether current is going through it
on the primary side. This will add a little circuitry - I guess a resistor an opto-
coupler per relay and an imput multiplexter per shift register - but you can add to
your system a self-test mode for diagnostics and check whether something
supposedly on is really on. Together with the display on the Arduino, the debugging
and maintenance will become a lot easier. The checking on the Arduino side won't
be time critical.

And as a last advice, once your project becomes better defined, post here about it.
You'll find here many helpful people with practical experience in the hardware and
software development. Read the tutorials first, play around a little and once your
think you got it right or are stuck, post. Real life project on the industrial scale are
specially popular, specially if you post some images too to give us a better idea
what kind of beast you want to hook up.

All in all, you have a fun project well suited to start learning to develop with the
Arduino. You can start out with the most simple programs and add in small steps
the necessary additional functions.

Korman

Title: Re: Industrial Egg Incubator with Arduino.


Post by: Chagrin on Jun 01, 2011, 09:47 pm

For your door open/close you should just have your fan wired through a contact on
the door. I.e. door open, contact is open, fan shuts off. Safer than relying on on
programming.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: wildbill on Jun 01, 2011, 10:00 pm
Quote

That is why I suggested storing the start time in non-volatile memory (NVM) somewhere so
you can restart the cycle if you haven't lost too much time. There are also tricks of saving
"checkpoints" to NVM every so often (like every 60 seconds). So that if you lose power, you
can check how long the machine has been down and take the ambient readings to see if the
batch is still OK or doomed.

Consider getting a suitable shield and using a SD card for this - it'll mean you can
do huge amounts of logging, which will be invaluable while you're debugging your
build, or diagnosing a failure when you have deployed it for real.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: Korman on Jun 02, 2011, 12:20 am
Quote from: wildbill on Jun 01, 2011, 10:00 pm

Consider getting a suitable shield and using a SD card for this - it'll mean you can do huge
amounts of logging, which will be invaluable while you're debugging your build, or
diagnosing a failure when you have deployed it for real.

For this application, that would be overdoing it. The hassles to log to the SD-card
are greater than the benefit it brings. And for the general state of the system, the
512 bytes provided by the processor itself is amply sufficient.

Korman

Title: Re: Industrial Egg Incubator with Arduino.


Post by: AbdouRetro on Jun 02, 2011, 01:54 am

Quote from: Chagrin on Jun 01, 2011, 09:47 pm

For your door open/close you should just have your fan wired through a contact on the
door. I.e. door open, contact is open, fan shuts off. Safer than relying on on programming.

nah, what if door contact malfunctions , the arduino should be able to trigger the
high alarm

i forgot to mention that in the original post. there is an implementation of a high


alarm and a low alarm.

and as for the LCD i have thought of that but discarded it due to the complexity of
the amount of buttons needed, but the rotating encoder revives the concept again.
can u further elaborate on the opto-isolator concept to detect if the relay is
activated, as i can't imagine that in action.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: PaulS on Jun 02, 2011, 11:09 am

Quote

nah, what if door contact malfunctions , the arduino should be able to trigger the high alarm

How? If the door contact malfunctions, the Arduino will see that the door is closed,
which presumably is it's normal state, and be perfectly happy with that.

And, what if the Arduino is the thing that malfunctions?

If you can't rely on a simple switch, you can't rely on things more complex than a
simple switch to function, when the more complex thing gets input from the switch
you aren't relying on.

Title: Re: Industrial Egg Incubator with Arduino.


Post by: AbdouRetro on Jun 02, 2011, 04:32 pm

what i mean is, if the worker does not shut the door properly, there will be no way
to indicate that the pulsator fan is halted. that way the eggs will be toasted... so its
better to rely on the arduino to detect the door opening. via a contact or proximity
sensor or any i2c option.
gosh! i love i2c

Title: Re: Industrial Egg Incubator with Arduino.


Post by: Korman on Jun 03, 2011, 05:16 pm

Quote from: AbdouRetro on Jun 02, 2011, 01:54 am

and as for the LCD i have thought of that but discarded it due to the complexity of the
amount of buttons needed, but the rotating encoder revives the concept again.

Samples on for rotary encoders with push button exist plenty and if I'm not
mistaken, there's even a library out there handle LCD menus with an encoder. Even
if this would be a little complex for beginners, I guess it's a task you'll be able to
handle once your project is at a stage where you can use it.

Quote from: AbdouRetro on Jun 02, 2011, 01:54 am


can u further elaborate on the opto-isolator concept to detect if the relay is activated, as i
can't imagine that in action.

First I have to admit, I'm more a software guy and not so much from the hardware
side. So better have the idea checked by the hardware fraction. Now, what kind of
things are attached to the relays on your shift registers? Are the switching for most
part just AC appliances running at 220V AC (or 110V AC if you're on the American
continent)? If so, look at your basic LED AC Circuit, those are quite simple. One or
two diodes, a capacitor, a resistor. If you put this in parallel to your load between
the switched part of the relay and the AC-ground, you'll have for each relay a LED
as an indicator whether the relay is open or not. Of you take the idea a step further
not to connect an LED but the emitter part of an opto-isolator, on the receiver side
of the opto-isolator you have galvanic separated a nice TTL level to tell you whether
the relay switched or not. Collect those input with a CD4012 and read them with
ShiftIn (http://www.arduino.cc/en/Tutorial/ShiftIn). If you use quad opto-isolators
like the NTE3221, this will set you back less than $10 per block of 8 relays. On the
software side you will need to take into account that the signal on the input side is
non rectified AC, so that it might read low from time to time, but as your timing
isn't that critical, you have lots of leeway.

Another idea is to add a hall current sensor like the ACS712 (or the models
matching the amperage going through the relays) per relay. This will allow you to
get an idea about the current and you can estimate in software whether the
consumer working properly (eg if the current drops a lamp might have blown). The
main problem here might be cost, as those current sensor will set you back $3 to
$7 per relay. The access would then be multiplexed with cascaded 4051B as
described here (http://www.arduino.cc/playground/Learning/4051). The coding
again won't be time critical and you might have average several measures to weed
out flukes.

I hope this gives you some ideas. More details can be worked out as your design
progresses.

Korman

Text only | Text with Images


SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Project Guidance => Topic started by: Shan9 on
Apr 22, 2016, 03:36 pm

Title: Arduino based incubator issues


Post by: Shan9 on Apr 22, 2016, 03:36 pm

Hi guys,

I am currently working for a project which is built an arduino based incubator.


however, there are several problems tat i meet. I need help urgently since de due
date of my project is coming soon. I am not sure what is happening. the problems
are:

1) The lcd 1602 not show any values that i program which are temperature and
humidity.
2) The arduino mega will auto restart after several minutes or hours.

Title: Re: Arduino based incubator issues


Post by: larryd on Apr 22, 2016, 06:17 pm

Attach your code using the </> icon on the left side of the posting menu.

If you upload a simpler LCD sketch does the LCD display anything?

Please show us a schematic of your circuit.


A good photo of your wiring and any links to components, will get responses.

Title: Re: Arduino based incubator issues


Post by: Shan9 on Apr 22, 2016, 06:18 pm
And i just find out that my arduino mega regulator is running extremely hot. Is it
normal? Is it the reason to cause the board to reset?

Title: Re: Arduino based incubator issues


Post by: larryd on Apr 22, 2016, 06:20 pm
It should run cool to warm!

Title: Re: Arduino based incubator issues


Post by: Shan9 on Apr 22, 2016, 06:34 pm

Sorry guys.. i am a newbie to arduino and also tis forum. i haven done the
schematic diagram. i will upload it once i am done. thx to Larry for giving guidance.

Code: [Select]
#include <LiquidCrystal.h>
#include <PID_v1.h>
#include "DHT.h"

#define temLowTrigger 37.8 //Setting the trigger value for the temperture,
once the temperture lower than this trigger value, the heater band will start
heating
#define humLowTrigger 45 //Setting the trigger value for the humidity, once
the humidity lower than this value, start humidification

#define DHTPIN A2 // what pin we're connected to

// Uncomment whatever type you're using!


//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V


// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

const int relay1 = 12; // the number of the relay 1 pin(motor)


const int relay2 = 13; // the number of the relay 2 pin(light bulb)
const int relay3 = 11;
int motorState=LOW; //motorstate used to set the motor state
unsigned long previousMillis=0; //will store last time motor was update
long OnTime=5000; //milliseconds of on-time
long OffTime=28800000; //milliseconds of off-time
DHT dht(DHTPIN, DHTTYPE);

//Pin assignments for DFRobot LCD Keypad Shield


LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
//---------------------------------------------

void setup()
{

pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(relay3, OUTPUT);
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("initializing...");
lcd.setCursor(0, 1);
delay(1000);

Serial.begin(9600);
dht.begin();
delay(1000);
lcd.clear();

digitalWrite(relay1,HIGH);
digitalWrite(relay3, LOW);
digitalWrite(relay2, HIGH);

void loop()
{

// 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();
float t = dht.readTemperature();

// check if returns are valid, if they are NaN (not a number) then
something went wrong!
if (isnan(t) || isnan(h)) {
Serial.println("error");
} else {

//Display
lcd.setCursor(0, 0);
lcd.print("H: ");
lcd.print(h);

lcd.setCursor(9, 0);
lcd.print("T: ");
lcd.print(t);

if(t < temLowTrigger)


digitalWrite(relay2, LOW);//start heating
else
digitalWrite(relay2, HIGH);

if(h< humLowTrigger)
digitalWrite(relay3, HIGH);
else
digitalWrite(relay3,LOW);

unsigned long currentMillis=millis();

if((motorState == HIGH) && (currentMillis - previousMillis >= OnTime))


{
motorState=LOW; //turn it off
previousMillis = currentMillis; //remember the time
digitalWrite(relay1,motorState); //update the actual motor state
}
else if ((motorState==LOW) && (currentMillis-previousMillis >=OffTime))
{
motorState = HIGH; //turn it on
previousMillis = currentMillis; //remember the time
digitalWrite(relay1,motorState); //update the actual LED
}

} }

However, i will try to post the photo first..

Title: Re: Arduino based incubator issues


Post by: CrossRoads on Apr 22, 2016, 06:48 pm
What voltage is coming in from the barrel jack? Try a lower voltage, down to 7.5V.
Overheated regulator will go into thermal shutdown, then turn back on when it
cools down. Then off, on, off, on.
You should be able to monitor the voltage with a meter and confirm.

Title: Re: Arduino based incubator issues


Post by: larryd on Apr 22, 2016, 06:53 pm

We need to see a schematic.


From your current wiring, please draw a schematic.
What voltage is seen on Vin?

Title: Re: Arduino based incubator issues


Post by: Shan9 on Apr 22, 2016, 07:32 pm
I have total 3 power supply:
1) 12V and 1000mA for the arduino
2) 240V for the light bulb and synchronous motor to turn the egg turner in interval
of 8 hours once.
3) an ac-dc adapter for fan.. however, the ac-dc adapter i also plug into a dc-dc
stepdown for humidifier

Okay Larry.. I am working on the schematic diagram..

Cross Roads,

I already measured the voltage from the regulator which is 4.96V.. but the board
haven reset itself yet.. thus, i cannot measure it is there any voltage drop when the
board is reset.. can i know the reason why the regulator is extremely hot?

Title: Re: Arduino based incubator issues


Post by: Shan9 on Apr 24, 2016, 10:26 pm
Hi,

i jux done my circuit drawing. My drawing was not standard. hope u all can
understand.. Yrs reply or help will be highly appreciated..

Title: Re: Arduino based incubator issues


Post by: larryd on Apr 25, 2016, 05:08 pm

Is the regulator still getting hot?

How are you powering the the Arduino? What voltage?

Title: Re: Arduino based incubator issues


Post by: Shan9 on Apr 25, 2016, 06:45 pm

Ya, the regulator is really hot.. so i unplug the relay that connected with humidifier
and also motor.. Now, the arduino board dont reset anymore but is still very hot.. I
used 12V 1A adapter to power the arduino board.

Title: Re: Arduino based incubator issues


Post by: PaulS on Apr 25, 2016, 06:51 pm

Quote

I used 12V 1A adapter to power the arduino board.

That means that the regulator needs to dump 7 volts * however many amps your
circuit is drawing. A 9V adapter will allow the regulator to dump less voltage (in the
form of heat).

Title: Re: Arduino based incubator issues


Post by: Shan9 on Apr 25, 2016, 08:09 pm

Okay.. I will try used 9V adapter and observe the performance of the board. Ya..
Jux wondering how to reduce the current drawn..

Title: Re: Arduino based incubator issues


Post by: larryd on Apr 25, 2016, 08:47 pm

If you can find one, get a 7.5 V wallwart.

https://www.dipmicro.com/store/DCA-07510
(https://www.dipmicro.com/store/DCA-07510)

(https://www.dipmicro.com/img/1/400x300/DCA-FULLVIEW.jpg)

Text only | Text with Images


SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Project Guidance => Topic started by: les_well on
Jan 07, 2015, 09:42 pm

Title: Help with very slow stepper motor


Post by: les_well on Jan 07, 2015, 09:42 pm

Hi. This is my first arduino project.

My project is an egg incubator.


Using an LCD, DHT11 Humidity temp control. A stepper to turn the eggs for 18 days
out of 21. Heater to maintain temperature and humidity control.

I have combined 3 sketches, each work independently.


When combined, the motor speed is so slow (one rpm every hour, ish). also affects
humidity readings over time.

I would appreciate it if you could look over the code for me.

Title: Re: Help with very slow stepper motor


Post by: Robin2 on Jan 07, 2015, 10:34 pm

Quote from: les_well on Jan 07, 2015, 09:42 pm

When combined, the motor speed is so slow (one rpm every hour, ish). also affects
humidity readings over time.

15K is a lot of code to "look over" and I am lazy.

Do you mean that the motor speed is too slow?


Do you mean that the motor speed affects the humidity readings?

I noticed the use of delay() in your code. Usually a bad sign if you want several
things at a time (http://forum.arduino.cc/index.php?topic=223286.0) to happen
without interfering with each other.

...R
Title: Re: Help with very slow stepper motor
Post by: Henry_Best on Jan 08, 2015, 03:49 am

What speed do you want the motor turning at?


Faster, slower or the speed it is now?

Title: Re: Help with very slow stepper motor


Post by: raschemmel on Jan 08, 2015, 04:59 am

For one thing , you could do a test. Save you sketch with a different name (add
_TEST at the end of the
current name). The comment out ALL of the LCD and Serial prints EXCEPT the ones
that are critical. If
you have a way to monitor the parameters of the incubator WITHOUT the prints to
the LCD and serial
monitor, then comment out ALL of the prints and observe the motor speed and
incubator parameters.
Serial prints are very time consuming and LCD prints are probably not much better.
You need to find out
if the prints are causing the motor to turn slower and the best way to do that is to
eliminate some variables from the equation and then continue this process until you
locate the offending code.

Title: Re: Help with very slow stepper motor


Post by: tinkertech on Jan 08, 2015, 01:38 pm

You have added all of your custom code inside the setOutput() function which
needs to be called every time you move a step on the motor. You are adding about
20 Serial.print commands which take a long time and updating your display, so the
motor will never move.

Move your code out of the setOutput() function and into at least one new function.

Code: [Select]

void setOutput(int out)


{
digitalWrite(motorPin1, bitRead(lookup[out], 0));
digitalWrite(motorPin2, bitRead(lookup[out], 1));
digitalWrite(motorPin3, bitRead(lookup[out], 2));
digitalWrite(motorPin4, bitRead(lookup[out], 3));
//motorcodeend
// //////////////////////////tempcodestart
Serial.println("\n");

int chk = DHT11.read(DHT11PIN);

Serial.print("Read sensor: ");


switch (chk)
{
case DHTLIB_OK:
Serial.println("OK");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.println("Checksum error");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.println("Time out error");
break;
default:
Serial.println("Unknown error");
break;
}

Serial.print("Humidity (%): ");


Serial.println((float)DHT11.humidity, 2);

Serial.print("Temperature (C): ");


Serial.println((float)DHT11.temperature, 2);

Serial.print("Temperature (F): ");


Serial.println(Fahrenheit(DHT11.temperature), 2);

Serial.print("Temperature (K): ");


Serial.println(Kelvin(DHT11.temperature), 2);

Serial.print("Dew Point (C): ");


Serial.println(dewPoint(DHT11.temperature, DHT11.humidity));

Serial.print("Dew PointFast (C): ");


Serial.println(dewPointFast(DHT11.temperature, DHT11.humidity));

//delay(2000);

//delay(100);
// ///////////////////////////tempcodeend
// =========================================
//try to get temp humidity onto display
lcd.begin( 16, 2 );
//Print some initial text to the LCD.
lcd.setCursor( 0, 0 ); //top left
// 1234567890123456
lcd.print( "H:");
lcd.setCursor( 2, 0); //top left
lcd.print((float)DHT11.humidity, 2);

lcd.setCursor( 8, 0 ); //bottom left


// 1234567890123456
lcd.print( "T:");
lcd.setCursor( 10, 0); //top left
lcd.print((float)DHT11.temperature, 2);

//===========================================

byte button;
byte timestamp;

//get the latest button pressed, also the buttonJustPressed,


buttonJustReleased flags
button = ReadButtons();
//blank the demo text line if a new button is pressed or released, ready
for a new label to be written
if( buttonJustPressed || buttonJustReleased )
{
// delay to slow display of serial out for testing buttons
// delay (1000);

lcd.setCursor( 4, 1 );
lcd.print( " " );
}
//show text label for the button pressed
switch( button )
{
case BUTTON_NONE:
{
break;
}
case BUTTON_RIGHT:
{
lcd.setCursor( 4, 1 );
lcd.print( "RIGHT" );
break;
}
case BUTTON_UP:
{
lcd.setCursor( 4, 1 );
lcd.print( "UP" );
break;
}
case BUTTON_DOWN:
{
lcd.setCursor( 4, 1 );
lcd.print( "DOWN" );
break;
}
case BUTTON_LEFT:
{
lcd.setCursor( 4, 1 );
lcd.print( "LEFT" );
break;
}
case BUTTON_SELECT:
{
lcd.setCursor( 4, 1 );
lcd.print( "SELECT-FLASH" );

//SELECT is a special case, it pulses the LCD backlight off and on


for demo
digitalWrite( LCD_BACKLIGHT_PIN, LOW );
delay( 150 );
digitalWrite( LCD_BACKLIGHT_PIN, HIGH ); //leave the backlight on
at exit
delay( 150 );

/* an example of LCD backlight control via macros with nice labels


LCD_BACKLIGHT_OFF();
delay( 150 );
LCD_BACKLIGHT_ON(); //leave the backlight on at exit
delay( 150 );
*/

/*
// an example of LCD backlight control via a macro with nice label,
called with a value
LCD_BACKLIGHT(false);
delay( 150 );
LCD_BACKLIGHT(true); //leave the backlight on at exit
delay( 150 );
*/

break;
}
default:
{
break;
}
}
/*
//remove time stamp ////////////////
print the number of seconds since reset (two digits only)
timestamp = ( (millis() / 1000) % 100 ); //"% 100" is the remainder of a
divide-by-100, which keeps the value as 0-99 even as the result goes over 100
lcd.setCursor( 14, 1 );
if( timestamp <= 9 )
lcd.print( " " ); //quick trick to right-justify this 2 digit value
when it's a single digit
lcd.print( timestamp, DEC );
// ///////////////////////////////////////
*/
/*
//debug/test display of the adc reading for the button input voltage pin.
lcd.setCursor(12, 0);
lcd.print( " " ); //quick hack to blank over default left-
justification from lcd.print()
lcd.setCursor(12, 0); //note the value will be flickering/faint on
the LCD
lcd.print( analogRead( BUTTON_ADC_PIN ) );
*/
//clear the buttonJustPressed or buttonJustReleased flags, they've already
done their job now.
if( buttonJustPressed )
buttonJustPressed = false;
if( buttonJustReleased )
buttonJustReleased = false;
}

Title: Re: Help with very slow stepper motor


Post by: tinkertech on Jan 08, 2015, 01:57 pm
What else are you using for your setup?
What are you using to turn the eggs? a roller attached to the gear head of the
motor?
How many motors are you using?
How are you heating the eggs?

If its a glass tank with a halogen bulb you will need a separate power supply and a
relay that can be switched with 5V.

I believe these motors are used in Air-Con units to flip the grill and are fairly
reliable for the price but they work better with a 12V supply, the ULN2003 usually
comes on a board that has 12V supply pins but i doubt speed is a huge concern.

You might want to order a RTC (Real Time Clock) too so you can set a profile for
timing the turns.

Post a photo of the setup if its built so we can see what you are working with

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Motors, Mechanics, and Power => Topic started
by: polmourgos on Feb 23, 2016, 03:47 pm

Title: Motor works 1 minute every 2 hours..??


Post by: polmourgos on Feb 23, 2016, 03:47 pm
Hi.
I am new to arduino and not expert with electronics.
I want to change my incubator setup that i had till now and rebuild it with arduino
commands and control.
With the thermometer and humidity i have done it.
The problem i face and can't find a solution after many hours of search is the
following...
I want to trigger a motor with a relay (egg turning motor) for one minute every
two or three hours.
Can someone helps what do i must search for so i find a solution?
Thanks alot for any help.

Pol

Title: Re: Motor works 1 minute every 2 hours..??


Post by: JimboZA on Feb 23, 2016, 04:28 pm

The kind of thinking embodied in Blink Without Delay (aka BWOD) is good for this
stuff. Instead of an led you have your relay, presumably via a transisitor.

It so happens I have a library to do BWOD for on time and off time differing. By my
calculations, in milliseconds you have an on time of 60000 in every 9000000
(taking 2.5 hours.)

Usage is as below and library is attached. Just have (presumably) one instance of
BWOD in there- call it what you like, perhaps BWOD turnMotor;

Code: [Select]
/* Blink without Delay in a class in a library
*/

#include <BWOD.h>

BWOD myBWOD;
BWOD anotherBWOD;

void setup() {
myBWOD.attach(8, 97, 110); //pin, on interval, off interval
anotherBWOD.attach(14, 1798, 1015);
}
void loop()
{
myBWOD.manageBlink();
anotherBWOD.manageBlink();
}

Title: Re: Motor works 1 minute every 2 hours..??


Post by: polmourgos on Feb 23, 2016, 07:01 pm
Thank you JimboZA for your time to give me an answer and help.I will try it and i
will report if it works as i want.
Thank you again.

Title: Re: Motor works 1 minute every 2 hours..??


Post by: JimboZA on Feb 24, 2016, 03:25 am

You should look at the BWOD example


(https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay) if you didn't already, to
familiarise yourself with the approach. My library uses that thinking, but you ought
to understand the idea.

Title: Re: Motor works 1 minute every 2 hours..??


Post by: Robin2 on Feb 24, 2016, 10:01 am
You may also find some useful ideas in Several Things at a Time
(http://forum.arduino.cc/index.php?topic=223286.0)

...R

Title: Re: Motor works 1 minute every 2 hours..??


Post by: outsider on Feb 24, 2016, 03:43 pm

@JimboZA:

BWOD.zip
(http://forum.arduino.cc/index.php?action=dlattach;topic=381425.0;attach=15607
7)

Neat, K++
Title: Re: Motor works 1 minute every 2 hours..??
Post by: polmourgos on Feb 24, 2016, 04:02 pm

@Jimbo

The BWOD it works exactly as it should be.Is what i was looking for.Thank you.
But the problem i have now is how do i compile the incubator sketch with the
BWOD.

Code: [Select]

#include <dht22.h>

dht22 dht22;//change to dht22 DHT22; if using the dht22

//you will also need to change all instances of DHT22 to DHT22

byte umidifiyerrelaypin = 2;// pin 2 humidifier relay

byte heatrelaypin = 3;// pin for heater resistant relay

void setup()

dht22.attach(4);// pin from dht22


Serial.begin(9600);

Serial.println("Virtuabotix DHT22 FAN & Heater CONTROL");

pinMode(umidifiyerrelaypin, OUTPUT);

digitalWrite(umidifiyerrelaypin, LOW);//turn off the relay

pinMode(heatrelaypin, OUTPUT);

digitalWrite(heatrelaypin, LOW);//turn off the relay

void loop()
{

Serial.println("\n");

int chk = dht22.read();

Serial.print("Read sensor: ");

switch (chk)

case 0: Serial.println("OK"); break;

case -1: Serial.println("Checksum error"); break;

case -2: Serial.println("Time out error"); break;

default: Serial.println("Unknown error"); break;

Serial.print("Humidity (%): ");

Serial.println((float)dht22.humidity, DEC);

if(dht22.humidity > 57)//incubator's humidity

digitalWrite(umidifiyerrelaypin, LOW);//off humidifier

else

digitalWrite(umidifiyerrelaypin, HIGH);

}
Serial.print("Temperature (C): ");

Serial.println(dht22.temperature, DEC);

if(dht22.temperature < 26)//incubator's temperature


{

digitalWrite(heatrelaypin, HIGH);//heater off

else

digitalWrite(heatrelaypin, LOW);

delay(2000);

I know i ask too much but i am newbie .


Thank you all for your time to answer and help me.
Pol

Title: Re: Motor works 1 minute every 2 hours..??


Post by: JimboZA on Feb 24, 2016, 04:24 pm

Just put these above setup with your existing code:

Code: [Select]
#include <BWOD.h>

BWOD myBWOD; // change name to suit

This in setup with the existing stuff:

Code: [Select]
myBWOD.attach(8, 97, 110); //pin, on interval, off interval
// chnge name and use your values

And this somewhere in loop:

Code: [Select]
myBWOD.manageBlink(); // with your name

Title: Re: Motor works 1 minute every 2 hours..??


Post by: polmourgos on Feb 24, 2016, 08:04 pm
Yeaaaa ...i did it.
Thanks alot Jimbo.
Now the last thing to do is to add the 16 x 2 lcd screen so i can control the data
without use the pc and run the serial.
But i will try tomorrow for this.

And if all go ok then in the future i will try to add or touch screen or buttons to
change and correct the data.But this is not for now.
I will report the results in the future about the chicks.

Thanks again for the help.

Pol

Title: Re: Motor works 1 minute every 2 hours..??


Post by: JimboZA on Feb 25, 2016, 05:56 am

Glad it works... just a note on why it does work, in case you didn't pick that up:

Blink without Delay as an approach, doesn't stop other code from working while it's
doing its thing. It uses millis(), the Arduino's own timer, to see what the time is and
to see if it's time to do blink-related stuff.

So it basically turns the led on or off, and notes the time. The processor continues
doing other work in loop(). Then when loop starts again, we check the time elapsed
since we last did blink stuff, against the required interval. Has the interval elapsed?
If no, do no blink stuff and carry on in loop. If yes, do blink stuff (ie toggle the led
on or off depending on if it's off or on) and continue in loop.

Round to top of loop again, rinse and repeat.

All I did with my library was bundle all that thinking into a couple of functions, with
a bit of extra stuff to allow you to set the pin number and have on and off times
that are not the same.

So with the library, every time it gets to do bwod.manageBlink(), that's it looking to


see if the time has elapsed and it acts accordingly.

The whole point of this, is that the blinking doesn't interfere with your other code.
All I did was bundle existing Blink WithOut Delay thinking, into a a library to make
it easy to use.

Title: Re: Motor works 1 minute every 2 hours..??


Post by: larryd on Feb 25, 2016, 06:15 am
int ledPin;
int ledState; // ledState used to set the LED
long previousMillis; // will store last time LED was updated

@JimboZA, may want to update to: unsigned long previousMillis;


There maybe a few other variables too that should be unsigned long.
.

Title: Re: Motor works 1 minute every 2 hours..??


Post by: JimboZA on Feb 25, 2016, 06:19 am

Quote from: LarryD on Feb 25, 2016, 06:15 am

int ledPin;
int ledState; // ledState used to set the LED
long previousMillis; // will store last time LED was updated

@JimboZA, may want to update to: unsigned long previousMillis;


There maybe a few more too.
.

Funny you should day that, I was just wondering if I got those right.

Title: Re: Motor works 1 minute every 2 hours..??


Post by: larryd on Feb 25, 2016, 06:22 am

unsigned long previousMillis; // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,


// will quickly become a bigger number than can be stored in an int.
unsigned long interval; // interval at which to blink (milliseconds)
unsigned long onTime;
unsigned long offTime;
and
void BWOD::attach(int p,unsigned long on, unsigned long off)

FYI
BWD using structure example:

Code: [Select]

//Blink without Delay skeleton example using a structure.


//LarryD

//======================================================================
struct timer
{
//lastMillis = the time this "timer" was (re)started
//waitMillis = delay time (mS) we are looking for. You can use math
60*60*1000 for 1 hour
//restart = do we start "this timer" again and again
//enableFlag = is "this timer" enabled/allowed to be accessed
//**********************
//For each timer object you need:
//Example:
// timer myTimer = //give the timer a name "myTimer"
// {
// 0, 200UL, true, true //lastMillis, waitMillis, restart, enableFlag
// };
// You have access to:
// myTimer.lastMillis, myTimer.waitMillis, myTimer.restart,
myTimer.enableFlag, myTimer.CheckTime()
//**********************

unsigned long lastMillis;


unsigned long waitMillis;
bool restart;
bool enableFlag;
bool CheckTime() //Delay time expired function "CheckTime()"
{
//is the time up for this task?
if (enableFlag && millis() - lastMillis >= waitMillis)
//Note: if delays of < 2 millis are needed use micros() and adjust
waitMillis as needed
{
//should this start again?
if(restart)
{
//get ready for the next iteration
lastMillis += waitMillis;
}
//time was reached
return true;
}
//time was not reached
return false;
} //END of CheckTime()

}; //END of structure timer


//======================================================================

//**********************************************************************
//Let's create 6 timer objects and initialize them in this sketch
//**********************************************************************
timer pin13 = //create timer pin13
{
0, 200UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer pin12 = //create timer pin12
{
0, 3*1000UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer pin11 = //create timer pin11
{
0, 10*1000UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer pin10 = //create timer pin10
{
0, 6*1000UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer Toggle10 = //create timer Toggle10
{
0, 50UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer checkSwitches = //create timer checkSwitches
{
0, 50UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************

byte lastMySwitchState = 1; //for mySwitch on Pin 2


byte counter = 0;

const byte Pin13 = 13;


const byte Pin12 = 12;
const byte Pin11 = 11;
const byte Pin10 = 10;
const byte Pin9 = 9;

const byte mySwitch = 2;

//**********************************************************************

void setup()
{
Serial.begin(9600);

pinMode(Pin13,OUTPUT);
pinMode(Pin12,OUTPUT);
pinMode(Pin11,OUTPUT);
pinMode(Pin10,OUTPUT);
pinMode(Pin9, OUTPUT);
digitalWrite(Pin13,LOW);
digitalWrite(Pin12,LOW);
digitalWrite(Pin11,LOW);
digitalWrite(Pin10,LOW);
digitalWrite(Pin9, LOW);

pinMode(mySwitch,INPUT_PULLUP);

} // >>>>>>>>>>>>>> E N D O F s e t u p ( ) <<<<<<<<<<<<<<<<<

void loop()
{
//Below are examples demonstrating different timing situations

//***************************
//example 1 Toggle Pin13 every 200ms
if (pin13.CheckTime())
{
//Toggle Pin13
digitalWrite(Pin13,!digitalRead(Pin13));

//if you only want this section of code to happen once


//uncomment the next line
//pin13.enableFlag = false;
}

//***************************
//example 2 After 3 seconds, Pin12 goes and stays HIGH
if (pin12.CheckTime())
{
//Make Pin12 HIGH now
digitalWrite(Pin12,HIGH);
//disable timing section of code
pin12.enableFlag = false;
}

//***************************
//example 3 Pin11 is HIGH for 10 seconds, then goes and stays LOW
if (pin11.enableFlag && !pin11.CheckTime())
{
digitalWrite(Pin11,HIGH);
}
//10 seconds is now up now, leave the Pin11 LOW
else
{
digitalWrite(Pin11,LOW);
//disable timing section of code
pin11.enableFlag = false;
}

//***************************
//example 4 For 6 seconds, toggle Pin10
if (pin10.enableFlag && !pin10.CheckTime())
{
//example 5 Toggling Pin10 every 50mS
if(Toggle10.CheckTime())
{
//toggle Pin10
digitalWrite(Pin10,!digitalRead(Pin10));
}
}
//6 seconds is now up, toggling is stopped
else
{
digitalWrite(Pin10,LOW);
//disable timing section of code
pin10.enableFlag = false;
}

//***************************
//example 6 Is it time to check the switches?
if (checkSwitches.CheckTime())
{
//time to read the switches
Switches();
}
//**********************************
//Put other non-blocking stuff here
//**********************************

} // >>>>>>>>>>>>>> E N D O F l o o p ( ) <<<<<<<<<<<<<<<<<

//======================================================================
// F U N C T I O N S
//======================================================================

//**********************************************************************
//switches are checked every checkSwitches.waitMillis milli seconds
//no minimum switch press time is validated with this code (i.e. No glitch
filter)
void Switches()
{
boolean thisState; //re-usable for all the switches

//*************************** mySwitch Pin 2 code


//check if this switch has changed state
thisState = digitalRead(mySwitch);
if (thisState != lastMySwitchState)
{
//update the switch state
lastMySwitchState = thisState;

//This switch position has changed, let's do some stuff

//"HIGH condition code"


//switch goes from LOW to HIGH
if(thisState == HIGH)
{
//example: LED on Pin9 is Push ON, Push OFF
digitalWrite(Pin9,!digitalRead(Pin9));
}

//"LOW condition code"


//switch goes from HIGH to LOW
else
{
//example: display the current switch push count
Serial.println(++counter);
}
} //END of mySwitch Pin 2 code

//******************************************
//similar code for other switches goes here
//******************************************

} //END of Switches()

//======================================================================
// E N D O F C O D E
//======================================================================

Title: Re: Motor works 1 minute every 2 hours..??


Post by: polmourgos on Mar 04, 2016, 02:58 pm
I would like to report that the above sketch working like a charm, perfect.I have
finished the incubator construction and setup everything.Put it to work and four
days now is working very precise.
The arduino controls the heater resistant ,the turn egg motor,and the humidifier.
Thank you all for helping me.

I will also report the incubation results .

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images


Arduino Forum
Using Arduino => Programming Questions => Topic started by:
34DOL on Dec 07, 2012, 04:43 am

Title: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper


Post by: 34DOL on Dec 07, 2012, 04:43 am

Basically I'm looking to have my Arduino Uno control 2 fans based on temperature
readings from DHT11 (i.e. go on above a certain temperature) and turn on 2
different sets of lights based on the time of day (DS1307 RTC).

Both the DS1307 RTC and the DHT11 are communicating with the Arduino and
displaying on the LCD.

The relays are currently wired with the Com to 12V and the NC to the various
device (i.e. fans or lights). The relays seem to cycle. I can hear them clicking, but
my code doesn't control them as I intend. Please assist...

I have yet to connect or code for the stepper motor, but essentially it will open and
close a door with a screw drive based on the time of day.

Code: [Select]

#include <LiquidCrystal.h>
#include <DFR_Key.h>
#include <Wire.h>
#include "RTClib.h"
#include "DHT.h"

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

DFR_Key keypad;

int localKey = 0;
String keyString = "";

RTC_DS1307 RTC;

int StartHrRelay_1 = 21;


int StartMinRelay_1 = 00;

int StartHrRelay_2 = 21;


int StartMinRelay_2 = 00;

int StartHrRelay_3 = 7;
int StartMinRelay_3 = 44;

int StartHrRelay_4 = 7;
int StartMinRelay_4 = 44;

long Sleep = 1L;

long MultiMinute = 60000L;

boolean LightOn = false;

DateTime future;
DateTime DelayFuture;
DateTime Start;

int DurDay1 = 0;
int DurHour1 = 10;
int DurMinute1 = 0;
int DurSecond1 = 0;

int DurDay2 = 0;
int DurHour2 = 8;
int DurMinute2 = 0;
int DurSecond2 = 0;

int DurDay3 = 0;
int DurHour3 = 1;
int DurMinute3 = 0;
int DurSecond3 = 0;

int DurDay4 = 0;
int DurHour4 = 1;
int DurMinute4 = 30;
int DurSecond4 = 0;
#define RELAY_ON 0
#define RELAY_OFF 1

int Relay_1 = 3;
int Relay_2 = 4;
int Relay_3 = 5;
int Relay_4 = 6;

long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}

#define DHTPIN 2

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

double dewPoint(double celsius, double humidity)


{
double A0= 373.15/(273.15 + celsius);
double SUM = -7.90298 * (A0-1);
SUM += 5.02808 * log10(A0);
SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
SUM += log10(1013.246);
double VP = pow(10, SUM-3) * humidity;
double T = log(VP/0.61078); // temp var
return (241.88 * T) / (17.558-T);
}

void setup() {
Serial.begin(57600);
lcd.begin (16,2);
lcd.print(" Chicken Coop ");
Wire.begin();
RTC.begin();

RTC.adjust(DateTime(__DATE__, __TIME__));

if (! RTC.isrunning()) {
lcd.setCursor (0,0);
lcd.print(" *-- RTC's --*");
lcd.setCursor (0,1);
lcd.print(" NOT running!");
Serial.println(" *-- RTC's NOT running! --*");
delay (5000) ;
lcd.clear();
RTC.adjust(DateTime(__DATE__, __TIME__));
}

DateTime now = RTC.now();


DateTime
SetStart(now.year(),now.month(),now.day(),StartHrRelay_1,StartMinRelay_1,now.
second());

Start = SetStart;

digitalWrite(Relay_1, RELAY_OFF);
pinMode(Relay_1, OUTPUT);

digitalWrite(Relay_2, RELAY_OFF);
pinMode(Relay_2, OUTPUT);

digitalWrite(Relay_3, RELAY_OFF);
pinMode(Relay_3, OUTPUT);

digitalWrite(Relay_4, RELAY_OFF);
pinMode(Relay_4, OUTPUT);
delay(4000);

dht.begin();

void loop()
float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(t) || isnan(h)) {
lcd.setCursor (0,0);
lcd.print("*-- Failed to");
lcd.setCursor (0,1);
lcd.print(" read T&H --*");
Serial.println("*-- Failed to read T&H --*");
delay (5000) ;
lcd.clear();
}
else {
lcd.setCursor (0,0);
lcd.print("Temp (F): ");
lcd.print(t*9/5 + 32);
lcd.print(" *F");
lcd.setCursor (0,1);
lcd.print("Humidity: ");
lcd.print(h);
lcd.print("% ");

delay (5000) ;
lcd.clear();

lcd.setCursor (0,0);
lcd.print("Temp (C): ");
lcd.print(t);
lcd.print(" *C");
lcd.setCursor (0,1);
lcd.print("Dew Point: ");
lcd.print(dewPoint(t, h));
lcd.print(" *C");

delay (5000) ;
lcd.clear();

Serial.print("Temp (F): ");


Serial.print(t*9/5 + 32);
Serial.println(" *F");
Serial.print("Humidity: ");
Serial.print(h);
Serial.println("% ");

Serial.print("Temp (C): ");


Serial.print(t);
Serial.println(" *C");
Serial.print("Dew Point: ");
Serial.print(dewPoint(t, h));
Serial.println(" *C");
}

if (dht.readTemperature() >= 20) {


digitalWrite(Relay_1, RELAY_OFF);
}
else if (dht.readTemperature() < 18) {
digitalWrite(Relay_1, RELAY_ON);
}

if (dht.readTemperature() >= 25) {


digitalWrite(Relay_2, RELAY_OFF);
}
else if (dht.readTemperature() < 23) {
digitalWrite(Relay_2, RELAY_ON);
}

lcd.setCursor (0,0);
lcd.print("Volts (mV): ");
lcd.print( readVcc(), DEC );
delay(5000);
lcd.clear();

DateTime now = RTC.now();

lcd.setCursor (0,0);
lcd.print(" ");
lcd.print(now.year(), DEC);
lcd.print('/');
lcd.print(now.month(), DEC);
lcd.print('/');
lcd.print(now.day(), DEC);

lcd.setCursor (0,1);
lcd.print(" ");
lcd.print(now.hour(), DEC);
lcd.print(':');
lcd.print(now.minute(), DEC);

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.println(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();

delay(5000);
lcd.clear();

if (LightOn == false) {

DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_3 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_3 &&
(int)now.minute() <= DelayFuture.minute()) {

future = CalcFuture(now,DurDay3,DurHour3,DurMinute3,DurSecond3);

LightOn = true;
digitalWrite(Relay_3, RELAY_ON);

Serial.println("\r\nLight On\r\n");

}
}

else {

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {

LightOn = false;
digitalWrite(Relay_3, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));

if (LightOn == false) {

DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_4 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_4 &&
(int)now.minute() <= DelayFuture.minute()) {

future = CalcFuture(now,DurDay4,DurHour4,DurMinute4,DurSecond4);

LightOn = true;
digitalWrite(Relay_4, RELAY_ON);

Serial.println("\r\nLight On\r\n");
}
}

else {

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {

LightOn = false;
digitalWrite(Relay_4, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));
}

DateTime CalcFuture (DateTime now, int Days, int Hours, int Minutes, int
Seconds){

DateTime future;
long DaySeconds = 86400L;
long HourSeconds = 3600L;
long MinuteSeconds = 60L;

future = (now.unixtime() + (Days * DaySeconds) + (Hours * HourSeconds) +


(Minutes * MinuteSeconds) + (Seconds));
return future;
}

//
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 07, 2012, 06:36 am

Quote

I can hear them clicking, but my code doesn't control them as I intend. Please assist.

That's a real shame.


Now, perhaps if you told us how you intended that code to work, and how it
actually works, we could help you.

All those delay()s aren't.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 07, 2012, 07:36 am

9500 character post limit, you were lucky to get what you got. I had to delete all of
my comments out of the code.

I intend the code to work such that the relays are turned on or off based on
information supplied by the RTC and DHT. Relays 1 & 2 are intended to control the
fans. Relays 3 & 4 are intended to control the lights.

The arduino is receiving data from the RTC and DHT and displays as the data
intended on the LCD. What doesn't work, or doesn't work as intended, is my code
to use that data to control the relays. What does that part of the code do? Well,
from what I can tell, pretty much nothing. I've search all over for code that I could
use to turn relays on or off based off data values from the RTC and DHT compared
to pre-assigned arguments and haven't been able to put together anything that
works. What I have here is the closest I've been able to come.

Maybe my relays are connected incorrectly, but I don't think so. Since I wired
them as normally closed I am able to tell that they are at least getting the 12V
power. The lights and fans come on when plugged in.

Most likely it is a problem with my code.

Digital pin 3 is connected to line 1 on the relay board, pin 4 to line 2, pin 5 to line 3
and pin 6 to line 4. The 5V feed from the Arduino is connected to the VCC on the
relay board as is the ground. On the relay side, the Coms are daisy chained
together and supplied with 12V DC from a separate power source. The normally
closeds are then connected to the positive terminal on a 4 separate RCA jacks. The
jacks are used to connect the fans and lights. The negative to the jacks comes
straight from the power source.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 07, 2012, 03:27 pm

Quote

9500 character post limit, you were lucky to get what you got.
Somehow I don't feel lucky. 8)

The 9500 character limit does not apply to attached code.

9500 characters is more than plenty to write a sketch that demonstrates that a
relay can be toggled on and off every second.

9500 characters is more than enough to verify that the temperature sensor can be
read and the value printed to the serial monitor.

9500 characters is more than enough to verify that you can write to the LCD.

Writing one huge program that does everything, and is full of delay()s, is not the
way to approach programming.

Develop a series of little sketches that demonstrate that the individual pieces all
work. When you know that that happens, start combining them, two at a time. If,
or when, stuff doesn't work together, it is so much simpler to detect why.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: liuzengqiang on Dec 07, 2012, 04:24 pm

I can only infer you are using some sort of shield from some dfr seller. Are you sure
you don't have a pin conflict between this hardware and your relays on pins 3,4,5,
and 6?

To trigger event at certain time of RTC, I would look into how to do that in my
alarm clock code that I wrote for my phi-2 shield.

http://liudr.wordpress.com/shields/phi-2-shield/

There is a link to the alarm clock source code download. To be honest, this shield,
which I designed, is much better than what you're using. There is an on board RTC
and well-written menu and interaction libraries for user interface.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 07, 2012, 08:53 pm

Maybe I have not been clear about what I have done. Let me simplify...

I wrote code for the LCD with just the LCD attached. Tested it and it worked, so I
moved on.
I then wrote code for the DHT. Tested it and it worked, so I moved on.

I then wrote code for the RTC. Tested it and it worked, so I moved on.

As the RTC and DHT were successfully communicating with the Arduino which was
successfully displaying their data on the LCD, and both the RTC and DHT are
needed in the code I am writing for the relays, it was time for me to write code for
the last step, using the RTC and DHT data to control the relay board. Before I did
that, I took one step sideways and I tested that the Arduino communicates
successfully with the relay board using a simple loop on/off code and that worked.

PaulS your suggesting that I should "develop a series of little sketches that
demonstrate that the individual pieces all work" and then, "when (I) know that that
happens, start combining them, two at a time" is, as you can now see, exactly what
I did. But good advice none-the-less and maybe it will help someone else reading
this post on one of their projects.

I apologize if this was not clear in my initial post but like I said, we are limited to
9500 characters. And to PaulS suggestion that that does not include attached code,
yes PaulS the 9500 character limit does include attached code. Deleting the
comment lines out of my code is what got me under 9500 characters.

@liudr, I am using an LCD shield, everything else is connected through that shield
to the Arduino. Your shields look do look great though and I may look to use them
for another project, but for this project, I already have all the pieces I need and
just need help with the code. If you think the libraries or code you have written
for them will assist me with using what I already have, please send my way.
Thanks

Here is a list of what I am using:


Tiny I2C RTC DS1307 AT24C32 Real Time Clock Module For Arduino AVR ARM PIC
L298N Dual H Bridge DC Stepper Motor-Treiber Controller Board
5V 4-Channel Relay Module Board for Arduino PIC MSP W/ Optocouple SRD-
05VDC-SL-C
DHT11 Arduino Compatible Digital Temperature Humidity Sensor Module+Dupond
1602 LCD Board Keypad Shield Blue Backlight For Arduino Duemilanove Robot

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: liuzengqiang on Dec 07, 2012, 10:17 pm
http://code.google.com/p/phi-prompt-user-interface-
library/downloads/detail?name=Phi_2_project_alarm_clock_v6.zip&can=2&q=

Code above is an alarm clock. You can modify the alarm function to check whether
it is time to do certain thing according to RTC.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 07, 2012, 11:40 pm

Quote

I apologize if this was not clear in my initial post but like I said, we are limited to 9500
characters. And to PaulS suggestion that that does not include attached code, yes PaulS
the 9500 character limit does include attached code. Deleting the comment lines out of my
code is what got me under 9500 characters.

The 9500 character limit refers to posted code. That is code in this box. And text.
But, see down there? Below this window? The Additional Options link. Well, OK, so
it does not look a lot like a link. But, it is. Select that. You can attach much larger
than 9500 character files.

I am happy to hear that you are developing the code in pieces. That wasn't clear
from your post.

I still think that those delays have got to go. The millis() function and a state
machine (what do I need to do on this pass through loop, if is is time to do
anything) is much better than sitting on your hands for relatively long periods of
time.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 12:47 am

Got it. Was just following instructions. The forum says to post code between

Code: [Select]

using the #.

Anyways... Which delays do you suggest I delete? All of them? Are you
suggesting the delays are causing the issue? If I don't have any delays, won't that
cause a display issue on the LCD (i.e. the data won't be displayed long enough for
anyone to read it)?

What is the millis() function?


Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 12:55 am

Quote

Anyways... Which delays do you suggest I delete? All of them?

If I ask you to make me breakfast, consisting of eggs, bacon, toast, and coffee, can
you figure out how to make all the food get done at the same time? Or, am I going
to gets eggs, then, some time later, bacon, then, some time later, toast, and
finally, after I've finished eating, the coffee will be ready?

Yes, all of the delays.

Quote
Are you suggesting the delays are causing the issue?

I don't understand what the issue is. I don't see any serial out put that says "Time
to turn the relay on" and "Time to turn the relay off", annotated to note whether
that happened, or not. Calls to delay() do not belong in a sketch that is doing more
than blinking an LED.

Quote
If I don't have any delays, won't that cause a display issue on the LCD (i.e. the data won't
be displayed long enough for anyone to read it)?

Not if you don't immediately overwrite the data. See the comments above.

Quote
What is the millis() function?

Is it necessary to point out that up there at the top of the page there is a link that
says Main Site, and that on that page there is one that says Reference, and that on
that page all the Arduino-specific functions are documented?

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 01:04 am

And to think I questioned whether posting here would be of any help or if I would
just receive smart ass comments...

Code that I meant to turn relays on and off:


Code: [Select]

if (LightOn == false) {

//Calculate current time + delay minuts (Sleep variable time) to give a


wide window making sure we can hit the start time.
//If the program starts after this window then the relay will not start
until StartHr & StartMin the following day.

DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_3 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_3 &&
(int)now.minute() <= DelayFuture.minute()) {

//Set future DateTime used to determine the duration of light on time

future = CalcFuture(now,DurDay3,DurHour3,DurMinute3,DurSecond3);

//Turn on light
LightOn = true;
digitalWrite(Relay_3, RELAY_ON);

Serial.println("\r\nLight On\r\n");

}
}

else {

//Check current time - turn off light when conditions are met

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {

//Turn off light


LightOn = false;
digitalWrite(Relay_3, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));

//Check status of light


if (LightOn == false) {

//Calculate current time + delay minuts (Sleep variable time) to give a


wide window making sure we can hit the start time.
//If the program starts after this window then the relay will not start
until StartHr & StartMin the following day.

DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_4 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_4 &&
(int)now.minute() <= DelayFuture.minute()) {

//Set future DateTime used to determine the duration of light on time

future = CalcFuture(now,DurDay4,DurHour4,DurMinute4,DurSecond4);

//Turn on light
LightOn = true;
digitalWrite(Relay_4, RELAY_ON);

Serial.println("\r\nLight On\r\n");

}
}

else {

//Check current time - turn off light when conditions are met

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {

//Turn off light


LightOn = false;
digitalWrite(Relay_4, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));
Code: [Select]
//Chimney fan (Relay_1) on-off temperature
if (dht.readTemperature() >= 20) {
digitalWrite(Relay_1, RELAY_OFF);
}
else if (dht.readTemperature() < 18) {
digitalWrite(Relay_1, RELAY_ON);
}

//Window fan (Relay_2) on-off temperature


if (dht.readTemperature() >= 25) {
digitalWrite(Relay_2, RELAY_OFF);
}
else if (dht.readTemperature() < 23) {
digitalWrite(Relay_2, RELAY_ON);
}

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 01:17 am

Code: [Select]

if ((int)now.hour() >= StartHrRelay_3 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_3 &&
(int)now.minute() <= DelayFuture.minute()) {

Doesn't now.hour() return an int? Why is it necessary to cast to int?

Nested ifs are far easier to understand and debug, in my opinion, than compound
ifs.

Please, do yourself, and us, a favor. Put each { on a new line, use the return key
more often, and use Tools + Auto Format.

You have Serial.print() statements in your code. You are not sharing what you see,
bogart.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 01:23 am
Quote

Doesn't now.hour() return an int? Why is it necessary to cast to int?

No idea, I didn't write that code. I borrowed it from someone else's project. If it
doesn't need to be there, or if it should be changed to something different, what do
you suggest?

I've now used Tools + Auto Format. Didn't even know that feature existed. Other
than making my code look pretty, I don't think it will solve my issue. But then
again, neither will removing the delays.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 01:35 am

Quote

Other than making my code look pretty, I don't think it will solve my issue.

No, but it makes it easier to see the structure.

Quote
But then again, neither will removing the delays.

Maybe not. But you aren't being clear on what the problem is, or where in the
code/when the problem occurs.

Quote
If it doesn't need to be there, or if it should be changed to something different, what do you
suggest?

I suggest that you look at the documentation for the class that now is an instance
of, and determine what type the hour(), minute(), and second() functions return,
and determine whether it is necessary to cast that value to a different type.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 01:49 am

Thanks for your help PaulS.

Anyone else??? Paul doesn't seem to understand the issue.

Attached is my code. The delays are still in but I have Auto Formatted it. Seems
to me that if I delete the delays the loop will cycle through too fast for the
information to be displayed on the LCD.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 02:24 am
Quote

Paul doesn't seem to understand the issue.

Perhaps because you have not stated the problem clearly enough.

Something like this. I see this in the serial monitor:

Quote

Time to turn the relay.

My code looks like this:

Code: [Select]

Serial.print("Time to turn the relay on");


digitalWrite(relayPin, HIGH);

The relay does not come on.

Now, something like that would be easy to troubleshoot.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 02:32 am

Read up ^. The relays cycle when using a test code (i.e. one that cycles the relay
and does nothing else) but don't with the attached code. The test code I used was
essentially the same code as you listed in your preceding post.

I think its time for you to move on PaulS. This issue seem to be above your level of
competency. Thanks for your help.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 02:44 am

One last post, then I'll leave you alone.


Why are you reading the temperature so many times?

Code: [Select]
float h = dht.readHumidity();
float t = dht.readTemperature();

if (dht.readTemperature() >= 20)


{
digitalWrite(Relay_1, RELAY_OFF);
}
else if (dht.readTemperature() < 18)
{
digitalWrite(Relay_1, RELAY_ON);
}

//Window fan (Relay_2) on-off temperature


if (dht.readTemperature() >= 25)
{
digitalWrite(Relay_2, RELAY_OFF);
}
else if (dht.readTemperature() < 23)
{
digitalWrite(Relay_2, RELAY_ON);
}

Where are the serial print statements to show whether the relay is to be turned on
or off? What actually happens?

I know that it is frustrating when code doesn't work as you want, but, you need to
remember that we can't see what you are seeing. If you don't show serial output,
we can't see it. If you don't say what the relays are actually doing, we don't know.

Anyway, I wish you luck in solving your problem.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 02:49 am

Maybe that is what is missing, the serial print statements. Maybe serial print
statements should replace dht.readTemperature().

I don't know what the relays are doing with that code. As I said, they don't seem
to be doing anything.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 08:53 am

Attached is my revised code using PaulS's suggestions. I haven't been able to test
it, because the USB chip on my Arduino burned up, but I've ordered a replacement.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: Docedison on Dec 08, 2012, 12:53 pm
Why write the data unless it has changed? is what I think the center of the issue
here.
What the total center that is being asked is why do anything that doesn't need to
be done. millisec() is great for that I've heard/.

Bob

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 09:36 pm

I'm not sure what millisec() does. I've never heard of it and can't find any
documentation on it.

I have however removed my delays and inserted millis()s. I've never used this
function before and am not sure if I did it correct. Attached is my code.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: Docedison on Dec 08, 2012, 11:08 pm

There is a page here you might find useful


http://arduino.cc/en/Reference/HomePage
(http://arduino.cc/en/Reference/HomePage)
and Specifically:http://arduino.cc/en/Reference/Millis
(http://arduino.cc/en/Reference/Millis)
For further reading try the Blink without delay Sketch. I've taken the liberty of
posting it here for your perusal...
Please read the comments...

Code: [Select]

// constants won't change. Used here to


// set pin numbers:
const int ledPin = 13; // the number of the LED pin

// Variables will change:


int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,


// will quickly become a bigger number than can be stored in an int.
long interval = 1000; // interval at which to blink (milliseconds)

void setup()
{
pinMode(ledPin, OUTPUT); // set the digital pin as output:
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval)
{
// save the last time you blinked the LED
previousMillis = currentMillis;
if (ledState == LOW) // if the LED is off turn it on and vice-versa:
ledState = HIGH;
else
ledState = LOW; // set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}

Bob

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 09, 2012, 03:11 am

Thanks Bob.

I had used a different tutorial to create my code around the millis() function. The
reference you provided makes more sense though...

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: scottyjr on Dec 09, 2012, 01:41 pm

Quote

This issue seem to be above your level of competency.

R i i i i i i g h t! - Scotty
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: liuzengqiang on Dec 09, 2012, 06:27 pm

Op, have you ever tested the code you wrote or borrowed with simple LEDs instead
of going straight for the relay board? If the LEDs don't behave what the relays
should, you have a software problem. If they do behave the way you intended your
relays do, you have hardware problem.

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

Text only | Text with Images

Arduino Forum
Using Arduino => Programming Questions => Topic started by:
34DOL on Dec 07, 2012, 04:43 am

Title: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper


Post by: 34DOL on Dec 07, 2012, 04:43 am

Basically I'm looking to have my Arduino Uno control 2 fans based on temperature
readings from DHT11 (i.e. go on above a certain temperature) and turn on 2
different sets of lights based on the time of day (DS1307 RTC).

Both the DS1307 RTC and the DHT11 are communicating with the Arduino and
displaying on the LCD.

The relays are currently wired with the Com to 12V and the NC to the various
device (i.e. fans or lights). The relays seem to cycle. I can hear them clicking, but
my code doesn't control them as I intend. Please assist...

I have yet to connect or code for the stepper motor, but essentially it will open and
close a door with a screw drive based on the time of day.

Code: [Select]

#include <LiquidCrystal.h>
#include <DFR_Key.h>
#include <Wire.h>
#include "RTClib.h"
#include "DHT.h"

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

DFR_Key keypad;

int localKey = 0;
String keyString = "";

RTC_DS1307 RTC;

int StartHrRelay_1 = 21;


int StartMinRelay_1 = 00;

int StartHrRelay_2 = 21;


int StartMinRelay_2 = 00;

int StartHrRelay_3 = 7;
int StartMinRelay_3 = 44;

int StartHrRelay_4 = 7;
int StartMinRelay_4 = 44;

long Sleep = 1L;

long MultiMinute = 60000L;

boolean LightOn = false;

DateTime future;
DateTime DelayFuture;
DateTime Start;

int DurDay1 = 0;
int DurHour1 = 10;
int DurMinute1 = 0;
int DurSecond1 = 0;

int DurDay2 = 0;
int DurHour2 = 8;
int DurMinute2 = 0;
int DurSecond2 = 0;

int DurDay3 = 0;
int DurHour3 = 1;
int DurMinute3 = 0;
int DurSecond3 = 0;

int DurDay4 = 0;
int DurHour4 = 1;
int DurMinute4 = 30;
int DurSecond4 = 0;

#define RELAY_ON 0
#define RELAY_OFF 1

int Relay_1 = 3;
int Relay_2 = 4;
int Relay_3 = 5;
int Relay_4 = 6;

long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}

#define DHTPIN 2

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);


double dewPoint(double celsius, double humidity)
{
double A0= 373.15/(273.15 + celsius);
double SUM = -7.90298 * (A0-1);
SUM += 5.02808 * log10(A0);
SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
SUM += log10(1013.246);
double VP = pow(10, SUM-3) * humidity;
double T = log(VP/0.61078); // temp var
return (241.88 * T) / (17.558-T);
}

void setup() {
Serial.begin(57600);
lcd.begin (16,2);
lcd.print(" Chicken Coop ");
Wire.begin();
RTC.begin();

RTC.adjust(DateTime(__DATE__, __TIME__));

if (! RTC.isrunning()) {
lcd.setCursor (0,0);
lcd.print(" *-- RTC's --*");
lcd.setCursor (0,1);
lcd.print(" NOT running!");
Serial.println(" *-- RTC's NOT running! --*");
delay (5000) ;
lcd.clear();
RTC.adjust(DateTime(__DATE__, __TIME__));
}

DateTime now = RTC.now();


DateTime
SetStart(now.year(),now.month(),now.day(),StartHrRelay_1,StartMinRelay_1,now.
second());

Start = SetStart;
digitalWrite(Relay_1, RELAY_OFF);
pinMode(Relay_1, OUTPUT);

digitalWrite(Relay_2, RELAY_OFF);
pinMode(Relay_2, OUTPUT);

digitalWrite(Relay_3, RELAY_OFF);
pinMode(Relay_3, OUTPUT);

digitalWrite(Relay_4, RELAY_OFF);
pinMode(Relay_4, OUTPUT);

delay(4000);

dht.begin();

void loop()
float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(t) || isnan(h)) {
lcd.setCursor (0,0);
lcd.print("*-- Failed to");
lcd.setCursor (0,1);
lcd.print(" read T&H --*");
Serial.println("*-- Failed to read T&H --*");
delay (5000) ;
lcd.clear();
}
else {
lcd.setCursor (0,0);
lcd.print("Temp (F): ");
lcd.print(t*9/5 + 32);
lcd.print(" *F");
lcd.setCursor (0,1);
lcd.print("Humidity: ");
lcd.print(h);
lcd.print("% ");

delay (5000) ;
lcd.clear();

lcd.setCursor (0,0);
lcd.print("Temp (C): ");
lcd.print(t);
lcd.print(" *C");
lcd.setCursor (0,1);
lcd.print("Dew Point: ");
lcd.print(dewPoint(t, h));
lcd.print(" *C");

delay (5000) ;
lcd.clear();

Serial.print("Temp (F): ");


Serial.print(t*9/5 + 32);
Serial.println(" *F");
Serial.print("Humidity: ");
Serial.print(h);
Serial.println("% ");

Serial.print("Temp (C): ");


Serial.print(t);
Serial.println(" *C");
Serial.print("Dew Point: ");
Serial.print(dewPoint(t, h));
Serial.println(" *C");
}

if (dht.readTemperature() >= 20) {


digitalWrite(Relay_1, RELAY_OFF);
}
else if (dht.readTemperature() < 18) {
digitalWrite(Relay_1, RELAY_ON);
}
if (dht.readTemperature() >= 25) {
digitalWrite(Relay_2, RELAY_OFF);
}
else if (dht.readTemperature() < 23) {
digitalWrite(Relay_2, RELAY_ON);
}

lcd.setCursor (0,0);
lcd.print("Volts (mV): ");
lcd.print( readVcc(), DEC );

delay(5000);
lcd.clear();

DateTime now = RTC.now();

lcd.setCursor (0,0);
lcd.print(" ");
lcd.print(now.year(), DEC);
lcd.print('/');
lcd.print(now.month(), DEC);
lcd.print('/');
lcd.print(now.day(), DEC);

lcd.setCursor (0,1);
lcd.print(" ");
lcd.print(now.hour(), DEC);
lcd.print(':');
lcd.print(now.minute(), DEC);

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.println(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();

delay(5000);
lcd.clear();

if (LightOn == false) {

DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_3 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_3 &&
(int)now.minute() <= DelayFuture.minute()) {

future = CalcFuture(now,DurDay3,DurHour3,DurMinute3,DurSecond3);

LightOn = true;
digitalWrite(Relay_3, RELAY_ON);

Serial.println("\r\nLight On\r\n");

}
}

else {

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {

LightOn = false;
digitalWrite(Relay_3, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));

if (LightOn == false) {
DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_4 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_4 &&
(int)now.minute() <= DelayFuture.minute()) {

future = CalcFuture(now,DurDay4,DurHour4,DurMinute4,DurSecond4);

LightOn = true;
digitalWrite(Relay_4, RELAY_ON);

Serial.println("\r\nLight On\r\n");

}
}

else {

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {

LightOn = false;
digitalWrite(Relay_4, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));
}

DateTime CalcFuture (DateTime now, int Days, int Hours, int Minutes, int
Seconds){

DateTime future;
long DaySeconds = 86400L;
long HourSeconds = 3600L;
long MinuteSeconds = 60L;

future = (now.unixtime() + (Days * DaySeconds) + (Hours * HourSeconds) +


(Minutes * MinuteSeconds) + (Seconds));
return future;
}

//

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 07, 2012, 06:36 am

Quote

I can hear them clicking, but my code doesn't control them as I intend. Please assist.

That's a real shame.

Now, perhaps if you told us how you intended that code to work, and how it
actually works, we could help you.

All those delay()s aren't.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 07, 2012, 07:36 am

9500 character post limit, you were lucky to get what you got. I had to delete all of
my comments out of the code.

I intend the code to work such that the relays are turned on or off based on
information supplied by the RTC and DHT. Relays 1 & 2 are intended to control the
fans. Relays 3 & 4 are intended to control the lights.

The arduino is receiving data from the RTC and DHT and displays as the data
intended on the LCD. What doesn't work, or doesn't work as intended, is my code
to use that data to control the relays. What does that part of the code do? Well,
from what I can tell, pretty much nothing. I've search all over for code that I could
use to turn relays on or off based off data values from the RTC and DHT compared
to pre-assigned arguments and haven't been able to put together anything that
works. What I have here is the closest I've been able to come.

Maybe my relays are connected incorrectly, but I don't think so. Since I wired
them as normally closed I am able to tell that they are at least getting the 12V
power. The lights and fans come on when plugged in.

Most likely it is a problem with my code.


Digital pin 3 is connected to line 1 on the relay board, pin 4 to line 2, pin 5 to line 3
and pin 6 to line 4. The 5V feed from the Arduino is connected to the VCC on the
relay board as is the ground. On the relay side, the Coms are daisy chained
together and supplied with 12V DC from a separate power source. The normally
closeds are then connected to the positive terminal on a 4 separate RCA jacks. The
jacks are used to connect the fans and lights. The negative to the jacks comes
straight from the power source.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 07, 2012, 03:27 pm

Quote

9500 character post limit, you were lucky to get what you got.

Somehow I don't feel lucky. 8)

The 9500 character limit does not apply to attached code.

9500 characters is more than plenty to write a sketch that demonstrates that a
relay can be toggled on and off every second.

9500 characters is more than enough to verify that the temperature sensor can be
read and the value printed to the serial monitor.

9500 characters is more than enough to verify that you can write to the LCD.

Writing one huge program that does everything, and is full of delay()s, is not the
way to approach programming.

Develop a series of little sketches that demonstrate that the individual pieces all
work. When you know that that happens, start combining them, two at a time. If,
or when, stuff doesn't work together, it is so much simpler to detect why.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: liuzengqiang on Dec 07, 2012, 04:24 pm

I can only infer you are using some sort of shield from some dfr seller. Are you sure
you don't have a pin conflict between this hardware and your relays on pins 3,4,5,
and 6?

To trigger event at certain time of RTC, I would look into how to do that in my
alarm clock code that I wrote for my phi-2 shield.
http://liudr.wordpress.com/shields/phi-2-shield/

There is a link to the alarm clock source code download. To be honest, this shield,
which I designed, is much better than what you're using. There is an on board RTC
and well-written menu and interaction libraries for user interface.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 07, 2012, 08:53 pm

Maybe I have not been clear about what I have done. Let me simplify...

I wrote code for the LCD with just the LCD attached. Tested it and it worked, so I
moved on.

I then wrote code for the DHT. Tested it and it worked, so I moved on.

I then wrote code for the RTC. Tested it and it worked, so I moved on.

As the RTC and DHT were successfully communicating with the Arduino which was
successfully displaying their data on the LCD, and both the RTC and DHT are
needed in the code I am writing for the relays, it was time for me to write code for
the last step, using the RTC and DHT data to control the relay board. Before I did
that, I took one step sideways and I tested that the Arduino communicates
successfully with the relay board using a simple loop on/off code and that worked.

PaulS your suggesting that I should "develop a series of little sketches that
demonstrate that the individual pieces all work" and then, "when (I) know that that
happens, start combining them, two at a time" is, as you can now see, exactly what
I did. But good advice none-the-less and maybe it will help someone else reading
this post on one of their projects.

I apologize if this was not clear in my initial post but like I said, we are limited to
9500 characters. And to PaulS suggestion that that does not include attached code,
yes PaulS the 9500 character limit does include attached code. Deleting the
comment lines out of my code is what got me under 9500 characters.

@liudr, I am using an LCD shield, everything else is connected through that shield
to the Arduino. Your shields look do look great though and I may look to use them
for another project, but for this project, I already have all the pieces I need and
just need help with the code. If you think the libraries or code you have written
for them will assist me with using what I already have, please send my way.
Thanks

Here is a list of what I am using:


Tiny I2C RTC DS1307 AT24C32 Real Time Clock Module For Arduino AVR ARM PIC
L298N Dual H Bridge DC Stepper Motor-Treiber Controller Board
5V 4-Channel Relay Module Board for Arduino PIC MSP W/ Optocouple SRD-
05VDC-SL-C
DHT11 Arduino Compatible Digital Temperature Humidity Sensor Module+Dupond
1602 LCD Board Keypad Shield Blue Backlight For Arduino Duemilanove Robot

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: liuzengqiang on Dec 07, 2012, 10:17 pm

http://code.google.com/p/phi-prompt-user-interface-
library/downloads/detail?name=Phi_2_project_alarm_clock_v6.zip&can=2&q=

Code above is an alarm clock. You can modify the alarm function to check whether
it is time to do certain thing according to RTC.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 07, 2012, 11:40 pm

Quote

I apologize if this was not clear in my initial post but like I said, we are limited to 9500
characters. And to PaulS suggestion that that does not include attached code, yes PaulS
the 9500 character limit does include attached code. Deleting the comment lines out of my
code is what got me under 9500 characters.

The 9500 character limit refers to posted code. That is code in this box. And text.
But, see down there? Below this window? The Additional Options link. Well, OK, so
it does not look a lot like a link. But, it is. Select that. You can attach much larger
than 9500 character files.

I am happy to hear that you are developing the code in pieces. That wasn't clear
from your post.

I still think that those delays have got to go. The millis() function and a state
machine (what do I need to do on this pass through loop, if is is time to do
anything) is much better than sitting on your hands for relatively long periods of
time.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 12:47 am
Got it. Was just following instructions. The forum says to post code between

Code: [Select]

using the #.

Anyways... Which delays do you suggest I delete? All of them? Are you
suggesting the delays are causing the issue? If I don't have any delays, won't that
cause a display issue on the LCD (i.e. the data won't be displayed long enough for
anyone to read it)?

What is the millis() function?

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 12:55 am

Quote

Anyways... Which delays do you suggest I delete? All of them?

If I ask you to make me breakfast, consisting of eggs, bacon, toast, and coffee, can
you figure out how to make all the food get done at the same time? Or, am I going
to gets eggs, then, some time later, bacon, then, some time later, toast, and
finally, after I've finished eating, the coffee will be ready?

Yes, all of the delays.

Quote
Are you suggesting the delays are causing the issue?

I don't understand what the issue is. I don't see any serial out put that says "Time
to turn the relay on" and "Time to turn the relay off", annotated to note whether
that happened, or not. Calls to delay() do not belong in a sketch that is doing more
than blinking an LED.

Quote
If I don't have any delays, won't that cause a display issue on the LCD (i.e. the data won't
be displayed long enough for anyone to read it)?

Not if you don't immediately overwrite the data. See the comments above.

Quote
What is the millis() function?
Is it necessary to point out that up there at the top of the page there is a link that
says Main Site, and that on that page there is one that says Reference, and that on
that page all the Arduino-specific functions are documented?

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 01:04 am

And to think I questioned whether posting here would be of any help or if I would
just receive smart ass comments...

Code that I meant to turn relays on and off:

Code: [Select]

if (LightOn == false) {

//Calculate current time + delay minuts (Sleep variable time) to give a


wide window making sure we can hit the start time.
//If the program starts after this window then the relay will not start
until StartHr & StartMin the following day.

DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_3 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_3 &&
(int)now.minute() <= DelayFuture.minute()) {

//Set future DateTime used to determine the duration of light on time

future = CalcFuture(now,DurDay3,DurHour3,DurMinute3,DurSecond3);

//Turn on light
LightOn = true;
digitalWrite(Relay_3, RELAY_ON);

Serial.println("\r\nLight On\r\n");

}
}

else {

//Check current time - turn off light when conditions are met

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {
//Turn off light
LightOn = false;
digitalWrite(Relay_3, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));

//Check status of light

if (LightOn == false) {

//Calculate current time + delay minuts (Sleep variable time) to give a


wide window making sure we can hit the start time.
//If the program starts after this window then the relay will not start
until StartHr & StartMin the following day.

DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);

if ((int)now.hour() >= StartHrRelay_4 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_4 &&
(int)now.minute() <= DelayFuture.minute()) {

//Set future DateTime used to determine the duration of light on time

future = CalcFuture(now,DurDay4,DurHour4,DurMinute4,DurSecond4);

//Turn on light
LightOn = true;
digitalWrite(Relay_4, RELAY_ON);

Serial.println("\r\nLight On\r\n");

}
}

else {

//Check current time - turn off light when conditions are met

if ((int)now.day() >= (int)future.day() && (int)now.hour() >=


(int)future.hour() && (int)now.minute() >= (int)future.minute()) {

//Turn off light


LightOn = false;
digitalWrite(Relay_4, RELAY_OFF);

Serial.print("\r\nLight Off\r\n");

}
}
delay((Sleep*MultiMinute));

Code: [Select]
//Chimney fan (Relay_1) on-off temperature
if (dht.readTemperature() >= 20) {
digitalWrite(Relay_1, RELAY_OFF);
}
else if (dht.readTemperature() < 18) {
digitalWrite(Relay_1, RELAY_ON);
}

//Window fan (Relay_2) on-off temperature


if (dht.readTemperature() >= 25) {
digitalWrite(Relay_2, RELAY_OFF);
}
else if (dht.readTemperature() < 23) {
digitalWrite(Relay_2, RELAY_ON);
}

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 01:17 am

Code: [Select]

if ((int)now.hour() >= StartHrRelay_3 && (int)now.hour() <=


DelayFuture.hour() && (int)now.minute() >= StartMinRelay_3 &&
(int)now.minute() <= DelayFuture.minute()) {

Doesn't now.hour() return an int? Why is it necessary to cast to int?

Nested ifs are far easier to understand and debug, in my opinion, than compound
ifs.

Please, do yourself, and us, a favor. Put each { on a new line, use the return key
more often, and use Tools + Auto Format.

You have Serial.print() statements in your code. You are not sharing what you see,
bogart.
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 01:23 am
Quote

Doesn't now.hour() return an int? Why is it necessary to cast to int?

No idea, I didn't write that code. I borrowed it from someone else's project. If it
doesn't need to be there, or if it should be changed to something different, what do
you suggest?

I've now used Tools + Auto Format. Didn't even know that feature existed. Other
than making my code look pretty, I don't think it will solve my issue. But then
again, neither will removing the delays.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 01:35 am

Quote

Other than making my code look pretty, I don't think it will solve my issue.

No, but it makes it easier to see the structure.

Quote
But then again, neither will removing the delays.

Maybe not. But you aren't being clear on what the problem is, or where in the
code/when the problem occurs.

Quote
If it doesn't need to be there, or if it should be changed to something different, what do you
suggest?

I suggest that you look at the documentation for the class that now is an instance
of, and determine what type the hour(), minute(), and second() functions return,
and determine whether it is necessary to cast that value to a different type.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 01:49 am

Thanks for your help PaulS.

Anyone else??? Paul doesn't seem to understand the issue.


Attached is my code. The delays are still in but I have Auto Formatted it. Seems
to me that if I delete the delays the loop will cycle through too fast for the
information to be displayed on the LCD.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 02:24 am

Quote

Paul doesn't seem to understand the issue.

Perhaps because you have not stated the problem clearly enough.

Something like this. I see this in the serial monitor:

Quote

Time to turn the relay.

My code looks like this:

Code: [Select]

Serial.print("Time to turn the relay on");


digitalWrite(relayPin, HIGH);

The relay does not come on.

Now, something like that would be easy to troubleshoot.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 02:32 am

Read up ^. The relays cycle when using a test code (i.e. one that cycles the relay
and does nothing else) but don't with the attached code. The test code I used was
essentially the same code as you listed in your preceding post.

I think its time for you to move on PaulS. This issue seem to be above your level of
competency. Thanks for your help.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 02:44 am
One last post, then I'll leave you alone.
Why are you reading the temperature so many times?

Code: [Select]
float h = dht.readHumidity();
float t = dht.readTemperature();

if (dht.readTemperature() >= 20)


{
digitalWrite(Relay_1, RELAY_OFF);
}
else if (dht.readTemperature() < 18)
{
digitalWrite(Relay_1, RELAY_ON);
}

//Window fan (Relay_2) on-off temperature


if (dht.readTemperature() >= 25)
{
digitalWrite(Relay_2, RELAY_OFF);
}
else if (dht.readTemperature() < 23)
{
digitalWrite(Relay_2, RELAY_ON);
}

Where are the serial print statements to show whether the relay is to be turned on
or off? What actually happens?

I know that it is frustrating when code doesn't work as you want, but, you need to
remember that we can't see what you are seeing. If you don't show serial output,
we can't see it. If you don't say what the relays are actually doing, we don't know.

Anyway, I wish you luck in solving your problem.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 02:49 am

Maybe that is what is missing, the serial print statements. Maybe serial print
statements should replace dht.readTemperature().

I don't know what the relays are doing with that code. As I said, they don't seem
to be doing anything.
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 08:53 am

Attached is my revised code using PaulS's suggestions. I haven't been able to test
it, because the USB chip on my Arduino burned up, but I've ordered a replacement.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: Docedison on Dec 08, 2012, 12:53 pm

Why write the data unless it has changed? is what I think the center of the issue
here.
What the total center that is being asked is why do anything that doesn't need to
be done. millisec() is great for that I've heard/.

Bob

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 08, 2012, 09:36 pm

I'm not sure what millisec() does. I've never heard of it and can't find any
documentation on it.

I have however removed my delays and inserted millis()s. I've never used this
function before and am not sure if I did it correct. Attached is my code.

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: Docedison on Dec 08, 2012, 11:08 pm

There is a page here you might find useful


http://arduino.cc/en/Reference/HomePage
(http://arduino.cc/en/Reference/HomePage)
and Specifically:http://arduino.cc/en/Reference/Millis
(http://arduino.cc/en/Reference/Millis)
For further reading try the Blink without delay Sketch. I've taken the liberty of
posting it here for your perusal...
Please read the comments...

Code: [Select]

// constants won't change. Used here to


// set pin numbers:
const int ledPin = 13; // the number of the LED pin

// Variables will change:


int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,


// will quickly become a bigger number than can be stored in an int.
long interval = 1000; // interval at which to blink (milliseconds)

void setup()
{
pinMode(ledPin, OUTPUT); // set the digital pin as output:
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval)
{
// save the last time you blinked the LED
previousMillis = currentMillis;
if (ledState == LOW) // if the LED is off turn it on and vice-versa:
ledState = HIGH;
else
ledState = LOW; // set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}

Bob

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: 34DOL on Dec 09, 2012, 03:11 am

Thanks Bob.

I had used a different tutorial to create my code around the millis() function. The
reference you provided makes more sense though...
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: scottyjr on Dec 09, 2012, 01:41 pm

Quote

This issue seem to be above your level of competency.

R i i i i i i g h t! - Scotty

Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: liuzengqiang on Dec 09, 2012, 06:27 pm

Op, have you ever tested the code you wrote or borrowed with simple LEDs instead
of going straight for the relay board? If the LEDs don't behave what the relays
should, you have a software problem. If they do behave the way you intended your
relays do, you have hardware problem.

Text only | Text with Images

SMF 2.1 Beta 1 2014, Simple Machines

HOME
BUY
SOFTWARE
PRODUCTS
LEARNING
FORUM
SUPPORT
BLOG

SIGN IN

Reference Language | Libraries | Comparison | Changes


Language Reference
Arduino programs can be divided in three main parts: structure, values (variables and
constants), and functions.

Structure Variables Functions


setup() Constants Digital I/O
loop()
HIGH | LOW pinMode()
Control Structures INPUT | OUTPUT | INPUT_PULLUP digitalWrite()
LED_BUILTIN digitalRead()
if true | false
if...else integer constants Analog I/O
for floating point constants
switch case analogReference()
while Data Types analogRead()
do... while analogWrite() - PWM
break void
continue boolean
return Due & Zero only
char
goto unsigned char
analogReadResolution()
byte
analogWriteResolution()
Further Syntax int
unsigned int
; (semicolon) word Advanced I/O
{} (curly braces) long
// (single line unsigned long tone()
comment) short noTone()
/* */ (multi-line float shiftOut()
comment) double shiftIn()
#define string - char array pulseIn()
#include String - object
array Time
Arithmetic Operators
Conversion millis()
= (assignment micros()
operator) char() delay()
+ (addition) byte() delayMicroseconds()
- (subtraction) int()
* (multiplication) word() Math
/ (division) long()
% (modulo) float() min()
max()
Comparison Variable Scope & Qualifiers abs()
Operators constrain()
variable scope
map()
static
== (equal to) pow()
volatile
!= (not equal to) sqrt()
const
< (less than)
> (greater than) Trigonometry
Utilities
<= (less than or equal
to) sin()
>= (greater than or sizeof()
cos()
equal to) PROGMEM
tan()

Boolean Operators Characters

&& (and) isAlphaNumeric()


|| (or) isAlpha()
! (not) isAscii()
isWhitespace()
Pointer Access isControl()
Operators isDigit()
isGraph()
isLowerCase()
* dereference
isPrintable()
operator
isPunct()
& reference operator
isSpace()
isUpperCase()
Bitwise Operators isHexadecimalDigit()

& (bitwise and) Random Numbers


| (bitwise or)
^ (bitwise xor)
randomSeed()
~ (bitwise not)
random()
<< (bitshift left)
>> (bitshift right)
Bits and Bytes
Compound
Operators lowByte()
highByte()
bitRead()
++ (increment)
bitWrite()
-- (decrement)
bitSet()
+= (compound
bitClear()
addition)
bit()
-= (compound
subtraction)
*= (compound External Interrupts
multiplication)
/= (compound attachInterrupt()
division) detachInterrupt()
%= (compound
modulo)
&= (compound Interrupts
bitwise and)
|= (compound interrupts()
bitwise or) noInterrupts()

Communication

Serial
Stream

USB (32u4 based boards


and Due/Zero only)

Keyboard
Mouse

Looking for something else?

See the libraries page for


interfacing with particular
types of hardware. Try
the list of community-
contributed code. The
Arduino language is
based on C/C++. It links
against AVR Libc and
allows the use of any of
its functions; see its user
manualfor details.
Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-
ShareAlike 3.0 License. Code samples in the reference are released into the public
domain.

Share
NEWSLETTER
SUBSCRIBE

Copyright Notice

Contact Us

About Us

Careers

2017 Arduino

HOME
BUY
SOFTWARE
PRODUCTS
LEARNING
FORUM
SUPPORT
BLOG

SIGN IN
Reference Language | Libraries | Comparison | Changes

millis()
Description

Returns the number of milliseconds since the Arduino board began running the
current program. This number will overflow (go back to zero), after approximately 50
days.

Parameters

None

Returns

Number of milliseconds since the program started (unsigned long)

Note:

Please note that the return value for millis() is an unsigned long, logic errors may
occur if a programmer tries to do arithmetic with smaller data types such as int's. Even
signed long may encounter errors as its maximum value is half that of its unsigned
counterpart.

Example

unsigned long time;

void setup(){
Serial.begin(9600);
}
void loop(){
Serial.print("Time: ");
time = millis();
//prints time since program started
Serial.println(time);
// wait a second so as not to send massive amounts of data
delay(1000);
}

[Get Code]
See also

micros()
delay()
delayMicroseconds()
Tutorial: Blink Without Delay

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-
ShareAlike 3.0 License. Code samples in the reference are released into the public
domain.

Share

NEWSLETTER
SUBSCRIBE

Copyright Notice

Contact Us

About Us

Careers

2017 Arduino

REPRAPPRO.ME Search this site

RepRapPro.me RepRapPro.me > Level 3 >


o Level 1
o
o
Level 2
Level 3
Arduino with 3 relays and
3D Printing This is the Arduino Mega with 3 relays controlled by values f
o 3D Design
and a Photoresistor

o Melzi Ardentissimo
o RepRap
Digispark
When the humidity is lower than 21 the system is OFF. When
o NRF24L01 When the temperature is above 25C the cooling system in O
ESP8266
o Arduino When light hits the photoresistor (more than 850) the system
o NodeMCU
than 850 the lights turn ON.
Garduino
o Garduino v1.2
Home made Microcontroller The values are showed on the LCD
Microchip PIC
o Level 1
o Level 2
o Level 3
NetCar
o Level 1
o Level 2
Quadcopter
o DJI NAZA
o Fatshark
o Materials
o MultiWii Lite
o Step By Step
Raspberry Pi
o Level 1
o Level 2
Side projects
o Beer machine
o IR miniRadar
o Roskilde PowerBox display unit
o Signals and linear systems in discrete time
o UltraSound miniSonar
o WLG (wire loop game)
Solar
o LM2596
o Solar Panel DIY
STM32
Webshop
Sitemap I have used this code:

#define dht11_pin 54 //Analog port 0 on A

// include the library code:

#include <LiquidCrystal.h>

// initialize the library with the number

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte read_dht11_dat()

{
byte i = 0;

byte result=0;

for(i=0; i< 8; i++)

while (!digitalRead(dht11_pin));

delayMicroseconds(30);

if (digitalRead(dht11_pin) != 0 )

bitSet(result, 7-i);

while (digitalRead(dht11_pin));

return result;

//define digital outputs to which we have


and light) and LED (temperature)

int HumidityTempSensor = 0;

int lightSensor = 1;

//int tempSensor = 2;

//define variables to store moisture, lig

int ht_val;

int light_val;

//int temp_val;

void setup() {

pinMode(dht11_pin, OUTPUT);

digitalWrite(dht11_pin, HIGH);
lcd.begin(16,2);

pinMode (2, OUTPUT);

pinMode (7, OUTPUT);

pinMode (8, OUTPUT);

pinMode (9, OUTPUT);

digitalWrite (2, LOW);

digitalWrite (7, LOW);

digitalWrite (8, LOW);

digitalWrite (9, LOW);

void loop() {

byte dht11_dat[5];

byte dht11_in;

byte i;// start condition

digitalWrite(dht11_pin, LOW);

delay(18);

digitalWrite(dht11_pin, HIGH);

delayMicroseconds(1);

pinMode(dht11_pin, INPUT);

delayMicroseconds(40);

if (digitalRead(dht11_pin))
{

lcd.println("dht11 start condition 1


response signal: LOW

delay(1000);

return;

delayMicroseconds(80);

if (!digitalRead(dht11_pin))

lcd.println("dht11 start condition 2


response signal:HIGH

return;

delayMicroseconds(80);// now ready for

for (i=0; i<5; i++)

{ dht11_dat[i] = read_dht11_dat();} /
Details are described in datasheet

pinMode(dht11_pin, OUTPUT);

digitalWrite(dht11_pin, HIGH);

byte dht11_check_sum = dht11_dat[0]+dht

if(dht11_dat[4]!= dht11_check_sum)

lcd.println("DHT11 checksum error");

ht_val = analogRead(HumidityTempSensor);
HumidityTemp sensor

lcd.print("Humidity = ");

lcd.print( dht11_dat[0], DEC );

lcd.print("% ");

lcd.setCursor (0, 1);

lcd.print("Temp = ");

lcd.print( dht11_dat[2], DEC );

lcd.print("C ");

delay(2000);

lcd.clear();

if (dht11_dat[0] < 21)

lcd.print("Humidity Outlet");

lcd.setCursor (0, 1);

lcd.print(" - OFF -");

digitalWrite (7, HIGH);

delay(2000);

lcd.clear();

if (dht11_dat[0] > 21)

lcd.print("Humidity Outlet");

lcd.setCursor (0, 1);

lcd.print(" - ON -");
digitalWrite (7, LOW);

delay(2000);

lcd.clear();

if (dht11_dat[2] < 25)

lcd.setCursor (1, 0);

lcd.print("Cooling System");

lcd.setCursor (0, 1);

lcd.print(" - ON -");

digitalWrite (9, HIGH);

delay(2000);

lcd.clear();

if (dht11_dat[2] > 25)

lcd.print("Cooling System");

lcd.setCursor (0, 1);

lcd.print(" - OFF -");

digitalWrite (9, LOW);

delay(2000);

lcd.clear();

light_val = analogRead(lightSensor); // r
photosensor
lcd.print("Light = ");

lcd.print( light_val );

delay(2000);

lcd.clear();

if (light_val > 850)

lcd.setCursor(1, 0);

lcd.print("Lights System");

lcd.setCursor(0, 1);

lcd.print(" - ON - ");

digitalWrite (8, HIGH);

delay(2000);

lcd.clear();

if (light_val < 850)

lcd.setCursor(1, 0);

lcd.print("Lights System");

lcd.setCursor(0, 1);

lcd.print(" - OFF - ");

digitalWrite (8, LOW);

delay(2000);

lcd.clear();

}
//temp_val = analogRead(tempSensor);

//Serial.print("temp sensor reads ");

//Serial.println( temp_val );

//if (temp_val < 920)

//{

//Serial.println("turning on low-temperat

//digitalWrite (2, HIGH);

//delay(2000);

//}

//if (temp_val > 920)

//{

//Serial.println("turning off low-tempera

//digitalWrite (2, LOW);

//delay(2000);

//}

Comments

You do not have permission to add comments.


Sign in|Recent Site Activity|Report Abuse|Print Page|Powered By Google Sites
/********************************
name: 5V relay module and DHT 11/22/21 humidity and temperature sensor
module
function: This program shows how the temperature and humidity sensor turns
on
devices or power sockets connected to 5V relay module
email: info.acoptex@gmail.com
web: http://acoptex.com
********************************/
#include <DHT.h> // include libraries
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

const int relayPin = 8;


const int DHTPIN = A0;

// Uncomment whatever type you're using!


#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);// Initialize DHT sensor


LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);//Initialise
the LCD 1602 I2C module
/********************************/
void setup() {
Serial.begin(9600);
pinMode(relayPin, OUTPUT);
dht.begin();
}

void loop()
{
//Define the LCD as 16 column by 2 rows
lcd.begin (16, 2);
//Switch on the backlight
lcd.setBacklight(HIGH);

// 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);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
//goto first column (column 0) and first line (Line 0)
lcd.setCursor(0, 0);
lcd.print("Temp = ");
lcd.print(t);
lcd.print(" *C ");
lcd.setCursor(0, 1);
lcd.print(" Hum = ");
lcd.print(h);
lcd.print(" % ");

Serial.print("Temperature = ");
Serial.print(t);
Serial.print(" *C ");
Serial.print("Temperature = ");
Serial.print(f);
Serial.print(" *F ");
Serial.print("Humidity = ");
Serial.print(h);
Serial.print(" %\t ");
Serial.println();
if (h >= 66) { // you can change humidity value here - h>=66 to your
preffered number
digitalWrite(relayPin, HIGH);
}
else {
digitalWrite(relayPin, LOW);
}
if (t >= 26) {// you can change temperature value here - t>= 30 to your
preferred number or change from Celsius to Fahrenheit readings
digitalWrite(relayPin, HIGH);
}
else {
digitalWrite(relayPin, LOW);
}
delay(1000);// 1 second delay between measurements
}

Acoptex.com
About Us


Contact Us
Search for a proje

(for example: "Arduino", "Raspberry, Bluetooth", "FeeTech FS90R 360 Servo")

POST A NEW PROJECT

ARDUINO
RASPBERRY PI
ARDUINO PROJECTS
ARDUINO ROBOTIX
RASPBERRY PROJECTS
BOOKS / NOTES / INSTRUCTIONS
DRIVERS / SOFTWARE
Home

Navigation

Seen recently
Basics: Project 011e 5V relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or
0
0

Google +

Vkontakte

Odnoklassniki

mail.ru

New

0
members
Basics: Project 011e 5V relay, DHT 11 21 22
sensor, LCD 1602 I2C module - Humidity or
of Acoptex.com in UNO
Basics: Project 011e
Project name: 5V relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or Temperature controlled relay
Attachments: libraries and program
WARNING THIS PROJECT INVOLVES HIGH VOLTAGES THAT CAN CAUSE SERIOUS INJURY OR DEATH.
PLEASE TAKE ALL NECESSARY PRECAUTIONS, AND TURN OFF ALL POWER TO A CIRCUIT BEFORE
WORKING ON IT. WE ARE NOT RESPONSIBLE FOR ANY DAMAGE, INJURY, DEATH AND OTHER THINGS
CAUSED BY THIS PROJECT IMPLEMENTATION.
In this project, you needed these parts :
1.Aruduino Uno R3 (you can also use the other version of Arduino)

2.5V Relay module 1 pc

3.Arduino IDE ( you can download it from here )


4.Jumper cables

5.Light bulb 60 W 220 V with connector 1pc


6.DHT11 or DHT21 or DHT22 - 1 pc

7.Resistor 1 KOm 1 pc

8. LCD 1602 I2C module

Understanding the Relay


You can read more about relay here.
You can find 5V relay module datasheet here.
Understanding DHT humidity and temperature sensor
You can read more about it here.
Datasheet can be found here.
Understanding LCD 1602 I2C module
You can read more about it here.
Signals and connections of DHT11 module
There are 3 : VCC (+5V), Data, GND (-)

Signals and connections of 5V Relay module nad LM35 sensor.


The SRD-05VDC-SL-C relay has three high voltage terminals (NC, C, and NO) which connect to the device you want to control.
The other side has three low voltage pins (Ground, Vcc, and Signal) which connect to the Arduino.

5V Relay Pinout

NC: Normally closed 120-240V terminal

NO: Normally open 120-240V terminal

C: Common terminal

Ground: Connects to the ground pin on the Arduino

5V Vcc: Connects the Arduinos 5V pin


Signal: Carries the trigger signal from the Arduino that activates the relay

Inside the relay is a 120-240V switch thats connected to an electromagnet. When the relay receives a HIGH signal at the signal
pin, the electromagnet becomes charged and moves the contacts of the switch open or closed.

NORMALLY OPEN VS. NORMALLY CLOSED

The relay has two different types of electrical contacts inside normally open (NO) and normally closed (NC). The one you use
will depend on whether you want the 5V signal to turn the switch on or turn the switch off. The 120-240V supply current enters
the relay at the common (C) terminal in both configurations. To use the normally open contacts, use the NO terminal. To use the
normally closed contacts, use the NC terminal.

The 5V Relay module has three high voltage terminals (NC, C, and NO) which connect to the device you want to control. The
other side has three low voltage pins (GND (0V), VCC (+5V), and S(Signal)) which connect to the Arduino board.
NC: Normally closed 120-240V terminal
NO: Normally open 120-240V terminal
C: Common terminal

Signals and contacts of LCD 1602 I2C module


As you can see on the back of LCD 1602 module there 4 connections: GND (-), VCC (+5V), Serial Data Line (SDA) and Serial
Clock Line (SCL).

Wiring
Let us build a HUMIDITY or TEMPERATURE controlled relay circuit that will turn on a light bulb when the humidity value
of a DHT 11 sensor reaches 66% or temperature value reaches 25 degrees Celsius. DHT 11 OR 21 OR 22 sensors are really
useful with 5V relays. You can use them to turn off a or turn on devices or power sockets depending on temperature or humidity
values.
Make sure that the high voltage connections to the 5V relay module are very well secured.

Identify the hot power wire (red wire in the diagram above) in the cord leading to the light bulb and make a cut. Connect the side
leading to the light bulb to the NO terminal of the 5V relay, and the side leading to the plug to the C terminal. This way the relay
is on the hot side, and current is switched before it reaches the light bulb. Its dangerous to put the relay on the neutral wire, since
if the device fails current can still fault to ground when the relay is off.
The following picture shows the needed connections with the Arduino Uno
or
Step by Step instruction
1. Plug your Adruino Uno board into your PC and select the correct board and com port
2. Open up serial monitor and set your baud to 9600 baud
3. Verify and upload the the sketch to your Adruino Uno
4. Comment or Delete the lines of code if you decide to use temperature or humidity values to activate the 5 V relay module:
if (h >= 66) { // you can change humidity value here - h>=66 to your preffered number
digitalWrite(relayPin, HIGH);
}
else {
digitalWrite(relayPin, LOW);
}
OR
if (t >= 25) {// you can change temperature value here - t>= 25 to your preffered readings or Celsius or Fahrenheit readings
digitalWrite(relayPin, HIGH);
}
else {
digitalWrite(relayPin, LOW);
}
Libraries:
See attachments on the begining of this project description
DHT-sensor-library-master.ZIP library included. You will need to unzip and add the DHT-sensor-library-master library to
libraries in your PC, for example C:\Users\toshiba\Documents\Arduino\libraries OR
You can install it in Arduino IDE too: select Sketch-> Include library->Manage your libraries->type DHT in Filter your
search line and you will see DHT sensor library by Adafruit->More info->select version->install
If it will be problem with compilation - remove 2 files from the library - DHT_U.cpp and DHT_U.h.
We have used the library - NewliquidCrystal_1.3.4.zip which I downloaded, unzipped, changed the name of folder
to LiquidCristal and added to libraries in my PC, for example C:\Users\toshiba\Documents\Arduino\libraries. This link you
can find in Preferences of Adruino IDE program which installed in your PC.
If you have LiquidCristal folder in this location already - delete this folder and copy folder, which was made by you, to this
location.
Wire library included in Arduino IDE which is installed in your PC.
Program/Sketch:
See attachment on the begining of this project description.

Other projects of Acoptex.com

Basics: Project 026c PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer, 5V Relay
moduof Acoptex.com in UNO 09-09-2017

Basics: Project 026b PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer - motion
detecof Acoptex.com in UNO 09-09-2017

NEW of Acoptex.com in UNO 08-09-2017

Advanced: Project 027b L293D H-bridge motor control shield, 2 stepper motors DC 5V 28BYJ-48 or W-
24B of Acoptex.com in UNO 07-09-2017

Basics: Project 022n 4x4 matrix membrane and rigid keypads, LEDs, active piezo buzzer,LCD1602 I2C
mo of Acoptex.com in UNO 06-09-2017

Go back to category
Is this project fake? Report it!
Recommend to a friend

Published at 13-07-2017
Viewed: 55 times

SITE LINKS:
About Us
Contact Us
Privacy Policy
How to post project/information / or comment it

Post a new project


Terms and Conditions
Our Partners
Members A-Z
Boards/Modules/Shields A-Z
Sitemap

2017. All rights reserved. ACOPTEX.COM

Acoptex.com
About Us


Contact Us
Search for a proje

(for example: "Arduino", "Raspberry, Bluetooth", "FeeTech FS90R 360 Servo")

POST A NEW PROJECT

ARDUINO
RASPBERRY PI
ARDUINO PROJECTS
ARDUINO ROBOTIX
RASPBERRY PROJECTS
BOOKS / NOTES / INSTRUCTIONS
DRIVERS / SOFTWARE
Home

Navigation

Seen recently
Basics: Project 011e 5V relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or
0

Google +
0

Vkontakte

Odnoklassniki

mail.ru

New

0
members

Basics: Project 011e 5V relay, DHT 11 21 22


sensor, LCD 1602 I2C module - Humidity or
of Acoptex.com in UNO
Basics: Project 011e
Project name: 5V relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or Temperature controlled relay
Attachments: libraries and program
WARNING THIS PROJECT INVOLVES HIGH VOLTAGES THAT CAN CAUSE SERIOUS INJURY OR DEATH.
PLEASE TAKE ALL NECESSARY PRECAUTIONS, AND TURN OFF ALL POWER TO A CIRCUIT BEFORE
WORKING ON IT. WE ARE NOT RESPONSIBLE FOR ANY DAMAGE, INJURY, DEATH AND OTHER THINGS
CAUSED BY THIS PROJECT IMPLEMENTATION.
In this project, you needed these parts :
1.Aruduino Uno R3 (you can also use the other version of Arduino)
2.5V Relay module 1 pc

3.Arduino IDE ( you can download it from here )


4.Jumper cables

5.Light bulb 60 W 220 V with connector 1pc

6.DHT11 or DHT21 or DHT22 - 1 pc

7.Resistor 1 KOm 1 pc
8. LCD 1602 I2C module

Understanding the Relay


You can read more about relay here.
You can find 5V relay module datasheet here.
Understanding DHT humidity and temperature sensor
You can read more about it here.
Datasheet can be found here.
Understanding LCD 1602 I2C module
You can read more about it here.
Signals and connections of DHT11 module
There are 3 : VCC (+5V), Data, GND (-)

Signals and connections of 5V Relay module nad LM35 sensor.


The SRD-05VDC-SL-C relay has three high voltage terminals (NC, C, and NO) which connect to the device you want to control.
The other side has three low voltage pins (Ground, Vcc, and Signal) which connect to the Arduino.

5V Relay Pinout

NC: Normally closed 120-240V terminal

NO: Normally open 120-240V terminal

C: Common terminal

Ground: Connects to the ground pin on the Arduino

5V Vcc: Connects the Arduinos 5V pin

Signal: Carries the trigger signal from the Arduino that activates the relay

Inside the relay is a 120-240V switch thats connected to an electromagnet. When the relay receives a HIGH signal at the signal
pin, the electromagnet becomes charged and moves the contacts of the switch open or closed.

NORMALLY OPEN VS. NORMALLY CLOSED

The relay has two different types of electrical contacts inside normally open (NO) and normally closed (NC). The one you use
will depend on whether you want the 5V signal to turn the switch on or turn the switch off. The 120-240V supply current enters
the relay at the common (C) terminal in both configurations. To use the normally open contacts, use the NO terminal. To use the
normally closed contacts, use the NC terminal.

The 5V Relay module has three high voltage terminals (NC, C, and NO) which connect to the device you want to control. The
other side has three low voltage pins (GND (0V), VCC (+5V), and S(Signal)) which connect to the Arduino board.
NC: Normally closed 120-240V terminal
NO: Normally open 120-240V terminal
C: Common terminal

Signals and contacts of LCD 1602 I2C module


As you can see on the back of LCD 1602 module there 4 connections: GND (-), VCC (+5V), Serial Data Line (SDA) and Serial
Clock Line (SCL).

Wiring
Let us build a HUMIDITY or TEMPERATURE controlled relay circuit that will turn on a light bulb when the humidity value
of a DHT 11 sensor reaches 66% or temperature value reaches 25 degrees Celsius. DHT 11 OR 21 OR 22 sensors are really
useful with 5V relays. You can use them to turn off a or turn on devices or power sockets depending on temperature or humidity
values.
Make sure that the high voltage connections to the 5V relay module are very well secured.

Identify the hot power wire (red wire in the diagram above) in the cord leading to the light bulb and make a cut. Connect the side
leading to the light bulb to the NO terminal of the 5V relay, and the side leading to the plug to the C terminal. This way the relay
is on the hot side, and current is switched before it reaches the light bulb. Its dangerous to put the relay on the neutral wire, since
if the device fails current can still fault to ground when the relay is off.
The following picture shows the needed connections with the Arduino Uno
or
Step by Step instruction
1. Plug your Adruino Uno board into your PC and select the correct board and com port
2. Open up serial monitor and set your baud to 9600 baud
3. Verify and upload the the sketch to your Adruino Uno
4. Comment or Delete the lines of code if you decide to use temperature or humidity values to activate the 5 V relay module:
if (h >= 66) { // you can change humidity value here - h>=66 to your preffered number
digitalWrite(relayPin, HIGH);
}
else {
digitalWrite(relayPin, LOW);
}
OR
if (t >= 25) {// you can change temperature value here - t>= 25 to your preffered readings or Celsius or Fahrenheit readings
digitalWrite(relayPin, HIGH);
}
else {
digitalWrite(relayPin, LOW);
}
Libraries:
See attachments on the begining of this project description
DHT-sensor-library-master.ZIP library included. You will need to unzip and add the DHT-sensor-library-master library to
libraries in your PC, for example C:\Users\toshiba\Documents\Arduino\libraries OR
You can install it in Arduino IDE too: select Sketch-> Include library->Manage your libraries->type DHT in Filter your
search line and you will see DHT sensor library by Adafruit->More info->select version->install
If it will be problem with compilation - remove 2 files from the library - DHT_U.cpp and DHT_U.h.
We have used the library - NewliquidCrystal_1.3.4.zip which I downloaded, unzipped, changed the name of folder
to LiquidCristal and added to libraries in my PC, for example C:\Users\toshiba\Documents\Arduino\libraries. This link you
can find in Preferences of Adruino IDE program which installed in your PC.
If you have LiquidCristal folder in this location already - delete this folder and copy folder, which was made by you, to this
location.
Wire library included in Arduino IDE which is installed in your PC.
Program/Sketch:
See attachment on the begining of this project description.

Other projects of Acoptex.com

Basics: Project 026c PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer, 5V Relay
moduof Acoptex.com in UNO 09-09-2017

Basics: Project 026b PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer - motion
detecof Acoptex.com in UNO 09-09-2017

NEW of Acoptex.com in UNO 08-09-2017

Advanced: Project 027b L293D H-bridge motor control shield, 2 stepper motors DC 5V 28BYJ-48 or W-
24B of Acoptex.com in UNO 07-09-2017

Basics: Project 022n 4x4 matrix membrane and rigid keypads, LEDs, active piezo buzzer,LCD1602 I2C
mo of Acoptex.com in UNO 06-09-2017

Go back to category
Is this project fake? Report it!
Recommend to a friend

Published at 13-07-2017
Viewed: 55 times

SITE LINKS:
About Us
Contact Us
Privacy Policy
How to post project/information / or comment it

Post a new project


Terms and Conditions
Our Partners
Members A-Z
Boards/Modules/Shields A-Z
Sitemap

2017. All rights reserved. ACOPTEX.COM

Acoptex.comAbout Us Contact Us (for example: "Arduino", "Raspberry, Bluetooth", "FeeTech FS90R 360 Servo") POST A NEW PROJECT
ARDUINO RASPBERRY PI ARDUINO PROJECTS ARDUINO ROBOTIX RASPBERRY PROJECTS BOOKS / NOTES /
INSTRUCTIONS DRIVERS / SOFTWARE Home Navigation Seen recently Basics: Project 011e 5V relay, DHT 11 21 22 sensor, LCD
1602 I2C module - Humidity or 0 0 0 0 Google + 0 Vkontakte 0 Odnoklassniki 0 mail.ru 0 New 0 members Basics: Project 011e 5V
relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or of Acoptex.com in UNO Basics: Project 011e Project name: 5V relay, DHT
11 21 22 sensor, LCD 1602 I2C module - Humidity or Temperature controlled relay Attachments: libraries and program WARNING THIS
PROJECT INVOLVES HIGH VOLTAGES THAT CAN CAUSE SERIOUS INJURY OR DEATH. PLEASE TAKE ALL NECESSARY
PRECAUTIONS, AND TURN OFF ALL POWER TO A CIRCUIT BEFORE WORKING ON IT. WE ARE NOT RESPONSIBLE FOR ANY
DAMAGE, INJURY, DEATH AND OTHER THINGS CAUSED BY THIS PROJECT IMPLEMENTATION. In this project, you needed these
parts : 1.Aruduino Uno R3 (you can also use the other version of Arduino) 2.5V Relay module 1 pc 3.Arduino IDE ( you can download it
from here ) 4.Jumper cables 5.Light bulb 60 W 220 V with connector 1pc 6.DHT11 or DHT21 or DHT22 - 1 pc 7.Resistor 1 KOm 1 pc 8.
LCD 1602 I2C module Understanding the Relay You can read more about relay here. You can find 5V relay module datasheet here.
Understanding DHT humidity and temperature sensor You can read more about it here. Datasheet can be found here. Understanding LCD
1602 I2C module You can read more about it here. Signals and connections of DHT11 module There are 3 : VCC (+5V), Data, GND (-)
Signals and connections of 5V Relay module nad LM35 sensor. The SRD-05VDC-SL-C relay has three high voltage terminals (NC, C, and
NO) which connect to the device you want to control. The other side has three low voltage pins (Ground, Vcc, and Signal) which connect to
the Arduino. 5V Relay Pinout NC: Normally closed 120-240V terminalNO: Normally open 120-240V terminalC: Common terminalGround:
Connects to the ground pin on the Arduino5V Vcc: Connects the Arduinos 5V pinSignal: Carries the trigger signal from the Arduino that
activates the relayInside the relay is a 120-240V switch thats connected to an electromagnet. When the relay receives a HIGH signal at the
signal pin, the electromagnet becomes charged and moves the contacts of the switch open or closed.NORMALLY OPEN VS. NORMALLY
CLOSEDThe relay has two different types of electrical contacts inside normally open (NO) and normally closed (NC). The one you use will
depend on whether you want the 5V signal to turn the switch on or turn the switch off. The 120-240V supply current enters the relay at the
common (C) terminal in both configurations. To use the normally open contacts, use the NO terminal. To use the normally closed contacts,
use the NC terminal. The 5V Relay module has three high voltage terminals (NC, C, and NO) which connect to the device you want to
control. The other side has three low voltage pins (GND (0V), VCC (+5V), and S(Signal)) which connect to the Arduino board. NC: Normally
closed 120-240V terminal NO: Normally open 120-240V terminal C: Common terminal Signals and contacts of LCD 1602 I2C module As you
can see on the back of LCD 1602 module there 4 connections: GND (-), VCC (+5V), Serial Data Line (SDA) and Serial Clock Line (SCL).
Wiring Let us build a HUMIDITY or TEMPERATURE controlled relay circuit that will turn on a light bulb when the humidity value of a DHT 11
sensor reaches 66% or temperature value reaches 25 degrees Celsius. DHT 11 OR 21 OR 22 sensors are really useful with 5V relays. You
can use them to turn off a or turn on devices or power sockets depending on temperature or humidity values. Make sure that the high voltage
connections to the 5V relay module are very well secured. Identify the hot power wire (red wire in the diagram above) in the cord leading to
the light bulb and make a cut. Connect the side leading to the light bulb to the NO terminal of the 5V relay, and the side leading to the plug to
the C terminal. This way the relay is on the hot side, and current is switched before it reaches the light bulb. Its dangerous to put the relay on
the neutral wire, since if the device fails current can still fault to ground when the relay is off. The following picture shows the needed
connections with the Arduino Uno or Step by Step instruction Plug your Adruino Uno board into your PC and select the correct board and
com port Open up serial monitor and set your baud to 9600 baud Verify and upload the the sketch to your Adruino Uno Comment or Delete
the lines of code if you decide to use temperature or humidity values to activate the 5 V relay module: if (h >= 66) { // you can change
humidity value here - h>=66 to your preffered number digitalWrite(relayPin, HIGH); } else { digitalWrite(relayPin, LOW); } OR if (t >=
25) {// you can change temperature value here - t>= 25 to your preffered readings or Celsius or Fahrenheit readings digitalWrite(relayPin,
HIGH); } else { digitalWrite(relayPin, LOW); } Libraries: See attachments on the begining of this project description DHT-sensor-library-
master.ZIP library included. You will need to unzip and add the DHT-sensor-library-master library to libraries in your PC, for example
C:\Users\toshiba\Documents\Arduino\libraries OR You can install it in Arduino IDE too: select Sketch-> Include library->Manage your
libraries->type DHT in Filter your search line and you will see DHT sensor library by Adafruit->More info->select version->install If it will be
problem with compilation - remove 2 files from the library - DHT_U.cpp and DHT_U.h. We have used the library -
NewliquidCrystal_1.3.4.zip which I downloaded, unzipped, changed the name of folder to LiquidCristal and added to libraries in my PC, for
example C:\Users\toshiba\Documents\Arduino\libraries. This link you can find in Preferences of Adruino IDE program which installed in your
PC. If you have LiquidCristal folder in this location already - delete this folder and copy folder, which was made by you, to this location.
Wire library included in Arduino IDE which is installed in your PC. Program/Sketch: See attachment on the begining of this project
description. Other projects of Acoptex.com Basics: Project 026c PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer, 5V
Relay modu of Acoptex.com in UNO 09-09-2017 Basics: Project 026b PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer -
motion detec of Acoptex.com in UNO 09-09-2017 NEW of Acoptex.com in UNO 08-09-2017 Advanced: Project 027b L293D H-bridge motor
control shield, 2 stepper motors DC 5V 28BYJ-48 or W-24B of Acoptex.com in UNO 07-09-2017 Basics: Project 022n 4x4 matrix membrane
and rigid keypads, LEDs, active piezo buzzer,LCD1602 I2C mo of Acoptex.com in UNO 06-09-2017 Go back to category Is this project
fake? Report it! Recommend to a friend Published at 13-07-2017 Viewed: 55 times SITE LINKS: About Us Contact Us Privacy Policy How
to post project/information / or comment it Post a new project Terms and Conditions Our Partners Members A-Z Boards/Modules/Shields A-Z
Sitemap 2017. All rights reserved. ACOPTEX.COM Acoptex.comAbout Us Contact Us (for example: "Arduino", "Raspberry, Bluetooth",
"FeeTech FS90R 360 Servo") POST A NEW PROJECT ARDUINO RASPBERRY PI ARDUINO PROJECTS ARDUINO
ROBOTIX RASPBERRY PROJECTS BOOKS / NOTES / INSTRUCTIONS DRIVERS / SOFTWARE Home Navigation Seen recently
Basics: Project 011e 5V relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or 0 0 0 0 Google + 0 Vkontakte 0 Odnoklassniki
0 mail.ru 0 New 0 members Basics: Project 011e 5V relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or of Acoptex.com in
UNO Basics: Project 011e Project name: 5V relay, DHT 11 21 22 sensor, LCD 1602 I2C module - Humidity or Temperature controlled relay
Attachments: libraries and program WARNING THIS PROJECT INVOLVES HIGH VOLTAGES THAT CAN CAUSE SERIOUS INJURY OR
DEATH. PLEASE TAKE ALL NECESSARY PRECAUTIONS, AND TURN OFF ALL POWER TO A CIRCUIT BEFORE WORKING ON IT.
WE ARE NOT RESPONSIBLE FOR ANY DAMAGE, INJURY, DEATH AND OTHER THINGS CAUSED BY THIS PROJECT
IMPLEMENTATION. In this project, you needed these parts : 1.Aruduino Uno R3 (you can also use the other version of Arduino) 2.5V Relay
module 1 pc 3.Arduino IDE ( you can download it from here ) 4.Jumper cables 5.Light bulb 60 W 220 V with connector 1pc 6.DHT11 or
DHT21 or DHT22 - 1 pc 7.Resistor 1 KOm 1 pc 8. LCD 1602 I2C module Understanding the Relay You can read more about relay here.
You can find 5V relay module datasheet here. Understanding DHT humidity and temperature sensor You can read more about it here.
Datasheet can be found here. Understanding LCD 1602 I2C module You can read more about it here. Signals and connections of DHT11
module There are 3 : VCC (+5V), Data, GND (-) Signals and connections of 5V Relay module nad LM35 sensor. The SRD-05VDC-SL-C
relay has three high voltage terminals (NC, C, and NO) which connect to the device you want to control. The other side has three low voltage
pins (Ground, Vcc, and Signal) which connect to the Arduino. 5V Relay Pinout NC: Normally closed 120-240V terminalNO: Normally open
120-240V terminalC: Common terminalGround: Connects to the ground pin on the Arduino5V Vcc: Connects the Arduinos 5V pinSignal:
Carries the trigger signal from the Arduino that activates the relayInside the relay is a 120-240V switch thats connected to an electromagnet.
When the relay receives a HIGH signal at the signal pin, the electromagnet becomes charged and moves the contacts of the switch open or
closed.NORMALLY OPEN VS. NORMALLY CLOSEDThe relay has two different types of electrical contacts inside normally open (NO) and
normally closed (NC). The one you use will depend on whether you want the 5V signal to turn the switch on or turn the switch off. The 120-
240V supply current enters the relay at the common (C) terminal in both configurations. To use the normally open contacts, use the NO
terminal. To use the normally closed contacts, use the NC terminal. The 5V Relay module has three high voltage terminals (NC, C, and NO)
which connect to the device you want to control. The other side has three low voltage pins (GND (0V), VCC (+5V), and S(Signal)) which
connect to the Arduino board. NC: Normally closed 120-240V terminal NO: Normally open 120-240V terminal C: Common terminal Signals
and contacts of LCD 1602 I2C module As you can see on the back of LCD 1602 module there 4 connections: GND (-), VCC (+5V), Serial
Data Line (SDA) and Serial Clock Line (SCL). Wiring Let us build a HUMIDITY or TEMPERATURE controlled relay circuit that will turn on a
light bulb when the humidity value of a DHT 11 sensor reaches 66% or temperature value reaches 25 degrees Celsius. DHT 11 OR 21 OR
22 sensors are really useful with 5V relays. You can use them to turn off a or turn on devices or power sockets depending on temperature or
humidity values. Make sure that the high voltage connections to the 5V relay module are very well secured. Identify the hot power wire (red
wire in the diagram above) in the cord leading to the light bulb and make a cut. Connect the side leading to the light bulb to the NO terminal
of the 5V relay, and the side leading to the plug to the C terminal. This way the relay is on the hot side, and current is switched before it
reaches the light bulb. Its dangerous to put the relay on the neutral wire, since if the device fails current can still fault to ground when the
relay is off. The following picture shows the needed connections with the Arduino Uno or Step by Step instruction Plug your Adruino Uno
board into your PC and select the correct board and com port Open up serial monitor and set your baud to 9600 baud Verify and upload the
the sketch to your Adruino Uno Comment or Delete the lines of code if you decide to use temperature or humidity values to activate the 5 V
relay module: if (h >= 66) { // you can change humidity value here - h>=66 to your preffered number digitalWrite(relayPin, HIGH); } else
{ digitalWrite(relayPin, LOW); } OR if (t >= 25) {// you can change temperature value here - t>= 25 to your preffered readings or Celsius or
Fahrenheit readings digitalWrite(relayPin, HIGH); } else { digitalWrite(relayPin, LOW); } Libraries: See attachments on the begining of this
project description DHT-sensor-library-master.ZIP library included. You will need to unzip and add the DHT-sensor-library-master library to
libraries in your PC, for example C:\Users\toshiba\Documents\Arduino\libraries OR You can install it in Arduino IDE too: select Sketch->
Include library->Manage your libraries->type DHT in Filter your search line and you will see DHT sensor library by Adafruit->More info-
>select version->install If it will be problem with compilation - remove 2 files from the library - DHT_U.cpp and DHT_U.h. We have used the
library - NewliquidCrystal_1.3.4.zip which I downloaded, unzipped, changed the name of folder to LiquidCristal and added to libraries in my
PC, for example C:\Users\toshiba\Documents\Arduino\libraries. This link you can find in Preferences of Adruino IDE program which installed
in your PC. If you have LiquidCristal folder in this location already - delete this folder and copy folder, which was made by you, to this
location. Wire library included in Arduino IDE which is installed in your PC. Program/Sketch: See attachment on the begining of this project
description. Other projects of Acoptex.com Basics: Project 026c PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer, 5V
Relay modu of Acoptex.com in UNO 09-09-2017 Basics: Project 026b PIR sensor HC - SR 501 or HC - SR 505, LEDs, active piezo buzzer -
motion detec of Acoptex.com in UNO 09-09-2017 NEW of Acoptex.com in UNO 08-09-2017 Advanced: Project 027b L293D H-bridge motor
control shield, 2 stepper motors DC 5V 28BYJ-48 or W-24B of Acoptex.com in UNO 07-09-2017 Basics: Project 022n 4x4 matrix membrane
and rigid keypads, LEDs, active piezo buzzer,LCD1602 I2C mo of Acoptex.com in UNO 06-09-2017 Go back to category Is this project
fake? Report it! Recommend to a friend Published at 13-07-2017 Viewed: 55 times SITE LINKS: About Us Contact Us Privacy Policy How
to post project/information / or comment it Post a new project Terms and Conditions Our Partners Members A-Z Boards/Modules/Shields A-Z
Sitemap 2017. All rights reserved. ACOPTEX.COM

You might also like