Background Lecture - IEEE Real World Engineering Projects

Download Report

Transcript Background Lecture - IEEE Real World Engineering Projects

Microcontroller-based Smart House for
Improved Energy Efficiency
Background
The Problem
Reducing the energy footprint at the individual level can have a major
impact on total energy and environmental costs:
A typical U.S. household could save 25% of its $1,900 yearly energy bill
through improved energy efficiency.1
The average U.S. household produces
22,880 lbs of CO2 per year2 – a 25%
reduction would correspond to a
savings of over 2.5 metric tons.
In this project you will program a
microcontroller to measure status
and control heating and cooling
components to maintain a
comfortable temperature in a
foam smart house.
1US
Dept. of Energy “Energy Savers Booklet,”
http://www1.eere.energy.gov/consumer/tips/pdfs/energy_savers.pdf
2http://www.epa.gov/climatechange/emissions/downloads/emissionsfactorsbrochure2004.pdf
Energy Efficient Smart House
Lecture 1: Introduction to Microcontrollers
Outline
Introduction to microcontrollers
Microcontroller architectures
Programming languages
Introduction to C Programming Language
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
– Onboard memory for storing program and variables
– 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)
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.
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.
Generic Microcontroller Architecture
*Cady, Fredrick M. Assembly and C Programming for the Freescale HCS12 Microcontroller.
New York: Oxford University Press, 2008
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.
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)
How it All Works
*Cady, Fredrick M. Assembly and C Programming for the Freescale HCS12 Microcontroller.
New York: Oxford University Press, 2008
1. The program counter places the address containing the next
instruction to be executed on the address bus
2. 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)
How it All Works
*Cady, Fredrick M. Assembly and C Programming for the Freescale HCS12 Microcontroller. New York:
Oxford University Press, 2008
3. If data are required, the address of the data is read and the data
fetched
4. The instruction is executed
5. Any results are placed in the appropriate register or memory
6. The PC is advanced to the location of the next instruction
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)
The Programming Model
Accumulator A, 8 bits wide
(used for general-purpose
calculations, logical functions,
etc.)
Index Register, 16 bits wide,
formed by concatenating the 8bit 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.
Stack Pointer (SP), 16
bits wide, the stack is
used to store the status of
the system in case of an
interrupt
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.
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
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
Energy Efficient Smart House
Programming the Freescale
HCS08 Microcontroller in C
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 = 0b1111111111111111
Note that this is different from, e.g., Intel
machines
65,535 = 0FFFFH
or Freescale assembly language, where
65,535 = $FFFF
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
0b10000110
0b00010110
($A6)
($16)
Load Accumulator
2210
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
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
ADDA $1001
STA $1000
;Loads the first number
;Adds it to the second number
;Stores the result back in memory
In C, this would be written simply as:
A=A+B;
//Add B to A
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 0131103628)
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
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 machinecode operations performed will depend on the type of the
variable (floating point number, signed 8-bit integer, unsigned
16-bit integer, etc.)
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.)
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;
msleep(10);
PTAD = 0x00;
msleep(10);
b++;
//
//
// (A short routine to turn the outputs
// of Port A on and off every 10ms,
// for ten times.)
//
}
if(a==7){
PTAD = 0x00;}
else{
PTAD = 0x01;}
//An “if” statement, to turn PTAD
// off if “a” is equal to 7, and on
// otherwise.
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!
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.
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
Energy Efficient Smart House
I/O Ports and Timing
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 - they 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
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
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
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
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
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”
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 & 0b00000110;
if (a==0){ /* Put code to run when bits are zero here */
}
else
{ /* Put code to run when one or more bits are one here */
}
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)
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
PTBD = 0x01;
// turn on bit PTB0
msleep(1000);
//Delay 1000ms=1sec
PTBD = 0x00
// turn off bit PTB0
msleep(1000);
//Delay 1000ms=1sec
while(1){
}
}
Some Basic Concepts in
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
Some Basic Concepts in
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
Some Basic Concepts in
Thermodynamics
We can characterize the temperature behavior of the room
using Newton’s law of cooling:
The rate at which the temperature inside the room will change
is proportional to the difference in temperature inside and
outside
dTin(t)/dt = -[Tin (t) - Tout]
where t is the time and  is a characteristic time constant
This may be integrated to give the inside temperature as a
function of time
Tin (t) = Tout + Tin (0) - Tout) e-t/
Controlling the Temperature
To control the temperature of the Smart House you need to
understand two components:
The first is a thermoelectric heat pump
• Based on the Peltier effect – when a current
passes through a junction of dissimilar metals,
heat is pumped from one metal to the other
• Can be used as a thermoelectric cooler (TEC)
or as a heater if the direction of the current is
reversed
• Typical efficiencies are in the range of 5-20%
(compared with resistive heating, which is
essentially 100% efficient)
• Most efficient when the difference between the
inside and outside temperatures is small
To use the TE heat pump, just sandwich it between two heatsinks and
connect to your circuit, as described In the lab exercise – if the wrong
side becomes cold, just reverse the wires
Controlling the Temperature
To control the temperature of the Smart House you need to
understand two components:
The second is the Maxim DS18B20 Programmable
Resolution Digital Thermometer
• Digital thermometer-on-a-chip
• Includes all electronics to sense, digitize, and
transmit the temperature to the microcontroller
• Output is degrees Celsius with ½ degree
accuracy and selectable resolution ranging
from 1/2 to 1/16 degree
To use the DS18B20, connect it to the circuit as shown in the instructions
in the lab exercise and schematic
To get the temperature, use the subroutine GetTemp, as described in the
lab exercise
Now you’re ready to write your own code
to control the house climate.