Duplicating variables

Hi, I am new to coding and Arduino as well. I've been through most of the beginners tutorials and a few example sketches and circuit also. I have since moved on to begin building my project and am painstakingly trying to audit my code. I know I am pretty far away from having a complete functional code, but before I get too far into the deep end, I was hoping some of you can critique my code point out known errors.

Before I get into the code, I want it to be known that I am using a Mega/r3 (counterfeit), an Ethernet Shield (clone), Data Logging Shield with RTC (DS1307)(Adafruit), two DHT22 sensors to read temps and humidity and an 8 channel relay module (Sainsmart).

I want to have a web server (open to suggestion), or an internet accessible web page to view sensor readings, look at logged data and also have function on/off capabilities, an override if you will. I don't know which of the Firmata or Ethernet examples will get me as close to where I want to go with this, hence (open to suggestions).

4 of the 8 relays will be assigned timed alarms to trigger them on for 12 hours and off for 12 hours. The other channels will be reserved for "if" tests and be cycled on or off according to the DHT sensor readings.

I am still yet to learn how to graft in code to log the data and make it retrievable over the internet. I am mostly concerned with the fact that I am using 2 DHT sensors, and dealing with all of the variable names. I fear I may have over did the names as I duplicated everything and terminated each with a capital A or B. The relays may also present similar problems for me, but the simplicity of their function may be my saving grace on that. If you can see my code heading in the wrong direction, please outline my errors in example format so that you don't end up giving me the answers without the knowledge as the knowledge of how to make my own code is what I mostly seek. I've been through Robin2's How to Do Multiple Things thread already and it has gotten me pretty far.

//=====================================VARIABLE DEFINITIONS=======================================//
relayA - pin8/const int/digitalWrite()/
relayB - pin9/const int/digitalWrite()/
relayC - pin10/const int/digitalWrite()/
relayD - pin11/const int/digitalWrite()/
relayE - pin12/const int/digitalWrite()/
relayF - pin13/const int/digitalWrite()/
relayG - pin14/const int/digitalWrite()/
relayH - pin15/const int/digitalWrite()/

relay0 - boolean/beginning state is false
relay1 -  boolean/beginning state is true

dhtA - pin4/const int/analogRead()/
dhtB - pin5/const int/analogRead()/
hA - float/analogRead()//dhtA humidity value
hB - float/analogRead()//dhtB humidity value
tA - float/analogRead()//dhtA celcius value
tB - float/analogRead()//dhtB celcius value
fA - float/analogRead()//dhtA fahrenheit value
fB - float/analogRead()//dhtB fahrenheit value

//===========================================CODE====================================================//
#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetStreamEnc28J60.h>
#include <EthernetStreamW5100.h>
#include <EthernetUdp.h>
#include <util.h>

#include <Wire.h>

#include <RTClib.h>

#include <Time.h>
#include <TimeAlarms.h>

#include <SD.h>

const int dhtA = 4;
const int dhtB = 5;
const int relayA = 8; //relayA Pin #
relayA = relay0
const int relayB = 9; //relayB Pin #
relayB = relay0
const int relayC = 10; //relayC Pin #
relayC = relay1
const int relayD = 11; //relayD Pin #
relayD = relay1
const int relayE = 12; //relayE Pin #
const int relayF = 13; //relayF Pin #
const int relayG = 14; //relayG Pin #
const int relayH = 15; //relayH Pin #

boolean relay0 = false; //beginning state of relayA and relayB
boolean relay1 = true; //beginning state of relayC and relayD

#include "DHT.h"
#define DHTTYPE DHT22   

DHT dhtA(dhtA, DHTTYPE); // Initialize DHT sensor A for normal 16mhz Arduino
DHT dhtB(dhtB, DHTTYPE); // Initialize DHT sensor B for normal 16mhz Arduino
void setup() {
  dht.begin();
  Serial.begin(9600); //DHT, DataLogger, Time Alarms - 9600, RTC - 57600, 
  Serial.println("DHTxx test!");

   pinMode(relayA, OUTPUT); 
   pinMode(relayB, OUTPUT); 
   pinMode(relayC, OUTPUT); 
   pinMode(relayD, OUTPUT); 
   pinMode(relayE, OUTPUT); 
   pinMode(relayF, OUTPUT); 
   pinMode(relayG, OUTPUT); 
   pinMode(relayH, OUTPUT); 
   pinMode(dhtA, INPUT);
   pinMode(dhtB, INPUT);
}

