real time control - using pcs and microcontrollers

25
1 Centre for Intelligent Products and Manufacturing Systems Department of Mechanical and Production Engineering National University of Singapore Real Time Control - Using PCs and Microcontrollers Dr. Marcelo H. Ang Jr. Mr. Yee Choon Seng Control and Mechatronics Laboratory E4-06-30 1 st Semester, 1997-98 Part 1: I/O Using a PC Digital I/O Timers Analog I/O Timer Interrupt Programming Part 2: I/O Using Motorola 68HC11 68HC11 standalone board Hardware and Ports Programming Part 3: Digital Sensors, Actuators and Drivers limit switches optical sensors amplifiers DC motor drivers stepper motor drivers and controllers

Upload: others

Post on 27-Dec-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

1

Centre for Intelligent Products and Manufacturing SystemsDepartment of Mechanical and Production Engineering

National University of Singapore

Real Time Control -Using PCs and Microcontrollers

Dr. Marcelo H. Ang Jr.Mr. Yee Choon Seng

Control and Mechatronics LaboratoryE4-06-30

1st Semester, 1997-98

Part 1: I/O Using a PC• Digital I/O• Timers• Analog I/O• Timer Interrupt Programming

Part 2: I/O Using Motorola 68HC11• 68HC11 standalone board• Hardware and Ports• Programming

Part 3: Digital Sensors, Actuators and Drivers• limit switches• optical sensors• amplifiers• DC motor drivers• stepper motor drivers and controllers

2

Part 1: Input/Output Using a Personal Computer

1.0 Introduction

• Each card one plugs into a PC has a unique address, often referred to as a baseaddress. This base address is the starting address of memory in the card, which canbe 16 bytes, or even a few megabytes.

• The IBM PC Compatible computer (or 80x86-architecture PC) has a separate I/OAddress space (different from memory address space). The memory and registersin the add-on cards of the PC reside in this I/O Address space.

• Data is written to and read from the I/O address space using “in” and “out”commands.

unsigned char x,y; /* C syntax: unsigned char = 1 byte */

outportb(address, x); /* write byte data, x, into address */y = inportb (address); /* read one byte of data from

address and store into y */

2.0 Digital Input/Output

• A typical digital I/O card has typically 1 or more I/O chip (e.g., Intel 8255), and atimer chip (Intel 8253)

• A card we have at Control Lab, for example has at least 1 8255 and another 8253.

• One 8255 chip has 3 8-bit ports, namely Ports A, B and C, thus providing 24digital input and output (I/O) lines. One 8253 chip has 3 sixteen bit timers,Timers0, 1 and 2.

• The Digital I/O Card has the following important I/O addresses:

0x1b0 Port 1A read/write buffer0x1b1 Port 1B read/write buffer0x1b2 Port 1C read/write buffer0x1b3 Port 1 control register (8255): :0x1b8 Counter 0 read/write buffer0x1b9 Counter 1read/write buffer0x1ba Counter 2read/write buffer0x1bb Counter Chip (8253) control register

• The pin layout (“pin-outs”) are defined as follows:

Pin 1 Ground: :Pin 4 PA3Pin 5 PA1

3

Pin 6 PA2Pin 7 CLK0Pin 8 PA0Pin 9 GATE0Pin 10 OUT0: :Pin 37 + 5 VPin 38 − 5VPin 39 + 12 VPin 40 − 12 V

• Digital SignalsA digital ‘1’ 5 V (TTL), or 12 V, or 24VA digital ‘0’ 0V

An 8-bit port can have a value of

255 0xff 1 1 1 1 1 1 1 10 0x00 0 0 0 0 0 0 0 015 0x0f 0 0 0 0 1 1 1 1129 0x81 1 0 0 0 0 0 0 1Etc.

2.1 Digital Input/Output

The Steps for digital input/output are as follows

a) Decide on which ports is/are input and output ports.outportb(0x1b3, 0x82); /* Port A,C are output, B is input */0x1b3 = address of command word for 1st 8255 chip

b) Read or write data into the respective ports

Example C Code (Borland C):

Inputunsigned char x;while (!kbhit() ) /* keep looping while not key board hit */x = inportb(0x1b1); /* read from Port B, 0x1b1 is address of B */

/* all 8 bits read simultaneously */if (x & 0x01)

printf(“Bit 0 of Port B is high!\n”);else

printf(“Bit 0 of Port B is low!\n”);

4

Outputoutportb(0x1b0, 0xf0); /* bits 4 to 7 of Port A is set to ‘1’, the rest to ‘0’ */

/* all 8 bits written simultaneously */

2.2 Timer

