lab2_motorcontrol_08[1]

18
EE505 Electrical Engineering Lab. Spring 2008 Lab 2. DC Motor Control Using a Microcontroller 1. Purpose The main purpose of this experiment is to design and implement a DC motor position control system using a microcontroller, especially, to design an elevator position control system. Experimental steps include a sequence of development stages composed of getting acquainted with a microcontroller development system, actuating a DC motor with PWM (Pulse Width Modulation) switching amplifier, obtaining position feedback signal using optical encoder, designing and implementing a suitable feedback position controller for elevator. Students can establish a firm concept on control system implementation, which is one of typical design examples with judicious combination of both hardware and software. 2. Problem Statement Problem 2 Design and implement an elevator position control system for 6-story building using a DC motor and a microcontroller. Given a DC motor, design and implement a suitable elevator position feedback control system using a microcontroller as a digital controller, H-bridge PWM amplifier as an actuator, and an optical encoder as a position sensor. Overall block diagram is shown in Fig. 1. User interface Elevator Control System Micro- controller PWM amplifier DC M PC oto Fig. 1. Block diagram of an elevator control system Development system Encoder logic r Encode r 1

Upload: daiduong

Post on 20-Dec-2015

214 views

Category:

Documents


0 download

DESCRIPTION

Kiến thức

TRANSCRIPT

Page 1: Lab2_MotorControl_08[1]

EE505 Electrical Engineering Lab. Spring 2008

Lab 2. DC Motor Control Using a Microcontroller

1. Purpose

The main purpose of this experiment is to design and implement a DC motor position control

system using a microcontroller, especially, to design an elevator position control system. Experimental

steps include a sequence of development stages composed of getting acquainted with a

microcontroller development system, actuating a DC motor with PWM (Pulse Width Modulation)

switching amplifier, obtaining position feedback signal using optical encoder, designing and

implementing a suitable feedback position controller for elevator. Students can establish a firm

concept on control system implementation, which is one of typical design examples with judicious

combination of both hardware and software.

2. Problem Statement Problem 2 Design and implement an elevator position control system for 6-story building using a DC motor and a microcontroller. Given a DC motor, design and implement a suitable elevator position feedback control system using a microcontroller as a digital controller, H-bridge PWM amplifier as an actuator, and an optical encoder as a position sensor. Overall block diagram is shown in Fig. 1.

User interface Elevator Control System

Micro-

controller

PWM

amplifier DC

MPC

oto

Fig. 1. Block diagram of an elevator control system

Development

system

Encoder

logic

r

Encode

r

1

Page 2: Lab2_MotorControl_08[1]

3. Lab Overview 1) Microcontroller Microcontroller is a VLSI (Very Large Scale Integration) chip, which contains CPU (Central Processing Unit), memory, and input/output devices. In this experiment, a microcontroller named ATmega128 will be used. It is available from Atmel Co. Ltd., and has features of 8-bit RISC (Reduced Instruction Set Computer) CPU, program memory of 128 Kbytes, data memory of 4 Kbytes, and has many input/output interface devices. It is a typical small-but-powerful microcontroller. By integrating a suitable hardware and installing a suitable software program, one can implement a desired target system. Detailed documentations including datasheet on ATmega128 can be found at http://www.atmel.com.

In this experiment, for rapid and convenient implementation, a PCB board including

ATmega128will be utilized. The ATMega128BK3 board from Interboard Co. Ltd is selected. This board includes an ATmega128 microcontroller, SRAM (Static Random Access Memory) of 32 Kbytes, a RS-232C driver, a 16 MHz crystal oscillator, a reset switch, and also an ISP (In-System Programming) connector. Detailed documents and circuit diagram can be found at http://www.interboard.co.kr.

Note that the 2-pin connector at the bottom-center is the power connector (5V Red, Ground

Black), and the 10-pin connector at the top-left is the ISP-232 connector.

Fig. 2. ATmega128BK3 board

2

THANH TRAN
Note
Page 3: Lab2_MotorControl_08[1]

2) Cross Development System Cross development system is a software development system for developing software which is to be executed in the target embedded board. As a suitable hardware, a general-purpose computer is necessary including a keyboard and display for user input/output, and also a disk for program storage. Since vast amount of PCs (Personal Computers) are widely available, a PC can be utilized as a development system (sometime called a host computer or a host development system). Suitable cross-development development software should be installed and utilized, which includes an editor, a compiler, a linker, and a debugger. The compiler here does not generate Pentium binary codes, but generates ATmel binary codes. Hence this compiler is called a cross compiler, and the system is called a cross-development system. Software for development system is often called development tools. (1) Assembler