{
  Alarm.alarmRepeat(9,00,0, MorningAlarm);  // 9:00am every day
  Alarm.alarmRepeat(21,01,0, EveningAlarm);  // 9:01pm every day  
  //Alarm.alarmRepeat();
  //Alarm.alarmRepeat();
  //Alarm.alarmRepeat();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float hA = dht.readHumidity();
  dhtA = hA; //hA value stored in dhtA
  float hB = dht.readHumidity();
  dhtB = hB; //hB value stored in dhtB
  // Read temperature as Celsius
  float tA = dht.readTemperature();
  dhtA = tA; //tA value stored in dhtA
  float tB = dht.readTemperature();
  dhtB = tB; //tB value stored in dhtB
  // Read temperature as Fahrenheit
  float fA = dht.readTemperature(true);
  dhtA = fA; //fA value stored in dhtA
  float fB = dht.readTemperature(true);
  dhtB = fB; //fB value stored in dhtB
  // 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;
  }
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(fA. fB, hA, hB);

  Serial.print("HumidityA: "); 
  Serial.print("HumidityB: ");
  Serial.print(hA);
  Serial.print(hB);
  Serial.print(" %\tA");
  Serial.print(" %\tB");
  Serial.print("TemperatureA: "); 
  Serial.print("TemperatureB: ");
  Serial.print(tA);
  Serial.print(tB);
  Serial.print(" *CA ");
  Serial.print(" *CB ");
  Serial.print(fA);
  Serial.print(fB);
  Serial.print(" *F\tA");
  Serial.print(" *F\tB");
  Serial.print("Heat indexA: ");
  Serial.print("Heat indexB: ");
  Serial.print(hiA);
  Serial.print(hiB);
  Serial.println(" *FA");
  Serial.println(" *FB");
}

// functions to be called when an alarm triggers:
void MorningAlarm()
{
  Serial.println("Alarm: - turn lights off");    
}

void EveningAlarm(){
  Serial.println("Alarm: - turn lights on");           
}

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}
///////////Below tests DHT sensor for humidity and temp.  If temp or humidty is high, relayE on pin 12 is energized
{
if(dhtA h >= 55); //if humidity is 55% or more
{
 digitalWrite(relayEPin, HIGH); //Turns on fan connected to relayE
}
else if(dhtB t >= 27.777); //or else if celcius equals or exceeds 27°
{
digitalWrite(relayEPin, HIGH); //Also turns on fan connected to relayE
}
else 
{
digitalWrite(relayEPin, LOW); //Otherwise relayE is unenergized (do I need this line?)
}

As you can probably tell, I just copy/pasted example code into a single sketch. I am now going through it over and over looking for syntax errors and such and trying to tie it all together as seamlessly as my limited understanding will afford me. I've made some notes in the comments here and there.

Any and all feedback is most welcomed and greatly appreciated!

This leapt off the page and attacked my eyes.

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}
///////////Below tests DHT sensor for humidity and temp.  If temp or humidty is high, relayE on pin 12 is energized
{
if(dhtA h >= 55); //if humidity is 55% or more
{
 digitalWrite(relayEPin, HIGH); //Turns on fan connected to relayE
}

Apart from the semicolons after the "if", the code is outside any function, so can't possibly compile.

   pinMode(relayA, OUTPUT); 
   pinMode(relayB, OUTPUT); 
   pinMode(relayC, OUTPUT); 
   pinMode(relayD, OUTPUT); 
   pinMode(relayE, OUTPUT); 
   pinMode(relayF, OUTPUT); 
   pinMode(relayG, OUTPUT); 
   pinMode(relayH, OUTPUT);

When you find yourself subscripting variable names, it's really time you started using arrays.

Well, you defined dhtA as a const int equal to 4, and then tried to assign another value to it. That's kind of like saying "let's change the value of the number 4 to 7". It's hard to imagine what you were trying to do.

DHT dhtA(dhtA, DHTTYPE);
...
...
  float hA = dht.readHumidity();
  dhtA = hA; //hA value stored in dhtA

I really can't figure out what it is you're trying to do there.

const int dhtA = 4; <-Is this not how to tell my arduino which of it's pins I am referring to? Then tell it in pinMode how that pin (via it's variable name) how to behave?

Apart from the semicolons after the "if", the code is outside any function, so can't possibly compile.

I'm not seeing what you mean. Can you please elaborate further? I am a noob.

When you find yourself subscripting variable names, it's really time you started using arrays.

I don't yet know what subscripting means, but I will begin the search for that right away.

AWOL:

DHT dhtA(dhtA, DHTTYPE);

...
...
  float hA = dht.readHumidity();
  dhtA = hA; //hA value stored in dhtA


I really can't figure out what it is you're trying to do there.

To be honest, I am still trying to figure that out myself, but it is example code for the DHT22. I just pasted it in and am trying to get all my variable names in order and how each will work in the sketch. For the record, I have never written a program yet so this is what I'm using to learn it.

DHT dhtA(dhtA, DHTTYPE);
const int dhtA = 4;
dhtA = hA;

