Fall 2026 Project
Thermostat
Introduction
This semester’s class project is to build a thermostat similar to ones that are installed in most homes. The user can set hot and cold thresholds and the device will monitor the room temperature and control heating and air conditioning devices based on the desired temperatures set on the thermostat.
Note: This is a non-trivial project that requires you to not only use the concepts and skills you’ve learned from past labs but to extend that knowledge and use the higher-level understanding of how embedded systems and microcontrollers work to include use of new components and modules.
All students are expected to do the work on the project individually. Sharing code with another student is an Academic Integrity volation. No use of AI tools is allowed.
Getting a full score is not a guarantee. It will require time and intelligent work (not just guess, but verifying on paper and using some of the approaches outlined below). But it is definitely doable. We have broken the project into 2 checkpoints (1 due each week) to help limit the scope of your work to more manageable deliverables. Also, note that while we will still provide help in terms of concept and approach, we will leave it to you to do most of the debugging. When you do need help debugging you should have already used the tools at your disposal: the DMM or scope to verify basic signals are as you expect, LCD print statements to see where your code is executing, whether you are getting into an ISR at all, or what the value of various readings/variables is. Test your code little by little (this is the reason we do checkpoints) and do not implement EVERYTHING and only then try to compile. In addition, when something doesn’t work, back out any changes you’ve made (comment certain portions, etc.) to get to a point where you can indicate what does work and then slowly reintroduce the new changes to see where an issue might lie. If you have not done your own debugging work and just ask for help, we will direct you to go back and perform some of these tasks.
To start, please read the overall project a few times before you even consider thinking about the many details. Get the big picture, hear the terms we use, look for the requirements and/or limitations we specify. Make sure you fully understand what it is the project does and how it works from the user’s level. You can’t write code to make the project do something if you don’t know what it’s suppose to do. Only then consider starting on your project.
For a copy of the project grading sheet, click here.
Thermostat Overview
In its simplest form a thermostat measures the temperature in a room and shows the temperature on both an LCD display and on a indicator dial where an pointer rotates to point to the current temperature. Based on setting that can be adjusted by the user, it decides whether to activate a heater to warm the room, or to activate an air conditioner to cool it. A block diagram of our thermostat is shown below and it will have the following features.
-
A temperature sensor that determines the temperature in the room.
-
A servo motor for positioning a pointer to indicate the temperature on a dial.
-
An LCD display for showing the current temperature in the room and the high and low temperature settings.
-
A control knob for adjusting the high and low temperature settings.
-
Two buttons for selecting whether the knob is used to set the high temperature or the low temperature.
-
Green, red and blue LEDs to indicate that the heater or air conditioner has been turned on, or both are off
-
A buzzer for generating an audio alert tone if the temperature is significantly above the high setting or below the low setting.
-
A button for putting the device in a low-power sleep mode, or waking it from sleep mode.

