1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

Lập trình Vi Xử lý bằng ngôn ngữ C

142 809 7
Tài liệu được quét OCR, nội dung có thể không chính xác
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Programming Embedded Systems
Tác giả Michael J. Pont
Trường học University of Leicester
Thể loại Tài liệu
Năm xuất bản 2002-2003
Thành phố Leicester
Định dạng
Số trang 142
Dung lượng 2,65 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The 8051 microcontroller The “super loop” software architecture Strengths and weaknesseses of “super loops” Example: Central-heating controller Reading from and writing to port pins SFRs

Trang 2

Seminar 1: “Hello, Embedded World”

Overview of this seminar

Overview of this course

By the end of the course

Main course textbook

Why use C?

Pre-requisites!

The 8051 microcontroller

The “super loop” software architecture

Strengths and weaknesseses of “super loops”

Example: Central-heating controller

Reading from (and writing to) port pins

SFRs and ports

SFRs and ports

Creating and using sbit variables

Example: Reading and writing bytes

Creating “software delays”

Using the performance analyzer to test software delays

Strengths and weaknesses of software-only delays

Preparation for the next seminar

Seminar 2: Basic hardware foundations (resets, oscillators and port I/O)

Review: The 8051 microcontroller

Review: Central-heating controller Overview of this seminar Oscillator Hardware How to connect a crystal to a microcontroller Oscillator frequency and machine cycle period Keep the clock frequency as low as possible Stability issues

Improving the stability of a crystal oscillator Overall strengths and weaknesses

Reset Hardware More robust reset circuits Driving DC Loads Use of pull-up resistors Driving a low-power load without using a buffer Using an IC Buffer

Example: Buffering three LEDs with a 74HC04 What is a multi-segment LED?

Driving a single digit Preparation for the next seminar

42

43

44

Trang 3

Seminar 3: Reading Switches

Introduction

Review: Basic techniques for reading from port pins

Example: Reading and writing bytes (review)

Example: Reading and writing bits (simple version)

Example: Reading and writing bits (generic version)

The need for pull-up resistors

The need for pull-up resistors

The need for pull-up resistors

Dealing with switch bounce

Example: Reading switch inputs (basic code)

Example: Counting goats

Trang 4

Two further registers

Example: Generating a precise 50 ms delay

Example: Creating a portable hardware delay

The need for ‘timeout’ mechanisms - example

Creating loop timeouts

Example: Testing loop timeouts

Example: A more reliable switch interface

Creating hardware timeouts

Is this approach portable?

Example: Milk pasteurization Conclusions

Preparation for the next seminar

Trang 5

Seminar 7: Multi-State Systems and Function Sequences

Introduction

Implementing a Multi-State (Timed) system

Example: Traffic light sequencing

Example: Animatronic dinosaur

Implementing a Multi-State (Input/Timed) system

Example: Controller for a washing machine

The software architecture Overview

Using the on-chip U(S)ART for RS-232 communications Serial port registers

Baud rate generation Why use 11.0592 MHz crystals?

PC Software What about printf()?

RS-232 and 8051: Overall strengths and weaknesses Example: Displaying elapsed time on a PC Example: Data acquisition

Conclusions Preparation for the next seminar

Trang 6

Seminar 9: Case Study: Intruder Alarm System

Introduction

System Operation

Key software components used in this example

Running the program

The robot brain How does the robot move?

Pulse-width modulation Software PWM

The resulting code

More about the robot Conclusions

Trang 7

e Consider how you can generate delays (and why you might

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 1 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 2

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 8

a small amount of hardware) for embedded systems constructed

based on small, industry standard, microcontrollers;

(including both ‘Standard’ and ‘Small’ devices) programming language CC”), and

3 Begin to understand issues of reliability and safety and how software design and programming decisions may have a positive or negative impact in this area

All programming is in the ‘C’ language

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 3 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 4

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 9

Main course textbook

Throughout this course, we will be making heavy use of this book:

e It is very efficient;

e It is popular and well understood;

e Even desktop developers who have used only Java or C++

can soon understand C syntax;

e Good, well-proven compilers are available for every embedded processor (8-bit to 32-bit or more);

e Experienced staff are available;

e Books, training courses, code samples and WWW sites discussing the use of the language are all widely available

Overall, C may not be an perfect language for developing embedded systems, but it is a good choice (and is unlikely that a ‘perfect’ language will ever be created)

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 5

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 10

