holding information need revision.

/*==============================================================\\
|| Date   : November 27th 2016                                  ||
|| Author : Unknown                                             ||
|| Description: This project is aimed to help familarize myself ||
|| with different sensors and efficiency for programming.       ||
\\==============================================================*/
#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,10,11,12,13);
int page = 2;
const int temp = A0;  //Temperature Sensor
const int phot = A1;  //Photoresistor
const int lbtn = 2;   //Left Button
const int rbtn = 3;   //Right Button
int trig = 4; //sonar trigger
int echo = 5; //sonar echo

void setup(){
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  pinMode(lbtn,INPUT);
  pinMode(rbtn,INPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);
}
float temperature(int pin){
  float t = (((analogRead(pin)/1024.0) * 5) - 0.5) * 100; //Conversion to celsius Degrees
  return t;
}
int light(int pin){
  //anything below value of 100 is considered dark/night time
  return analogRead(pin);
}
int distance(int t, int e){
  float cm;
  digitalWrite(t, LOW); //Low high and low level take a short time to TrigPin pulse
  delayMicroseconds(2);
  digitalWrite(t, HIGH);
  delayMicroseconds(10);
  digitalWrite(t, LOW);
  cm = pulseIn(e, HIGH) / 58.0; //Echo time conversion into cm
  cm = (int(cm * 100.0)) / 100.0; //Keep two decimal places
  return cm;
}
void loop(){
  switch(page){
    case 1:
      lcd.clear();
      lcd.print("Degree:");
      lcd.setCursor(8,0);
      lcd.print(temperature(temp));
      lcd.setCursor(8,1);
      lcd.print("Dstnce=>");
    break;
    case 2:
      lcd.clear();
      lcd.print("Dstnce:");
      lcd.setCursor(8,0);
      lcd.print(distance(trig,echo));
      lcd.print(" cm");
      lcd.setCursor(0,1);
      lcd.print("<=Temp");
      lcd.setCursor(8,1);
      lcd.print("Light=>");
    break;
    case 3:
      lcd.clear();
      lcd.print("Light:");
      lcd.setCursor(8,0);
      lcd.print(light(phot));
      lcd.setCursor(0,1);
      lcd.print("<=Dstnce");
    break;
  }
  //left button
  if(digitalRead(2) == HIGH && page > 1){
    page--;
  }
  //right button
  if(digitalRead(3) == HIGH && page < 3){
    page++;
  }
  delay(250);
}

pin 2 is left button pin 3 is right button.

youy press left and you go to the first item and such.

my question is can i revise this anymore? im hoping to clean this up or use more correct syntax. can someone proofread this code and critic it for efficiency.

It's okay. A switch-case statement is often like that. No need to revise that.

If you want to make better code, I can mention a few minor things.

  • Use a 'const' variable for the pin numbers, not just '2' and '3'. For example : " const int pinLeft = 2 ; ". Also for temperature and light for pin A0 and A1.
  • The delay at the end of the loop is very long. When you use a debounce library, there is no need for a delay.
  • In the c-language, a " page = page - 1 ; " can also be written as " page--; " and increment is " page++ ; ".
  • The "temperature()" function uses numbers (1024.0, 5, 0.5, 100) without any explanation. They are used in a single code line which mixes floating point with integer. Please show in the code when it is integer and when it is floating point. About three code lines there, instead of just one might be better to understand what is going on.
  • Use more comments. At least at the top a name for the sketch and the date and for which Arduino board it is. Also show in the sketch which kind of sensors are connected. It would be nice to know if you are using a TMP36 or DS18B20 or a diode as temperature sensor.

You don't have to add comments for me, but for yourself. They are very useful when you look at your sketch after a year, and have forgotten for which sensor it was or which Arduino board.

  1. Done.
  2. Debounce is outdated => Arduino Playground - Debounce
  3. Done.
  4. The temperature function is to convert it to degrees Celsius as a return result. I dont want the temperature to display any floating numbers so i set it to int for a solid number. Ill add comments.
  5. That actually is a good idea. ill label the parts im using into the code.

now that i made revisions is there anything else i can optimize?

i updated it in the first post. i also added the sonar function.

is there anything else i can do to make it more efficient or....

There is a link to the newer Bounce, and that links to Bounce2 : GitHub - thomasfredericks/Bounce2: Debouncing library for Arduino and Wiring
The zip file on the right of that Github page can be imported in the Arduino IDE (in the menu: "add a .zip library").

In the Arduino IDE in the Library Manager has no default debounce library for the buttons, someone should add that.

If the Bounce2 works, perhaps you can get rid of the delay. Removing the delay is the only thing to make it more efficient as far as I can see.
When the delay is gone, it will be easier to add other things (hopefully those other things are also without delay).