An assembler performs a conversion function from an assembly language program to a machine language, the latter is often called an object code. A typical and useful assembler is the AVRASM, which can be freely downloaded from ATmel. (2) C compiler

A C compiler performs a conversion function from a C language program to a machine language program (or an object code). The AVRGCC, which is freely downloadable from Gnu has good performance. In the AVRGCC package, a linker is also included, which combines multiple object codes and suitable libraries, and then generates an executable code. We will use the AvrEdit package, which contains the AVR GCC as well as a graphic user interface. (3) ISP program

The ATmega128BK3 board supports ISP (In-System Programming), which is a function to write the executable code into the program memory (or flash memory). A representative program, the PonyProg2000 with version of V2.06C, will be used.

In this case, a suitable hardware to connect the PC and the MTmega128 microcontroller is necessary. The ISP232-2 board from Interboard Co. Ltd. as shown in Fig. 3 will be used.

The top-right connector of the ISP board and the top-left connector of the ATmega128BK3 board should be connected with 10 pin flat cable. Two left-side 3-pin connectors of the ISP board are used for serial connections to the COM ports (COM1 and COM2) of the development PC. Only one serial connection (from the bottom-left of the ISP board to the COM1 port of the PC) is sufficient in this Lab.

3

Page 4: Lab2_MotorControl_08[1]

Fig. 3. ISP232-2 ISP board

Overall flow of the development process is illustrated in Fig. 4.

C compiler

Assembler

Linker

Programmer

Executable code

in the target

Executable code in the host

Object code

Assembly language file

C language file

Library

Object code

Fig. 4. Program Cross-Development Process

3) RS-232C Serial Interface

Communication between the microcontroller and the development PC are mainly performed by a serial communication, specifically named as RS-232C serial interface.

In the serial Interfaces, a data is transmitted along one wire (for each direction). Bits of the data are sent one after the other. Less data wires are required in the cable but it is slower since many bit transmission time is required.

In most cases, any device you connect to the serial port will need the serial transmission converted

4

Page 5: Lab2_MotorControl_08[1]

back to parallel so that it can be used. This can be done using a UART (Universal Asynchronous Receiver Transmitter). On the software side of things, there are many more registers that you have to attend to than on a Standard Parallel Port (SPP).

RS-232C/V24 is an Asynchronous Serial Interface with the following features: Early (1970’s) “asynchronous” serial interface used for slow printers. No transmitted clock signal. Character orientated. Transmits in units of one fixed sized binary word (5-8 bits). Transmission starts with a 0-level “start” bit, followed by the data, and terminating with one

(or two) 1-level “stop” bits. Multiple characters sent in this format. Any time may elapse between end of one character and beginning of next.

RS-232/V24 Timing is shown in Fig. 5. We can use 1, 1 ½, or 2 stop bits, and 10 to 11 bits/1 character.

Fig. 5. One character timing in RS-232C

Hardware properties of Serial interface are as follows. Two categories:

DCE (Data Communications Equipment): modem, TA adapter, plotter etc. DTE (Data Terminal Equipment): Computer or Terminal.

The electrical specifications: the EIA (Electronics Industry Association) RS232C standard. A "Space" (logic 0) will be between +3 and +25 Volts. A "Mark" (Logic 1) will be between -3 and -25 Volts. The region between +3 and -3 volts is undefined.

An open circuit voltage should never exceed 25 volts (In Reference to GND). A short circuit current should not exceed 500mA. The driver should be able to handle this

without damage. (Take note of this one!) The EIA RS232-C standard: maximum baud rate of 20,000 BPS! A new standard, RS-232D has been recently released. Two "sizes“

D-Type 25 pin male connector and D-Type 9 pin male connector.

Connection signals for the RS232C are described below.

D-type 25 pin D-type 9 pin Symbol Name

2 3 TD Transmit data

3 2 RD Receive data

5

Page 6: Lab2_MotorControl_08[1]

4 7 RTS Request to Send

5 8 CTS Clear to Send

6 6 DSR Data Set Ready

7 5 SG Signal Ground

8 1 CD Carrier Detect

20 4 DTR Data Terminal Ready

22 9 RI Ring Indicator

4) DC Motor Plant The plant to be controlled in this experiment is a DC motor. A general-purpose DC motor with gear will be used, and an external encoder for position sensing will be designed and attached to the DC motor. 5) PWM Amplifier