Pre-requisites!

e Throughout this course, it will be assumed that you have had

previous programming experience: this might be in - for

Typical features of a modern 8051:

e Thirty-two input / output lines

e Internal data (RAM) memory - 256 bytes

e Up to 64 kbytes of ROM memory (usually flash)

e Three 16-bit timers / counters

e Nine interrupts (two external) with two priority levels

¢ Low-power Idle and Power-down modes

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 7

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 8

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 11

The “super loop” software architecture

}

Crucially, the ‘super loop’, or ‘endless loop’, is required because we

have no operating system to return to: our application will keep looping

until the system power is removed

Strengths and weaknesseses of “super loops”

© The main strength of Super Loop systems is their simplicity This makes them (comparatively) easy to build, debug, test and maintain

© Super Loops are highly efficient: they have minimal hardware resource implications

© Super Loops are highly portable

BUT:

® If your application requires accurate timing (for example, you need to acquire data precisely every 2 ms), then this framework will not provide the accuracy or flexibility you require

@ The basic Super Loop operates at ‘full power’ (normal operating mode) at all times This may not be necessary in all applications, and can have a dramatic impact on system power consumption

[As we will see in Seminar 6, a scheduler can address these

problems |

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 9

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 10

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 12

Temperature dial

/* Find out what temperature the user requires

(via the user interface) */

C_HEAT Get Required Temperature () ;

/* Find out what the current room temperature is (via temperature sensor) */

C_HEAT Get Actual _ Temperature () ;

/* Adjust the gas burner, as required */

C_HEAT Control Boiler () ;

The Standard 8051s have four 8-bit ports

All of the ports are bidirectional: that is, they may be used for both input and output

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 11 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 12

Trang 13

SFRs and ports

Control of the 8051 ports through software is carried out using what

are known as ‘special function registers’ (SFRs)

Physically, the SFR is a area of memory in internal RAM:

e PO is at address 0x80

e PI at address 0x90

e P2 at address 0xA0

e P3 at address 0xB0

NOTE: Ox means that the number format is HEXADECIMAL

- see Embedded C, Chapter 2

unsigned char Port data;

Port data = 0x0F;

Pl = Port_data; /* Write 00001111 to Port 1 */

Similarly, we can read from (for example) Port 1 as follows:

unsigned char Port data;

Pl = OxFF; /* Set the port to ‘read mode’ */

Port_data = Pl; /* Read from the port */

Note that, in order to read from a pin, we need to ensure that the last

thing written to the pin was a ‘1’

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 13

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 14

To write to a single pin, we can make use of an sbit variable in the

Keil (C51) compiler to provide a finer level of control

Here’s a clean way of doing this:

The input port

#define LED PORT P3

#define LED ON 0 /* Easy to change the logic here */

unsigned char Portl_ value;

sbit Warning led = LED PORT‘0; /* LED is connected to pin 3.0 */ /* Must set up Pl for reading */

Pl = OxFF;

while (1)

/* delay */

} }

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 15 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 16

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 15

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

