header
Connect Potentiometer

In our previous code, we set a variable (alarmLevel) to a value of 800. How do we know that this is the correct value to use? We don't. In fact, you may have had to change this value to get your system to work. It would be much better if we could adjust something on our monitor itself that would change the value for us.

We're going to use another adjustable resistor, like we're using with our lcd screen, to let us adjust this value. These adjustable resistors are also called potentiometers or pots. We're going to connect it so that we can read the value of the pot on analog pin 2. Normally, we'd read a value from 0 - 1023 on this pin. We're going to have to adjust this to a range that works for our light sensor. In the code below, the values will read from 700 - 1723.

connect potentiometer
// include the library code
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12,11,5,4,3,2);

// initialize our variables
int sensorPin = 0;
int photocellPin = 1;
int speaker = 10;
int tempC, tempF, lightReading, potReading;
int potPin = 2;

// some notes to use on the speaker
int G = 392;
int C = 523;

void setup() {
  // set up the LCD's number of columns and rows
  lcd.begin(16, 2);
  
  // set up speaker
  pinMode(speaker, OUTPUT);
}

void loop() {  
  tempC = get_temperature(sensorPin);
  tempF = celsius_to_fahrenheit(tempC);
  lightReading = get_light_reading(photocellPin);
  potReading = read_pot(potPin);
  
  if (lightReading < potReading) sound_alarm();
  
  lcd.setCursor(0,0);
  lcd.print(tempF); lcd.print(" "); lcd.print((char)223); lcd.print("F"); lcd.print(" SET: "); lcd.print(potReading);

  lcd.setCursor(0,1);
   lcd.print("READ: ");lcd.print(lightReading);
  delay(200);
}

int read_pot(int pin) {
    int potReading = analogRead(pin);
    int temp = potReading + 700;
    return temp;
}

void sound_alarm() {
  tone(speaker, G);
  delay(200);
  tone(speaker, C);
  delay(200);
  tone(speaker, G);
  delay(200);
  noTone(speaker);
  
}

int get_light_reading(int pin) {
  int photocellReading = analogRead(pin);
  return photocellReading;
}

int get_temperature(int pin) {
  // We need to tell the function which pin the sensor is hooked up to. We're using
  // the variable pin for that above
  
  // Read the value on that pin
  int temperature = analogRead(pin);
  
  // Calculate the temperature based on the reading and send that value back
  float voltage = temperature * 3.6;
  voltage = voltage / 1024.0;
  return ((voltage - 0.5) * 100);
}

int celsius_to_fahrenheit(int temp) {
  return (temp * 9 / 5) + 32;
}


Once the code is uploaded try adjusting the pot and see if the values change on the lcd screen. If you adjust it to a value less than the light reading, you should hear the alarm.

Next: Top of Project