Operation of the Thermostat
The following is a description of the operation of the thermostat
To see a short video demonstrating the operation of the thermostat, click here.
-
The thermostat is always reading the temperature from the temperature sensor IC and displaying the value in degrees Fahrenheit on the LCD with 0.1 degree precision.
-
In addition to the temperature being displayed on the LCD, the servo motor is used to rotate a pointer to indicate the current temperature on a dial that shows temperatures from 40 to 100 degrees Fahrenheit. If the temperature goes below 40 degrees, the pointer should point to 40, and if it goes above 100 degrees it should point to 100.
-
The LCD display also shows the current values for the high and low temperature settings that determine whether to turn the heater or A/C on.
-
Adjusting the high and low temperature settings is done by first pressing one of the two buttons to select which setting to change, high or low. The LCD must indicate which setting will be adjusted if the knob is turned.
-
The rotary encoder is used set the high and the low temperature settings. As the user rotates the knob the temperature setting should change on the LCD display. If they then press the other button they can adjust the other setting.
-
The LCD display should always be showing the temperature and the two settings values even when the high and low temperature settings are being adjusted. It should not switch to a separate screen for adjusting the temperature and then switch back when done.
-
The high and low settings can be set to any integer value between 50 and 90 degrees. The software must make sure that the setting are never adjusted to where the low setting is higher than the high setting. The settings can be adjusted to the same value.
-
If the temperature in the room goes above the high setting, the thermostat turns on the A/C, which we indicate by lighting up the blue element of the RGB LED. Similarly, if the temperature goes below the low setting we show that the heater has come on by illuminating the red element of the RGB LED. If the temperature is equal to or higher than the low setting, and equal to or below the high setting, both the heater and A/C are off. This is indicated by having the green element of the RBG LED turn on.
-
If the temperature in the room is more than 3 degrees above the high setting, or more than 3 degrees below the low setting, the buzzer sounds an alert tone for a 0.5 second duration. The tone is only sounded once for each time the temperature goes outside the 3 degree limit. It will not sound again until after the temperature has changed to be within the 3 degreen limit.
-
The high and low temperature settings are stored in the Arduino’s EEPROM non-volatile memory so the values are retained even if the power is turned off. This makes it unnecessary for the user to set these values each time the device is turned on.
-
If there is no activity with any of the buttons or controls for fifteen seconds the device goes in to a low-power mode. In this mode the LCD display is turned off (both the display and the backlight) and the servo pointer no longer points to the current temperature. To wake the device up, the WAKE/SLEEP button must be pressed. Pressing the WAKE/SLEEP button can also be used to put it in low-power mode without having to wait for the 15 seconds to elapse.
Getting Started
Create a project folder inside your ee109 folder like you have done for all
the previous lab assignments this semester. We suggest starting with a copy of
your code from Lab 5 since this project uses the rotary encoder. It’s strongly
recommended that you remove from the lab5.c file any code or variables that
will not be used in this project.
Most of the components used in this project have been used in previous labs, and your C code from the other labs can be reused if that helps. The project involves the use of two new elements:
- An external temperature sensor
- The non-volatile memory (EEPROM) on the Arduino
Download from the class web site the file project.zip that contains the files
ds18b20.c and ds18b20.h that are needed to work with the DS18B20
temperature sensor that is described below. It also contains the
Project_Answers.txt file with information about what needs to be demonstrated
to show the project is working.
Additional details about the temperature sensor and using the EEPROM memory are provided later on this web page.
Which Port Bits to Use
Since the CPs grading the project may wish to try running the code on their project board, it is very important (and required) that all students use the port connections shown below to connect their buttons, rotary encoder, LEDs, etc. If other port bits are used the project will not operate when the program is run on another board.
| Port Bit | Function |
|---|---|
| PORTB, bit 2 (PB2) | Backlight control for LCD (see below) |
| PORTB, bit 3 (PB3) | PWM signal to servo motor |
| PORTB, bit 4 (PB4) | Red LED |
| PORTB, bit 5 (PB5) | Green LED |
| PORTC, bit 1 (PC1) | Blue LED |
| PORTC, bit 2 (PC2) | Low set button |
| PORTC, bit 3 (PC3) | High set button |
| PORTC, bit 4 (PC4) | Sleep/Wake button |
| PORTC, bit 5 (PC5) | 1-Wire bus to DS18B20 |
| PORTD, bit 1 (PD1) | Buzzer |
| PORTD, bit 2 (PD2) | Rotary encoder |
| PORTD, bit 3 (PD3) | Rotary encoder |
Note: In previous labs we never used Port B, bit 2 (PB2) since it controls the LCD backlight, and warned students to never make PB2 an output by setting DDRB, bit 2 to a one since this would likely turn the backlight off. In this project we will be using PB2 and to have the LCD operate normally the PB2 bit must be set for an output (DDBB, bit 2 = 1) and the output be a 1 (PORTB, bit 2 = 1). In the initialization part of your code we recommend adding the two lines to set these two bits to ones so the LCD will operate normally.
Hardware Construction Tips
The buttons, LEDs, rotary encoder, buzzer and DS18B20, and the various resistors should all be mounted on your breadboard. It’s strongly recommended that you try to wire them in a clean and orderly fashion. Don’t use long wires that loop all over the place to make connections. You will have about 11 wires going from the Arduino to the breadboard so don’t make matters worse by having a rat’s nest of other wires running around on the breadboard. Feel free to cut off the leads of the LEDs and resistors so they fit down close to the board when installed.
Make use of the bus strips along each side of the breadboard for your ground and +5V connections. Use the red for power, blue for ground. There should only be one wire for ground and one for +5V coming from your Arduino to the breadboard. All the components that need ground and/or +5V connections on the breadboard should make connections to the bus strips, not wired back to the Arduino.
DS18B20 Temperature Sensor
A new component to this project is the DS18B20 temperature sensor. This is an integrated circuit that connects to the microcontroller using a single wire called a “1-Wire” interface by the manufacturer. This single wire is used to both send commands from the Arduino to the sensor, and to read back data from the sensor to the Arduino. Your code will preform the sending and receiving of data on this wire.
A picture, pin diagram and schematic diagram of the DS18B20 is shown below. The IC needs to have ground and power connections provided on pins 1 and 3 respectively.
WARNING! Make sure you install the power and ground connections to the DS18B20 correctly and don’t reverse them. If the power and ground are reversed the DS18B20 will quickly get very hot and eventually burn out.
The Arduino communicates with the DS18B20 by connecting the “DQ” pin (pin 2) to one of the Arduino’s I/O port bits. Note from the schematic that the DQ line must have an external 4.7kΩ pull-up resistor on it. This is not an option, without it the 1-Wire bus will not operate. You can not use the port bit’s internal pull-up instead of the external resistor.