- Needs a clock input - external or internal- Select whether clock input is external or internal (1.19 Mhz, available in the

card), selection by switch setting in the carde.g., SW3=ON - Counter 0 uses internal clock SW3 = OFF - Counter 0 uses external clock

- External clock is connected to CLK0- output of counter 0 is available at pin OUT0

The Steps for programming the timer are as follows

a) Decide on what mode the counter is to operate:

Mode 3: Square Wave Generator

outportb(0x1bb, 0x36); /* 0x1bb = 0011x110 *//* bits 7,6 : select counter 0

bits 5,4 : read/write least significant byte first, then most sig. bytebits 3,2,1: Mode 3bit 0 : Binary counter - 16 bits

*/b) Latch the counter data to allow stable reading while the counter is reading (if

needed)

outportb(0x1bb, 0); /*0x1bb = 0000xxxx *//* bits 7,6 : select counter 0

bits 5,4 : 00 - latchingother bits : don’t care */

For Mode 3: this step is not needed because counter is not to be read

c) Store the required 16-bit data (X) into the counter

Square wave output = clock frequency ÷ X

/* For example, X=10 = 0x000A, clock input = 1 Khz,then clock output = 100 Hz.*/

outportb(0x1b8, 0x0A); /* LSB first*/outportb(0x1b8, 0x00); /* MSB next */

5

3.0 Analog Input/Output

• ADDA (Analog to Digital and Digital to Analog Converter) Card is used

• A typical ADDA card consists of two Digital-to-Analog (or D/A) output channelsand 16 Analog-to-Digital (or A/D) input channels.

• Both the A/D and D/A converters can be configured to operate in unipolar (onlypositive voltages) or in bipolar (with positive and negative voltages) mode.(typicall set by jumpers in the card)

• The range of voltage inputs can also be changed by adjusting a potentiometer in thecard. A typical default setting is ±8V.

• Being a 14-bit ADDA card, the digital signal has a range of 16,384 steps,beginning with 0 (zero) to 16,383.

The conversion from an analog signal to digital value is given by Equation (1)below, while the digital to analog value conversion is given by Equation (2).

Digital = 8192 + ( Analog × 16,384 ÷ 16 ) (1)Analog = ( Digital − 8192 ) × 16 ÷ 16,384 (2)

The multiplier is given by the ratio between the voltage range of 16 Volts (from -8Volts to +8 Volts) and the digital signal range of 16,384 (which is 214). The 0V(zero voltage) point is at 8192, -8V is 0 and +8V corresponds to 16,383 (which is214-1.)

• Because this is a 14-bit command, input and output need to be done in two steps insequence, operating on an 8-bit data at a time..

• The ADDA Card has the following important I/O addressess:

0x170 A/D Channel Number0x171 A/D register, write 0 to clear0x172 A/D low 8-bit data0x173 A/D high 6-bit data0x174 D/A2 low 8-bit data0x175 D/A2 high 6-bit data0x176 D/A1 low 8-bit data0x177 D/A1 high 6-bit data0x178 read 8 times to start AD high byte conersion0x17C read 8 times to start AD low byte conversion

• Selected Pin-Outs are as follows:

Pin 1 +12 VPin 2 D/A1 OutPin 3 GroundPin 4 A/D 14Pin 5 A/D 12

6

: :Pin 13 + 5 VPin 14 − 12 V: :Pin 25 − 5 V

3.1 Analog Output

The steps to send an analog voltage output to a specific channel are as follows:1. Convert voltage level into 14-bit word using Equation (1).2. Split the 14-bit word into a low byte (LB) and High byte (HB). Note that a valid

high-byte is a number between from 0 to 63.3. Send LB to address 0x176 (for channel 1).4. Send HB to address 0x177 (for channel 1).

• For example, to output +2.4 Volts to Channel 1,• 2.4 Volts can be converted to a 14-bit digital word which is 10650, or 10-1001-

1001-1010 in binary.• This 14-bit word is then divided into a high-byte word and a low-byte word, in this

case, 41 and 154 respectively and the values sent out through the respectiveaddresses as shown in the example below:

Steps in C-code:

float volt; int dig, LB, HB;volt = 2.4;dig = 8192 + (int)(volt / 16.0 * 16384.0); /*convert to digital */if (dig > 16383) dig = 16383; /* make sure 0 ≤ dig ≤ 16383 */else if (dig < 0) dig = 0;LB = dig % 256; /*find remainder--low-byte*/HB = dig / 256; /*find high byte*/outportb( 0x176, LB); /*output low-byte first*/outportb( 0x177, HB); /*output high byte*/

3.2 Analog Input

