Download presentation
Presentation is loading. Please wait.
Published byScot Mervin Wheeler Modified over 9 years ago
1
Microcontroller-based Smart House for Improved Energy Efficiency
Background
2
The Problem Reducing the energy footprint at the individual level can have a major impact on total energy and environmental costs. A typical household could save two metric tons of CO2 and $400 (US) per year though improved energy efficiency.* In this project you will program a microcontroller to measure status and control heating and cooling components to maintain an comfortable temperature in a foam smart house. *
3
Energy Efficient Smart House
Lecture 1: Introduction to Microcontrollers
4
Outline Introduction to microcontrollers Microcontroller architectures
Programming languages Introduction to C Programming Language
5
What is a Microcontroller?
A microcontroller is a “system-on-a-chip” typically intended for embedded applications such as telephones, automobile engine control systems, remote controls, office machines, appliances, toys, etc. Low cost (few dollars to $10s) Low power Usually low speed High degree of integration lots of onboard memory Analog-to-Digital, Digital-to-Analog Converters (ADCs, DACs) clock(s), timer(s) lots of Inputs and Outputs (I/O) Often emphasize interrupt response time over throughput (instructions per second) Often programmed using a low-level language (e.g., Assembly)
6
Microcontrollers vs. Microprocessors
A typical home in the US is likely to have between one and two dozen microcontrollers, compared to just a few microprocessors (desktop, laptop computers, etc.) A typical mid-range car can have over 50 microcontrollers.
7
Generic Microcontroller Architecture
*Cady, Fredrick M. Assembly and C Programming for the Freescale HCS12 Microcontroller. New York: Oxford University Press, 2008 The components of a microcontroller (and microprocessors, too) are connected via three data buses (sets of parallel wires) - data, address, and control. The central processing unit fetches instructions and data, performs arithmetic or logical operations on the data, and stores the results in special local register or general purpose memory (ROM or RAM). The I/O interfaces allow the microcontroller to communicate with and sense signals from the outside world.
8
Generic Microcontroller Architecture
If the instructions and data are stored in separate memory spaces, the architecture is said to be a “Harvard” architecture. If they are stored in a common memory space the architecture is said to be a “Von Neumann” architecture.
9
Microcontroller Components: CPU
*Cady, Fredrick M. Assembly and C Programming for the Freescale HCS12 Microcontroller. New York: Oxford University Press, 2008 Three main parts: ALU (contains adders, multipliers, logic functions, etc.) Special registers (Accumulator, Index register, Program counter) Control unit (Instruction Decoder, Sequence Controller)
10
How it All Works The program counter places the address containing the next instruction to be executed on the address bus The instruction is read from memory and decoded by the Instruction Decoder (some examples are ADD, logical AND, shift contents of a register or memory right or left, etc. - there are lots of them)
11
How it All Works If data are required, the address of the data is read and the data fetched The instruction is executed Any results are placed in the appropriate register or memory The PC is advanced to the location of the next instruction
12
What You Need to Know In order to program a microcontroller you need to know three things: the programming model (describes special-purpose registers) the memory map the instruction set (next lecture)
13
The Programming Model Accumulator A, 8 bits wide (used for general-purpose calculations, logical functions, etc.) Stack Pointer (SP), 16 bits wide, the stack is used to store the status of the system in case of an interrupt Index Register, 16 bits wide, formed by concatenating the 8-bit H register and the 8-bit X register (used for things like counting and addressing) - denoted H:X Program Counter (PC), 16 bits wide, points to the location of the next instruction to be executed Condition Code Register (CCR), 8 bits wide, keeps track of whether the last operation resulted in a zero, negative number, carry/borrow, two’s complement overflow, etc.
14
Memory The HCS08 has a 16-bit-wide address bus, which means it can address 216 = 65,536 individual memory locations (not all of these are implemented in the device). There are two types of memory present: RAM (Random Access Memory) - this type can be written to or read from as the program runs, however the information in it is lost when the microcontroller is powered down Flash ROM (Read Only Memory) - this is a type of memory that retains its contents when the chip is shut off. It can be erased and reprogrammed in large blocks but only when the program is downloaded; once the program is running it can’t be written to by the microcontroller Typically the program code and any data constants are stored in ROM, variables are stored in RAM.
15
MC9S08QG8 Memory Map I/O registers, control registers
Usually used for variable data storage and the Stack Usually used for program code and storage of constants and Interrupt vectors
16
C (and other higher-level languages)
The Programmer’s Model of the HCS08 and other microcontrollers is abstracted quite a bit when programming in C or other high-level programming languages. Typically, instead of assigning variables to memory locations manually as in assembly, you instead declare the variable names and types at the beginning of the program (or subroutine), and the C compiler takes care of allocating memory for these variables. Likewise, the accumulator (A) and Index Registers are generally not directly accessed in C. Instead, the programmer declares variables and works with those variables; the compiler then determines the best way to implement these higher-level instructions using HCS08 assembly-code instructions.
17
Energy Efficient Smart House
Programming the Freescale HCS08 Microcontroller in C
18
Numerical notation in C
Hexadecimal numbers are indicated by a prepended “0x” Binary numbers are indicated by a prepended “0b” Decimal numbers have no precedent Example: 65,535 = 0xFFFF = 0b Note that this is different from, e.g., Intel machines 65,535 = 0FFFFH or Freescale assembly language, where 65,535 = $FFFF
19
Programming languages
All processors are programmed in “machine code” using instructions and data represented by binary numbers (i.e., bits). As an example, the machine code sequence to load the Accumulator with the number 2210 is 0b ($A6) Load Accumulator 0b ($16) This is a cumbersome process. To speed the process assembly languages were developed. The equivalent Assembly code would be LDA #22 The Assembler (CodeWarrior for your microcontroller) converts this into the machine code above.
20
Programming languages
The trend is toward programming using higher-level languages such as C or C++. The higher the level of programming language, the less control you have over the resulting machine code – but the easier the code is to write. This makes it feasible to write programs of considerable complexity in reasonable amounts of time. As a small example, to add two numbers (A, at 1000 and B, at 1001) together in assembly, you would write: LDA $1000 ;Loads the first number ADDA $1001 ;Adds it to the second number STA $1000 ;Stores the result back in memory In C, this would be written simply as: A=A+B; //Add B to A
21
A Short Introduction to C
The “C” programming language Originally developed by Dennis M. Ritchie at Bell Labs Later greatly expanded as C++ One of the most widely used programming languages Almost as fast as assembly language, but much easier “The C Programming Language” by Kernighan & Ritchie (ISBN )
22
A Short Introduction to C
C code comprises four kinds of statements: Instructions - these are the things the microcontroller will perform while executing your program Compiler Directives - these are directions to the C compiler that give it additional information on how to compile your program (for instance, to “include” an additional file containing definitions or subroutines) Variable declarations - these are symbols representing locations or variable names in your program Comments - these are statements that you include in your program to document what you are doing
23
A (very) Short Introduction to C
(This introduction will provide enough of a background in C to complete the exercises in this module, as well as to give a general flavor of the language. For a more in-depth look at C, we recommend a good C textbook such as The C Programming Language by Kernighan & Ritchie.) C programming essentially resembles algebra, with a few additions to allow various programming operations. Variables are given names (such as: a, temp, indoorTemperature, maxWidth, quotient, runningAverage, etc), and various operations can be performed with these variables. Variables must be declared at the beginning of a program or subroutine; this instructs the compiler to set aside memory space for these variables. In addition, the specific machine- code operations performed will depend on the type of the variable (floating point number, signed 8-bit integer, unsigned 16-bit integer, etc.)
24
Some examples: a = a + 1; //Add one to the value in “a”
a = a * 2; //Multiply “a” by two a = a & 0x0F; //Perform a bit-by-bit AND function, //keeping only the lowest four bits //of “a”. (All other bits in “a” are //reset back to zero.) a = a | 0x04; //Sets the third bit of “a” (the fours’ // place) to 1. (It may have already // been either zero or one; it will be // a 1 after this instruction.) msleep(10); //Call the “msleep” function to delay //for ten milliseconds. (This function //is not a built-in part of C, and must //be defined. We provide it for you. a = b + 5; //Set “a” equal to “b” plus 5. (The value // of “b” is not changed.)
25
Some More Examples PTADD = 0xFF; //Set Port A direction to all-outputs
PTAD = 0x00; //Set all Port A outputs to zero b=0; // while (b<10){ // PTAD = 0xFF; // (A short routine to turn the outputs msleep(10); // of Port A on and off every 10ms, PTAD = 0x00; // for ten times.) msleep(10); // b++; } if(a==7){ //An “if” statement, to turn PTAD PTAD = 0x00;} // off if “a” is equal to 7, and on else{ // otherwise. PTAD = 0x01;} Note that if you are assigning a value, you use a single equals sign. If you are comparing or testing a value, use a double equals sign!
26
An example program in C // Here is an example program in C. Anything on a line that appears after // two forward slashes is a comment. (These lines are a comment, for example.) // Comments are not processed at all by the compiler; they are there for the // benefit of the programmers writing (and later, maintaining) the code. #include <stdio.h> //An “include” instruction, which tells the compiler to insert // the contents of the requested file here. This file can contain // additional needed subroutines, functions, and definitions. // It is included here because it provides the “printf()” – // formatted print – functionality, to be used in our program. void main(){ //The declaration of the main program body. // The “void” part means that it does not return a value when done. int x; // Declares “x” to be an integer. This sets aside memory for this // value. (One big difference from Assembly language is that the // specific memory location of “x” is not necessarily specified.) printf(“Hello, World!\n”); //Prints “Hello, World!” to the display, and then //skips to the next line (the “\n” part stands for New Line.) for(x=1;x<=10;x++){ // A “for” loop. The first part (“x=1”) defines the conditions at the start // of the loop; the second condition (“x<=10”) is the “continuation” // condition – the loop will run while this is true – and the “x++” part // is code executed each time through the loop. In this case, “x++” is // C shorthand for “Add one to the value stored in x.” printf(“X is %d\n”,x); // Prints out a diagnostic message showing what x is. This will // be executed ten times (once for each value of x.) } // A closing brace, to show the end of the “for” loop } //Another closing brace, to show the end of the “main()” program.
27
Energy Efficient Smart House
In the following series of laboratory exercises, you will learn to program a microcontroller to measure and control temperatures in a “smart” house and to devise strategies for intelligent control to reduce energy consumption
28
Energy Efficient Smart House
I/O Ports and Timing
29
Background Microcontrollers communicate with the outside world via “Ports,” which are internal 8-bit memory locations (addresses) that are connected to physical external pins on the chip These ports are multifunctional - the can be, e.g., digital signals analog signals analog-to-digital converters timing signals serial communications lots more You can tell the microcontroller what function each bit of a port should be by writing to its “control” registers
30
MC9S08QG8 16-pin DIP Pinouts Notice that each pin can serve multiple functions For example, pin 6 can be PORT B, Pin 6 (PTBD bit 6), a serial data line (SDA), or an input from an external crystal clock (XTAL) The default is “Parallel I/O Port,” which is what we’ll be using in the lab, so you don’t have to do anything to tell it what function the ports should be.
31
Parallel I/O Ports The HSC08 has two parallel bidirectional I/O ports, Port A (PTAD) and Port B (PTBD). Logically, the ports look to the processor like ordinary memory locations that may be read or written to: Port A is referenced as variable “PTAD” Port B is referenced as variable “PTBD” Bits of either port can be made to be an input or an output by writing a 0 (input) or 1 (output) to the corresponding bit of the port’s Data Direction Register (DDR). Port A has 4 bidirectional I/O bits, PTAD bit 0 through PTAD bit 3. Port B has 8 I/O bits, PTBD bit 0 through PTBD bit 7.
32
Parallel I/O Ports The ports are configured via “Data Direction Registers” (DDRs) on a bit-by-bit basis. Logical “1” configures the bit to be an output, “0” to be an input. The DDR variable for Port A is PTADD. The DDR variable for Port B is PTBDD.
33
Parallel I/O Ports For example, in the code PTBDD = 0x07; PTBD = 0x08;
the first line makes bits 0 through 3 of Port B all outputs and bits 4 through 7 all inputs. The second line makes bit 3 of Port B = 1. The result will be that pin 9 of the microcontroller (PTBD bit 3) will be high (about 3.3 volts). The instruction PTBD = 0x00; will result in 0 volts appearing at that pin.
34
Parallel I/O Ports If, at the same time an external device (a switch, external logic, sensor, etc.) is attached to pin 8 (PTB4) and produces a 3.3 volt signal while bits 5-7 are grounded, the instruction a = PTBD; will result in a 1 being written to bit 4 of the variable “a”.
35
Parallel I/O Ports Sometimes it’s necessary to test if one or more bits in a register or memory address are equal to 1. You do this by using a Boolean “AND” function, then testing for zero. (A single ampersand represents the bitwise AND function.) For instance, to test if bits 1 or 2 of Port A (PTAD) are set to 1, you could use the following code fragment: a = PTAD & 0b ; if (a==0){ /* Put code to run when bits are zero here */ } else { /* Put code to run when bits are one here */ }
36
Timing Delay Loops There are many ways, including using built-in timer functionality or writing custom assembly code, to get a microcontroller to delay for a certain amount of time. These techniques will be covered in depth if you take any course in beginning microcontroller programming, and so are not covered here. A delay function – msleep() – is provided for you; simply call it with the (integer) number of milliseconds that you want to wait. For instance, to wait 50 milliseconds, you could use: msleep(50); This subroutine is available only if the corresponding code is copied into your program body (or if you use the provided C programming stationery.)
37
Putting it all together
Suppose you want to turn an LED attached to PTB0 (pin 12) on for 1 second then off for 1 second, and repeat the cycle continuously Here’s the code: void main(){ PTBDD = 0xFF; // make PTB0 an output while(1){ PTBD = 0x01; // turn on bit PTB0 msleep(1000); //Delay 1000ms=1sec PTBD = 0x00 // turn off bit PTB0 }
38
Algorithms The prescription in the previous slide is example of an “algorithm” An algorithm is a precise description of the process or set of rules used to solve a problem To be useful, an algorithm must solve a specified problem, which includes the circumstances in which it must work and the properties the output must have The algorithm is independent of the language in which the program is written or the machine on which it is run Good algorithms have two important features Correctness (it must give the right answer) Efficiency (it must run in the allotted time and not use an excessive amount of resources)
39
Algorithms Modern programs are based on three basic structures:
Sequence - the sequence of functions or operations that the program is to perform Selection - the decision of which piece of the program to execute next, based on the value of some Boolean variable Iteration - executing parts of the program until some Boolean variable is true The structured program theorem states that these three structures are sufficient to express any computable function
40
Algorithms Programs that implement complex algorithms are usually developed in a systematic way The steps taken in the development include Design - the requirements for the program must be carefully analyzed and a design developed and broken down into suitable modules Coding - the various modules of the design must be written in the selected programming language and integrated Testing - the code must be tested to ensure correctness and that critical goals are met documentation - the code must be fully documented to support maintenance and future upgradeability
41
Some Basic Concepts in Electricity and Thermodynamics
Electrical power is the rate at which electrical energy is transferred by an electrical circuit The unit of power in the SI system of units is the Watt (W) In resistive dc circuits, the power dissipated in a component, P, is given by Joule’s law: P = V·I, where V is the potential difference across the component, and I is the current through it The energy and power are related by P = dE/dt E = ∫P dt
42
Some Basic Concepts in Electricity and Thermodynamics
In an isomorphic homogeneous material, the potential difference and current are related by Ohm’s law: I = V/Re where Re is the electrical resistance
43
Some Basic Concepts in Electricity and Thermodynamics
In a typical house heat can be lost via three mechanisms: Conduction - heat transfer between adjacent particles in a solid due to a temperature difference Convection - heat transfer due to the motion of molecules in a fluid both by random motion at the molecular level and by bulk motion of the fluid Radiation - heat transfer by electromagnetic radiation
44
Some Basic Concepts in Electricity and Thermodynamics
Conduction: In the steady state, the rate of heat flux (heat transferred per unit time per unit area) through a uniform material of thickness d that is maintained at a temperature T1 on one side and T2 on the other is given by Fourier’s law q’’ = k (T1 - T2)/d, where q’’ is the rate of heat flux and k is the thermal conductivity of the material
45
Some Basic Concepts in Electricity and Thermodynamics
Conduction: This equation may be rewritten as q’’ = T/Rt where Rt = d/k Note the similarity between this equation and Ohm’s law I = V/Re This suggests that the system may be modeled using standard techniques used for modeling electrical circuits, with the electrical resistance replaced by a thermal resistance, Rt
46
Some Basic Concepts in Electricity and Thermodynamics
Covection: Similarly, the heat flux from a surface to the outside environment due to convection may be written as q’’ = h (Tsurf - Tenv), where h is the convection heat transfer coefficient for the fluid outside the surface as before, we can rewrite this in terms of a thermal resistance q’’ = T/Rt, where Rt = 1/h
47
Some Basic Concepts in Electricity and Thermodynamics
Radiation: For radiation, the heat flux from a surface to the outside environment may be written as q’’ = hr (Tsurface - Tsurroundings), where h is a temperature dependent radiation heat transfer coefficient, given by hr = (Tsurface + Tsurroundings) (T2surface + T2surroundings), where is the absorptivity of the material and is Stefan’s constant We can again rewrite this in terms of a thermal resistance q’’ = T/Rt, where Rt = 1/hr
48
Some Basic Concepts in Electricity and Thermodynamics
Suppose you have a room at temperature Tin surrounded by walls in contact with the outside environment at temperature Tout The room loses heat to the walls through convection and radiation, the conduction in the walls transfer the heat to the outside surface, and the heat is transferred to the outside air by convection and radiation convection and radiation act in parallel with each other and in series with the conduction in the wall
49
Some Basic Concepts in Electricity and Thermodynamics
The analogous thermal circuit model might look like this where R_rad(in) = 1/hr(in) R_conv(in) = 1/h(in) R_cond = d/k (d = wall thickness) R_rad(out) = 1/hr(out) R_conv(out) = 1/h(out)
50
Some Basic Concepts in Electricity and Thermodynamics
The equivalent thermal circuit looks like this where R_equiv = R_cond , 1/R_rad(in) + 1/R_conv(in) /R_rad(out) + 1/R_conv(out) and the heat loss, which is equal to the heat that must be provided by the house heating system, is just q’’ = (Tin - Tout) /Requiv
51
Some Basic Concepts in Electricity and Thermodynamics
Time-varying temperature effects are more difficult to model A lumped capacitance model, similar to the lumped-resistance model just described, won’t work because the heat conduction inside our house walls is much less than the heat convection away from them We can still characterize the behavior using Newton’s law of Cooling: The rate of change in the temperature is proportional to the difference in temperature between the object and its environment dT(t)/dt = -[T(t) - Tenv]. where is a characteristic time constant This may be integrated to give the temperature as a function of time T(t) - = Tenv + T(0) - Tenv) e-t/
52
Thermoelectric Effects
Two thermoelectric effects are relevant to controlling the temperature of the house, the Seebeck and Peltier effects In the Seebeck effect an electromotive force is generated when two dissimilar metals are joined at their ends and the two junctions are kept at different temperatures The EMF is proportional to the temperature difference This is the basis for the thermocouple temperature sensor used to send the temperature insdie and outside the house The Peltier effect is the reverse of the Seebeck effect When a current is run through the junction of two dissimilar metals, heat will be transferred from one metal to the other The rate of heat transfer is proportional to the current and the difference in the Peltier coefficients of the two metals
53
Efficiency of Energy Conversion
The efficiency with which electrical energy is converted to heat depends on how the conversion is done Resistive heaters are essentially 100% efficient The thermoelectric heaters are very efficient when the difference between the inside and outside temperatures is small, but the efficiency decreases dramatically as the temperature difference grows Typical thermoelectric heater/cooler efficiencies are in the range of 20% of the theoretical maximum refrigerator efficiency
54
Now you’re ready to write your own code to control the house climate.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.