From the class web site you can download the files ds18b20.c and ds18b20.h
that contains software to communicate with the DS18B20 temperature sensor over
the 1-Wire bus. The routines in ds18b20.c assume the DS18B20’s “DQ” pin is
connected to Port C, bit 5. If you decide to connect it to some other I/O
pin, the routines in ds18b20.c will have to be modified to match your
configuration.
Testing the DS18B20
Once you have wired the DS18B20 to +5V, ground and PB4 for the data connection,
you can test the sensor using the test program available on the class web site.
Download the temp_test.zip file to a another folder inside the project area
and break it apart. It will contain a Makefile and a test.hex file. Edit
the PROGRAMMER line in the Makefile if necessary, and then run the command
make test to download the sensor test program to your Arduino.
When the test program runs, it will go into a loop querying the DS18B20 for the temperature data. If it can not read data from the sensor, it will write “No DS18B20 found” on the LCD screen. This error is most likely due to a wiring mistake, or neglecting to install the pull-up resistor.
If it can query the sensor, it will write the two bytes of data it received on the LCD in hexadecimal, and the results of converting that to Fahrenheit degrees. You should be able to see the temperature change if you warm or cool the sensor.
Important: Make sure the test program is displaying valid temperature results before you proceed with writing your own code to read the sensor and convert the data to degrees Fahrenheit. If the test program can’t read the sensor that has to be fixed before you can proceed.
DS18B20 Application Programming Interface
We’ve provided some of the routines that do the work necessary for using the
DS18B20. The ds18b20.c file contains the following three top-level
routines that make up the API (Application Programming Interface) to the
sensor.
-
ds_init- Initializes the 1-Wire bus and the DS18B20. Theds_initroutine only has to be called once at the start of the program. The routine returns 0 if the initialization failed, perhaps due to a defective or missing DS18B20, or more likely due to an error in coding of the functions called by ds_init to communicate with the DS18B20. If the initialization was successful, the routine returns a 1. -
ds_convert- Starts a temperature conversion by the DS18B20. Theds_convertroutine has to be called each time you want to acquire a new temperature sample. The call tods_convertstarts the conversion but returns before the conversion has completed. -
ds_temp- Theds_temproutine must be called to acquire the temperature data. The function is called with one argument, the name of aunsigned chararray of length 2. If it is called prior to the conversion completing, it will return a value of zero. If the conversion has completed, it returns a value of 1, and the two data bytes containing the temperature data are placed in the two element array. The format of the temperature data stored in the array is described below.
The ds18b20.h file contains declarations for these three three functions and
can be included in your program file to declare the functions.
char ds_init(void);
void ds_convert(void);
char ds_temp(unsigned char *);
Below is a sample of some code that uses these routines to read the temperature data.
#include "ds18b20.h"
main()
{
unsigned char t[2];
if (ds_init() == 0) { // Initialize the DS18B20
// Sensor not responding
}
ds_convert(); // Start first temperature conversion
while (1) {
if (ds_temp(t)) { // True if conversion complete
/*
Process the values returned in t[0]
and t[1] to find the temperature.
*/
ds_convert(); // Start next conversion
}
}
}
The temperature data is returned in two elements of the char array
that is passed to the ds_temp function. Element 0 of the array
contains the eight least significant bits. Bits 3, 2, 1 and 0 are the
fractional part of the temperature value. Element 1 of the array contains the
four most significant bits of the temperature value. The result is essentially
a 12-bit 2’s complement number stored in two 8-bit bytes with the sign (‘S’ in
the diagram below) extended to fill it out to a 16-bit 2’s complement
number. The two bytes together represent the temperature in degrees Celsius
times 16. For example if the temperature is 27.5 degrees Celsius, 16 times this
is 44010, or 0x01B8 in hex. The two values in the array elements
would then be 0x01 in element 1 and 0xB8 in element 0.