To read in data from the A/D converters, you need to first select the channel to access,clear the registers, conduct the conversions before reading the data. The steps are asfollows:1. Clear A/D register (address is 0x171).2. Output channel number to addrexx 0x170.3. Read address 0x178 eight times.4. Read address 0x177 eight times.5. Low byte (LB) is obtained by reading address 0x172.6. High bye (HB) is obtained by reading address 0x173.7. Form 14-bit digital word by combining LB and HB.8. Compute analog voltage equivalent to digital word using Equation (2).

7

• The Steps in C-code are shown below:

int LB, HB, WORD; float volt;while (!kbhit() ) /* keep reading while not keyboard hit */outportb( 0x171, 0); /*to clear register*/outportb( 0x170, 0); /*to select channel 0*/for( i=0; i<8; i++) inportb(0x178); /*conversion*/for( i=0; i<8; i++) inportb( 0x17c); /*conversion*/LB = inportb(0x172); /*read low byte*/HB = inportb(0x173) & 0x3F; /*read high byte*/WORD = HB * 256 + LB; /*combine low & high bytes*/VOLT = (WORD - 8192)*16.0/16384.0; /*final input voltage*/

4.0 Timer Interrupt Programming

The PC has an internal clock that can generate timer interrupts. By default, the timerinterrupt rate is about 18.2 Hz. MS-DOS uses this timer interrupt to update the systemdate and time.

The timer interrupt can be programmed to interrupt at a different rate by the followingroutine:

void set_samp_freq(double freq)unsigned int tmr_ctr;unsigned char *buf;double sample_time;

sample_time = 1.0/freq;tmr_ctr = (int)(sample_time*1.19318e6);buf = (unsigned char *) & tmr_ctr;outportb(0x43, 0x36); /* set counter to mode 3, 16 bits binary */outportb(0x40, buf[0]); /* low byte */outportb(0x40, buf[1]); /* high byte */

freq is the desired interrupt frequency. Please note that the frequency must be at least18.2 Hz.

Each possible interrupt in the PC has an interrupt number. For the timer interrupt it is0x1C. Everytime the timer generates an interrupt a certain routine is called. Thisroutine updates the system date and time, and does other functions. The interruptnumber can be “associated” with the interrupt routine using the Borland/Turbo Cfunction

setvect(0x1C, handler);where handler is declared as an interrupt function:

void interrupt handler(void);

8

Everytime there is a timer interrupt (0x1c), the routine handler() is calledautomatically. Your program need not explicitly call handler.

To find out what routine is “associated” with an interrupt number, the followingfunction in Borland/Turbo C can be used:

void interrupt (*routine)(void);routine = getvect(0x1c);

routine can now be used as a function.

The following example shows the use of the timer interrupt.

/* Test Stack overflow must be turned off! when using interrupts */#include <stdio.h> /* needed when using file or screen i/o */#include <dos.h> /* needed by routines to do

data acquisition and interrupts */#include <math.h> /* needed when using trascendental function calls */

#define INTR 0X1C /* clock tick interrupt */

void interrupt (*timer_routine_dos)(void);void interrupt handler (void);void set_samp_frequency( double);int main(void) disable(); /* disables all interrupts */set_samp_freq(100.0);/* set timer interrupt frequency at 100.0 Hz */timer_routine_dos = getvect(INTR); /* save the old interrupt routine */setvect(INTR, handler); /* install the new interrupt handler */enable(); /* enables all interrupts *//* now the handler is called automatically 100 times a second */while(!kbhit()) /* do user interface her, data gathering, display, etc... whatever you do here will not affect the interrupt rate, handler will always be called100 times a second *//* to restore back the old interrupt: */setvect(INTR, timer_routine_dos); /* restore back old interrupt handler */return 0;

void interrupt handler() /* declare local variables here, if any */ /* typically you do the real time control here:

- read signals- compute voltages- send out voltages

/* end of routine */

9

Part 2: I/O Using Motorola 68HC11

1.0 CIPMAS' Standalone 68HC11 Board

• Stand alone microcontroller board using the Motorola 68HC11 chip (Fig 1)• Kit can be borrowed from Control and Mechatronics Lab, E4-06-30• Requires at least 5 volts power supply, can be obtained from four 1.5 volt batteries• Programmed using C (Interactive C)• Need an IBM PC Compatible with a serial port to program

− Download− Interactive, interpreter mode− Battery needed, once power lost, program is lost

• 32 Kbyte RAM• 3 I/O Ports (Ports A, D, and E) available for use

− Digital I/O− Timer, Counter or Pulse Accumulator− SerialTable 1 provides a listing of all the ports.