It's a constant, or a sensor instance or. . . what?

myggle:
const int dhtA = 4; <-Is this not how to tell my arduino which of it's pins I am referring to? Then tell it in pinMode how that pin (via it's variable name) how to behave?

Yes, but you're also using the same variable name to refer to the temp measured by the DHT:

dhtA = fA; //fA value stored in dhtA

And to refer to the DHT itself!

DHT dhtA(dhtA, DHTTYPE); // Initialize DHT sensor A for normal 16mhz Arduino

AWOL:

DHT dhtA(dhtA, DHTTYPE);
const int dhtA = 4;
dhtA = hA;

It's a constant, or a sensor instance or. . . what?

Y = Z, The value of Z is stored in Y, but DHT returns 2 or 3 values with each reading so should I create a separate empty variable to receive these readings? This is why I duplicated the example code, then modified it's variables to also call the 2nd DHT sensor. In the example, there is an "h" for the humidity. I figured I needed to alter it to read hA, then hB in the following line. Would it be better for me to group all of the A sensor code together, then in a separate block of code, the B sensor?

DrAzzy:
Yes, but you're also using the same variable name to refer to the temp measured by the DHT:

dhtA = fA; //fA value stored in dhtA

And to refer to the DHT itself!

DHT dhtA(dhtA, DHTTYPE); // Initialize DHT sensor A for normal 16mhz Arduino

Should I remove the const to free up the variable's ability to receive values? Please advise

Should I remove the const to free up the variable's ability to receive values?

No just use another variable. One variable defines the pin to use and another to have the value of that pin stored in by a read call.

but DHT returns 2 or 3 values with each reading so should I create a separate empty variable to receive these readings?

If you need several readings in the one variable then use an array.
http://www.thebox.myzen.co.uk/Tutorial/Arrays.html

myggle:
Before I get into the code, I want it to be known that I am using a Mega/r3 (counterfeit), an Ethernet Shield (clone), Data Logging Shield with RTC (DS1307)(Adafruit), two DHT22 sensors to read temps and humidity and an 8 channel relay module (Sainsmart).

Before going any further, have you written separate short programs to work with each of these accessories on its own?

It is a guarantee of frustration and almost certain failure if you have not done so.

I have probably written more programs than you and the first thing I do when I get a new device is write a short program to learn how to use it without any distractions from other hardware.

If you write the code in your test/learning programs in functions it will be easy to incorporate the known working function into your main project. See the structure in planning and implementing a program.

...R

Thanks Grumpy_Mike for the arrays link, very helpful! A question about this though, do you know where I can go to learn some added syntax? I'm curious where there are spaces before and after the = sign, but not the less than < sign. Also want to learn the difference between the 3 types of brackets used (), {}, []. Little stuff like this makes it difficult to learn because not all of these are outlined in the reference page.
void setup():
{
for(int i = 8; i<16; i++) pinMode(i, OUTPUT); //array to set pins 8-15 as outputs
}

This is what I come up with after reading the link. It shrunk my code from 8 lines to 1 for the pinMode. What I don't understand is how the array can set more than a single pin to output? What I was starting to learn about incrementing is that if (i) is less than (16 in my case), i++, wouldn't that just change the value from 8 to 9 than stop counting? The reason I ask this is because I also am starting to learn that the void setup function is only called once before the loop, so how is it that the other outputs get included and set as outputs? Will there be more passes through the setup? Will all my outputs get set in the first reading of that for loop? Will it even loop as it is a for loop?

Robin, I just spent about a week in your 'doing many things at once' thread. Very informative write up! Thank you! I did test each component, but if you recall, I also had some difficulty learning the code as there are characters and words being used in the code that are not clearly defined on the reference page, so I don't yet possess a full enough understanding of the code to write all my own code from scratch. So I elected to begin writing the code that is important to me, and shall use it to further my code learning.

wouldn't that just change the value from 8 to 9 than stop counting?

No, because nine is also less than sixteen.

You can put spaces between any lexical token, but be careful of operators like"+=" or ">=" where both characters are part of the same token.

myggle:
so I don't yet possess a full enough understanding of the code to write all my own code from scratch. So I elected to begin writing the code that is important to me, and shall use it to further my code learning.

That is very sensible.
But I can't see how the very complex code in your original Post in this Thread fits into that category.

...R

I'm curious where there are spaces before and after the = sign, but not the less than < sign.

No specific reason, just layout. Spaces do not matter to a computer it is just easier to read for us. That is considering what AWOL says.

lso want to learn the difference between the 3 types of brackets used (), {}, [].