A variety of DC motor requires driving voltage from 3 to 400 V, and driving current from 1 to 50 amps, and hence 5V logic voltage is insufficient to drive them: A power-driver as well as a suitable power-supply is required. Also in order to provide rotation both in the clockwise and counter-clockwise directions, positive and negative voltages should be applied. For variable speed for rotation, a power amplifier with variable voltage output is required. The power loss in the power amplifier is not negligible.

In order to resolve these disadvantages, switching amplifiers as shown in Fig. 6 can be usually used. Fig. 6a shows a switching amplifier. For clockwise rotation, a PWM signal is applied to the base of Q1. The rotational speed is proportional to the width of on-cycle of the PWM. For counter-clockwise rotation, a PWM signal is applied to the base of Q2. Main disadvantage of this switching amplifier is that it requires two separate power supplies +Vs and –Vs.

An H-bridge type switching power amplifier is shown in Fig. 6b. For clockwise rotation, a PWM signal is applied to both bases of Q1 and Q4, where the rotational speed is proportional to the on-cycle of the PWM. For counter-clockwise rotation, a PWM signal is applied to both bases of Q2 and Q3. Although it requires 4 power transistors, it requires a single power supply only. In most applications, H-bridge switching power amplifier is used. In this experiment, a commercialized H-bridge IC will be used.

6

Page 7: Lab2_MotorControl_08[1]

Fig. 6. (a) Switching amplifier with dual power supply, (b) H-bridge switching amplifier

6) Optical Encoder

Principle for the optical encoder is to detect the disk rotation via slotted disk and utilizing a light transmitter and a light sensor, ash shown in Fig. 7. In order to detect the rotational direction also, two sets of light transmitter and sensor are utilized and located to get 90 degree phase difference. Fig. 8 shows two light sensor signals A and B for this configuration. Also a marker pulse, usually denoted as Z, may be obtained to detect a certain position in the disk rotation in some encoders.

By detecting both rising and falling edges in both signals A and B, one can obtain the accuracy improvement of 4 times.

Fig. 7. Principles of Encoder

7

Page 8: Lab2_MotorControl_08[1]

Fig. 8. Encoder signal A & B

By installing two sets of IR diode and IR photo-detector, we can implement an encoder. A sensor

accuracy up to 4 times the number of slots can be obtained. 7) Digital Controller

A microcontroller functions as a digital controller. The reference input x_d is obtained from the

development PC via RS-232C serial port. Here, the unit of degree is used. The current position x is sensed via encoder logic, which os fed by encoder signals A and B. The position error e = x_d – x is computed, and a suitable PID controller algorithm is programmed to compute the controller output u.

The PID control action in analog controllers is given by

0

1( ) [ ( ) ( ) + ( )] t

Di

u t K e t e d T e tT

η η= + ∫ &

where K is the proportional gain, T_i is the integral time, and T_D is the derivative time. The PID controller has three terms and can be converted into discrete form as follows.

0

Continuous vs. DiscreteProportional control: ( ) ( ) ( ) ( )

Integral control: ( ) ( ) ( ) ( -1) ( )

Derivative c

t

i i

u t Ke t u k Ke kK Ku t e d u k u k Te kT T

η η

= =

= = +∫

ontrol: ( ) ( ) ( ) [ ( ) ( 1)]DD

KTu t KT e t u k e k e kT

= = −& −

Hence the analog controller can be transformed into discrete form as

( ) ( 1) (1 ) ( ) (1 2 ) ( 1) ( 2)D D D

I

T T TTu k u k K e k e k e kT T T T

⎡ ⎤= − + + + − + − + −⎢ ⎥

⎣ ⎦

8

Page 9: Lab2_MotorControl_08[1]

The value of u(k) is converted into a PWM signal and transferred to the PWM generator. These sequences should be repeated for each sampling interval T, which is equal to 5 ms. The sampling interval T can be generated by the timer 0 in ATmega128.

4. Preparation 1) Pre-Report Week 1

(A) Hardware Circuit

Design a PWM amplifier and encoder detection logic circuit for the Problem 2. Understand the required electronic parts (components) as listed in section 3) below. Using these components, design the circuit. For the PWM generation, read carefully the section on counter in the datasheet of ATmaga128, and devise how to utilize the counters.

For the actuation of the DC motor, use the counter 2 in the ATmega128 to generate a PWM signal. The PWM signal is transferred to the H-bridge switching amplifier. Design the circuit for the H-bridge amplifier.