• Can use all the features of the 68HC11. Board allows easy use of all features of68HC11. Please refer to 68HC11 manual. List of registers and their addresses sreshown in Table 2. Detailed descriptions are found in the manual. Excerpts of thisinformation is in the 68HC11 Kit borrowed from Control and Mechatronics Lab.

Fig. 1: Schematic Diagram of CIPMAS' 68HC11 Board

Port B Port C

Both Ports B and C arenot available. They areinternal add. & data lines

Spare groundpoints

Port E, analogor digitalinputs.

0

7

0 0

0 0 75

Power LED

Reset LED

ResetButton

Expansion slot

RS232 socket

Port D, digital I/O Port A, digital I/O

Special InterruptRequest lines

Mode switch:Run Download

10

Port BitSingle-Chip &Bootstrap Mode

Expanded Multiplexed &Special Test Mode

A-0 PA0/IC3 PA0/IC3A-1 PA1/IC2 PA1/IC2A-2 PA2/IC1 PA2/IC1A-3 PA3/OC5/and-or OC1 PA3/OC5/and-or OC1A-4 PA4/OC4/and-or OC1 PA4/OC4/and-or OC1A-5 PA5/OC3/and-or OC1 PA5/OC3/and-or OC1A-6 PA6/OC2/and-or OC1 PA6/OC2/and-or OC1A-7 PA7/PAI/and-or OC1 PA7/PAI/and-or OC1B-0 PB0 A8B-1 PB1 A9B-2 PB2 A10B-3 PB3 A11B-4 PB4 A12B-5 PB5 A13B-6 PB6 A14B-7 PB7 A15C-0 PC0 A0/D0C-1 PC1 A1/D1C-2 PC2 A2/D2C-3 PC3 A3/D3C-4 PC4 A4/D4C-5 PC5 A5/D5C-6 PC6 A6/D6C-7 PC7 A7/D7D-0 PD0/RxD PD0/RxDD-1 PD1/TxD PD1/TxDD-2 PD2/MISO PD2/MISOD-3 PD3/MOSI PD3/MOSID-4 PD4/SCK PD4/SCKD-5 PD5/-SS PD5/-SS

STRA ASSTRB R/-W

E-0 PE0/AN0 PE0/AN0E-1 PE1/AN1 PE1/AN1E-2 PE2/AN2 PE2/AN2E-3 PE3/AN3 PE3/AN3E-4 PE4/AN4 PE4/AN4E-5 PE5/AN5 PE5/AN5E-6 PE6/AN6 PE6/AN6E-7 PE7/AN7 PE7/AN7

Table 1: 68HC11 Port Signal Summary

11

Addr. Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Name Description$1000 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 PORTA I/O Port A$1001 Reserved$1002 STAF STAI CWOM HNDS OIN PLS EGA INVB PIOC Parallel I/O Control Register$1003 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 PORTC I/O Port C$1004 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 PORTB Output Port B$1005 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 PORTCL Alternate Latched Port C$1006 Reserved$1007 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 DDRC Data direction for Port C$1008 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 PORTD I/O Port D$1009 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 DDRD Data Direction for Port D$100A Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 PORTE Input Port E$100B FOC1 FOC2 FOC3 FOC4 FOC5 CFORC Compare Force Register$100C OC1M7 OC1M6 OC1M5 OC1M4 OC1M3 OC1M OC1 Action Mask Register$100D OC1D7 OC1D6 OC1D5 OC1D4 OC1D3 OC1D OC1 Action Data Register$100E Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$100F Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TCNT Timer Counter Register

$1010 Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$1011 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TIC1 Input Capture 1 Register

$1012 Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$1013 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TIC2 Input Capture 2 Register

$1014 Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$1015 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TIC3 Input Capture 3 Register

$1016 Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$1017 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TOC1 Output Compare 1 Register

$1018 Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$1019 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TOC2 Output Compare 2 Register

$101A Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$101B Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TOC3 Output Compare 3 Register

$101C Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$101D Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TOC4 Output Compare 4 Register

$101E Bit 15 Bit 14 Bit 13 Bit 12 Bit 11 Bit 10 Bit 9 Bit 8$101F Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TOC5 Output Compare 5 Register