In the Arduino there is no multitasking core, so the best efficient sketch runs the loop() very fast without delay. The sketch should only do a quick check for incoming data, for buttons and for timing with millis(), and processes that if needed.

I see too many mixing of float an int. Maybe the compiler is not confused, but I am.

Let's get rid of mixing float and int:

float temperature(int pin){
  float v = (float) analogRead(pin) / 1024.0 * 5.0;  // voltage at the Arduino pin.
  float t = ( v - 0.5 ) * 100.0; //Conversion to celsius Degrees
  return t;
}

Do you notice that I use " 5.0 " instead of " 5 ", and " 100.0 " instead of " 100 ". That is to make it clear that the calculation is done with floating point numbers. I cast the analogRead() to " (float) " and after that everything is done with float.
I'm helping with the code, without knowing which sensor needs - 0.5 * 100.0. That makes my hair curl :wink:

Can you improve the function distance() in the same way ?
I can see 4 problems. The cm is a float, but the function returns an integer. The pulseIn returns an unsigned long. The int * 100.0 / 100.0 is ugly. Stay away from things like that. There should be comment to tell what the return value is (is it cm ?).

the 0.5 * 100.0 is just a conversion for celsius that is all. its a standard tmp sensor.

how would i restructure the distance then? i wasnt sure how i can get readable data with it so i copyu+pasted it from the folder that came with the package of sensors.

so when you put in (float) like that you mean to tell me that its declaring anything after that as float?

The (float) analogRead() casts the integer to a float. Then I use floating point numbers like 1024.0 and so and the result is stored in a float. The compiler can do that by its own, but writing coding that way makes it clear how the int and float are used.

In most cases when a float variable is multiplied by 100 (the 100 is an integer), then the calculation is done with float numbers. However, when everything is mixed (int, unsigned long, float), then its getting far to confused for me.

I know that that is a conversion for the TMP36 sensor, but I want you to write in the sketch which sensor it is.

Would it be possible to divide the unsigned long from pulseIn() by 58 and return the unsigned long ?

unsigned long distance(int t, int e){
  ...
  unsigned long distance = pulseIn(e, HIGH) / 58UL; //Echo time conversion into cm
  return distance;
}

I'm doing it again: The 58UL means a value of 58 as "Unsigned Long". Without it the compiler would divide it by 58UL anyway, but I want to show what is going on.

got it.

now that we got it taken care of i feel more confident about coding.

Thanks alot appreciate the help.

Cool.
Your first sketch was already okay, so you know how to implement something in code.
The switch-case-statement is often a big blob of code. That's just how it is. They are also used in a state-machine, and they look just like that. A state-machine uses a variable that holds the state of the program, just like your 'page' variable.

http://arduinobasics.blogspot.ca/2014/09/relay-module.html

one last question. what software did the guy use to show how the schematic looks like on the board?

I don't know. It looks a little like Fritzing, but it uses real photos.

For schematics, Eagle from www.cadsoftusa.com is often used. I needs some time learn Eagle though.
If you want to draw schematics some day. Then don't spent time trying to use Fritzing, but start with Eagle, even if that will take three times more to get to know.

it is fritzing and my god its amazing.

one last question.

how could you have it run all the time to check if a button is pressed but keep the refresh rate at 250ms?

how could you have it run all the time to check if a button is pressed but keep the refresh rate at 250ms?

That depends on what "it" is.

i want it to be able to check all the time if a button is pressed and change the page. So no delay.

but when you view other pages it displays a value. how can i keep this at 250ms delay for the refresh rate.

i want it to be able to check all the time

Still with the pronoun, it, that refers to nothing.

When you reply, do NOT use it anywhere in your response.

i want it to check constantly?

With millis() it is possible to things at certain times or intervals.
A debounce library like Bounce2 don't need the delay either, a button can be checked as many times as possible. I'm not sure how to increment a value if the button is being pressed all the time. Perhaps millis() has to be used for that as well.

With millis() it is also possible to have many different intervals. For example update a display three times per seconds and do something else ten timer per second.

To use millis(), start with this : https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.

ok so i updated the code to improve on it.

check out the pictures. i want to make sure i got the diagram right n stuff.

/*==============================================================\\
|| Date   : November 27th 2016                                  ||
|| Author : Unknown                                             ||
|| Description: This project is aimed to help familarize myself ||
|| with different sensors and efficiency for programming.       ||
\\==============================================================*/
#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,10,11,12,13);
unsigned long prechk  = 0;
float stemp           = 0;
unsigned long sdist   = 0;
int sphot             = 0;
int page              = 2;
const int temp        = A0; //Temperature Sensor
const int phot        = A1; //Photoresistor
const int rgbred      = A2; //Red pin
const int rgbgrn      = A3; //Green pin
const int rgbblu      = A4; //Blue pin
const int lbtn        = 2;  //Left Button
const int rbtn        = 3;  //Right Button
const int trig        = 4;  //Sonar trigger
const int echo        = 5;  //Sonar echo
const int piezo       = 6;  //Piezo / Buzzer

