Professional Documents
Culture Documents
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);
}
}
2.
5. Nov 1, 2015#14
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.
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:
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.
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
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. .
https://www.backyardchickens.com/t/976303/building-a-incubator-from-a-wine-
cooler link to the first arduino one I built.
12.
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.
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.
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
#include "DHT.h"
#include <LiquidCrystal.h>
#include <Servo.h>
#define RELAY 9
Servo myservo;
int pos = 0;
int istate = 0;
float time, s1, m1, h1, d1; // Set up variables to calculate time
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() {
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
float f = dht.readTemperature(true);
m1 = s1 / 60;
h1 = m1 / 60;
d1 = h1 / 24;
ida = 21 - id;
// Check if any reads failed and exit early (to try again).
return;
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(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)
else {
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;
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);
for (pos = 180; pos >=0; pos -= 1) { // goes from 80 degrees to 0 degrees
myservo.write(pos);
istate = 0;
}
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?
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() {
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()
#1
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]
#2
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()
#3
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
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).
byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){
}
return result;
}
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()
{
if(dht11_in){
Serial.println("dht11 start condition 1 not met");
return;
}
delayMicroseconds(80);
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);
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
#1
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
nathanas
Full Member
Posts: 195
Karma: 1 [add]
Arduino rocks
#2
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
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...
#4
Rob Tillaart
Thinkerion
Guest
#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.
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...
#6
Go Up
Pages: [1]
Jump to:
NEWSLETTER
void InitDHT() {
pinMode(TEMP_RH_PIN, OUTPUT);
delay(1000);
digitalWrite(TEMP_RH_PIN,HIGH);
}
void ReadDHT() {
bGlobalErr=0;
byte dht_in;
byte i;
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();
}
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
4 comments:
1.
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.
3.
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.
Add comment
#define dht_dpin 14
#define LIGHT_SENSOR_PIN 1
#include <LiquidCrystal.h>
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
#1
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;
#2
eclipsear
Guest
#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>
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
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.
eclipsear
Guest
#5
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>
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 3-Servo rotates 180 degrees in the opposite direction of step one.
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 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.
FCjosh
Newbie
Posts: 6
Karma: 0 [add]
Re: Help with programming servo and stepper motor at the same time
#1
wg0z
Full Member
Posts: 150
Karma: 18 [add]
Re: Help with programming servo and stepper motor at the same time
#2
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
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.
FCjosh
Newbie
Posts: 6
Karma: 0 [add]
Re: Help with programming servo and stepper motor at the same time
#4
Delta_G
Shannon Member
Posts: 11,334
Karma: 1116 [add]
Re: Help with programming servo and stepper motor at the same time
#5
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
Re: Help with programming servo and stepper motor at the same time
#6
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
byte directionPin = 9;
byte stepPin = 8;
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);
}
}
#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]
#2
It is just a very basic test program to prove that the motor works. Move it one way. Move it the other way.
Stop.
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
daniellyall
Full Member
Posts: 148
Karma: 12 [add]
#3
richblus
Guest
#4
dptdpt
Full Member
Posts: 137
Karma: 1 [add]
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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]
#7
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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
#9
Marco
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
daxasd
Newbie
Posts: 13
Karma: 1 [add]
#11
Newbie
Posts: 13
Karma: 1 [add]
#12
#13
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]
#14
it's the LOW to HIGH transition that steps the motor. The time between this, controls how fast the motor moves.
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]
#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);
thanks
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#16
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]
#17
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]
#18
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.
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]
#19
Newbie
Posts: 2
Karma: 0 [add]
#20
Anyone have a pic for the wiring on this code for Old Burt Brains?
Thank you,
Dan
MaxDan
Newbie
Posts: 2
Karma: 0 [add]
#21
Jan 10, 2016, 04:50 am
Hello,
Anyone have a pic for the wiring on this code for Old Burt Brains?
Thank you,
Dan
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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]
#23
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#24
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.
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
paul_larner
Newbie
Posts: 14
Karma: 3 [add]
#25
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#26
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]
#27
rpt007
Dipl.-Ing.
Edison Member
Posts: 1,585
Karma: 319 [add]
#28
Go with a "normal" bipolar stepper and the popular A4988 or DRV8825 and you will be happy.
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#29
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.
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]
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.
...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]
#1
// SeveralThingsAtTheSameTimeRev1.ino
// 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!
//=======
// -----LIBRARIES
#include <Servo.h>
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 servoPin = 5; // the pin number for the servo signal
const int blinkDuration = 500; // number of millisecs that Led's are on - all three
leds use this
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 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 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
//========
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 (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()
//=====END
Guest
#2
Faraday Member
Posts: 2,743
Karma: 317 [add]
#3
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]
#4
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]
#5
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/
#6
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]
#7
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.
...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?
#8
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;
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;
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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
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
...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/
#11
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]
#12
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;
}
}
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#13
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
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]
#14
@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
Go Up
Newbie
Posts: 9
Karma: 0 [add]
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;
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);
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.
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.
#1
Also, please provide a wiring diagram how everything is connected. A photo / scan of a handdrawn one is
fine.
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]
#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.
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
Re: Having problems in code
#3
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
trode
Newbie
Posts: 9
Karma: 0 [add]
#4
septillion
Faraday Member
Posts: 5,739
Karma: 658 [add]
Re: Having problems in code
#5
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#6
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]
#7
cattledog
Faraday Member
Posts: 3,825
Karma: 806 [add]
#8
May 16, 2017, 08:36 pm Last Edit: May 16, 2017, 08:38 pm by cattledog
Quote
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]
#9
Faraday Member
Posts: 3,825
Karma: 806 [add]
#10
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.
PRINT
Go Up
Pages: [1]
Brattain Member
Posts: 40,256
Karma: 1843 [add]
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
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.
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.
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
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.
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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.
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.
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
daniellyall
Full Member
Posts: 148
Karma: 12 [add]
#2
Dec 11, 2014, 11:37 am Last Edit: Dec 11, 2014, 11:38 am by daniellyall
bang on
Cactusface
God Member
Posts: 601
1.
Karma: 133 [add]
Half intelligent old fart.....
www.melsaunders.co.uk
#3
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]
#4
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
#5
Dec 11, 2014, 02:13 pm
Good stuff.
Thanks
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#6
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]
#7
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]
#8
Dec 11, 2014, 06:15 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:
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]
#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]
#10
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]
#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.
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]
#12
Dec 12, 2014, 11:13 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]
#13
Dec 12, 2014, 12:46 pm
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.
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]
#14
Dec 12, 2014, 01:04 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
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>
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;
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.
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?
J-M-L
Tesla Member
Posts: 8,160
Karma: 679 [add]
#1
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]
#2
J-M-L
Tesla Member
Posts: 8,160
Karma: 679 [add]
#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]
#4
Faraday Member
Posts: 5,870
Karma: 546 [add]
#5
J-M-L
Tesla Member
Posts: 8,160
Karma: 679 [add]
Re: Combining codes
#6
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
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
#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
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]
#16
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]
#17
Dec 12, 2014, 02:43 pm Last Edit: Dec 12, 2014, 02:47 pm by nilton61
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.
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
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#18
Dec 12, 2014, 02:50 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.
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 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]
#19
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]
#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 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]
#21
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
Full Member
Posts: 103
Karma: 6 [add]
#22
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
#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
#24
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]
#25
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,
Can you post a few sentences that may be suitable to incorporate in the text?
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
daniellyall
Full Member
Posts: 148
Karma: 12 [add]
#26
Faraday Member
Posts: 5,065
Karma: 424 [add]
#27
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.
.
daniellyall
Full Member
Posts: 148
Karma: 12 [add]
#28
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.
Go Up
Pages: 1 [2] 3 4
Jump to:
#30
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]
#31
...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
#32
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.
Sr. Member
Posts: 468
Karma: 87 [add]
#33
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]
#34
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]
Feb 19, 2015, 12:12 am Last Edit: Feb 19, 2015, 11:44 pm by 1:1
I would be happy to do so. Have you any suggestions, or perhaps you could write a few lines yourself?
...R
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'.
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.
The XY problem: "the over-use of one line responses that simply link though to websites that describe the XY
problem"
marco1990
Guest
#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?
ShapeShifter
Edison Member
Posts: 2,447
Karma: 313 [add]
#37
If my millisbetweenSteps are 25 is correct to take the frequency equal to: f = 1/0.0025 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]
#38
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]
#39
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]
#40
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
#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.
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?
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
#42
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#43
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
CoffeeMan
Guest
#44
Go Up
Pages: 1 2 [3] 4
Jump to:
NEWSLETTER
Re: Stepper Motor Basics
#45
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
I have checked my board as Mega 2560, serial communication port, drivers, connections etc.
All looks perfect.
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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.
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
ShapeShifter
Edison Member
Posts: 2,447
Karma: 313 [add]
#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]
#49
Isabelle_VP
Newbie
Posts: 43
Karma: 12 [add]
#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]
#51
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]
#52
Feb 07, 2016, 06:05 pm Last Edit: Feb 07, 2016, 06:06 pm by Robin2
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.
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.
Go Up
Pages: 1 2 3 [4]
Jump to:
#15
Pete
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#16
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
#17
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]
#18
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).
...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/
#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
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/
#20
MY CONCLUSION ... is that this is a discussion about angels on the head of a pin.
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#21
Mar 11, 2014, 09:18 am
Quote from: Coding Badly on Mar 11, 2014, 08:45 am
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
#22
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/
#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.
void setup()
{
Serial.begin( 115200 );
Serial.println( F( "Five seconds to lift off..." ) );
}
void loop()
{
unsigned long Current;
unsigned long Delta;
Current = millis();
if ( Delta != 0 )
{
Previous = Current;
return;
}
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/
#24
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]
...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?
#26
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]
#27
@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
void setup()
{
Serial.begin( 115200 );
Serial.println( F( "Five seconds to lift off..." ) );
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/
#28
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. */
Guest
#30
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.
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/
#31
A word of caution about the basic "mile marker" approach: an overrun will wreak havoc. A while loop
overcomes the problem.
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 );
}
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#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.
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/
#33
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]
#34
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
cootcraig
Newbie
Posts: 8
Karma: 6 [add]
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.
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
...
#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
}
#36
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]
#37
...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]
#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
any ideas?
cr0sh
Tesla Member
Posts: 6,497
1.
Karma: 442 [add]
Where's the beer?
#39
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/
#40
Too late.
Quote
/remember, this forum caters to many age groups and such; let's try to keep it somewhat in line with that...
@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]
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
evancleary
Newbie
Posts: 28
Karma: 9 [add]
#42
// ==================variables====================================
//===================================================================
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
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
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/
#44
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.
Go Up
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/
#45
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]
#46
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]
#47
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]
#48
ie 26 degrees = 1 1 0 1 0
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]
#49
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
...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
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#51
He has. Twice...
Thanks, I hadn't spotted those.
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
evancleary
Newbie
Posts: 28
Karma: 9 [add]
#52
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]
#53
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]
#54
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;
}
}
}
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
#55
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]
#56
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]
#57
Mar 25, 2014, 09:17 pm Last Edit: Mar 26, 2014, 03:43 am by beefy23 Reason: 1
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]
#58
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
#59
Go Up
Pages: 1 2 3 [4] 5 6 7
Jump to:
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]
#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
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
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]
#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.
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
beefy23
Jr. Member
Posts: 57
Karma: 0 [add]
#63
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]
#64
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
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
#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]
#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.
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
#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
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
#69
npp1.png
21.19 KB
downloaded 242 times
npp2.png
18.44 KB
downloaded 187 times
beefy23
Jr. Member
Posts: 57
Karma: 0 [add]
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,
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
#71
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]
#72
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
#73
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.
Ray
beefy23
Jr. Member
Posts: 57
Karma: 0 [add]
#74
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
Jump to:
NEWSLETTER
#75
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.
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
#76
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]
#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.
#78
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.
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#79
Jun 05, 2014, 08:07 am
Quote from: GoForSmoke on Jun 05, 2014, 12:20 am
...R
Two or three hours spent thinking and reading documentation solves most programming problems.
GoForSmoke
#80
Full Member
Posts: 178
Karma: 6 [add]
Like to build typing devices, and heard unicorns
#81
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]
#82
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
#83
GoForSmoke
#84
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
#85
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.
JimboZA
Tesla Member
Posts: 8,723
Karma: 838 [add]
#86
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]
#87
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
#88
#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.
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.
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:
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
led = 0;
}
void loop()
{
millisNow = (unsigned int)( millis() & 0xFFFF ); // lower 16 bits roll over just
fine
{
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;
}
}
/*
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!
*/
// #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
// 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
#if SERPRINT
Serial.print( " OFF millis = " );
Serial.print( waitBlink[ led ][ 0 ] );
Serial.print( " ON millis = " );
Serial.println( waitBlink[ led ][ 1 ] );
#endif
led = 0;
}
void loop()
{
millisNow = (unsigned int)( millis() & 0xFFFF ); // lower 16 bits roll over just
fine
{
#if SERPRINT
Serial.print( led, DEC );
Serial.print( " t " );
Serial.print( millisNow );
/*
Serial.print( " states " );
Serial.print( ledState, BIN );
*/
#endif
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();
led++;
if ( led >= LEDS )
{
led = 0;
}
}----
Global Moderator
Brattain Member
Posts: 18,603
1.
Karma: 1118 [add]
http://code.google.com/p/arduino-tiny/
#90
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#91
Sep 20, 2014, 04:31 pm Last Edit: Oct 02, 2014, 08:35 am by Robin2 Reason: 1
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]
#92
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
#93
You don't seem to have changed the line with since = currentmillis.
previousmillis = currentmillis
with
Code: [Select]
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.
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#94
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
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.
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!
GoForSmoke
Old And In The Way
Tesla Member
Posts: 8,705
Karma: 608 [add]
I learn a bit every time I visit the forum.
#96
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.
Shannon Member
Posts: 12,488
Karma: 1163 [add]
The last thing you did is where you should start looking.
#97
No technical PMs.
The last thing you did is where you should start looking.
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#98
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
#99
Robin2
Brattain Member
Posts: 40,256
Karma: 1843 [add]
#100
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
#101
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]
#102
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...
#103
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)
Go Up
Jump to:
servo motore
#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()
{
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]
#2
c0rsa1r
Awesome
Full Member
Posts: 172
Karma: 41 [add]
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]
#4
Awesome
Full Member
Posts: 172
Karma: 41 [add]
#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]
#6
Colzadanicola
Full Member
Posts: 153
Karma: 5 [add]
#7
brunello22
Faraday Member
Posts: 5,138
Karma: 444 [add]
Code: [Select]
"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]
#9
Colzadanicola
Full Member
Posts: 153
Karma: 5 [add]
#10
#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()
{
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);
}
#11
Faraday Member
Posts: 5,138
Karma: 444 [add]
#12
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()
{
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)
{
else{
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);
}
else{
delay(2000);
}
motor.write(4) prima di
motor.attach(4)
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
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!
#include <Servo.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);
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();
}
I realize there are likely several beginner errors and sloppy syntax. Any constructive criticism and
guidance is apppreciated.
Errors
#include <Servo.h>
//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);
--------
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();
}
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.
But the problem arises when I try to control humidity and also the egg turner.
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]
#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
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]
#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.
Faraday Member
Posts: 5,870
Karma: 546 [add]
#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]
#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]
#5
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.
Newbie
Posts: 4
Karma: 0 [add]
#6
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.
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]
#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...
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
Fuzzoffury
Newbie
Posts: 1
Karma: 0 [add]
#9
Wawa
Tesla Member
Posts: 7,695
Karma: 848 [add]
#10
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..
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);
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(){
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);
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);
}
#15
void setup(){
delay (3000);
lcd.clear();
void loop(){
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);
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
delay (2000);
lcd.clear();
delay (500);
// 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
}
#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);
void setup(){
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);
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);
delay (2000);
lcd.clear();
delay (500);
}
else
{
lcd.print("Error No :");
lcd.print(err);
}
delay(DHT11_RETRY_DELAY); //delay for reread
delay (2000);
lcd.clear();
delay (500);
#17
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]
#11
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
void setup(){
void loop(){
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++;
}
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
// 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);
delay (3000);
lcd.clear();
delay (500);
delay (3000);
lcd.clear();
delay (500);
// 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
}
Arduino Forum
Using Arduino => Project Guidance => Topic started 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
Code: [Select]
DHT dht(DHTPIN, DHTTYPE);
and have
Code: [Select]
Then have
Code: [Select]
dht1.begin();
dht2.begin();
Code: [Select]
float h2 = dht2.readHumidity();
#define DHTPIN2 3
@JimboZA,
I think you mean....
Probably 8)
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:
#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");
}
}
You didn't actually say so, but assuming my stab in the dark worked Chris?
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.
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.
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.
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.
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.
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.
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.
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);
};
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
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.
Code: [Select]
#include <LCD.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <dht11.h>
#include <Servo.h>
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
Cosa fa il servo?
Dacci lo sketch completo.
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
Arduino Forum
Using Arduino => Programming Questions => Topic started 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);
void loop() {
temp = readTemp(); // get the temperature
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};
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;
void setup() {
pinMode(PinOne, OUTPUT);
pinMode(PinTwo, OUTPUT);
digitalWrite(PinOne, PinOneState);
digitalWrite(PinTwo, PinTwoState);
}
void loop() {
digitalWrite(PinOne ,LOW);
digitalWrite(PinTwo ,LOW);
}
}
thanks
walter
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.
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.
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.
Code: [Select]
#include <ShiftLCD.h>
ShiftLCD lcd(2, 4, 3);
int PinOne = 9;
int PinTwo = 10;
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
}
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() {
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.
Code: [Select]
#define LATCH 12
#define CLK 13
#define DATA 11
#include <ShiftLCD.h>
ShiftLCD lcd(2, 4, 3);
//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;
void setup(){
setupFirstCode();
setupSecondCode();
setupThirdCode();
}
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
}
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();
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
}
}
}
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?
Quote
Down the road, the Chevy dealer might be able to help you with your Ford.
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.
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();
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();
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();
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");
At least let us know what it does and does not do. As well as what you want it to
do.
Weedpharma
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.
future probably... you know those pesky racoons... set the temp to chicken and get
hard boiled quail eggs.
@nzioka,
If you monitor the Forum and respond to questions quickly it stops people
wandering off with idle (if humourous) speculations.
...R
Arduino Forum
Using Arduino => Programming Questions => Topic started by:
theslayer20099 on Jul 07, 2016, 01:13 pm
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 .
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
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...
Quote
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 ?
Code: [Select]
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
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 ?
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]
Or, because it boils down to every two minutes between 0 and 20...
Code: [Select]
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]
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
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?
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.
https://drive.google.com/open?id=0B0eWzIn-plF2SVNHR3BGTTBOY1E
Arduino Forum
Using Arduino => Programming Questions => Topic started by:
Cromp on Mar 26, 2012, 07:44 pm
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>
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(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
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;
}
}
}
humidity24Hours[hum24HourIndex] = averageHum1Hour;
Code: [Select]
if (temp1MinIndex == 5)
{
temp1MinIndex = 0; //reset
index
temperature1Hour[temp1HourIndex] = averageTemp1Minute;
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;
}
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;
}
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.
Code: [Select]
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.
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());
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.
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]
to
Code: [Select]
Wouter
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?
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.
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.
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?
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.
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.
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 ]:)
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.
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.
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?
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).
Title: Re: Arduino based incubator - hangs - SOLVED - power supply issues
Post by: sbolel on Oct 08, 2012, 08:53 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).
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.
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?
Arduino Forum
Using Arduino => Project Guidance => Topic started 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
(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
#include <DHT.h>
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
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();
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]
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]
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?
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
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.
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.
You don't need an ethernet/sd shield. Just use a serial line to the RPi over the UART
or USB.
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.
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.
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.
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
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.
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
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.
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.
...R
Arduino Forum
Using Arduino => Project Guidance => Topic started 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
(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
#include <DHT.h>
//#define HUMID_HIGH 60
//#define HUMID_LOW 20
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
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();
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]
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]
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?
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
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.
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
Code: [Select]
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <dht.h>
#include <Servo.h>
#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()
{
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>
#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()
{
Quote
So where is your attempt? There are tons of on line egg incubator projects - did
you check any?
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
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.
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)
{
}
read my topic again you will understand bro :)
Title: Re: programing problem
Post by: J-M-L on Apr 09, 2017, 08:02 pm
Arduino Forum
Using Arduino => Programming Questions => Topic started by:
hackertom on Jul 21, 2015, 10:35 am
(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
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.
Especially placing a switch or relay contact in the 240 VAC Return or Neutral Wire...
VERY BAD PRACTICE..
..
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:
My advice would be don't play with mains electricity if you don't know what you're
doing ( which clearly you don't ).
Anything powerful enough to create heat will probalby have enought power to be
fire risk. Learn about fuses.
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
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:
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.
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"
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// 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;
}
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??
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.
Code: [Select]
Arduino Forum
Using Arduino => Programming Questions => Topic started by:
Rooster14250 on Mar 16, 2015, 05:12 pm
Servo myservo;
int pos = 0;
#include "DHT.h"
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);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(f);
Serial.print(" *F\t");
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
Arduino Forum
Forum 2005-2010 (read only) => General => Exhibition => Topic
started 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
http://img213.imageshack.us/f/frontbhp.jpg/
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
Code: [Select]
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
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
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;
}
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);
}
}
}
Code: [Select]
{
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);
}
}
}
void set_hum() {
}
void set_hum_dif() {
}
*/
Arduino Forum
Using Arduino => Project Guidance => Topic started 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).
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.
Quote
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.
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?
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?
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
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 :)
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
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.
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.
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
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
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.
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.
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.
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
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.
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
Arduino Forum
Using Arduino => Project Guidance => Topic started by: Shan9 on
Apr 22, 2016, 03:36 pm
Hi guys,
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.
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?
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
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()
{
// 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(h< humLowTrigger)
digitalWrite(relay3, HIGH);
else
digitalWrite(relay3,LOW);
} }
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?
i jux done my circuit drawing. My drawing was not standard. hope u all can
understand.. Yrs reply or help will be highly appreciated..
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.
Quote
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).
Okay.. I will try used 9V adapter and observe the performance of the board. Ya..
Jux wondering how to reduce the current drawn..
https://www.dipmicro.com/store/DCA-07510
(https://www.dipmicro.com/store/DCA-07510)
(https://www.dipmicro.com/img/1/400x300/DCA-FULLVIEW.jpg)
Arduino Forum
Using Arduino => Project Guidance => Topic started by: les_well on
Jan 07, 2015, 09:42 pm
I would appreciate it if you could look over the code for me.
When combined, the motor speed is so slow (one rpm every hour, ish). also affects
humidity readings over time.
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
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.
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]
//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);
//===========================================
byte button;
byte timestamp;
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" );
/*
// 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;
}
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
Arduino Forum
Using Arduino => Motors, Mechanics, and Power => Topic started
by: polmourgos on Feb 23, 2016, 03:47 pm
Pol
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();
}
...R
@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>
void setup()
pinMode(umidifiyerrelaypin, OUTPUT);
pinMode(heatrelaypin, OUTPUT);
void loop()
{
Serial.println("\n");
switch (chk)
Serial.println((float)dht22.humidity, DEC);
else
digitalWrite(umidifiyerrelaypin, HIGH);
}
Serial.print("Temperature (C): ");
Serial.println(dht22.temperature, DEC);
else
digitalWrite(heatrelaypin, LOW);
delay(2000);
Code: [Select]
#include <BWOD.h>
Code: [Select]
myBWOD.attach(8, 97, 110); //pin, on interval, off interval
// chnge name and use your values
Code: [Select]
myBWOD.manageBlink(); // with your name
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.
Pol
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.
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.
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.
int ledPin;
int ledState; // ledState used to set the LED
long previousMillis; // will store last time LED was updated
Funny you should day that, I was just wondering if I got those right.
unsigned long previousMillis; // will store last time LED was updated
FYI
BWD using structure example:
Code: [Select]
//======================================================================
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()
//**********************
//**********************************************************************
//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
};
//***************************
//**********************************************************************
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));
//***************************
//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
//******************************************
//similar code for other switches goes here
//******************************************
} //END of Switches()
//======================================================================
// E N D O F C O D E
//======================================================================
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"
DFR_Key keypad;
int localKey = 0;
String keyString = "";
RTC_DS1307 RTC;
int StartHrRelay_3 = 7;
int StartMinRelay_3 = 44;
int StartHrRelay_4 = 7;
int StartMinRelay_4 = 44;
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
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__));
}
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();
lcd.setCursor (0,0);
lcd.print("Volts (mV): ");
lcd.print( readVcc(), DEC );
delay(5000);
lcd.clear();
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);
future = CalcFuture(now,DurDay3,DurHour3,DurMinute3,DurSecond3);
LightOn = true;
digitalWrite(Relay_3, RELAY_ON);
Serial.println("\r\nLight On\r\n");
}
}
else {
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);
future = CalcFuture(now,DurDay4,DurHour4,DurMinute4,DurSecond4);
LightOn = true;
digitalWrite(Relay_4, RELAY_ON);
Serial.println("\r\nLight On\r\n");
}
}
else {
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;
//
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.
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.
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)
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
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)?
Quote
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?
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...
if (LightOn == false) {
DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);
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
Serial.print("\r\nLight Off\r\n");
}
}
delay((Sleep*MultiMinute));
DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);
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
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);
}
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 01:17 am
Code: [Select]
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
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.
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
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
Perhaps because you have not stated the problem clearly enough.
Quote
Code: [Select]
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
Code: [Select]
float h = dht.readHumidity();
float t = dht.readTemperature();
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.
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
Code: [Select]
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
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.
Arduino Forum
Using Arduino => Programming Questions => Topic started 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"
DFR_Key keypad;
int localKey = 0;
String keyString = "";
RTC_DS1307 RTC;
int StartHrRelay_3 = 7;
int StartMinRelay_3 = 44;
int StartHrRelay_4 = 7;
int StartMinRelay_4 = 44;
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
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__));
}
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();
lcd.setCursor (0,0);
lcd.print("Volts (mV): ");
lcd.print( readVcc(), DEC );
delay(5000);
lcd.clear();
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);
future = CalcFuture(now,DurDay3,DurHour3,DurMinute3,DurSecond3);
LightOn = true;
digitalWrite(Relay_3, RELAY_ON);
Serial.println("\r\nLight On\r\n");
}
}
else {
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);
future = CalcFuture(now,DurDay4,DurHour4,DurMinute4,DurSecond4);
LightOn = true;
digitalWrite(Relay_4, RELAY_ON);
Serial.println("\r\nLight On\r\n");
}
}
else {
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;
//
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.
Now, perhaps if you told us how you intended that code to work, and how it
actually works, we could help you.
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.
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.
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
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)?
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 12:55 am
Quote
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?
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: [Select]
if (LightOn == false) {
DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);
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
Serial.print("\r\nLight Off\r\n");
}
}
delay((Sleep*MultiMinute));
if (LightOn == false) {
DelayFuture = CalcFuture(Start,0L,0L,Sleep,0L);
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
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);
}
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 01:17 am
Code: [Select]
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
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.
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
Title: Re: Chicken Coop - LCD + 2 Fans + 2 Lights + RTC + DHT11 + Stepper
Post by: PaulS on Dec 08, 2012, 02:24 am
Quote
Perhaps because you have not stated the problem clearly enough.
Quote
Code: [Select]
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();
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.
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
Code: [Select]
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
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.
HOME
BUY
SOFTWARE
PRODUCTS
LEARNING
FORUM
SUPPORT
BLOG
SIGN IN
Communication
Serial
Stream
Keyboard
Mouse
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
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
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
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
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:
#include <LiquidCrystal.h>
byte read_dht11_dat()
{
byte i = 0;
byte result=0;
while (!digitalRead(dht11_pin));
delayMicroseconds(30);
if (digitalRead(dht11_pin) != 0 )
bitSet(result, 7-i);
while (digitalRead(dht11_pin));
return result;
int HumidityTempSensor = 0;
int lightSensor = 1;
//int tempSensor = 2;
int ht_val;
int light_val;
//int temp_val;
void setup() {
pinMode(dht11_pin, OUTPUT);
digitalWrite(dht11_pin, HIGH);
lcd.begin(16,2);
void loop() {
byte dht11_dat[5];
byte dht11_in;
digitalWrite(dht11_pin, LOW);
delay(18);
digitalWrite(dht11_pin, HIGH);
delayMicroseconds(1);
pinMode(dht11_pin, INPUT);
delayMicroseconds(40);
if (digitalRead(dht11_pin))
{
delay(1000);
return;
delayMicroseconds(80);
if (!digitalRead(dht11_pin))
return;
{ dht11_dat[i] = read_dht11_dat();} /
Details are described in datasheet
pinMode(dht11_pin, OUTPUT);
digitalWrite(dht11_pin, HIGH);
if(dht11_dat[4]!= dht11_check_sum)
ht_val = analogRead(HumidityTempSensor);
HumidityTemp sensor
lcd.print("Humidity = ");
lcd.print("% ");
lcd.print("Temp = ");
lcd.print("C ");
delay(2000);
lcd.clear();
lcd.print("Humidity Outlet");
delay(2000);
lcd.clear();
lcd.print("Humidity Outlet");
lcd.print(" - ON -");
digitalWrite (7, LOW);
delay(2000);
lcd.clear();
lcd.print("Cooling System");
lcd.print(" - ON -");
delay(2000);
lcd.clear();
lcd.print("Cooling System");
delay(2000);
lcd.clear();
light_val = analogRead(lightSensor); // r
photosensor
lcd.print("Light = ");
lcd.print( light_val );
delay(2000);
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Lights System");
lcd.setCursor(0, 1);
lcd.print(" - ON - ");
delay(2000);
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Lights System");
lcd.setCursor(0, 1);
delay(2000);
lcd.clear();
}
//temp_val = analogRead(tempSensor);
//Serial.println( temp_val );
//{
//Serial.println("turning on low-temperat
//delay(2000);
//}
//{
//delay(2000);
//}
Comments
void loop()
{
//Define the LCD as 16 column by 2 rows
lcd.begin (16, 2);
//Switch on the backlight
lcd.setBacklight(HIGH);
// 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
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)
7.Resistor 1 KOm 1 pc
5V Relay Pinout
C: Common terminal
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.
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
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.
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
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
Acoptex.com
About Us
Contact Us
Search for a proje
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
7.Resistor 1 KOm 1 pc
8. LCD 1602 I2C module
5V Relay Pinout
C: Common terminal
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.
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
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.
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
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
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