DS18B20 Low-Level Functions
The three API high-level routines described above make use of several low-level
routines in ds18b20.c that are not intended to be seen or used by a user of
the API. These routines do the actual work of communicating with the DS18B20 to
acquire the temperature data.
-
ds_reset - Send a reset pulse to the DS18B20. This routine is provided for you.
-
ds_writebyte - Send one 8-bit byte to the DS18B20. This routine is provided for you.
-
ds_readbyte - Read one 8-bit byte from the DS18B20. This routine is provided for you.
-
ds_write1bit - Send a 1 bit to the DS18B20. This routine you will have to write.
-
ds_write0bit - Send a 0 bit to the DS18B20. This routine you will have to write.
-
ds_readbit - Read a single bit from the DS18B20. This routine you will have to write.
The code for most of the above routines is provided in the ds18b20.c file but
you will have to write the code for the ds_write0bit, ds_write1bit and
ds_readbit routines.
The Arduino sends bits to, and receives bits from, the temperature sensor (the DS18B20) by signaling over the 1-Wire bus. The 1-Wire bus uses a single wire that is used to send data from the Arduino to the DS18B20, and at other times from the DS18B20 to the Arduino.
Signaling on a 1-Wire bus is based on the idea that both devices connected to the bus allow the bus to “float”, also called “releasing the bus”, by not putting any signal on the bus. A pull-up resistor connected to the bus then pulls the bus to the high state and it sits in the high state when neither device is trying to send any information. When one device needs to send data to the other it sends 0’s and 1’s by putting a zero volts signal on the bus for different lengths of time and letting it float the rest of the time. The receiving device notes how long the bus was in the 0 volts state and from that determines whether a 0 or 1 was being sent to it.
The diagram below shows the timing for sending a 0 bit and a 1 bit from the Arduino to the DS18B20. For each bit being sent, the Arduino must make the bus low for the indicated amount of time, and then release it (so it goes back to the high state) for the indicated amount of time. After that has been done, it can then repeat the process to send the next bit.

Reading bits is done in a similar fashion. The Arduino signals the DS18B20 to send bits by pulling the bus down to 0v for short time and then releasing it to go high. It then monitors the bus to see if the other device pulls the bus low (sending a 0) or leaves it high (sending a 1). This can be done by simply reading the state of the bit in the PIN register after the specified amount of time has gone by.
The diagram below shows the timing for reading a 0 and 1 bit sent from the DS18B20 to the Arduino.

The operations of pulling the 1-Wire bus down to zero volts, or letting it float so the pull-up resistor makes it a high voltage, can be done by just changing the value of the DDR bit for that I/O port bit.
-
If the PORT bit is 0 and the DDR bit is 0 making it an input, the I/O pin floats and the pull-up resistor will make the bus go to the high state or 1 state.
-
If the PORT bit is 0 and the DDR bit is 1, then the I/O pin becomes a output. The zero in the PORT bit will make the I/O pin pull the bus down to the low state or 0 state.
Therefore all you need to do to change the state of the bus is change the DDR bit.
The DS18B20 datasheet describes the timing for writing ones and zeros, and for reading a bit from the DS18B20 in more detail on pages 15-17. You should refer to these pages when completing the code for the these routines.
Temperature Calculations
The DS18B20 converts the temperature into a two’s complement 12-bit value (8-bits for the integer portion and a 4-bit fractional portion) representing the temperature in degrees Celsius, and stores these in two bytes that can be transferred from the DS18B20 by your program. The DS18B20 datasheet on pages 5 and 6 describes the format of how the temperature data is stored, and includes several examples of how values are represented.
Your program should convert these two bytes to an Fahrenheit value. The Fahrenheit value to be displayed should include one digit to the right of the decimal point (e.g. 74.6). The bits for the fractional part of a degree Celsius that are included in the data returned from the DS18B20 must be properly factored into the conversion to the Fahrenheit temperature. In other words, don’t throw away any of the precision of the sampled value. Use all of it to give the most accurate Fahrenheit value possible for displaying (to one decimal place).
Hint: The ds_temp routine returns the temperature in two bytes. Combine
these two 8-bit values into a single 16-bit signed variable before doing any
operations to convert it to Fahrenheit.
Converting from Celsius temperature to Fahrenheit is usually done with the formula