$1020 OM2 OL2 OM3 OL3 OM4 OL4 OM5 OL5 TCTL1 Timer Control Register 1$1021 EDG1B EDG1A EDG2B EDG2A EDG3B EDG3A TCTL2 Timer Control Register 2$1022 OC1I OC2I OC3I OC4I OC5I IC1I IC2I IC3I TMSK1 Timer Interrupt Mask Register 1$1023 OC1F OC2F OC3F OC4F OC5F IC1F IC2F IC3F TFLG1 Timer Interrupt Flag Register 1$1024 TOI RTII PAOVI PAII PR1 PR0 TMSK2 Timer Interrupt Mask Register 2$1025 TOF RTIF PAOVF PAIF TFLG2 Timer Interrupt Flag Register 2$1026 DDRA7 PAEN PAMOD PEDGE RTR1 RTR0 PACTL Pulse Accumulator Control Register$1027 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 PACNT Pulse Accumulator Count Register$1028 SPIE SPE DWOM MSTR CPOL CPHA SPR1 SPR0 SPCR SPI Control Register$1029 SPIF WCOL MODF SPSR SPI Status Register$102A Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 SPDR SPI Data Register$102B TCLR SCP1 SCP0 RCKB SCR2 SCR1 SCR0 BAUD SCI Baud Rate Control$102C R8 T8 M WAKE SCCR1 SCI Control Register 1$102D TIE TCIE RIE ILIE TE RE RWU SBK SCCR2 SCI Control Register 2$102E TDRE TC RDRF IDLE OR NF FE SCSR SCI Status Register$102F Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 SCDR SCI Data (Read RDR,Write TDR)$1030 CCF SCAN MULT CD CC CB CA ADCTL A/D Control Register$1031 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 ADR1 A/D Result Register 1$1032 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 ADR2 A/D Result Register 2$1033 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 ADR3 A/D Result Register 3$1034 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 ADR4 A/D Result Register 4

$1035 thru $1038 Reserved$1039 ADPU CSEL IRQE DLY CME CR1 CR0 OPTION System Config. Option$103A Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 COPRST Arm/Reset COP Timer Circuitry$103B ODD EVEN BYTE ROW ERASE EELAT EEPGM PPROG EEPROM Programming Control Reg.$103C RBOOT SMOD MDA IRV PSEL3 PSEL2 PSEL1 PSEL0 HPRIO Highest Priority 1-Bit Int & Misc$103D RAM3 RAM2 RAM1 RAM0 REG3 REG2 REG1 REG0 INIT RAM & I/O Mapping Register$103E TILOP OCCR CBYP DISR FCM FCOP TCON TEST1 Factory TEST Control Register$103F NOSEC NOCOP ROMON EEON CONFIG COP, ROM & EEPROM Enables

Table 2: Register Addresses and Control Bit Assignments

12

2.0 Hardware

2.1 Port D

• Six bit port. Only bits 0, 1 to 5 are available• Address of Port D is 0x1008• Address of Control Register for Port D is 0x1009

− Corresponding bit in control register indicates whether bit in Port D is input oroutput

− 1 = output− 0 = input

• If bit is set as input, and user sends an output, output is latched (remembered). Thenext time the bit is set as output, the old value to be output is remembered and isoutput.

2.2 Port A

• Address of Port A is 0x1000• Input bits: 0,1,2• Output bits: 3, 4, 5, 6• Writing or reading from input and output bits, respectively are ignored.• Bit 7 = can be set as Input or Output

− Depending on state of bit 7 of DDRA7 (at address 0x1026)• Port A can be used as a timer, counter or pulse accumulator

− Output a continuous pulse, which can be used as a pulse width modulator forcontrol of DC motors (see circuit diagram)

− Please refer to section of 68HC11 manual on programming the timer.

2.3 Port E

• 8 A/D channels• 0 to 5 volts• 8-bit A/D, quantized to 256 levels from 0 to 5 volts• can be used as digital input (subset of analog input)• address of Port E is 0x100A• can use int analog (int chan) of IC (see Section 3.2 below)

− with the use of analog, we don’t need to worry of A/D conversion status, etc.

3.0 Programming

3.1 IC Development Environment

Programming is done using Interactive C. Kit contains the micro controller board, 4AA batteries, and a serial cable. A PC (386 and above) with a serial port is required.A diskette containing the following files is provided:

Files used: IC.EXE, DL.EXE, PCODERWL.S19, LIB_RW11.C

IC.EXE and DL.EXE are MS-DOS programs.

13

The Steps involved are :

a. Create sub-directory and copy all necessary files from diskette.b. Create or edit your C programs using any text editor. For example, your

program may be called prog.c.c. Connect up the 68HC11 board to the battery. Connect the board to COM2 of

the PC. Switch to DL mode. (towards RESET button.). Press RESET afterpower-up. (Fig. 1)

d. From PC DOS prompt, runc:\> dl -port com2 pcoderwl.s19 <return>

You should see 2 levels of downloading, initially of 256 bytes of code,followed by the program in the PCODERWL.S19 file. This downloadsnecessary libraries.

e. Switch the SPDT away from the RESET position to change to RUN mode,followed by pressing the RESET button.

f. From PC DOS prompt, runC:\> ic <return>