7 Bits 0 PI: [OxFB NI Viv B

min time: maxtime: avgtime: totaltime: % count Pins: JosFB VNI Viv 0.983998 0983998 [0.981895 4.261982 100.0 96

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 18

Trang 16

Strengths and weaknesses of software-only delays

© SOFTWARE DELAY can be used to produce very short delays

© SOFTWARE DELAY requires no hardware timers

© SOFTWARE DELAY will work on any microcontroller

BUT:

® Itis very difficult to produce precisely timed delays

@ The loops must be re-tuned if you decide to use a different processor,

change the clock frequency, or even change the compiler optimisation

settings

Preparation for the next seminar

In the lab session associated with this seminar, you will use a hardware simulator to try out the techniques discussed here This will give you a chance to focus on the software aspects of

embedded systems, without dealing with hardware problems

In the next seminar, we will prepare to create your first test systems

on “real hardware”

EMBEDDED Please read Chapters 1, 2 and 3

before the next seminar

Michael J Pont

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 19

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 17

Seminar 2:

Basic hardware foundations (resets,

oscillators and port

Typical features of a modern 8051:

e Thirty-two input / output lines

e Internal data (RAM) memory - 256 bytes

e Up to 64 kbytes of ROM memory (usually flash)

e Three 16-bit timers / counters

e Nine interrupts (two external) with two priority levels

¢ Low-power Idle and Power-down modes

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 21

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 18

Review: Central-heating controller

Temperature sensor

Temperature dial

/* Find out what temperature the user requires

(via the user interface) */

C_HEAT Get Required Temperature () ;

/* Find out what the current room temperature is (via temperature sensor) */

C_HEAT Get Actual _ Temperature () ;

/* Adjust the gas burner, as required */

C_HEAT Control Boiler () ;

}

Overview of this seminar

This seminar will:

e Consider the techniques you need to construct your first

“real” embedded system (on a breadboard)

Specifically, we'll look at:

e Oscillator circuits

e Reset circuits

e Controlling LEDs

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 23

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 24

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 19

e All digital computer systems are driven by some form of

e This circuit is the ‘heartbeat’ of the system and is crucial to known as a Pierce oscillator

Crystal

e If the oscillator runs irregularly, any timing calculations

e A variant of the Pierce oscillator is common in the 8051

family To create such an oscillator, most of the components

are included on the microcontroller itself

e The user of this device must generally only supply the

crystal and two small capacitors to complete the oscillator

implementation

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 25 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 26

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 20

How to connect a crystal to a microcontroller Oscillator frequency and machine cycle period

e In the original members of the 8051 family, the machine

rapidly

In the absence of specific information, a capacitor value of

30 pF will perform well in most circumstances

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 27 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 28

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 21

Keep the clock frequency as low as possible

Many developers select an oscillator / resonator frequency that is at

or near the maximum value supported by a particular device

This can be a mistake:

e Many application do not require the levels of performance

that a modern 8051 device can provide

e The electromagnetic interference (EMI) generated by a

circuit increases with clock frequency

e In most modern (CMOS-based) 8051s, there is an almost

linear relationship between the oscillator frequency and the

power-supply current As a result, by using the lowest

frequency necessary it is possible to reduce the power

requirement: this can be useful in many applications

e When accessing low-speed peripherals (such as slow

memory, or LCD displays), programming and hardware

design can be greatly simplified - and the cost of peripheral

components, such as memory latches, can be reduced - if the

chip is operating more slowly

Stability issues

e A key factor in selecting an oscillator for your system is the

issue of oscillator stability In most cases, oscillator stability

is expressed in figures such as ‘+20 ppm’: ‘20 parts per million’

e To see what this means in practice, consider that there are approximately 32 million seconds in a year In every million seconds, your crystal may gain (or lose) 20 seconds Over the year, a clock based on a 20 ppm crystal may therefore

gain (or lose) about 32 x 20 seconds, or around 10 minutes

Standard quartz crystals are typically rated from +10 to +100 ppm, and

so may gain (or lose) from around 5 to 50 minutes per year

In general, you should operate at the /owest possible oscillator

frequency compatible with the performance needs of your application

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 29

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 30

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 22

Improving the stability of a crystal oscillator Overall strengths and weaknesses

keep accurate time, you can choose to keep the device in an year (up to ~1 minute / week)

oven (or fridge) at a fixed temperature, and fine-tune the

software to keep accurate time This is, however, rarely

© The great majority of 8051-based designs use a variant of the simple crystal-based oscillator circuit presented here: developers are therefore familiar with crystal-based designs

Quartz crystals are available at reasonable cost for most common frequencies The only additional components required are usually two

¢ “Temperature Compensated Crystal Oscillators’ (TCXOs) small capacitors Overall, crystal oscillators are more expensive than

crystal oscillator, and circuitry that compensates for changes

+0.1 ppm (or more): in a clock circuit, this should gain or |

© The stability falls with age

TCXOs can cost in excess of $100.00 per unit

e One practical alternative is to determine the temperature-

frequency characteristics for your chosen crystal, and include

this information in your application

For the cost of a small temperature sensor (around $2.00),

you can keep track of the temperature and adjust the timing

as required

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 31 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 32

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 23

CERAMIC RESONATOR

Overall strengths and weaknesses

© Cheaper than crystal oscillators

© Physically robust: less easily damage by physical vibration (or

dropped equipment, etc) than crystal oscillator

© Many resonators contain in-built capacitors, and can be used without

any external components

© Small size About half the size of crystal oscillator

BUT:

@ Comparatively low stability: not general appropriate for use where

accurate timing (over an extended period) is required Typically +5000

ppm = +2500 min per year (up to ~50 minutes / week)

Reset Hardware

e The process of starting any microcontroller is a non-trivial one

e The underlying hardware is complex and a small,

manufacturer-defined, ‘reset routine’ must be run to place this hardware into an appropriate state before it can begin

executing the user program Running this reset routine takes time, and requires that the microcontroller’s oscillator is

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 33

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 34

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 24

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

30 pF +10

Driving DC Loads

e The port pins on a typical 8051 microcontroller can be set at

values of either OV or SV (or, in a3V system, OV and 3V) under software control

e Each pin can typically sink (or source) a current of around

10 mA

e The total current we can source or sink per microcontroller (all 32 pins, where available) is typically 70 mA or less

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 36

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 25

e LED forward voltage, Vaiode = 2V,

e Required diode current, Igioge = 15 mA (note that the data

sheet for your chosen LED will provide this information)

This gives a required R value of 200o

Use of pull-up resistors

To adapt circuits for use on pins without internal pull-up resistors is

straightforward: you simply need to add an external pull-up resistor:

The value of the pull-up resistor should be between IK and 10K

This requirement applies to all of the examples on this course

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 37

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 38

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 26

8051 Device to drive load R —=—_ CC toad

1 load

¬ Vec

Piezo-electric buzzer

PXY Logic 0 (0v) to sound buzzer

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 39

Pont, M.J (2002) “Embedded C”, Addison-Wesley

“Low” output =0V ——®> LED is (fully) ON R

“High” output =5V —®>_ LED is OFF

“Low” output = ~1V ——j» LED is ON R

“High” output = 5V — 3» LED is OFF

It makes sense to use CMOS logic in your buffer designs wherever

possible You should also make it clear in the design

documentation that CMOS logic is to be used

See “PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS”, p.118 (IC

BUFFER)

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 40

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 27

Example: Buffering three LEDs with a 74HC04

This example shows a 74HC04 buffering three LEDs As discussed

in Solution, we do not require pull-up resistors with the HC

(CMOS) buffers

In this case, we assume that the LEDs are to be driven at 15 mA

each, which is within the capabilities (50 mA total) of the buffer

PX.b, (Red (Amber) (Green)

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 41

Pont, M.J (2002) “Embedded C”, Addison-Wesley

What is a multi-segment LED?

Multiple LEDs are often arranged as multi-segment displays:

combinations of eight segments and similar seven-segment displays (without a decimal point) are particularly common

Such displays are arranged either as “common cathode’ or ‘common anode’ packages:

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 42 Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 28

Driving a single digit

e In most cases, we require some form of buffer or driver IC

between the port and the MS LED

e For example, we can use UDN2585A

Each of the (8) channels in this buffer can simultaneously

source up to 120 mA of current (at up to 25V): this 1s

enough, for example, for even very large LED displays

e Note that this is an inverting (current source) buffer Logic 0

on the input line will light the corresponding LED segment

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 43

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Preparation for the next seminar

EMBEDDED Please read Chapter 4

before the next seminar

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 44

Trang 29

) Ban

4

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 45

Introduction

e Embedded systems usually use switches as part of their user interface

e This general rule applies from the most basic remote-control

system for opening a garage door, right up to the most sophisticated aircraft autopilot system

e Whatever the system you create, you need to be able to create a reliable switch interface

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 46

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 30

Review: Basic techniques for reading from port pins

We can send some data to Port 1 as follows:

sfr Pl = 0x90; /* Usually in header file */

Pl = Ox0F; /* Write 00001111 to Port 1 */

In exactly the same way, we can read from Port | as follows:

unsigned char Port data;

Pl = OxFF; /* Set the port to ‘read mode’ */

Port_data = Pl; /* Read from the port */

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES

Pont, M.J (2002) “Embedded C”, Addison-Wesley

The input port

void main (void)

{ unsigned char Portl_ value;

/* Must set up P1 for reading */

Pl = OxFF;

while (1)

{ /* Read the value of P1 */

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 48

Trang 31

sbit Switch pin = P1^O;

sbit LED pin = P1“*1;

void main (void)

Experienced ‘C’ programmers please note these lines:

sbit Switch pin = P1%0;

sbit LED pin = ÐĐ1^1;

Here we gain access to two port pins through the use of an spit variable declaration The symbol ‘”’ is used, but the XOR bitwise operator is NOT involved

while (1)

{

x = Switch pin; /* Read Pin 1.0 */

LED pin = x; /* Write to Pin 1.1 */

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 49

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 32

Example: Reading and writing bits (generic version)

The six bitwise operators:

| Bitwise OR (inclusive OR)

Ầ Bitwise XOR (exclusive OR)

unsigned char x = OxFE;

unsigned int y = Ox0AOB;

printf ("%-35s","x") ; Display Byte (x) ;

printf ("$-35s","1s complement [~x]");

Display Byte (~x) ;

printf ("%$-35s","Bitwise AND [x & 0x0f]");

Display Byte(x & Ox0f);

printf ("%$-35s","Bitwise OR [x | 0x0f]");

Display Byte(x | Ox0f);

print£ ("%-35s","Bitwise XOR [x * O0x0f]");

Display Byte(x * Ox0f);

printf ("$-35s","Left shift, 1 place [x <<= 1] ");

Display Byte(x <<= 1);

x = Oxfe; /* Return x to original value */

printf ("%$-35s","Right shift, 4 places [x >>= 4]");

Display Byte(x >>= 4);

printf ("\n\n") ;

printf ("%$-35s","Display MS byte of unsigned int y");

Display Byte((unsigned char) (y >> 8));

printf ("%$-35s","Display LS byte of unsigned int y");

Display Byte((unsigned char) (y & OxFF));

return 0;

}

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 51

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 52

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 33

Bitwise XOR [x “* Ox0f] 11110001

Left shift, 1 place [x <<= 1] 11111100

Right shift, 4 places [x >>= 4] O0001111

Display MS byte of unsigned int y 00001010

Display LS byte of unsigned int y 00001011

/* - #—

Reading and writing individual port pins

NOTE: Both pins on the same port

—#Ý#T———————=———~—=—————————————————————————————————————————————————— */

#include <reg52.H>

void Write Bit Pl(const unsigned char, const bit) ;

bit Read Bit Pl(const unsigned char) ;

void main (void)

{

bit x;

while (1)

{

x = Read Bit P1(0); /* Read Port 1, Pin 0 */

Write Bit _P1(1,x); /* Write to Port 1, Pin 1 */

void Write Bit Pl(const unsigned char PIN, const bit VALUE)

{ unsigned char p = 0x01; /* 00000001 */

/* Left shift appropriate number of places */

p <<= PIN;

/* If we want 1 output at this pin */

if (VALUE == 1) {

Pl |= p; /* Bitwise OR */

return;

} /* If we want O output at this pin */

p= ~p; /* Complement */

Pl &= p; /* Bitwise AND */

}

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 53

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 54

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 34

The need for pull-up resistors

bit Read Bit Pl(const unsigned char PIN)

/* Write a 1 to the pin (to set up for reading) */ Port 2,

This hardware operates as follows:

e When the switch is open, it has no impact on the port pin

An internal resistor on the port “pulls up’ the pin to the supply voltage of the microcontroller (typically 5V) If we read the pin, we will see the value ‘1’

e When the switch is closed (pressed), the pin voltage will be

OV If we read the the pin, we will see the value ‘0’

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 55 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 56

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 35

The need for pull-up resistors

We briefly looked at pull-up resistors in Seminar 2

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 57

Pont, M.J (2002) “Embedded C”, Addison-Wesley

The need for pull-up resistors

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 58

Trang 36

Dealing with switch bounce

In practice, all mechanical switch contacts bounce (that is, turn on

and off, repeatedly, for a short period of time) after the switch 1s

As far as the microcontroller 1s concerned, each “bounce' 1s

equivalent to one press and release of an ‘ideal’ switch Without

appropriate software design, this can give rise to a number of

problems, not least:

e Rather than reading ‘A’ from a keypad, we may read

'AAAAA'”

e Counting the number of times that a switch is pressed

becomes extremely difficult

e If a switch is depressed once, and then released some time

later, the ‘bounce’ may make it appear as if the switch has

been pressed again (at the time of release)

Creating some simple software to check for a valid switch input is straightforward:

1 We read the relevant port pin

2 If we think we have detected a switch depression, we wait for

20 ms and then read the pin again

3 If the second reading confirms the first reading, we assume

the switch really has been depressed

Note that the figure of ‘20 ms’ will, of course, depend on the switch used

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 59

Pont, M.J (2002) “Embedded C”, Addison-Wesley

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 60

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 37

Example: Reading switch inputs (basic code)

This switch-reading code is adequate if we want to perform

operations such as:

e Drive a motor while a switch is pressed

e Switch on a light while a switch is pressed

e Activate a pump while a switch is pressed

These operations could be implemented using an electrical switch,

without using a microcontroller; however, use of a microcontroller

may well be appropriate if we require more complex behaviour

For example:

e Drive a motor while a switch is pressed

Condition: If the safety guard is not in place, don’t turn the

motor Instead sound a buzzer for 2 seconds

e Switch on a light while a switch is pressed

Condition: To save power, ignore requests to turn on the

light during daylight hours

e Activate a pump while a switch is pressed

Condition: If the main water reservoir is below 300 litres,

do not start the main pump: instead, start the reserve pump

and draw the water from the emergency tank

⁄% ——————————-—-—-——-——-——-—-—-—-———-—-—-—-——-——-——-—————————-——-———-——-——-——-—-———-—-——— *k—

Switch read.C (v1.00)

A simple 'switch input' program for the 8051

- Reads (and debounces) switch input on Pin 1%°0

- If switch is pressed, changes Port 3 output

—*¥ —-—-—-—-—-—-—-— — ~~ ~~ — */

#include <Reg52.h>

/* Connect switch to this pin */

sbit Switch pin = P1*0;

/* Display switch status on this port */

#define Output_port P3

/* Return values from Switch _Get_Input() */

#define SWITCH _NOT PRESSED (bit) 0

#define SWITCH PRESSED (bit) 1

/* Function prototypes */

void SWITCH Init (void) ; bit SWITCH _Get_Input(const unsigned char DEBOUNCE PERIOD) ; void DISPLAY SWITCH STATUS Init (void) ;

void DISPLAY SWITCH STATUS Update(const bit) ; void DELAY LOOP Wait(const unsigned int DELAY MS) ;

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 61

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Pont, M.J (2002) “Embedded C”, Addison-Wesley

Trang 38

Sw_state = SWITCH _Get_ Input (30) ;

DISPLAY SWITCH STATUS Update (Sw_state) ; }

}

⁄% ————-—-— — a —-— -—-— —-— -—-— —-—-—-— —-— —-—-— —-—-— —-—-—-—-—-—-— — -—-— — -—-—-— *-

SWITCH Ini E()

Initialisation function for the switch library

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 63

Pont, M.J (2002) “Embedded C”, Addison-Wesley

SWITCH Get_ Tnput ()

Reads and debounces a mechanical switch as follows:

1 If switch is not pressed, return SWITCH_NOT_ PRESSED

2 If switch is pressed, wait for the DEBOUNCE PERIOD (in ms)

Then:

a If switch is no longer pressed, return SWITCH_NOT PRESSED

b If switch is still pressed, return SWITCH_PRESSED

See Switch Wait.H for details of return values

/* Debounce - just wait */

DELAY LOOP Wai t (DE BOUNCE PERIOD );

/* Check switch again */

if (Switch _pin == 0)

{

Return_value = SWITCH _PRESSED;

} }

/* Now return switch value */

return Return_value;

}

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I -

Pont, M.J (2002) “Embedded C”, Addison-Wesley

64

Trang 39

/⁄#-—=—= =———=————=————=————=—=———=—————————=———=—=—=—————————=——=—=—————————— #—

DISPLAY SWITCH STATUS Tni£ ()

Initialization function for the DISPLAY SWITCH_STATUS library

DISPLAY SWITCH STATUS Update /()

Simple function to display data (SWITCH_STATUS)

on LEDs connected to port (Output_Port)

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 65

DELAY LOOP _Wait()

Delay duration varies with parameter

Parameter is, *ROUGHLY*, the delay, in milliseconds,

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from:

Pont, M.J (2002) “Embedded C”, Addison-Wesley

PES I - 66

Trang 40

Example: Counting goats

e With the simple code in the previous example, problems can arise whenever a switch 1s pressed for a period longer than the debounce interval

Pins |IxIF =F TPP hh Pins: |OXFE VV VM e This is a concern, because in many cases, users will press

switches for at least 500 ms (or until they receive feedback that the system has detected the switch press) As a result, a

user typing “Hello” on a keypad may see:

COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 67 COPYRIGHT © MICHAEL J PONT, 2001-2003 Contains material from: PES I - 68

Pont, M.J (2002) “Embedded C”, Addison-Wesley Pont, M.J (2002) “Embedded C”, Addison-Wesley

Ngày đăng: 19/01/2014, 23:30

TỪ KHÓA LIÊN QUAN

w