void setup(){
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  pinMode(lbtn,INPUT);
  pinMode(rbtn,INPUT);
  pinMode(trig,OUTPUT);
  pinMode(echo,INPUT);
  pinMode(piezo,OUTPUT);
  pinMode(rgbred,OUTPUT);
  pinMode(rgbgrn,OUTPUT);
  pinMode(rgbblu,OUTPUT);
  Serial.begin(9600);
}
float temperature(int pin){
  float v = (float) analogRead(pin) / 1024.0 * 5.0;  // voltage at the Arduino pin.
  float t = ( v - 0.5 ) * 100.0; //Conversion to celsius Degrees
  return t;
}
int light(int pin){
  //anything below value of 100 is considered dark/night time
  return analogRead(pin);
}
int distance(int t, int e){
  digitalWrite(t, LOW); //Low high and low level take a short time to TrigPin pulse
  delayMicroseconds(2);
  digitalWrite(t, HIGH);
  delayMicroseconds(10);
  digitalWrite(t, LOW);
  unsigned long distance = pulseIn(e, HIGH) / 58UL; //Echo time conversion into cm
  return distance;
}
long rgb(int red,int green,int blue){
  analogWrite(rgbred,(red*4));
  analogWrite(rgbgrn,(green*4));
  analogWrite(rgbblu,(blue*4));
}
void loop(){
  unsigned long cur = millis();
  switch(page){
    case 1:
      lcd.clear();
      lcd.print("Degree:");
      lcd.setCursor(8,0);
      if(cur - prechk >= 1000){
        stemp = temperature(temp);
        lcd.print(stemp);
        prechk = cur;
      }else{
        lcd.print(stemp);
      }
      lcd.setCursor(8,1);
      lcd.print("Dstnce=>");
    break;
    case 2:
      lcd.clear();
      lcd.print("Dstnce:");
      lcd.setCursor(8,0);
      if(cur - prechk >= 1000){
        sdist = distance(trig,echo);
        lcd.print(sdist);
        prechk = cur;
      }else{
        lcd.print(sdist);
      }
      lcd.print(" cm");
      lcd.setCursor(0,1);
      lcd.print("<=Temp");
      lcd.setCursor(8,1);
      lcd.print("Light=>");
    break;
    case 3:
      lcd.clear();
      lcd.print("Light:");
      lcd.setCursor(8,0);
      if(cur - prechk >= 1000){
        sphot = light(phot);
        lcd.print(sphot);
        prechk = cur;
      }else{
        lcd.print(sphot);
      }
      lcd.setCursor(0,1);
      lcd.print("<=Dstnce");
    break;
  }
  //left button
  if(digitalRead(lbtn) == HIGH && page > 1){
    page--;
  }
  //right button
  if(digitalRead(rbtn) == HIGH && page < 3){
    page++;
  }
  if(sdist <= 20){
    tone(piezo,420,20);
    rgb(255,0,0);
    delay(1000);
    rgb(0,255,0);
    delay(1000);
    rgb(0,0,255);
    delay(1000);
  }else{
    rgb(255,255,255);
  }
  delay(250);
}

also can you check this out too please?

Your RGB led needs analogWrite() with PWM, but the Mega has PWM on a few pins only.

A piezo element is often connected to an output pin of an Arduino. That causes current peaks. To be within the specifications, an extra series resistor of 150 or 220 ohm is needed. The resistor will make it less loud.

It's hard to check every wire of the lcd, but I think that is okay.

The buttons in the drawing are not okay. The digital input pin should always be connected to something. Either with the resistor or via the button. An open digital input pin receives noise and can be anything.
I prefer the resistor to 5V, and the button to GND. The resistor can be 4k7 or 10k or so.
Use them as in this picture : Pull-up Resistors - SparkFun Learn
If you use that, you have to change the sketch, since then the pin is LOW when the button is pressed.

They way you use millis() and 'cur' and 'prechk' is okay. However, it has a strange effect on the program flow. Because that timing is only used when that page is active. That is a little too much tangled together for me.
It is possible to collect all the information (sensors, buttons, everything) with millis(), or each with their own millis(), and update the display with another millis(). Those things will then be seperated, which makes it easier to add new things. But do that only if you see the advantage of it.

Your sketch has only two empty lines. I think there is no need to make it compact, but every programmer has his/her own way to write source code.

got it all. Thanks. You have been a big help.