Make sure all program files and C source files for the 68HC11 are locatedtogether here. If there are error messages on the PC DOS prompt, retry stepsd to f, check cable again, or double check if the SPDT switch has been turnedto RUN mode, away from the RESET.If successful, you will end up with a C prompt. (This is the prompt forInteractive C.)From this prompt, you can execute IC functions. Please refer to the IC manualthat comes with the kit.

Note that the LCD display is not implemented in the 68HC11 board.

g. Load the program you have written in Interactive C by typing at the new Cprompt:

C>load program.c<return>h. You can run the file after loading the source by calling the function directly,

C>routine();<return>Or by simply typing in IC commands, such as

C>poke(0x1008, 0x3f); <return>

Note:1. LEDs on Processor Board are configured as bits 2 to 5 of Port D, i.e. output of

xx1111xx to Port D would light up all LEDs.$1009 Port D Control Register, to be sent value $3c for the LEDs.$1008 Port D Address, for LEDs data

2. For IC programs, do not use the MAIN() function, as it would cause conflictwith the LIB_RW11.C program already downloaded when IC was invoked.

3.2 Functions and IC Commands

• All expressions must be ended with a semicolon.

14

− When expression is typed, it is compiled by the PC and downloaded to the68HC11 for evaluation. The result is returned to the PC for display in thescreen.

• LCD screen output (using prtinf statements) is currently not implemented.• Almost all C functions are supported plus the following IC commands

− load <filename>− unload <filename>− list files, functions, or globals− kill_all (kills all currently running processes)− ps (prints status of currently running processes)− help− quit− do not define a main() function, used by lib_rw11.c.

• Memory access functions− int peek (int loc)− int peekword (int loc)− void poke (int loc, int byte)− void pokeword (int loc, int word)− void bit_set(int loc, int mask)− void bit_clear(int loc, int mask)

• Time commands− Time variables implemented using long integer data type− void reset_system_time()§ resets system time to zero ms

− long mseconds()§ return the count of system time in ms

− float seconds()§ returns the count of system in seconds as a floating point number with a

resolution of ms− void sleep (float sec)− void msleep (long msec)

• Tone functions− void beep()§ Produces a tone of 500 Hz for a period of 0.3 sec

− void tone(float frequency, float length)§ Produces a tone of pitch frequency Hz for length seconds

− void set_beeper_pitch(float frequency)− void beeper_on()− void beeper_off()

• A/D input− int analog (int p)− p can be from 0 (Port E bit 0) to 7 (Port E bit 7)− 8-bit, 0 to 255, 0 to 5 volts, linear

• Port A can also be used as a programmer timer, real-time interrupt, and pulseaccumulator. (Please refer to 68HC11 technical manual for details)− Can be used to as PWM generator to provide input to an amplifier that drives a

DC motor. (Diagram appears in IC manual that comes with kit.)

15

• IC Manual that comes with the kit comes with a circuit diagram that containscircuit schematics for various sensors, motor drivers, encoders and expansion.Lib_rwll.c contains definitions to use these. For example, there are motor and shaftencoder functions provided (Appendix A.2 of IC manual.)

• Configuring IC− ic -help− ic - config§ to specify default com port, and library locations for load commands, etc.§ modifies ic.exe

3.3 Timing

• Programmable Timer− 16 bit free running counter (possible to divide by 4 pre-scalers: 1, 4, 8, 16),

driven by 68HC11 MCU E clock− high byte at 0x1000, low byte at 0x100F (Table 2)− after reset, pre-scaler is 1− can use different pre-scalers by writing pre-scalers control bits only once during

the first 64 cycles after reset− software can read counter anytime− counter is cleared to 0x0000 after reset− count from 0 to 0xFFFF, then back to 0− TOF (timer overflow flag, bit 7 at 0x1025) is set after overflow. Interrupt can

be "hooked" to TOF.

• Input Capture− Three 16-bit input capture registers (IC1, IC2, IC3 in Table 1, T1C1=0x1010,

etc, in Table 2)− Read only and not affected by reset− Used to latch value of counter when a defined transition is sensed by the

corresponding input capture edge detector (IC1, IC2, IC3 is at bits 0, 1, 2 ofPort A, Table 1)

− Input capture edge controlEDGxB EDBxA Configuration0 0 Capture disabled0 1 Capture on rising edges only1 0 Capture on falling edges only1 1 Capture on any (rising or falling) edge

− A read of MSB inhibits capture for one E cycle, to allow a double byte read ofa full 16-bit register, use int peekword(int loc)

• Output Compare− Five output compare registers (OC1, OC2, … OC5, Table 1) which are

initialized to 0xFFFF after reset,− Used as output waveform control or elapsed time indicators− Read/write registers− Causes an output action when there is a match between free running counter