Square brackets [ ] are used for the index of an array.
Braces { } are used to group lines of code and make them look like one line, like following an if only one line is executed if the condition is met. Putting many lines inside braces makes them all be done.
Curved brackets ( ) are used:-

  1. To enclose variables given to or received by a function.
  2. To set the order of computation for example 43 * (5-2) will multiply 43 by 3 where as 43 * 5 -2 will multiply 43 by 5 and then subtract 2.
  3. To enclose the comparison in an if statement.

AWOL:
No, because nine is also less than sixteen.

You can put spaces between any lexical token, but be careful of operators like"+=" or ">=" where both characters are part of the same token.

I completely misunderstood arrays from this and previous tutorials. Just to make sure I have it correctly this time, tell me if the following statement is true or false.

When an array is incrementing or decrementing, the counter keeps going through the array until the comparison is true?

Robin2:
That is very sensible.
But I can't see how the very complex code in your original Post in this Thread fits into that category.

...R

Sorry, I'm a bit lost. Which category did you mean? The very complex code is copy/pasted example code. It is my intent to use a project that I do want to build as a means to expose myself to code in a broader sense. I expect this code to be loaded with bugs, so until this all compiles, I will have to keep critiquing and analyzing and asking forum questions, and typing in phrases into google etc.

Grumpy_Mike:
No specific reason, just layout. Spaces do not matter to a computer it is just easier to read for us. That is considering what AWOL says.
Square brackets [ ] are used for the index of an array.
Braces { } are used to group lines of code and make them look like one line, like following an if only one line is executed if the condition is met. Putting many lines inside braces makes them all be done.
Curved brackets ( ) are used:-

  1. To enclose variables given to or received by a function.
  2. To set the order of computation for example 43 * (5-2) will multiply 43 by 3 where as 43 * 5 -2 will multiply 43 by 5 and then subtract 2.
  3. To enclose the comparison in an if statement.

Thanks again Grumpy_Mike! Do you know of a reference source, or other tutorial that teaches additional syntax not taught on the reference page? I am slowly building an understanding of the symbols used on the reference page, but all the materials not covered there are leaving me with a gap that I need to fill.

If not, can you shed some light on the use of two words with a period(.) in between?

Serial.print()
Serial.write()
Client.println() etc I know print, write, println etc are defined in Serial on the reference page, but I'm not seeing mention of the period or what it does if anything when words are tied by it.

Thank you for all the help everyone!

When an array is incrementing or decrementing, the counter keeps going through the array until the comparison is true?

An array does not increment or decrement; the index into the array may increment or decrement, or an element of an array may increment or decrement.

The counter/index will increment or decrement until you tell it not to.

that teaches additional syntax not taught on the reference page?

Well it is not syntax, that is always shown on the reference page. Style is a matter of personal taste.

http://ieng9.ucsd.edu/~cs30x/indhill-cstyle.html

can you shed some light on the use of two words with a period(.) in between?

These are class function calls. If you create a new class form an old one you automatically get these calls. For example the LCD class is derived from the print class and so has all the functions after the period that the original print class has. This is is not C but is C++. In good documentation it should have all the classes. For example the print is defined:-
http://arduino.cc/en/serial/print
where as the serial is defined:-

Notice that there are references to all the names after the period.

AWOL:
An array does not increment or decrement; the index into the array may increment or decrement, or an element of an array may increment or decrement.

The counter/index will increment or decrement until you tell it not to.

Please forgive my noobishness, I don't know exactly what is doing the incrementing or decrementing, just that it wasn't performed until the array appeared in the code. Also forgive if I don't know what/where the array is, but for the sake of streamlining my learning curve, I am understanding the single line of code to be the array. My question was regarding the functionality of the array, not so much the element or component that does the incrementing/decrementing, that I assume I will learn later on when I am exposed to those kinds of things.

Grumpy_Mike:
Well it is not syntax, that is always shown on the reference page. Style is a matter of personal taste.

http://ieng9.ucsd.edu/~cs30x/indhill-cstyle.html
These are class function calls. If you create a new class form an old one you automatically get these calls. For example the LCD class is derived from the print class and so has all the functions after the period that the original print class has. This is is not C but is C++. In good documentation it should have all the classes. For example the print is defined:-
http://arduino.cc/en/serial/print
where as the serial is defined:-
http://arduino.cc/en/reference/serial
Notice that there are references to all the names after the period.

I did notice the added definitions in the Serial page, but the period in between threw me for a loop (figuratively). Thank you also for the distinction between C and C++, this is all too new to me so locating the most applicable info is hard. As the reference page is my biggest tool in the box, I wish the materials were more inclusive of everything that can be in the code, even to the extent of referencing material such as HTML for making web pages for use with Ethernet Shields etc... Thank God there is always Google and helpful people in this forum!

I don't know exactly what is doing the incrementing or decrementing,

The for loop's ++ instruction is doing the incrementing.