ECE 4510/5530Microcontroller Applications
Week 2 Lab 2 Preparations
Dr. Bradley J. BazuinAssociate Professor
Department of Electrical and Computer EngineeringCollege of Engineering and Applied Sciences
ECE 2510 2
Lab 2 Overview
• Hardware Development– Parallel I/O ports– LEDs– Dip switches– 7-segment display– Keypad– Clock-recovery-generator
• Software Development Environment– Software control flow– Function calls– Software delay loops
ECE 2510
Basic Concepts of I/O
• I/O devices are also called peripheral devices.– For microcontrollers, they are usually part of the IC– For microprocessors, they are usually in separate ICs
• I/O devices are consist of circuitry (logic or a device) that exchange data with a computer processing unit (CPU).– Examples data includes: switches, light-emitting diodes, cathode-
ray tube screens, printers, modems, keyboards, and disk drives.
ECE 2510
Interface (Peripheral) Logic/IC (1 of 2)
• Logic/IC whose function is to synchronize data transfer between the CPU and I/O devices– Consists of control registers, status registers, data direction latches, and
control circuitry– Has pins that are connected to the CPU and I/O port pins that are
connected to the I/O devices
• Each interface chip has a chip enable signal input or inputs, when asserted, allow the interface chip to react to the data transfer request.– Data transfer between an I/O device and the CPU can be proceeded bit-
by-bit or in multiple bits (parallel).– For embedded devices, this is the peripheral register address!
ECE 2510
AddressDecoder
Microprocessor
Data Bus
Interfacechip 1
Interfacechip 1
frominputdevice
tooutputdeviceI/O pins
Figure 7.1 Interface chip, I/O devices, and microprocessor
CE CE
Interface (Peripheral) Chip (2 of 2)
• Address decoder makes sure that each time one and only one peripheral device responds to the CPU’s I/O request.
ECE 2510 6
HCS12 Parallel Ports
• The number of pins available in each I/O port for HCS12 are (see mc9s12dp256.s and mc9s12dp256.h for names):– PORTA 8 pins PA7 – PA0– PORTB 8 pins PB7 – PB0– PORTE 8 pins PE7 – PE0– PTH 8 pins PH7 – PH0– PTJ 4 pins PJ7, PJ6, PJ1, PJ0– PORTK 7 pins PK7, PK5 – PK0– PTM 8 pins PM7 – PM0– PTP 8 pins PP7 – PP0– PTS 8 pins PS7 – PS0– PTT 8 pins PT7 – PT0– PORTAD1, PORTAD0 16 pins PAD15 – PAD0
ECE 2510 7
Adapt9S12DP512 I/O Pins
ECE 2510
HCS12 Parallel Ports (1 of 3)
• All I/O pins serve multiple functions.– When a peripheral function is enabled, its associated pins cannot
be used as general purpose I/O pins.
• Each I/O port has several registers to support its operation.
• Registers related to I/O ports have been assigned a mnemonic name and the user can use these names to refer to them– movb #$FF, PortA ; output $FF to Port A
ECE 2510
HCS12 Parallel Ports (2 of 3)
• All I/O ports (except PORTAD0 and PORTAD1) have an associated data direction register and a data register.
• The name of the data direction register is formed by adding the letters “DDR” as the prefix to the port name. For example, DDRA, DDRB, and DDRT.– To configure a pin for output, write a ‘1’ to the associated bit in the
data direction register.– To configure a pin for input, write a ‘0’ to the associated bit in the
data direction register.
movb #$FF,DDRA ; configure port A for outputmovb #0,DDRA ; configure port A for inputbset DDRA,$81 ; configure Port A pin 7 and 0 for output
ECE 2510 10
HCS12 Parallel Ports (3 of 3)
• We use “PORT” as the prefix to the port name for ports A, B, E, and K.
• For the other ports, the register name is formed by adding letters “PT” as the prefix to the port name. For example, PTH, PTJ, PTM, PTP, PTS, and PTT.
• Output a value to a port is done by storing that value to the port data register address.
• movb #$FF,DDRH ; configure Port H for output• movb #$37,PTH ; output the hex value 37 to port H
• Input a value from an input port is done by loading from the port data register address.
• movb #0,DDRH ; configure Port H for input• ldaa PTH ; read data from port H into A
Port Integration Module (PIM)
• Parallel Ports – the “PT#” ports: T, S, M, P, H, J
• A standard PIM port pin has the following minimum features:– Input/output selection– 5V output drive with two selectable
drive strengths– 5V digital and analog input– Input with selectable pull-up or
pull-down device• Optional features:
– Open drain for wired-or connections– Interrupt inputs with glitch filtering
ECE 4510/5530
11
Block Diagram
ECE 4510/5530
12
• PT#: input/output data register
• PTI#: input register• DDR#: data direction
register
Special Pin Controls
• Data direction (DDR) – input or output• Output level (I/O) – same as PT describing the port value • Reduced drive (RDR) – full or 1/3 drive• Pull enable (PER) – enable a pull-up or pull-down• Interrupt enable (PIE) – for port P, H, and J only• Pull select (PPS) - select whether pull-up or -down
– if interrupt is enabled, configure the sensitive interrupt edge (rising or falling.
– if PE is active, select either a pull-up or pull-down device.
ECE 4510/5530
13
Port Registers – Pin Control
ECE 4510/5530
14
Memory Map
ECE 4510/5530
15
Address Base: 0x240(0x240 to 0x26F)
C Include File
#define PTS _P(0x0248)#define PTIS _P(0x0249)#define DDRS _P(0x024A)#define RDRS _P(0x024B)#define PERS _P(0x024C)#define PPSS _P(0x024D)#define WOMS _P(0x024E)
//#define Reserved _P(0x024F)
#define PTM _P(0x0250)#define PTIM _P(0x0251)#define DDRM _P(0x0252)#define RDRM _P(0x0253)#define PERM _P(0x0254)#define PPSM _P(0x0255)#define WOMM _P(0x0256)
//#define Reserved _P(0x0257)
#define PTP _P(0x0258)#define PTIP _P(0x0259)#define DDRP _P(0x025A)#define RDRP _P(0x025B)#define PERP _P(0x025C)#define PPSP _P(0x025D)#define PIEP _P(0x025E)#define PIFP _P(0x025F)
#define PTH _P(0x0260)#define PTIH _P(0x0261)#define DDRH _P(0x0262)#define RDRH _P(0x0263)#define PERH _P(0x0264)#define PPSH _P(0x0265)#define PIEH _P(0x0266)#define PIFH _P(0x0267)
ECE 4510/5530
16
#define PTJ _P(0x0268)#define PTIJ _P(0x0269)#define DDRJ _P(0x026A)#define RDRJ _P(0x026B)#define PERJ _P(0x026C)#define PPSJ _P(0x026D)#define PIEJ _P(0x026E)#define PIFJ _P(0x026F)
//#define Reserved _P(0x0270 -0x027F)
ECE 2510 17
Assembly Example
• This allows to use the symbolic name to access ports• Ex:
PORTA = $0000 PTH = $0260PORTB = $0001 DDRH = $0262DDRA = $0002 PTT = $0240DDRB = $0003 DDRT = $0242
LDAA #$FF ; Configure Port A for outputSTAA DDRALDAA #$FF ; Write to Port ASTAA PORTA
See mc9s12dp256.s
ECE 2510 18
C Example
• This allows to use the symbolic name to access ports• Ex:
# Define PORTA 0x0000; # Define PTH 0x0260;# Define PORTB 0x0001; # Define DDRH 0x0262# Define DDRA 0x0002; # Define PTT 0x0240# Define DDRB 0x0003; # Define DDRT 0x0242
DDRA = 0xFF; //Configure Port A for outputPORTA = 0xFF; //Write to Port A
DDRH |= 0xAA; // every other bit outputPTH |=0xAA; // set the outputsPTH &= ~0xAA; // clear the outputs
ECE 2510 19
Interfacing with Output Devices
• Many embedded devices only require interfacing with simple input and output devices such as switches, light emitting devices, keypads, seven segment displays etc
• Interfacing with LED’s:– LED’s are often used to indicate the system operation mode
• Whether the system is turned on• Whether the system operation is normal• Whether the system is in an error mode etc
– An LED can illuminate when it is forward biased and has sufficient current following through it
– The current required to light the LEDs that are used in the lab is nominally 10mA. (It isn’t a car tail light or a traffic light!)
ECE 2510 20
LED Driving by Port B
• Ex: Use Port B to drive eight LED’s. Turn on each LED one at a time for 0.5s and then repeat the process.
• Schematic for interfacing LED bar with Port B
Figure 7.30 Circuit connection for example 7.3
PB3
PB2
PB1
PB0
HCS12
PB7
PB6
PB5
PB4
1.5K
Note: this is not the preferred way!
Note: this is how the PTP bit 7 LED
is connected.
ECE 2510 21
Interfacing with LEDs
• Three methods for interfacing with LED’s• Method A and B are only recommended for use with LED’s that need
only 1 to 2mA to produce enough brightness (most LEDs want 10 mA or more!)
• The circuit C is recommended for use with LED’s that need larger current to turn on, the ECE 2510 labs, and all other ECE labs.
• Resistor value can be between 220 ohm and 1 Kohm
74HC04
VCC
Figure 7.29 An LED connected to a CMOS inverter through a current- limiting resistor.
Portpin
(a) positive direct drive (c) buffered drive
R1
R2
R3
VCC
Portpin
Portpin(b) inverse direct
drive
ECE 2510 22
Lab LED and Light Bar Connections
• Buffer the HC12 port (!!!)– Inverting buffer ‘540– Non-inverting buffer ‘541– Provide current sinking for the
LED
• Resistor between +5 and LED– The resistor provides current
limiting
• Resistor Value– LED needs ~1.2 to 1.5 V drop– LED wants ~ 10 mA or more
30010
8.02.15mA
VVVR OL
I ~ from 8 to 12 mA
ECE 2510 23
Interfacing with Output Devices
• To turn on the LED driven by pins PB7 – PB0 one at a time, one should output the values$80, $40, $20, $10, $08, $04, $02, $01 every 0.5s– Step1: Place the values $80, $40, ------------, $01 in an array. Use
index register X to point to the start of the array– Step2: Output the value pointed to by X to Port B. Increment the
pointer X– Step3: Run the delay for 0.5s– Step4: If X points to the end of array, reset X to point to the start of
the array. Go to step2
Arbitrary light patterns of different lengths and time delays can be easily created!
ECE 2510 24
;The assembly program that performs the operation is as follows:
.org $1000led_tab: .byte $80,$40,$20,$10,$08,$04,$02,$01
.byte $01,$02,$04,$08,$10,$20,$40,$80
.text_main::
movb #$FF,DDRB ; configure port B for output
forever: ldaa #16 ; initialize loop count to 8ldx #led_tab ; use X as the pointer to LED pattern table
led_lp: movb 1,x+,PTB ; turn on one LEDldy #5 ; wait for half a secondjsr delayby100ms ; "dbne a,led_lp ; reach the end of the table yet?bra forever ; start from beginning
Code in ASM
ECE 2510 25
The C language version of the program is as follows:
#include "c:\egnu091\include\hcs12.h"#include "c:\egnu091\include\delay.c"main (void){
char led_tab[8] = {0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
char i;DDRB = 0xFF; /* configure port B for output */
while (1){for (i = 0; i < 16; i++) {
PTB = led_tab[i];delayby100ms(5);
}}return 0;
}
Code in C (from text)
Interfacing with Seven Segment Displays
• Seven segment displays are often used when the embedded products needs to display only a few digits– Seven segment displays are mainly used to display decimal digits
and a small subset of letters
• Although HCS12 devices have enough current to drive a seven segment display, it is not advisable to do when a HCS12 based embedded product needs to drive many other I/O devices– Best way is to use a buffer chip 74HC244 between microcontroller
and seven segment display– 74HC244 provides 5v and using a 330 ohm resistor between
74HC244 and seven segment display provides a current of 10mA, sufficient to illuminate an LEDECE 2510 26
ECE 2510 27
7 Segment Display
74H
C244
PB6PB5PB4PB3PB2PB1PB0
abcdefgcommon cathode
a
b
cd
e
fg
HCS12
Figure 7.31 Driving a single seven-segment display
300 each
Note: ‘541 is an alternative buffer
BCD to 7 Segment Mapping
ECE 2510 28Done for discrete logic in an ECE2500 Lab!
ECE 2510 29
#include <hcs12.inc>.org $1000BCD7: .byte $7E, $30, $6D, $79, $33, $5B, $5F, $70, $7F, $7B, $77, $1F $4E, $3D,$4F, $47
BCDVal =4 ; BCD Value to be displayed
.text_main::
movb #$FF,DDRB ; configure PORT B for outputldaa #BCDVal ; load the BCD Valueldx #BCD7ldaa a,x ; load the 7 Segment Valuestaa PORTB ; output to 7 segment displayswi
Example: Write to One 7-Segment Display
• Write a sequence of instructions to display a BCD value on the seven-segment display previously shown.
• Solution:– Output the appropriate hex value to port B
What if we wanted
additional Hex Outputs?
ECE 2510 30
DIP Switches
• A switch is probably the simplest input device available• To make input more efficient, a set of eight switches
organized as a Dual inline package (DIP) is often used• A DIP package can be connected to any input port with
eight pins such as PortA, PortB etc• When a switch is closed, the associated port input is 0,
otherwise the associated port input is 1• Each port input is pulled up high via a 330 ohm or 1Kohm
resistor when the associated switch is open
ECE 2510 31
Connecting DIP SwitchesVCC
10K
PA0PA1PA2PA3PA4PA5PA6PA7
HCS12
Figure 7.39 Connecting a set of eight DIP switches to Port A of the HCS12
SW DIP-8
ECE 2510 32
Lab Dip Switch Connections
• Buffer the HC12 port (!!!)– Inverting buffer ‘540– Non-inverting buffer ‘541– Provide isolation from switch
• Resistor between +5 and switch– If you short the switch while
probing, the resistor provides current limiting.
• Resistor Value– 330 ohms or greater
(10 kohm preferred)
ECE 2510 33
Reading DIP Switches Steps
• Ex: Instruction to read data from DIP switches interfaced to PortA
• Step1: Define the corresponding Data Direction Register and Data Register of PortA
• Step2: Set the Data Direction Register of PortA to configure port as input port
• Step3: Read the data from the Data register of PortA according to the requirements of the program. Data from the DIP switches is always available in the Data Register of the corresponding port with which it’s interfaced to
ECE 2510 34
DIP to LED Example
; Dip Switch Inputs; LED Outputs
.area prog(abs)
PORTA = $00PORTB = $01DDRA = $02DDRB = $03.text_main::
ldaa #$00staa DDRAcomastaa DDRB
Loop:ldaa PORTAstaa PORTBBra Loop
VCC
10K
PA0PA1PA2PA3PA4PA5PA6PA7
HCS12
Figure 7.39 Connecting a set of eight DIP switches to Port A of the HCS12
SW DIP-8
Figure 7.30 Circuit connection for example 7.3
PB3
PB2
PB1
PB0
HCS12
PB7
PB6
PB5
PB4
1.5K
// Dip Switch Inputs// LED Outputs
# define PORTA 0x00# define PORTB 0x01# define DDRA 0x02# define DDRB 0x03Char temp;
void main(void){
DDRA = 0x00; // defaultDDRB = 0xFF; // output
while(1){
temp = PORTA;PORTB = temp;
}} // end main()
Switch Bounce
• Mechanical switches have a common problem called contact bounce– Mechanical switches or keypads are most popular due to their low
cost and minimal strength of construction
• Instead of producing a single clean output pulse, pressing a mechanical switch generates a series of pulses because switch contacts do not come to rest immediately– When the key is not presses, everything is fine– In order to detect which key has been presses, controller needs to
scan every key of keypad and may, due to contact bounce, determine that every low is a new key press (you get repeated characters when one was desired!)
ECE 2510 35
Contact Switch Bounce
• The switch bounces or chatters in transitioning from one to zero.
ECE 2510 36
De-bouncing
• The signal that falls and rises within a period of up to 5ms is likely a contact bounces
• Human being cannot press and release a switch in less than 20ms– a de-bouncer could recognize that the switch is closed after the
voltage is low for about 10ms and then could recognize after that the switch is open after the voltage is high for about 10ms.
• Both H/W and S/W solutions to the key bounce problem are available
• H/W solution includes an analog circuit that uses a resistor and a capacitor, and two digital solutions that uses S-R latches or CMOS buffers and double throw switches
ECE 2510 37
ECE 2510 38
Interfacing with Input Devices
• Set-Reset Latches– A key switch can be de-bounced using the S-R latches– Before being presses, the key is touching the set input and the Q
voltage is high– When pressed the key touches the reset position, the Q voltage will
go Low– If the key is bouncing and touching neither Set or Reset, both
inputs are pulled low by the pull-down resistor. Since both Set and reset are low, the Q voltage will remain low and the key will be recognized as pressed
ECE 2510 39
Interfacing with input Devices
There is an alternate configuration (ECE2500):• Two 2-in Nand• Pull-ups to switch that shorts• Setn and Resetn (negative logic) used
ECE 2510 40
Interfacing with input Devices
• Non inverting CMOS buffer with high input impedance– The CMOS buffer output is identical to its input– When the switch is pressed, the input to the buffer chip is
grounded and hence Vout is forced low– When the key switch is bouncing, the resistor R keeps the output
voltage low. This is due to the high input impedance of the buffer, which causes a negligible voltage drop on the feedback resistor
ECE 4510 41
Switch Bounce MitigationCapacitor
• Integrated de-bouncers– The RC constant of the integrator determines the rate at which the
capacitor charges up towards the supply voltage once the ground connection via the switch has been removed
– As long as the capacitor voltage does not exceed the logic 0 threshold value, the Vout signal will be recognized as logic 0
– The cheapest approach!
ECE 4510 42
Switch Bounce MitigationSoftware
• Technique #1– The most popular and simple one has been the wait and see
method. Wait to see if the switch value stabilizes.– In this method, the program simply waits for about 10 ms and
reexamines the same key again to see if it is still pressed.
• Technique #2– M of N detection.
• Make multiple periodic samples (shift the bit value into an 8-bit word).
• Count the number of ‘1’ in the word and determine if M or more of N=8 are high or low (compute M for ones and 8-M for zeros)
• When M (or more) of N agree, declare the level as appropriate.
Multiplexing 7-Segment Displays
ECE 4510/5530
43
.
.
.
a
b
g
PB
6
PB1
PB0
Figure 4.18 Port B and Port P together drive six seven -segment displays (MC9S12DG256)
. . .
. . .
. . .
74HC244
HCS12
a
b
g
.
.
.
commoncathode
commoncathode
commoncathode
ab
g
.
.
.
800
PP5
PP4
PP0
800
#5#1#0
74HC367
PP3
PP2
PP1
A5
Y0A0
Y5
A4
Y1
A3
A2
A1
Y2
Y3
Y4
Write a program to display 123456 on the six seven-segment displays shown in Figure 4.18.Solution: The values 1,2,3,4,5, and 6 are displayed on display #5, #4, …, #0, respectively.A table is set up to control the pattern and digit selection as shown in Table 4.8.
Seven-SegmentDisplay
DisplayedBCD Digit
Port B Port P
#5#4#3#2#1#0
123456
$06$5B$4F$66$6D$7D
$1F$2F$37$3B$3D$3E
Table 4.8 Table of display patterns for Example 4.14#include "c:\miniide\hcs12.inc".org $1000
DispTab: .byte $06,$1F, $5B,$2F, $4F,$37.byte $66,$3B, $6D,$3D, $7D,$3E
.text_main::Start: lds #$1500
movb #$FF,DDRBmovb #$3F,DDRP
Forever: ldx #DispTab ; set X to point to the display tableloopi: movb 1,x+,PTB ; output segment pattern
movb 1,x+,PTP ; output display select ldy #1jsr delayby1ms ; wait for 1 mscpx #DispTab+12 ; reach the end of the table?bne loopibra forever
Example 4.14
ECE 2510 45
16-Button Keypad
• 4200 Series by C&K Components, Inc. Web Site: www.ckcorp.com– Matrix connections based on which key is pressed– Time multiplex pins 1-4 while reading pins 5-8– A keypad controller IC can be purchased to act as a peripheral
ECE 2510 46
16-Button Keypad
• Series 96 by Grayhill, Inc. Web Site: www.grayhill.com– Matrix connections based on which key is pressed– Time multiplex pins 1-4 while reading pins 5-8– A keypad controller IC can be purchased to act as a peripheral
ECE 2510 47
Keypad Scanning
• Keypad scanning is usually performed row-by-row or column-by-column
• A 16-key keypad can be easily interfaced using any available 8-bit I/O port
• For the keypad application the upper four pins of the port should be configured for output and the lower four pins of the port should be configured for input (with pull-ups)
• The rows and columns of a keypad are simply conductors• The keypad interface setup to HCS12 PortA is as shown in
the next slide
ECE 2510 48
Keypad Circuitry
A
B
C
D
E
F
0
1
2
3
4
5
6
7
8
9
10K
VC C
PA7
PA6
PA5
PA4
PA3
PA2
PA1
PA0
HCS12 MCU
Figure 7 .41 S ixteen-key keypad connected to the H C S12
outputs
inputs
PA7 PA6 PA5 PA4 Selected keys
1110
1101
1011
0111
0,4,8,C,
1,5,9,D,
2,6,A,E,
and 3and 7and Band F
Table 7.16 Sixteen-key keypad row selections
ECE 2510 49
Keypad Operation
• Whenever a key switch is pressed, the corresponding row and column are shorted together
• In order to distinguish the row and column of the key pressed– Scan a zero through the columns– If an input row becomes zero, the key pressed must be connected
to the zeroed column. Figure it out to determine the key!
PA7 PA6 PA5 PA4 Selected keys
1110
1101
1011
0111
0,4,8,C,
1,5,9,D,
2,6,A,E,
and 3and 7and Band F
Table 7.16 Sixteen-key keypad row selections
Keypad Input vs. Key Pressed(When PA7-PA0 not all 1’s)
ECE 2510 50
Key PA7 PA6 PA5 PA4 PA3 PA2 PA1 PA0Driven Outputs Inputs
0 1 1 1 0 1 1 1 01 1 1 1 0 1 1 0 12 1 1 1 0 1 0 1 13 1 1 1 0 0 1 1 14 1 1 0 1 1 1 1 05 1 1 0 1 1 1 0 16 1 1 0 1 1 0 1 17 1 1 0 1 0 1 1 18 1 0 1 1 1 1 1 09 1 0 1 1 1 1 0 1A 1 0 1 1 1 0 1 1B 1 0 1 1 0 1 1 1C 0 1 1 1 1 1 1 0D 0 1 1 1 1 1 0 1E 0 1 1 1 1 0 1 1F 0 1 1 1 0 1 1 1
I/O SYNCHRONIZATION
ECE 4510/5530
51
ECE 2510 52
I/O Synchronization
• Microprocessors often deal with interface devices rather than an I/O device– The function of an interface device and the CPU are incorporated
onto the same chip in a microcontroller– When inputting data, microprocessor reads data from the interface– When outputting data, microprocessor writes data into the interface
• A mechanism should be available to make sure:– Data is valid when the microprocessor reads data– To make sure output device is ready to accept data when the
microprocessor outputs data
ECE 2510 53
MicroprocessorControl signals
(such as R/W orinterrupt)
Interface chip
handshake orstrobe signal I/O device
electronics
Data Bus
Dat
a B
us
Figure 7.2 The role of an interface chip
I/O Transfer Synchronization
• The role of an interface chip– Synchronizing data transfer between:
• the CPU and the interface chip• the interface chip and the I/O device
ECE 2510 54
I/O Synchronization Input
• Microprocessor needs to make sure that the interface chip has correctly latched data from the input device
• Status bits or registers provide information about when interfaces are ready– Can “poll” reading the status bite periodically– Can “interrupt” causing the program to immediately deal with the
interfaces
ECE 2510 55
Polling Method
• Interface chip uses a status flag to indicate whether it has valid data for the microprocessor
• Microprocessor knows that the interface chip has valid data when the status flag is a “1”
• Microprocessor keeps checking the status flag until the status flag is set to 1, and then reads data from the data register
• When this method is used, microprocessor can be tied up and cannot do any other task
• This method is very simple to implement and is often used when the microprocessor has nothing else to do except wait for completion of the operation
ECE 2510 56
Interrupt Driven Method
• The interface chip asserts an interrupt signal to the microprocessor when it has valid data in the data register
• Microprocessors then executes the service routine associated with the interrupt to read the data
• Advantage with this method is that microprocessor can perform other tasks till the interface chip asserts the interrupt signal
getchar and putchar polling
#include <stdio.h>
// CPU12 target#include <mc9s12dp256.h>//#define RDRF bit(5)
int getchar(void){while ((SC0SR1 & RDRF) == 0)
;return SC0DRL;}
ECE 2510 57
#include <stdio.h>
// CPU12 target#include <mc9s12dp256.h>//#define TDRE bit(7)
extern int _textmode;
int putchar(char c){if (_textmode && c == '\n')
putchar('\r');while ((SC0SR1 & TDRE) == 0)
;SC0DRL = c;return c;}
ECE 2510 58
I/O Synch Interactions
• The circuit designer is responsible for making sure that data is properly transferred to and from I/O devices– Microcontroller exists, so make sure the interface devices work
appropriately. Internal devices have been done by design, external devices are left to the designer.
• The following methods have been used to synchronize data transfer between the interface chip and I/O devices
– Brute-Force method– Strobe Method– Hand-Shake Method
ECE 2510 59
I/O Synch: Brute Force
• Brute-Force Method:– For input-- The microprocessor reads the interface chip and the
interface chip returns the voltage levels on the input port pins to the microprocessor.
– For output --The interface chip places the data that it received from the microprocessor directly on the output port pins.
– HCS12 microcontroller supports this Brute-Force method for all general purpose I/O ports available
• This method is useful in situations in which the timing of data is unimportant.
• This method can be used to:– Test voltage levels of a signal– Set the voltage levels of an output pin to low or high– Drive LED’s and read dip switches
ECE 2510 60
I/O Synch: Strobe
• Strobe Method -- a strobe signal used to indicate that data are stable on I/O port pins --– For input -- Input device asserts a strobe signal when data are
stable on the input port pins. Interface chip latches data into the data register using the strobe signal.
– For output -- Interface chip first places data on the output port pins when the data becomes stable, the interface chip asserts a strobe signal to inform output device to latch data on the output port pins
• HCS12 I/O ports does not support this method, but it can be implemented for outputs.– Use one or more “parallel port” pins as strobe signals– Software creates a strobe output (set and then clear parallel pin)– Sometimes called bit banging as software is controlling single bits
at a time to accomplish a task
ECE 2510 61
I/O Synch: Handshaking
• Handshake Method:– The previous two methods cannot guarantee correct data transfer
between an interface chip and I/O device when the timing of data is critical
– Best solution is to use a handshake protocol
• Two handshake methods are available:– Interlocked handshake– Pulse-mode handshake
• Both the handshake methods make use of two handshake signals H1 and H2– H1 asserted by the interface chip– H2 asserted by the I/O device
Simple Handshaking
• One devices offers.– The other agrees (continue) or ignores (time out)
• The agreeing devices acknowledges the offer– A transaction has begun and can continue
• The first device concludes the transaction– The asserted state is deasserted
• The second device acknowledges the end
ECE 2510 62
Software
Hardware
Other Handshaking Structures
• Software handshaking protocols– There are a large number of defined protocols for transferring
“information” from one entity to another– Secure transaction are some of the most demanding
• Hardware handshaking– Often present in hardware-to-hardware interfaces
• As transfer speed increase, timing and “flow-control” mechanisms become more important
– Found in many bus architectures• Bus request-grant, interrupt request-grant, address acknowledge,
wait lines, etc.
ECE 2510 63
LOGIC COMPATIBILITY:VOLTAGE AND CURRENT
ECE 2510 64
ECE 2510 65
Electrical Characteristic Consideration for I/O Interfacing
• Most systems require the use of logic chips and/or peripheral devices apart from the microcontroller to perform their function
• These chips may use different types of Integrated Circuit (IC) technologies, there is a concern that the resultant system may not function properly
• One primary question is: are they electrically compatible?• Two issues involve
– Voltage-level compatibility– Current drive capacity
ECE 2510 66
Voltage and Current
• Voltage-level compatibility– High output level of an IC chip high enough to be considered as a
high for the input of another chip– Low output level of an IC chip low enough to be considered as a
low for the input of another chip
• Current drive capability– Output of an IC chip have enough current to drive its load– Can the output circuit of an IC chip sink the current of its load
• Signal timing is also an important factor for making sure that the digital circuit functions properly– The main concern about timing is whether the signal from one chip
becomes “valid enough” to be used by another IC chip
ECE 2510 67
Voltage Level compatibility
Voltage level compatibility issue arises because IC technologies differ in the following four voltages:
Input High Voltage (VIH) treated as logic 1 when applied as input to the digital circuit
Input Low voltage (VIL) treated as logic 0 when applied as input to the digital circuit
Output High Voltage (VOH) voltage level when digital circuit outputs a logic 1
Output Low Voltage (VOL) voltage level when digital circuit outputs a logic 0
ECE 2510 68
Voltage Level compatibility (2)
• In order for the digital circuit X to be able to drive circuit Y, the following conditions must be satisfied.– The output high voltage of device X (VOH-X) must be higher than
the input high voltage of device Y (VIH-Y). – The output low voltage of device X (VOL-X) must be lower than
the input low voltage of device Y (VIL-Y).
TypicallyDesired Levels
Wires act like resistors in series
with the IC outputs(paracytics)
Voltage Level Changes TTL
• VOH must be higher than VIH– TTL output current through wire resistance causes voltage drop
• VOL must be lower than VIL– TTL output current sinking through wire resistance causes voltage
increase
ECE 2510 69
Voltage Level Changes CMOS
• VOH must be higher than VIH– PMOS output current through wire resistance causes voltage drop
• VOL must be lower than VIL– NMOS output current sinking through wire resistance causes
voltage increase
ECE 2510 70
ECE 2510 71
Logic Family Voltage Levels
Logic family VCC VIH VOH VIL VOL
HCS123
S4
LS4
AS4
F4
HC3
HCT3
ACT3
ABT5
BCT5
FCT5
5 V5 V5 V5 V5 V5 V5 V5 V5 V5 V5 V
3.25 V2 V2 V2 V2 V
3.5 V3.5 V2 V2 V2 V2 V
4.2 V3.0~3.4 V1
3.0~3.4 V1
3.0~3.4 V1
3.4 V4.9 V4.9 V4.9 V3 V
3.3 V2.4 V
1.75 V0.8 V0.8 V0.8 V0.8 V 1.5 V1.5 V0.8 V0.8 V0.8 V0.8 V
0.8 V0.4~0.5 V2
0.4~0.5 V2
0.35 V0.3 V0.1 V0.1 V0.1 V
0.55 V0.42 V0.55 V
Notes. 1. VOH value will get lower when output current is larger. 2. VOL value will get higher when output current is larger. The VOL values of different logic gates are slightly different. 3. HCS12, HC, HCT, ACT are based on the CMOS technology. 4. S, LS, AS and F logic families are based on the bipolar technology. 5. ABT, BCT, and FCT are using the Bi-CMOS technology.
Table 7.3 Input and output voltage levels of common logic families
TTL
CMOS
HC12
ECE 2510 72
HC12 Compatibility
• 5 Volt technology compatibility– CMOS is compatible– LS TTL is not compatible
ECE 2510 73
Voltage Level Compatibility (3)
Summarizing Voltage Level Compatibilities:• HCS12 can be driven by CMOS devices (HC, HCT)
• HCS12 may not work with ACT CMOS devices, VIL=VOL• HCS12 will likely have problems with Bi-CMOS ,
VIL=VOL and VOH <= VIH(HC12) (ABT, BCT, FCT)• HCS12 cannot be driven by a bipolar device (S, LS, AS, F).
ECE 2510 74
Current Drive Capability
• Microcontrollers needs to drive other peripheral I/O devices in an embedded system
• Another issue is whether the microcontroller can source (when the output voltage is high) or sink (when the output voltage is low) the current needed by the I/O device that it interfaces with
• Need to make sure the following two requirements– Each I/O pin can supply and sink the current needed by the I/O
device that it interfaces with– Total current required to drive I/O devices does not exceed the
maximum current rating of the microcontroller
ECE 2510 75
Current Considerations
• Each logic chip has the following four currents that are involved in the current drive calculations:– Input high current (IIH) Input current (flowing into the input pin)
when the input voltage is high
– Input low current (IIL) Input current (flowing out of the input pin) when the input voltage is low
– Output high current (IOH) Output current (flowing out of the output pin) when the output voltage is high
– Output low current (IOL) Output current (flowing into the output pin) when the output voltage is low
ECE 2510 76
Current Source and Sink
• To determine whether a pin can supply or sink currents to all peripheral pins that it drives correctly, designer needs to check the two requirements– The IOH of an output pin must be equal to or larger than the total
current flowing into all the peripheral pins that are connected to this pin.
– The IOL of an output pin must be equal to or larger than the total current flowing out from all the peripheral pins that are connected to this pin
• Also need to make sure that the total current needed to drive the peripheral signal pins do not exceed the total current the microcontroller can supply.
ECE 2510 77
Terms: Fan-out and Fan-in
Fan-in: the number of standard loads an input pin appears to be. The fan-in of all connected devices establishes the “current demand” for switching.
Fan-out: how many devices can be driven by a circuits output. Often done based on a technology family standard load input current
Note1: Driving analog circuits or LEDs can rapidly change the output current required (IIH and IIL)Note2: A digital output should never drive both analog and digital inputs!
inFanII
IIoutFan
IL
OL
IH
OH
,min
ILIHloadsinputdevice IINinFan ,__
ECE 2510 78
Logic Family Current Levels
TTL
CMOS
HC12
HC12 IC Specifications
ECE 2510 79
25 mA for all outputs
ECE 2510 80
HC12 I/O
P: Those parameters are guaranteed during production testing on each individual device.
C: Those parameters are achieved by the design characterization by measuring a statistically relevant sample size across process variations.
T: Those parameters are achieved by design characterization on a small sample size from typical devices under typical conditions unless otherwise noted. All values shown in the typical column are within this category.
D: Those parameters are derived mainly from simulations.
MC9S12DP256B Device User Guide V02.15, Doc. No. 9S12DP256BDGV2/D, Original Release Date: 29 Mar 2001, Revised: Jan 11, 2005, Motorola, Inc
ECE 2510 81
Fan-Out
• HC12* to HC12s
• HC12* to LS TTL
• HC12* to HC/HCT
• LS TTL to HC12
• HC/HCT to HC12
* 2.5 mA vs. 25 mA due to previous spec. sheet
000,15.25.2,
5.25.2min
uAmA
uAmAoutFan
5.122.05.2,
205.2min
mAmA
uAmAoutFan
500,215.2,
15.2min
uAmA
uAmAoutFan
000,65.2
24,5.2
15min
uAmA
uAmAoutFan
000,105.2
25,5.2
25min
uAmA
uAmAoutFan
ECE 2510 82
Fan-Out (Others)
• LS TTL to LS TTL
• S TTL to S TTL
• F TTL to F TTL
1202.0
24,2015min
mAmA
uAmAoutFan
200.1
20,05.00.1min
mAmA
mAmAoutFan
405.0
20,02.00.1min
mAmA
mAmAoutFan
SOFTWARE TIME DELAY
ECE 4510/5530
83
ECE 2510 84
Creating Time Delays
• There are many applications that require the generation of time delays. – Program loops are often used to create a certain amount of delay
unless the time delay needs to be very accurate.
• The creation of a time delay involves two steps:– Select a sequence of instructions that takes a certain amount of
time to execute. (a basic unit)– Repeat the selected instruction sequence for an appropriate number
of times. (Delay = Number x basic unit)
ECE 2510 85
Program Execution Time
• The HCS12 uses the bus clock (E clock) as a timing reference.– The frequency of the E clock is half of that of the onboard clock
oscillator (clock, 48 MHz, E-clock, 24 MHz).– Execution times of the instructions are also measured in E clock
cycles
ECE 2510 86
Program Execution Time
• Execution times of each instruction can be obtained from Appendix A of the textbook or from the reference manual– Number of letters in the column “Access Detail” of Appendix A
indicates the number of E cycles that a specific instruction takes to execute that particular instruction
– For example access detail column of PULA instruction contains three letters UFO which indicates that the PULA instruction takes 3 E cycles to complete
ECE 2510 87
Program Execution Time
• Speed of the E clock varies from controller to controller– Higher E clock indicates higher processing times– The E clock for the HCS12 is 24 MHz = 41.67ns– The least amount of time HCS12 takes to execute an instruction is
41.67ns– So HCS12 can only be used in applications that require a per
instruction computation time of >= 41.67ns
• How to Computing Program Execution Time– Count all the E Cycles in the code– Multiply by 41.67 nsec
ECE 2510 88
Program Execution Time
Example:• The following instruction takes 14E cycles for 1 loop
Loop: psha ; 2E cyclespula ; 3E cyclespsha ; 2E cyclespula ; 3E cyclesnop ; 1E cycleDbne X,Loop ; 3E cycles condition not satisfied
; 3E cycle condition satisfied– Assume that the HCS12 runs under a crystal oscillator with a
frequency of 16 MHz, with an E freq. of 8 MHz.The E-clock period is then 125 ns.
– Therefore, each repeated loop would take 14*125=1750ns=1.75us to execute. Total delay 1.75usec x X_value
ECE 2510 89
Program Execution Time (2)
Example:• Time the following instructions
ldx #1234 ; 2E cyclesLoop: psha ; 2E cycles
pula ; 3E cyclespsha ; 2E cyclespula ; 3E cyclesdex ; 1E cycle
bne Loop ; 3E cycles branch taken; 1E cycle branch not taken
• This requires a slightly different count! X = 12342 + ( (X-1)*14 + (1)*12) E Cycles = 17,276 E Cycles
12/14 E-clock
ECE 2510 90
Program Execution Time
• Example: find delay created if E = 41.67ns = 1/24 MHz.ldx #$1234 ; 2E
Loop1:ldy #$ABCD ; 2E
Loop2: dbne Y, Loop2 ; 3E taken/3E notdbne X, Loop1 ; 3E taken/3E not
• Total time – Inner loop: (2 + ($ABCD-1)*3 + 3) E Cycles – Assume IL = (($ABCD)*3 )*41.67ns = 43981*3/24 MHz – IL = 0.005497625 sec– Outer loop: (2+$1234*IL+($1234-1)*3 +1) * 41.67ns– Total = ($1234*$ABCD*3 +$1234*3) * 41.67ns– Total = (4660*(43981+1)*3) /24 MHz = 25.629515 sec
ECE 2510 91
Program Execution
• How many E cycles in 0.001 sec?– 24 MHz * 0.001 sec 24000 E-cycles– Or 8000*3 inner loops. Use $1F40
• How many inner loops needed for 1 sec?– 1 sec/0.001 sec 1000 or $03E8
• If we used these numbers in the last program …– Total = ($03E8*$1F40*3 +$ 03E8 *3) * 41.67ns– Total = (1000*(8000+1)*3) /24 MHz = 1.000125 sec
(use Y=>$1F3F and X=>$03E8 instead for 1.00 sec)
• Comment: if the average instruction requires 3 E cycles– The machine would average 24/3 8 Mips
ECE 2510 92
Loop: psha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclesnop ; 1 E cyclenop ; 1 E cycledbne d,loop ; 3 E cycles when condition is not satisfied
; 3 E cycles when condition is satisfied
Program Execution Time
000,000,24
3371337 regD
Time
ECE 2510 93
Write a program loop to create a delay of 100 ms, assuming E=125ns..Solution: A delay of 100 ms can be created by repeating the previous loop 20,000 times.The following instruction sequence creates a delay of 100 ms.
ldx #20000 ; 2 E cyclesloop psha ; 2 E cycles
pula ; 3 E cyclespshapulapshapulapshapulapshapulapshapulapshapulanop ; 1 E cyclenop ; 1 E cycledbne x,loop ; 3 E cycles/3 E cycles
(2(ldx)+40*(20000))*E ≈ 20000*E ≈ 20000*125ns ≈ 100ms.
Software Delay: Example 2.25
MHz
DTime reg
000,000,8401402
sec
401402000,800 regD
204$000,20 EDreg
ECE 2510 94
Software Time Delays
• Time delays created by program loops are not accurate– Some overhead is required to set up the loop count– To reduce the overheads one can adjust the number to be placed in
the index registers– By doing so one can achieve closer to the required time delays
• Program loops are not advisable to use in applications requiring precise timing calculation– Interrupts may exist that could significantly change time delays
• Typically, Microcontroller Timer modules are used in applications requiring precise timing calculations– Enhanced Capture Timer– 8 PWM channels
SUBROUTINE & FUNCTION CALLS
ECE 4510/5530
95
ECE 2510 96
Subroutines
• Good program design is based on the concept of modularity– Modularity partitioning of a large program into subroutines
• Program can be divided into two sections– Main program– Subroutines
• Main program contains the logical structure of the algorithm
• Subroutines Execute many of the details involved in the program
ECE 2510 97
Subroutine Hierarchy
• Structure of a modular program can be visualized as shown• Principles of program design involved in high-level
languages can be applied to assembly language programs– Subroutine “objects” with calls and returns
ECE 2510 98
Subroutines
• Subroutine is a sequence of instructions that can be called from many different places in a program
• A key issue in a subroutine call is to make sure that the program execution returns to the point immediately after the subroutine call after the subroutine completes its computations.
• The address for returning to the point immediately after the subroutine completes its computation is known as the “return address”
• This is normally achieved by saving and retrieving the return address in and from the stack
ECE 2510 99
Subroutine Program Flow
• The subroutine call (2) saves the return address, which is the address of the instruction immediately following the subroutine call instruction, in the stack system
• After completing the subroutine computation task (3), the subroutine will return to the instruction immediately following the instruction that made the call (4)
• This is achieved by executing a return instruction (4), which will retrieve the return address from the stack and transfer CPU control to it
ECE 2510
Issues in Subroutine Calls
• Parameter passing – Use registers– Use the stack or stack frame– Use global memory
• Returning results– Use registers– Use the stack frame
(caller created a hole in which the result will be placed)
– Use global memory
• Local variables allocation– Allocated by the callee– Use the following instruction is
the most efficient way for local variable allocation
– leas -n,sp ; • allocate n bytes in the stack
for local variables
• Local variables deallocation– Performed by the subroutine– Use the following instruction is
the most efficient way– Leas n,sp ;
• deallocate n bytes from the stack
ECE 2510 101
HCS12 Subroutines Instructions
• HCS12 provides three different instructions for making subroutine calls and two different instructions for returning from a subroutine
• Subroutine calls– BSR Branch Subroutine– JSR Jump Subroutine– Call Call a Subroutine
• Return Instructions– RTS Return from Subroutine– RTC Return from Call
ECE 2510 102
Jump and Subroutine Table
Mnemonic Function OperationBSR Branch to subroutine SP – 2 SP
RTNH : RTNL M(SP) : M(SP+1)PC + Rel offset PC
CALL Call subroutine in expanded memory
SP – 2 SPRTNH:RTNL M(SP) : M(SP+1)SP – 1 SP(PPAGE) M(SP)Page PPAGESubroutine address PC
JMP Jump Address PC
JSR Jump to subroutine SP – 2 SPRTNH : RTNL M(SP) : M(SP+1)Subroutine address PC
RTC Return from call M(SP) PPAGESP + 1 SPM(SP) : M(SP+1) PCH : PCLSP + 2 SP
RTS Return from subroutine M(SP) : M(SP+1) PCH : PCLSP + 2 SP
Push PC
Push PCPush PPAGE
Pull PPAGEPull PC
Push PC
Pull PC
The return address is stored on the stack!
ECE 2510 103
Example of Real-Time Code Flow
• Sequential Code with Infinite Loop– Process as time is available
• Interrupts that must be immediately processed
External Interrupt Priority
Interrupt 1
Int 1 Process
Set Int 1 Flag
RTI
Interrupt 2
Int 2 Process
Set Int 2 Flag
RTI
Interrupt M
Int M Process
Set Int M Flag
RTI
STACKS
ECE 4510/5530
104
ECE 2510 105
Simple Stack Operations
• A simple means to store and retrieve register values temporarilyStack Operation Instructions
Mnemonic Function Operation
PSHA Push A (SP) – 1 SP; (A) M(SP)
PSHB Push B (SP) – 1 SP; (B) M(SP)
PSHC Push CCR (SP) – 1 SP; (A) M(SP)
PSHD Push D (SP) – 2 SP; (A : B) M(SP) : M(SP+1)
PSHX Push X (SP) – 2 SP; (X) M(SP) : M(SP+1)
PSHY Push Y (SP) – 2 SP; (Y) M(SP) : M(SP+1)
PULA Pull A (M(SP)) A; (SP) + 1 SP
PULB Pull B (M(SP)) B; (SP) + 1 SP
PULC Pull CCR (M(SP)) CCR; (SP) + 1 SP
PULD Pull D (M(SP) : M(SP+1)) A : B; (SP) + 2 SP
PULX Pull X (M(SP) : M(SP+1)) X; (SP) + 2 SP
PULY Pull Y (M(SP) : M(SP+1)) Y; (SP) + 2 SP
ECE 2510 106
Stack Memory
pshA ; A=$55, SP=$3C00pre-decrement SP
$55
low address
Stack pointer
$3C00
empty
empty
empty
empty
$3BFF
pulD ; Read stack wordpost-increment SP twice
$34
low address
Stack pointer
$3C00
$12
$CD
$AB
empty
$3BFF
$3BFE
$3BFD
$3BFC
low address
Stack pointer
$3C00
empty
$3BFF $34$12$3BFE
$3BFD
$3BFC
$CD
$AB
SP = $3BFF D=A:B=$ABCD, SP = $3BFE
ECE 2510 107
Stack Worksheet
• This worksheet is on line for “planning” stack operations– Initialize the SP to $3C00
lds #$3C00– Keep track of data and SP
address content comment $3BE0 $3BE1 $3BE2 $3BE3 $3BE4 $3BE5 $3BE6 $3BE7 $3BE8 $3BE9 $3BEA $3BEB $3BEC $3BED $3BEE $3BEF $3BF0 $3BF1 $3BF2 $3BF3 $3BF4 $3BF5 $3BF6 $3BF7 $3BF8 $3BF9 $3BFA $3BFB $3BFC $3BFD $3BFE $3BFF $3C00 Do Not Use Stack Pointer Should Start Here
DEBUGGING TIPS
ECE 4510/5530
108
ECE 2510 109
Tips for Debugging Programs Involving Subroutine Calls
• What to do when the program gets stuck?– Step 1
• Setting a breakpoint immediately before the jsr or bsr instruction.– Did you successfully get to this point with everything the way it should be
– Step 2• Setting a breakpoint immediately after the jsr or bsr instruction.
– Did the subroutine execute and return (stack problem)– Did the subroutine do the tasks required (function problem)
• Can you separate flow and function?– Code flow (executes, but the answer is wrong)– Code function (logical errors in the algorithm)
Reasons Why Code Flow Fails
• Forgetting to restore registers pushed onto the stack before return. – The “bookends” around the routine must “match”
• Forgetting to deallocate local variables before return.– If you start with leas –size,SP you need to end with leas +size, SP
• There are some infinite loops in the subroutine.– Are the subroutine branches correct?– If the subroutine were test as stand-alone code, does it work?
• Calling other subroutines in the subroutine that do not return.– If subroutines are nested, is one of those at fault?
ECE 2510 110
ECE 2510 111
General Debugging Strategy
• Make sure all leaf subroutines work correctly– Test the subroutine with it’s own special calling program– Work from the bottom up
• Debug intermediate subroutines. Make sure no intermediate subroutines get stuck.
• Debug the top level program.– Use D-Bug12 to monitor program progress
• Use “leds” and text to monitor code progress– Use terminal I/O to write progress characters to the screen– Toggle the LED at the beginning of every code segment
C LANGUAGE LIBRARIES EXIST!!
ECE 2510 112
C Language: Character Type Functions
The following functions categorize input according to the ASCII character set. Use #include <ctype.h> > before using these functions.
int isalnum(int c) returns non-zero if c is a digit or alphabetic character.int isalpha(int c) returns non-zero if c is an alphabetic character.int iscntrl(int c) returns non-zero if c is a control character (for example, FF, BELL, LF).int isdigit(int c) returns non-zero if c is a digit.int isgraph(int c) ) returns non-zero if c is a printable character and not a space.int islower(int c) returns non-zero if c is a lower-case alphabetic character.int isprint(int c) returns non-zero if c is a printable character.int ispunct(int c) returns non-zero if c is a printable character and is not a space or a digit or
an alphabetic character.int isspace(int c) returns non-zero if c is a space character, including space, CR, FF, HT, NL,
and VT.int isupper(int c) returns non-zero if c is an upper-case alphabetic character.int isxdigit(int c) returns non-zero if c is a hexadecimal digit.int tolower(int c) returns the lower-case version of c if c is an upper-case character.
Otherwise it returns c.int toupper(int c) returns the upper-case version of c if c is a lower-case character. Otherwise
it returns c. ECE 2510 113
C Language: String Functions (1 of 2)
Use #include <string.h> > before using these functions. The file <string.h> defines NULL and typedefs size_t, and the following string and character array functions:
void *memchr(void *s, int c, size_t n) searches for the first occurrence of c in the array s of size n. It returns the address of the matching element or the null pointer if no match is found.
int memcmp(void *s1, void *s2, size_t n) compares two arrays, each of size n. It returns 0 if the arrays are equal and greater than 0 if the first different element in s1 is greater than the corresponding element in s2. Otherwise, it returns a number less than 0.
void *memcpy(void *s1, const void *s2, size_t n) copies n bytes starting from s2 into s1.
void *memmove(void *s1, const void *s2, size_t n) copies s2 into s1, each of size n. The routine works correctly even if the inputs overlap. It returns s1.
void *memset(void *s, int c, size_t n) stores c in all elements of the array s of size n. It returns s.
ECE 2510 114
C Language: String Functions (2 of 2)
Use #include <string.h> > before using these functions.
char *strcat(char *s1, const char *s2) concatenates s2 onto s1 . It returns s1.char *strchr(const char *s, int c) searches for the first occurrence of c in s, including its
terminating null character. It returns the address of the matching element or the null pointer if no match is found.
int strcmp(const char *s1, const char *s2) compares two strings. It returns 0 if the strings are equal, and greater than 0 if the first different element in s1 is greater than the corresponding element in s2. Otherwise, it returns a number less than 0.
char *strcpy(char *s1, const char *s2) copies s2 into s1. It returns s1.size_t strlen(const char *s) returns the length of s. The terminating null is not counted.
char *strstr(const char *s1, const char *s2) finds the substring of s1 that matches s2. It returns the address of the substring in s1 if found and a null pointer otherwise.
ECE 2510 115
See: ICC12 On-line Helpand then: C LIBRARY AND THE STARTUP FILE