and output compare register

16

§ OMx and OLx in TCTL1 (Table 2)OMx OLx Action taken after successful compare0 0 Timer disconnected from output pin logic0 1 Toggle OCx output line1 0 Clear OCx output line to zero1 1 Set OCx output line to one

− Can be hooked to an interrupt when match is found (OCxF, output compareflag) in TFLG1 is set, OCX1 in TMSK1 for interrupt control)

• Pulse Accumulator− 8 bit read/write counter− PAEN (Table 2) = 0, Pulse accumulator off; = 1, on.− external event counting (PAMOD = 0, Table 2)§ 8-bit counter is clocked to increasing values by external pin, PAI (PA7,

Table 1)§ maximum clocking rate is E clock divided by 2

− gated time accumulator (PAMOD = 1, Table 2)§ free running E clock divided by 64 signal drives the 8-bit counter, but only

while external pin (PAI) input is activated− PAI is bit 7 of Port A§ General purpose I/O Pin§ Normally set as input if used for pulse accumulator§ DDRA7 = Data direction for Port A bit 7

• 0 = input only• 1 = output

§ Pulse edge accumulator control (PEDGE, Table 2) has different meaningsdepending on the state of the PAMOD bitPAMOD PEDGE Action on Clock0 0 PAI falling edge increments counter0 1 PAI rising edge increments counter1 0 A '0' on PAI inhibits counting1 1 A '1' on PAI inhibits counting

• Real Time Interrupt− RTR1 and RTR0 bits in PACTL (Table 2) selects 1 of 4 interrupt rates− RTII bit in TMSK2 enables interrupt capability− Every timeout causes the RTIF bit in TFLG2 to be set, and if RTII is set, an

interrupt request is generated.

3.4 Multi-tasking

• Any C function can be spawned as a separate task• Processes communicate via global variables.• Each time a process runs, it executes for certain number of ticks, defined in ms.

The default number of ticks is 5, i.e., each process is given 5 ms to run.− After 5 ms, it's turn ends and the next process is run− All processes are kept in a process table.− Therefore, it's safe to have while (1) … loops in a process. No

hogging is guaranteed.

17

• Each process has its program stack− Function arguments− Local variables− Return addresses− Size of stack is 256 bytes by default

• Each process is assigned a unique id (pid, process identifier). The pid is used to killthe process

• Starting a process− int start_process(function_call(….), [TICKS],

[STACK_SIZE])− returns pid.

• Additional functions for process management− void hog_processor()§ allocates an addition 250 ms of execution to the currently running process§ calling this many times will "wedge" or only execute the process

− void defer()§ makes process swap out immediately after this function is called.

− These two functions can be used to provide different priorities for processes.

Part 3: Digital Sensors, Actuators and Drivers; Sample Application

1.0 Limit Switches• physical contact sensor• changes from normally open (NO) to close state, or from normally closed to

open state

2.0 Optical Sensor• infrared (IR) emitter and detector pair• emitter emits IR rays (e.g, RS 585-977)• detector detects IR rays (e.g., RS 585-983)• sensitivity can be adjusted by modifying the strength of the IR ray• output is a digital TTL signal (5V or 0 V)• activation is via direct IR beam or reflected IR beam from tape

18

3.0 Actuators

3.1 Solenoids• linear motion (fully extended or fully retracted)• electromagnetic actuation• high power consumption• needs an amplifier (e.g., 12 V, 1A needed )

3.2 DC motors• precise position and velocity control (capable of limitless resolution)• position feedback needed (typically by incremental encoder)• torque generated is proportional to current through motor• needs an amplifier

3.3 Stepper motors• much simpler to control compared to DC motor• open loop control - position feedback may be avoided• resolution is limited - 1 pulse produces 1 step• requires a pulse train and direction signal (clockwise or counter-clockwise)• position determined by number of pulses• speed determined by frequency of pulses• needs an amplifier and stepper controller circuit

Typical values forRd and Re = 1000 Ω

19

4.0 Darlington Switch• e.g., ULN 2074B• “logic amplifier”• logic (TTL) signal can be used to drive devices of up to 1.5 A load, 35 V.

• Device supply = supply voltage needed by the device to be turned on or off.This comes from a power supply.

• Device input = connected to the load. Voltage here is either supply voltage or 0volts depending on the logic signal from controller.

5.0 Transistors

• Resistor limits the current flowing through the load• The other resistors (100K and 39K) is to regulate current flow to enable the

switching of the transistor• Typical transistor : MPSA13 (capable of 1A)

Load

ground

Resistor12 V

Load

B

C

E100 KΩ

39 KΩ

ground

20