Encoder detection logic may be devised as follows. Use counters 1 and 3 in the ATmega128. Counter 1 can be used as an up-counter, and counter 3 can be used as a down counter. Using a program, the difference of up and down counters can be calculated, which results in the position of the motor. Using this method, a separate up/down counter is not necessary, and can simplify the overall circuit.

Hence we require up clock and down clock fed to the microcontroller. In order to obtain the best

resolution available, we require detecting every rising and falling edges of the A and B signals from the encoder. Design a sequential circuit for this encoder detection as follows:

Input: A and B signals from the encoder Output: Up and down clocks to the microcontroller Function: Detect every rising and falling edges from A and B signals from the encoder, and

generate up and down clocks to the microcontroller.

(B) PWM Test program

Design and write a PWM test program which constantly generates 10kHz PWM wave with 60% duty cycle. In order to generate PWM output, refer a PWM generator program in the Appendix.

(C) PWM & encoder test program

9

Page 10: Lab2_MotorControl_08[1]

Design and write a PWM and encoder test program which gets two inputs from up and down counters and accumulates. Transmit the count output to RS-232C each 1 sec. The result can be seen in the PC display via hyperterminal.

Week 2 (D) PID position controller program (week 2) A controller program for the PI position controller can be implemented using the C language. The

values of PID gain values, and the value of reference input, x_d, are assumed fixed in the program. The overall algorithm may be structured as follows Step 1. Initialize the microcontroller including timers and serial interface RS-232C. Step 2. Loop for the PID position controller For each sampling time t=kT (T = 5 ms), do If ( (k mod 200) <= 100 ) then x_r = x_d else x_r = 0. Obtain the motor position x(k) from the encoder counter readings A and B. Compute the error e(k) = x_r – x(k) Compute the controller output u(k) Output u(k) to the 10 kHz PWM amplifier Wait for the next sampling time In order to generate 5 ms sampling time, refer a timer interrupt program in the Appendix.

(E) Elevator position control system program (week 2) An elevator position control system program can be implemented by extending the above PID

controller. Again, the values of PID gain values, and the value of reference input, x_d, are assumed fixed in the program.

The overall algorithm may be structured as follows Step 1. Initialize the microcontroller including timers and serial interface RS-232C. Step 2. Loop for the elevator position control system Accept the desired floor for the elevator from the user via keyboard. Step 3. Loop for each sampling time t=kT (T = 5 ms) until the elevator reached the desired floor: Obtain the motor position x(k) from the encoder counter readings A and B. Compute the error e(k) = x_r – x(k) Compute the controller output u(k) Output u(k) to the 10 kHz PWM amplifier Wait for the next sampling time. When the elevator reached the desired floor, stop the elevator, and go to Step 2.

2) Lab Equipments

10

Page 11: Lab2_MotorControl_08[1]

1 IBM PC with Windows XP 1 ATmega128BK3 microcontroller board 1 ISP232-2 programmer board 1 Breadboard 3) Electronic Parts Required 1 KM3448D 2V DC motor gear encoder unit with stand 1 SN754410 H-bridge PWM amplifier chip (TI) 2 IR LED diode 2 IR photo transistor Some Logic ICs

5. Lab Experiment

Week 1 1) Implement the hardware using parts and wire connections on the breadboard. 2) Install the development software in the PC.

Install an assembler AVRASM. Download the AVR studio file named aStudio4b401.exe from http://www.atmel.com. Decompress the file, and install by running the setup.exe program. The installed directory is usually set to the directory C:₩Atmel₩AVRTools₩. Since we do not utilize the assembler, this installation step is optional.

Install the AvrEdit program, Avredit3.6korean.zip, which includes AVR GCC and graphic user

interface from http://www.terabank.co.kr. You may download the English version if desired. Decompress the file, and install by running the setup.exe in the Disk 1 folder. The installed directory is usually set to C:₩AvrEdit.

As an ISP (In-System Programming), download the PonyProg2000 V2.06C named

ponyprogV206c.zip from http://www.lancos.com. Decompress the file, and install by running setup.exe.

3) Using the AVR edit software, edit and compile the serial output program in the Appendix. An hex file will be generated. Download the hex file using the ponyprog program into the flash memory inside the ATmega chip. Using the hyper-terminal program in the PC, be prepared to display the input and output of the serial interface. Pressing the reset switch in the ATmega board starts execution of the downloaded program. When a message appears on the hyper-terminal, the installation of the development software is a success!