however in this project all temperature calculations must be done in integer
(fixed point) arithmetic. Do NOT use any floating point numbers (float
or double) either as constants (e.g. 0.1) or variables.
Watch this video for more tips on doing floating point operations using integers. The slides are available here.
When using integer arithmetic, and variables with a limited numeric range, it’s easy to go wrong. For example if we do the following
unsigned char c, f;
f = (9 / 5) * c + 32;
the integer division of “9 / 5” will be 1 and give result of “F = C + 32”. On the other hand, if we do it as
unsigned char c, f;
f = (9 * c) / 5 + 32;
The product “9 * c” will probably give a result outside the range of the unsigned char variable and result in an overflow. To get the correct answer, you must do the conversion using variables of the right size and do the calculations in the proper order.
Reminder: Any use of Floating Point variables OR constants will result in large deductions in the visual grading.
Testing Your Temperature Conversions
If you want to test your code that converts from the 16-bit temperature value returned by the sensor to a Fahrenheit value, try using some of the temperature values listed on page 6 of the DS18B20 datasheet (linked on Labs web page).
Pick one of the 16-bit values from the table, for example 0191 hexadecimal,
and set the variable in your code that holds the sensor data to 0x0191 rather
than having it hold the value returned by the sensor. Then run your program
and see what Fahrenheit value your code calculates. According to the table
this sensor value represents 25.0625 degrees Celcius, and using a calculator
this is 77.1 degrees Fahrenheit. If your result is way off then something is
wrong with the calculation. Try this test for few other values from the table
and confirm your code is coming up with the right Fahrenheit numbers.
Temperature Comparisons
While the temperature should be displayed to a 1/10 of a degree precision, you can do your temperature comparisons for turning LEDs on and off using just the integer portion of the temperature. You don’t have to do any rounding to get the integer values, simply drop the fractional part of the temperature. Similarly, the temperature settings done with the rotary encoder (and stored in the EEPROM) are only done to integer values.
High/Low Temperature Setting Buttons
The thermostat has two buttons for selecting whether the rotary encoder adjusts the low temperature setting or the high temperature setting.
-
If the low temperature button is pressed, the encoder adjust the temperature at which the heater will comes on if the temperature goes below that setting.
-
If the high temperature button is pressed, the encoder adjust the temperature at which the air conditioner comes on if the temperature goes above that setting.
The selected mode must be indicated in some way on the LCD screen so the user will know which setting will be adjusted if they rotate the encoder. The recommended way is to put a character of some type next to the low or high temperature setting that is shown on the LCD.
Once a button is pressed to change to the low or high mode, it should stay in the selected mode until the other button is pressed to switch the mode. The user does not have to hold the button down to make it stay in either the low or high mode.
Adjusting Temperature Settings
The rotary encoder is used to set the high and low temperature settings between 50 and 90 degrees as an integer value. Both temperature settings should be shown at all times on the LCD. As the user rotates the knob the selected temperature setting, high or low, changes. The software must ensure that the setting is never adjusted to be outside the 50 to 90 degree limits. In addition the program must ensure that the low setting is never adjusted to be above the high setting, or that the high setting is adjusted to be below the low setting. The two settings can be set to be the same number.
The rotary encoder code from prevous labs can be adapted to implement the settings adjustment. Be aware that the input bits use for the encoder in this project are not the same as those used in previous labs. When using the encoder code from other labs, make sure to modify it so it is reading the correct PIN input bits. Also make sure to change the pin change interrupts configuration so the correct PORT and bits within the PORT are being used, and the correct ISR is being invoked.
Whenever a new settings value is selected, it is stored in the non-volatile EEPROM (see below).
LEDs
The two temperature setting values and the current temperature are continuously compared to determine whether the heater or air conditioner (A/C) needs to be turned on. This is indicated by red, green and blue elements of the RGB LED. When doing the temperature comparison, only the integer part of the measured temperature need be used, the fractional part can be ignored.
-
If the measured temperature is less than the low setting, the red element of the RGB LED should be on to indicate the heater is on to heat the room.
-
If the measured temperature is greater than the high setting, the blue element of the RGB LED should be on to indicate the A/C is on to cool the room.
-
If the temperature is greater than or equal to the low setting (heater off) AND less then or equal to the high setting (A/C off), the green element of the RGB LED should be on.
Non-volatile EEPROM Memory
The ATmega328P microcontroller contains 1024 bytes of memory that retains its data when the power is removed from the chip. It’s similar to the FLASH memory where your program is stored but intended to be written to and read from your program rather than just during the “make flash” operation. In this project we will be using the EEPROM to store the two temperature settings. In this way when the device is turned on it will have the same settings as it had previously.
The avr-gcc software includes several routines that you can use for accessing the EEPROM. To use these functions, your program must have this “include” statement at the beginning of the file that uses the routines.
#include <avr/eeprom.h>
The two routines that you should use for your program are described below.
-
eeprom_read_byte- This function reads one byte from the EEPROM at the address specified and returns the 8-bit value. It takes one argument, the the EEPROM address (0-1023) to read from. For example to read a byte from EEPROM address 100:unsigned char x; x = eeprom_read_byte((void *) 100); -
eeprom_update_byte- This function writes one byte to the EEPROM at the address specified. It takes two arguments, the address to write to and the 8-bit value of the byte to be stored there. For example to write the value in the unsigned char variabletempto address 200 in the EEPROM:unsigned char temp; // Assume some value is assigned ‘temp’ eeprom_update_byte((void *) 200, temp);
Your code should use the above routines to store the two temperature settings in the EEPROM whenever it has been changed. You can assume the settings will always be in the range of 50 to 90 degrees. The number can be stored in an 8-bit variable and only requires writing a single “unsigned char” variable to the EEPROM. You can choose any address in the EEPROM address range (0 to 1023) to store the value.
When your program starts up it should read the value from the EEPROM, but it must then test the value to see if it is a valid setting value. If the EEPROM has never been programmed, it contains all 0xFF values. If you read the EEPROM data and the value is not in the range 50 to 90, then your program should ignore this number and revert to using a default setting value that is defined in your source code.
Buzzer
If the temperature is more than three degrees above the high setting, or more than three degrees below the low setting the buzzer sounds a short alert tone. The alert tone in only sounded once when the temperature goes beyond the 3 degree limit. It will not sound again until after it has changed to be inside the three degree range, and then once again goes outside this range.
In Lab 5 you worked with producing tones of different frequencies from the buzzer. At first those tones were done with code that used delays of half the desired output period between operations to make the output signal go high or low. The result was a squarewave signal at the desired frequency.
At the end of the lab you were asked to change the code to use one of the timers and interrupts to generate the delays needed to produce the tone. In this project you should use that technique to have a timer create the necessary delays for sounding the tone.
TIMER0, an 8-bit timer, should be used to generate a one half second tone of whatever frequency you choose. Unlike in Lab 5, in this project you only need to generate a tone of single frequency, so you can load the timer modulus number for a half-period delay in the TIMER0 initialization routine and it never has to be changed after that.
When the program wants to sound the buzzer it can start the timer running. Each time an interrupt occurs the ISR changes the state of the output bit driving the buzzer. After the required number of transitions have occured, the ISR can shut the timer off to end the output. Do not use the delay functions to drive the buzzer.
Servo Motor Indicator Dial
Besides displaying the temperature on the LCD, the temperature is also shown on a round dial by using a servo motor to rotate an indicator to point to the temperature. The dial shows temperatures from 40 to 100 degrees. If the temperature is outside this range it should point to the minimum or maximum value as appropriate.
The servo is controlled by Timer/Counter2 since this is the only timer with an output signal that is not blocked by the LCD panel. Servos normally operate with PWM signals with a period of 20ms, but with TIMER2 the longest period that can be achieved is 16.4ms and the servos will work properly with this period PWM signal.
The width of the PWM pulse must vary between 0.75ms and 2.25ms. Assuming TIMER2 is using the largest prescalar so as to have the maximum period, use that to determine the values that must go in the OCR2A register for the minimum pulse width of 0.75ms, and the value for the maximum pulse width of 2.25ms.
Once you have determined the two OCR2A values for the minimum and maximum pulse width, you can use those to develop an equation to map the temperature values to servo positions. The number that goes in the OCR2A register has a linear relationship with the temperature value. Linear equations are based on two points, and you have the two points:
-
The maximum OCR2A value will cause the motor to rotate fully to the left and point at the 40 degree position: (40, max OCR2A)
-
The minimum OCR2A value will cause the motor to rotate fully to the right and point at the 100 degree position: (100, min OCR2A)
Using these two points, determine a linear equation for mapping the temperature values to the OCR2A values. Once you have figured out the equation, write code to implement it, but remember to only use fixed point variables and operations. Do not use floating point operations or variables. Make sure the calculations do not result in overflows of the fixed point variables.
Every time the temperature changes, a new value for OCR2A should be calculated using the equation you developed above and stored in that register.
Reminder: Any use of Floating Point variables OR constants will result in large deductions in the visual grading
Low-Power Mode
Many household thermostats do not display the temperature setting all the time but rather shut the display off after some amount of time to save energy and preserve the display screen. We want our thermostat to do same thing. While it is in the low-power or sleep mode, it still responds to changes in the temperature and adjusts whether the heater or air conditioning is on or off.
Entering Low-Power Mode
When in normal mode, the low-power or sleep mode can be entered manually by the user pressing the SLEEP/WAKE button. The thermostat should also enter low-power mode if 15 seconds have elapsed since the last time either the high or low settings buttons have been pressed, or if 15 seconds have elapsed since the rotary encoder was used to set a high or low temperature. The 15 seconds is measured from the last one of these actions (pressing a button or turning the encoder) that have occured.
When entering low-power mode, the display can be be blanked by sending the LCD a command. When the screen is blanked no characters are visible. See the lecture slides on the operation of the LCD for information on what command value is used to blank the screen. In addition, the backlight can be turned off by setting Port B, bit 2 (PB2) to a zero.
The tri-color LED should be left illuminated while in sleep mode so we can confirm that the device is correctly responding to changes in the temperature even in sleep mode. When in sleep mode, the servo pointer should be left stationary and does not have to point to the current temperature.
Exiting Low-Power Mode
The thermostat can only be returned to normal mode from sleep mode by the user pressing the SLEEP/WAKE button. Pressing the high or low set buttons, or rotating the encoder should not bring it out of sleep mode, and should not make any changes to the settings while in sleep mode.
For example, the user has set the low temperature to 68 degrees and then walked away. After 15 seconds the device goes into sleep mode and shuts off the display. The user returns, and without pressing the SLEEP/WAKE button to bring the device back to normal mode and turn on the display, presses the low temperature setting button and then turns the encoder. This should not change the setting since the action of the setting buttons and the rotary encoder are ignored when in sleep mode.
When exiting low-power mode, the LCD can be returned to normal operation of displaying characters by sending it the proper command value. The backlight can be turned on by setting PB2 to a 1.
Low-Power Mode Time Delay
TIMER1, the 16-bit timer, can be used to implement the 15 second delay to enter sleep mode. Note that this timer, even with the largest prescaler, can not do a single timing of 15 seconds. You will have to break the time span up into smaller segments and track how many have gone by to reach 15 seconds.
Software Issues
Multiple Source Code Files
Your software should be designed in a way that makes testing the components of
the project easy and efficient. In previous labs we worked on putting all the
LCD routines in a separate file and this practice should be continued
here. Consider having a separate file for the encoder routines and its ISR.
All timer code could also be in a separate file. Code to handle the two
buttons and the RGB LED can either be in separate files or in the main program
since there isn’t much code for these. All separate code files must be listed
on the OBJECTS line of the Makefile to make sure everything gets linked
together properly.
For this project students are required to separate their program into at least four
.cfiles that have the corresponding.ofiles listed on the OBJECTS line of the Makefile.
Accessing Global Variables
In the project you may need to use global variables that are accessed in multiple source files. A global variable can be used in multiple files but it must be defined in one place. We define variables with lines like
char a, b;
int x, y;
Global variables must be defined outside of any function, such as at the start
of a file before any of the functions (like main()). Variables can only be
defined once since when a function is defined, the compiler allocates space for
the variable and you can’t have a variable stored in multiple places.
If you want to use that global variable in another source code file, the compiler needs to be told about that variable when compiling the other file. You can’t put another definition of the variable in the file for the reason given above. Instead we use a variable declaration. The declaration of a global variable (one that’s defined in a different file) is done using the “extern” keyword. The “extern” declaration tells the compiler the name of the variable and what type it is but does not cause any space to be allocated when doing the compilation of the file.
For example, let’s say the global variable “result” is accessed in two files, project.c and stuff.c, and you decide to define it in the project.c file. The project.c file would contain the line defining the variable
int result;
and the stuff.c file would need to have the line
extern int result;
declaring it in order to use the variable. If the “extern” keyword was omitted, both files would compile correctly, but when they are linked together to create one executable, you would get an error about “result” being multiply defined.
If you have global variables that need to be accessed in multiple files it’s recommended that you put the declarations in a “.h” file that can be included in all the places where they may be needed. For the example above, create a “project.h” file that contains the line
extern int result;
and then in both project.c and stuff.c add the line
#include "project.h"
It doesn’t cause problems to have the declaration of a variable, like from an “.h” file, included in the file that also contains the definition of the same variable. The compiler knows how to handle this correctly.
Improving Your Makefile
In class we discussed how the make program uses the data in the
Makefile various modules that make up a program. This project may require
several source code files, some with accompanying “.h” header files, so the
generic Makefile should be modified to describe this. For example, let’s say
you have five C files for the project and five header files:
-
The main program is in
project.cand has some global variables and functions declared inproject.h -
The LCD routines are in
lcd.cwith global declarations inlcd.h -
The functions to handle the rotary encoder are in
encoder.cwith global declarations inencoder.h -
The functions for the three timers are in
timers.cwith global declarations intimers.h -
The functions to handle the DS18B20 are in
ds18b20.cwith global declarations inds18b20.h
Let’s also say that project.h is “included” in the encoder.c and timers.c
files, and the header files for the LCD, encoder, timers and DS18B20 routines
are included in the project.c file. In this situation, the following lines
should be added to the Makefile after the “all: main.hex” and before the
“.c.o” line as shown below.
all: main.hex
project.o: project.c project.h lcd.h encoder.h timers.h ds18B20.h
encoder.o: encoder.c encoder.h project.h
timers.o: timers.c timers.h project.h
ds18b20.o: ds18b20.c ds18b20.h
lcd.o: lcd.c lcd.h
.c.o
Adding all the dependencies to the Makefile will make sure that any time a file
is edited, all the affected files will be recompiled the next time you type
make.
Building Your Design
It’s important that you test the hardware and software components individually before expecting them to all work together. Here’s a one possible plan for putting it together and testing it.
The project should be built in two stages with it checked off at each of the two stages.
For checkpoint 1:
-
Install the LCD shield and write code to put a splash screen on the LCD. This will confirm that you can write messages on both lines of the display. Use your file of LCD routines from the previous labs to implement this.
-
Edit the
ds18b20.cfile to finish the three routines that were left for you to complete. -
Install the DS18B20 thermometer IC. Write code that uses the provided routines to initialize the IC and then read the temperature from it. At first you can display the two bytes of temperature data as four hex digits (using the
%xformat string in ansnprintffunction call. Put this code in a loop so it continuously read the temperature and displays it on the LCD. Is the displayed value about what you would expect to see? Try heating up the DS18B20 by pressing your figure on it, or cool it by blowing on it, and confirm that the temperature changes. -
Once you know the sensor is returning valid data, implement the code to convert the Celsius temperature to Fahrenheit and display it on the LCD with one digit to the right of the decimal point.
-
Install the two high/low settings buttons. Write code to read the button presses. Use of the Pin Change Interrupts is recommended. Add code to indicate on the LCD which temperature setting, low or high, is being adjusted. Note that since we have separate buttons for the two modes we only need to detect that the button was pressed. We don’t have to deal with debouncing or having delays when sensing that a button is down.
-
Install the rotary encoder. Define the temperature setting variables and modify your encoder routines from Lab 5 to change this number up and down. Display the numbers on the LCD. Add code to make sure the numbers stay between 50 and 90 degrees.
-
Install the RGB LED. Add code to illuminate the one of the three LEDs based on the measured temperature and the temperature settings.
For checkpoint 2:
-
Add code to save the temperature settings in the EEPROM whenever they have been changed, and to read the values from the EEPROM when the program starts up. Check that value is within 50 to 90.
-
Install the buzzer on the breadboard. Write code to use TIMER0 to generate the tone on the buzzer, and to play the tone whenever the temperature goes more than 3 degrees above the hot setting or below the cold setting.
-
Add the servo motor. Write code to convert the measured temperature to the value to generate the correct PWM pulse. Try heating and cooling the temperature sensor and see if the servo points to the temperature displayed on the LCD.
-
Add the SLEEP/WAKE button and write code to determine if it has been pressed. Add code to shut off the LCD display and backlight when going to sleep mode, and turn them back on when returning to normal mode.
-
Add code to use TIMER1 to determine when 15 seconds have passed without either of the high or low settings buttons pressed or the encoder rotated. When this happens transition the device to sleep mode.
Results
Getting your project checked off can be done in multiple checkpoints to ensure you earn partial credit for parts that are working. At each checkpoint we will confirm operation of all the features from the previous checkpoints plus the new features added in the current checkpoint.
For both checkpoints, in addition to checking the following items of the project, you will be asked to explain how your code works. You should be prepared to explain the reasoning behind the code and how it implements the necessary tasks of the project.
Checkpoint 1:
-
Splash screen with your name shown at start.
-
Temperature sensor working and displaying temperature in degrees Fahrenheit on the LCD.
-
Buttons can select which temperature setting to adjust.
-
Rotary encoder can adjust temperature settings.
-
RGB LED operates correctly based on temperature and settings.
Checkpoint 2:
Demonstrate items from the previous checkpoint. Then demonstrate:
-
Settings stored in EEPROM and retrieved when Arduino restarted (power cycled).
-
Buzzer sounds warning if temperature above or below settings by more than 3 degrees.
-
Servo motor positions pointer to correct position for the measured temperature.
-
SLEEP/WAKE button works to put display to sleep and return to normal operation.
-
Thermostat correctly goes into sleep mode after 15 seconds of inactivity. SLEEP/WAKE button brings the device back to normal operation.
Review Questions
Be sure to answer the two review questions in Project_Answers.txt and
reprinted below:
-
Cost Analysis: Assume we are building 1000 units of this system. Use the provided part numbers (see the webpage) and the digikey.com or jameco.com website to find the total cost per unit (again assume we build a quantity of 1000 units) for these thermostats. Itemize the part costs (list each part and its unit cost when bought in units of 1000) and then show the final cost per unit below. Note: You only need to price the components used in the project (not all the components in your lab kit. Also, you do not need to account for the cost of the circuit board or wires. In a real environment we would manufacture a PCB (Printed Circuit Board). As an optional task, you can search online for PCB manufacturers and what the costs and options are in creating a PCB.
-
Reliability, Health, Safety: Assume this system was to be sold to consumers for use at their home.
-
What scenarios might you suggest testing (considering both HW and SW) before releasing the product for use?
-
How might you make your design more reliable? By reliability we don’t just mean keeping it running correctly (though you should consider that), but also how you can detect that a connected component has failed to gracefully handle such situations. You can consider both HW and SW points of failure, issues related to the operational environment, etc. and how to mitigate those cases.
-
Submission
Make sure to comment your code with enough information to convey your approach and intentions. Try to organize your code in a coherent fashion.
The Project_Answers.txt file and all source code (all .c and .h files and the
Makefile) must be uploaded to the Gradescope web site by the due date. Make sure
you have included all files since the graders may download your submission,
compile it on their computer and download it to their board for checking the
operation. See the Assignments page of the class web site for a link for
uploading.
Please make sure to save all the parts used in this lab in your project box. All the contents of the project box and components will need to be returned at the end the semester.