6.0 DC Motor Velocity Control

∗ If speed is low, voltage across tachometer is low thereby enabling thetransistor.

∗ Current therefore flows to the motor and motor speeds up.∗ When motor speed is high, transistor disable current flow to the motor, thereby

reducing the speed of the motor.∗ Transistor does fast switching to maintain a certain velocity.

21

7.0 Stepper Motor Control and Driver

• L298N - power amplifier, L297 - stepper motor controller• stepper motor = 8 wires (3 coils) or 6 wires (2 coils)• black and white wires = common (ground)• L297 - only for 6 wire stepper motor

• Possible winding configurations/connections:

• Rs1 and Rs2 are power resistors for current sensing, typical values are of order0.5 Ω.

• Rs1 senses current for current flow between terminal 2 and 3, Rs2 is for 13 and14.

• Important inputs∗ clock (pulse train)∗ ccw/cw (direction of motion)

• R = 22KΩ, C = 3.3nF (used to define chopper rate)∗ Freq = 1 / (0.69 R C)∗ Perhaps to get rid of noise∗ Must be much more than pulse train frequency.

orange

white

blue

Coils

red blackyellow

red

blue

white yellow

22

8.0 Amplifiers for DC Motors (PWM or Linear)

• TL494 PWM driver• generates a pulse train• amplitude of pulse train is 5 V (TTL)• average value of pulse train is proportional to input voltage (control signal),

average value is obtained by changing the duty cycle of the pulse traindepending on the control signal

• pulse train is input to the L298N• frequency of the pulse train is determined by the 12K resistor and 0.01 µF

capacitor, Freq = 1.2 / (R C) = 10,000 Hz.• pulse train is seen from Pin 11 of TL494 PWM driver

• L298N Linear amplifier• capable of 1 A per channel• can support four channels• direction control (TTL signal) from computer - allows current flow to

motor in different directions• pin 11 of L298N is Vinh (inhibit). A TTL (5V) value is expected to enable

the driver, 0V disables the driver.

• The PWM chip therefore enables and disables the linear amplifier at a certain rate,thereby resulting in an average current flow to the motor that is proportional to thecontrol signal.

0.01

12 K

23

• Control signal is from 0 to 3V. The D/A card of the computer has a typical rangeof ± 8 V. An operational amplifier may be needed to do some scaling.

9.0 Voltage Regulators

• Allow use of single voltage supply (e.g., 12 V lead-acid battery) to provide∗ ±5 V, ±12 V

• Can be used to power a PC motherboard• Input (supply) voltage must be greater than or equal to the desired output voltage. 9.1 Positive Voltage Regulators

• µA7800 series (3 terminals)∗ µA7805 for 5 volts∗ µA7812 for 12 volts∗ etc.

• For low power (current less than 1A)

• For high power (current ≥ 1A but less than 3 A)

• µA7805 3A is current available as off-the-shelf.

µA78XX

µA78XX

0.33 µF

0.33 µF

0.1 µF

0.1 µF

Vs

Vs

Voutput

Voutput

ground

ground

1

1

2

2

3

3

R=3Ω

2N6133

24

9.2 Negative Voltage Regulators

• µA7900 series (3 terminals)∗ µA7905 for 5 volts∗ µA7912 for 12 volts∗ etc.

• For low power (current less than 1A)

• For high power (current ≥ 1A but less than 3 A)

9.3 Power Supply

• Two 12-V batteries are needed, one provides 0-12 volts, the other -12 to 0 volts.

µA79XX

µA79XX

2.0 µF

2.0 µF

1.0 µF

1.0 µF

Vs

Vs

Voutput

Voutput

ground

ground

3

1

2

2

1

3

R=6Ω

2N3055

25

10.0 Example Application: Control of a Mobile Robot

11. PID Control Equations

The PID (Proportinal-Integral-Derivative) control equation is:

mn = mn-1 + K0 en + K1 en-1 + K2 en-2

where

K0 = Kp + Ki T + Kd/TK1 = −Kp − 2 Kd/TK2 = Kd/TT = sample perioden = error at the nth sampling instant = desired position − actual positionKp, Ki, Kd = are the PID (analog) gains, respectively.

PC Motherboard -• 1.44 MB Floppy Drive• Ram Disk (loaded via software)• no keyboard (disabled via BIOS)• no monitor• requires ± 12 V, ± 5 V

ADDA Card- use D/A Converter

only

Digital I/O Card

VoltageRegulator

12 VBattery

DriversDC Motors

Stepper MotorController and Driver

StepperMotors

DigitalSensors

• • • • • • •Retro-reflective tape(under sensors)

7 IR emitter-detector pairs

Top ViewLimit Switches