However, a minor modification of the program is required for correct display. Hint: Check the frequency of the crystal clock in the ATmega128BK3 board.

11

Page 12: Lab2_MotorControl_08[1]

4) Edit, compile, and download the prepared PWM test program. Check if the motor rotates smoothly. Repeat this step with 40% duty cycle. Observe the operation of the motor. 5) Test the encoder interface using the prepared PWM and encoder test program. Repeat this step with 40% duty cycle. Observe the operation of the encoder.

Week 2 6) Edit, compile, and download the prepared PID position controller program. Test the program with various PID settings. Serial output may be used for debugging. When the program in the ATmega microcontroller generates a character string, we can see the string on the hyper-terminal in the development PC. 7) Edit, compile, and download the prepared elevator position control system. Serial output may be used both for user input as well as for debugging. Test the program with various user requirements of desired floor. Here, assume that the desired floor ‘f’ and the motor position ‘p’ has the relation as p (in degrees) = (f – 1) * 60 Let the p (in degrees) denote the clockwise angle from the top position. 8) Improvement of the system performance: The elevator position controller is required to reach the desired floor as fast as possible, as smooth as possible with no overshoot. How can you tune the system for the best performance? Using a suitable microcontroller program, measure both the settling time and the overshoot when the elevator is commanded to move from the first floor to the 6-th floor. 9) Demonstration: When a successful performance of the elevator position control system is observed, demonstrate the experimental result to the TA.

6. Discussion In the Section of Discussion and Conclusion, discuss the following:

1) Search for several commercial encoders. Compare and discuss the resolution, accuracy, price of several encoders.

2) Search for a product with motor, gear, and encoder assembly. What is the main advantage of

these products? 3) Is the PID position controller better than the PI position controller? Justify your answer.

4) Investigate a suitable algorithm or method to adjusting the PID controller gain.

5) Two DC motors with encoders are to de driven using one ATmega128 microcontroller. How can

you implement this? You may add some (minimum) hardware in order to implement.

12

Page 13: Lab2_MotorControl_08[1]

6) In the actual elevator, there are up/down buttons on each floor, and many desired floor buttons inside the elevator cart. How can you get inputs from that many buttons, and how can you manage user commands in total?

7) Discuss how the BLDC motor is driven. What is the difference between the DC motor and the

BLDC motor.

7. References ATmega128 User’s Manual, http://www.atmel.com/dyn/products/product_card.asp?part_id=2018 Datasheets: ATmega128(L) Complete (389 pages, revision M, updated 11/04) AvrEdit User’s Manual, http://www/terabank.co.kr ISP user’s guide, http://www.lancos.com 윤덕용, “AVR ATmega128 마스터”, Ohm 사, 2004. (in Korean)

8. Appendix 1) RS-232C serial test program /* Title: AVR-GCC test program #4 for the STK200 eva board Author: Volker Oth Date: 4/1999 Purpose: Uses the UART to communicate with a terminal program on the pc. The "tranceive complete" interrupt is used to send the string "Serial Data from AVR receiced###" continuously to the pc. When a byte was received from the pc, the "receive complete" interrupt is called, which outputs the byte to PortB where the LEDs visualize the 8 bits it consists of. UART format: 9600 baud, 8bit, 1 stopbit, no parity needed Software: AVR-GCC to compile needed Hardware: ATS90S8515/8535/2313/mega(?) on STK200/300 board Note: To contact me, mail to [email protected] You might find more AVR related stuff at my homepage: http://members.xoom.com/volkeroth */ #include <io.h> #include <interrupt.h>

13

Page 14: Lab2_MotorControl_08[1]

#include <signal.h> #define F_CPU 16000000 /* For 16MHz crystal */ #define UART_BAUD_RATE 115200 /* 115200 baud */ #define UART_BAUD_SELECT (F_CPU/(UART_BAUD_RATE*16l)-1) typedef unsigned char u08; typedef char s08; typedef unsigned short u16; typedef short s16; /* uart globals */ static u08 *uart_data_ptr; static u08 uart_counter; SIGNAL(SIG_UART_TRANS) /* signal handler for uart txd ready interrupt */ { uart_data_ptr++; if (--uart_counter) outp(*uart_data_ptr, UDR); /* write byte to data buffer */ } SIGNAL(SIG_UART_RECV) /* signal handler for receive complete interrupt */ { register char led; led = inp(UDR); /* read byte for UART data buffer */ outp(led, PORTD); /* output received byte to PortB (LEDs) */ } void uart_send(u08 *buf, u08 size) /* send buffer <buf> to uart */ { if (!uart_counter) { /* write first byte to data buffer */ uart_data_ptr = buf; uart_counter = size; outp(*buf, UDR); } } void uart_init(void) /* initialize uart */

14

Page 15: Lab2_MotorControl_08[1]

{ /* enable RxD/TxD and ints */ outp((1<<RXCIE)|(1<<TXCIE)|(1<<RXEN)|(1<<TXEN),UCR); /* set baud rate */ outp((u08)UART_BAUD_SELECT, UBRR); } int main(void) { outp(0xff ,DDRD); /* PortB output */ outp(0x00, PORTD); /* switch LEDs on */ uart_init(); sei(); /* enable interrupts */ uart_send("Serial test##₩n", 14); for (;;) { /* loop forever */ } } 2) PWM generation example /* ========================================================== */ /* EXP05_2.C : PWM Output by OC1A Pin */ /* ========================================================== */ /* Designed and programmed by Duck-Yong Yoon in 2003. */ #include <avr/io.h> #include "c:₩AvrEdit₩Ok128c₩Ok128.h" void LCD_4d(unsigned int number) /* display 4-digit decimal number */ { unsigned int i; unsigned char flag; flag = 0; i = number/1000; // 10^3 if(i == 0) LCD_data(' '); else { LCD_data(i + '0'); flag = 1; } number = number % 1000; // 10^2 i = number/100; if((i == 0) && (flag == 0))

15

Page 16: Lab2_MotorControl_08[1]

LCD_data(' '); else { LCD_data(i + '0'); flag = 1; } number = number % 100; // 10^1 i = number/10; if((i == 0) && (flag == 0)) LCD_data(' '); else { LCD_data(i + '0'); flag = 1; } i = number % 10; // 10^0 LCD_data(i + '0'); } int main(void) { unsigned char i; unsigned int duty; MCU_initialize(); // initialize MCU Delay_ms(50); // wait for system stabilization LCD_initialize(); // initialize text LCD module LCD_string(0x80,"Period = 1250*2"); // display title LCD_string(0xC0,"Duty = 0000*2"); TCCR1A = 0x82; // Phase Correct PWM mode(10) TCCR1B = 0x13; TCCR1C = 0x00; ICR1H = (1250 >> 8); // f(PWM) = 16MHz/64/2/1250 = 100Hz ICR1L = 1250 & 0xFF; while(1) { for(i=0,duty=0; i<6; i++, duty += 250) { OCR1AH = (duty >> 8); // set duty ratio = duty/1250 OCR1AL = duty & 0xFF; LCD_command(0xCA); // display duty LCD_4d(duty); Beep(); Delay_ms(5000); } } }

16

Page 17: Lab2_MotorControl_08[1]

3) Timer interrupt example /* ========================================================== */ /* EXP04_2.C : Timer/Counter0 Interrupt(250Hz) */ /* ========================================================== */ /* Designed and programmed by Duck-Yong Yoon in 2003. */ #include <avr/io.h> #include <avr/interrupt.h> #include <avr/signal.h> #include "c:₩AvrEdit₩Ok128c₩Ok128.h" volatile unsigned char interrupt_count; // interrupt counter SIGNAL(SIG_OUTPUT_COMPARE0) /* OC0 interrupt function */ { PORTB = PORTB ^ 0x80; // toggle LED4 interrupt_count--; if(interrupt_count == 0) // 250th interrupt ? { interrupt_count = 250; // if yes, toggle LED3 PORTB = PORTB ^ 0x40; } } int main(void) { MCU_initialize(); // initialize MCU Delay_ms(50); // wait for system stabilization LCD_initialize(); // initialize text LCD module LCD_string(0x80," Timer0 "); // display title LCD_string(0xC0,"250 Hz Interrupt"); Beep(); PORTB = 0xC0; // LED4 and 3 on TCCR0 = 0x0E; // CTC mode(2), don't output OC0 ASSR = 0x00; // use internal clock OCR0 = 249; // 16MHz/256/(1+249) = 250Hz TCNT0 = 0x00; // clear Timer/Counter0 TIMSK = 0x02; // enable OC0 interrupt TIFR = 0x00; // clear all interrupt flags sei(); // global interrupt enable interrupt_count = 250; // interrupt counter

17

Page 18: Lab2_MotorControl_08[1]

18

while(1); // wait interrupt }