Sei sulla pagina 1di 124

ESW

USB

Chapter 1 Embedded C Programming

Outline
Introduction to 8051 Basic C Programming Language Extensions Preprocessor Advanced Programming

Introduction to 8051
An 8-bit Microcontroller optimized for control applications. A Microcontroller derivative family based on the 8051 core. A Microcontroller because you can make a one-chip system with the one chip containing: Program & Data Memory I/O Ports Serial Communication Counters/Timers Interrupt Control logic A-to-D and D-to-A convertors & so on ...

Features of the 8051(1/2)


- 8 Bit data path and ALU. - Easy interfacing. - 12 to 30 MHz versions available. ( 1 sec to 400 ns for single cycle instructions). - Full instruction set including: Multiply and Divide. Bit set, reset, and test (Boolean instructions). - Variety of addressing modes.

Features of the 8051(2/2)


- 4K X 8 ROM - Program memory. - 128 x 8 RAM - Data memory. - Special function registers. - Serial I/O port. - 32 I/O lines. - Two 16-bit counter/timers.

8051 Logic Symbol


VSS VCC RST

XTAL1

XTAL2

EA

P0.7 P0.6 P0.5 P0.4 P0.3 P0.2 P0.1 P0.0

P O R T 0

ADDRESS AND DATA BUS

PSEN
ALE

P1.7 P1.6 P1.5 P1.4 P1.3 P1.2 P1.1 P1.0


P2.7 P2.6 P2.5 P2.4 P2.3 P2.2 P2.1 P2.0

P O R T 1

SECONDARY FUNCTIONS

RxD TxD INT0 INT1 T0 T1 WR RD

P O R T 3

P3.7 P3.6 P3.5 P3.4 P3.3 P3.2 P3.1 P3.0

P O R T 2

ADDRESS BUS

80C51 Block Diagram


External Interrupts 4k byte ROM 128 byte RAM Timer 1 Timer 0 Counter Inputs

Interrupt Control

CPU

OSC

Bus Control

I/O Ports

Serial Port

TXD RXD

P0 P2
(Address/Data)

P1

P3

Addressing Space
- 64K X 8 ROM - Program memory. - 64K x 8 RAM - External data memory. - 256 x 8 RAM - Internal data memory. - 128 x 8 Special function registers (SFRs). - Bit addressing of 16 RAM locations and 16 SFRs.

Program Memory
- 16 bit Program Counter (PC). - 16 bit Data Pointer (DPTR). - 64K byte address space each for Program & Data. - Table lookup using relative addressing: PC + ACC (Move). DPTR + ACC (Move and jump). - EA pin disables internal ROM and activates external program memory and addressing.

Internal Data Memory


- 128 bytes of RAM. - Directly addressable range: 00 to 7F hexadecimal. - Indirectly addressable range: 00 to FF hexadecimal. - Bit addressable space: 20 to 2F hexadecimal . - Four register banks: 00 to 1F hexadecimal.

Internal Data Memory


7F 30 2F 20 1F 20 17 18 0F 08

END 8051 RAM FF . . . . . . . . . F8 07 . . . . . . . . . 00 REGISTER BANK 3 REGISTER BANK 2 REGISTER BANK 1

BIT ADDRESSABLE

07 R7

R6 R5 R4 R3 R2 R1
00 R0

REGISTER BANK 0

External Data Memory


- 64K byte address space. - Indirectly addressable via R0 and R1 in 256 byte segments. - Entire space is indirectly addressable via the data pointer DPTR.

External Bus Expansion


8051 A15 - A8: High byte of address PORT 2 PORT 0 ALE P3.7 P3.6 PSEN AD7 - AD0: Data and low byte address ALE: Address latch enable RD: Read strobe WR: Write strobe PSEN: Program store enable

External Program Memory


8051 PORT2 ALE AD7 - AD0 PORT0 A15 - A8 ROM(S) ADDRESS LATCH A7 - A0 D7 - D0 PSEN ADDRESS INPUTS DATA OUTPUTS OE

External Data Memory


64K byte adress space. Indirectly addressable via R0 and R1 in 256 byte segments. Entire space in indirectly addressable via the data pointer DPTR.

8051 PORT 2 ALE PORT 0 ADDRESS LATCH DECODE

RAM(S) or I/O CE ADDRESS INPUTS DATA OUTPUTS R/W OE

WR RD

Special Function Register Space


- 128 byte address space, directly addressable as 80 to FF hex. - 16 addresses are bit addressable: Set, Clear, AND, OR, MOV (those ending in 0 or 8). - This space contains: Special purpose CPU registers. I/O control registers. I/O ports.

Special Function Register Map


Bit Addressable

F8 F0 E8 E0 D8 D0 C8 C0 B8 B0 A8 A0 98 90 88 80 IP P3 IE P2 SCON P1 TCON P0 TMOD TL0 SP DPH TL1 DPL TH0 TH1 PCON SBUF PSW ACC B

Special Function Registers(1/2)


CPU registers: - ACC -B - PSW - SP - DPTR DPL). Interrupt control: -IE -IP I/O Ports: - P0 - P1 - P2 - P3 : Accumulator. : B register. : Program Status Word. : Stack Pointer. : Data Pointer (DPH,

: Interrupt Enable. : Interrupt Priority. : Port 0. : Port 1. : Port 2. : Port 3.

Special Function Registers (2/2)


TImers: - TMOD - TCON - TH0 - TL0 - TH1 - TL1 Serial I/O: - SCON - SBUF Other: - PCON : Power control & misc. : Serial port control. : Serial data registers. : Timer mode. : Timer control. : Timer 0 high byte. : Timer 0 low byte. : Timer 1 high byte. : Timer 1 low byte.

PSW : Program Status Word


CY AC
- CY

F0

RS1
: Carry Flag.

RS0

OV

----

- AC : Auxiliary Carry Flag. - F0 : Flag 0 (available for user). - RS1 : Register Select 1. - RS0 : Register Select 0. - OV : Arithmetic Overflow Flag. -P : Accumulator Parity Flag.

RS1 0 0 1 1

RSO 0 1 0 1

Register Bank 0 1 2 3

Address 00h - 07h 08h - 0Fh 10h - 17h 18h - 1Fh

I/O Ports
- Four 8-bit I/O ports. - Most have alternate functions. - Quasi-bidirectional: Soft pull-up when port latch contains a 1. Can be used as inputs (30Kohm average pullup). Strong pull-up for 2 CPU cycles during 0 to 1 transitions.

Port Configuration
CM OS
2 OSC. PERIODS
VC C VC C VC C P1 P2 P3

Q
FROM PORT LATCH
INPUT DATA

PORT PIN

NM OS
2 OSC. PERIODS

READ PORT PIN

PORT PIN

Q
FROM PORT LATCH

Counter / Timers
- Two 16-bit Counter/Timers: Up counters, can interrupt on overflow. - Counts: CPU cycles (crystal/12). External input (max. half CPU rate). - Four Operation Modes.

Timer Modes(1/2)
- Timer Mode 0 : Emulates 8048 counter/timer (13-bits). 8-bit counter (TL0 or TL1). 5-bit prescaler (TH0 or TH1). - Timer Mode 1 : Simple 16-bit counter. - Timer Mode 2 : 8-bit auto-reload. Counter in TL0 or TL1. Reload value in TH0 or TH1. Provides a periodic flag or interrupt.

Timer Modes (1/2)


- Timer Mode 3 : Splits timer 0 into two 8-bit counter/timers. First counter (TLO) acts like mode 0, without prescaler. Second counter (TH0): Counts CPU cycles. Uses TR1 (timer 1 run bit) as enable. Uses TF1 (timer 1 overflow bit) as flag. Uses Timer 1 interrupt. Timer 1 (when timer 0 is in mode 3 ): Counter stopped if in mode 3. Running in mode 0, 1, or 2. Has gate (INT1) and external input (T1), but no flag or interrupt. May be used as a baud rate generator.

Counter/Timer in 16-bit (Mode 1)


O sc.

? 2

Int errupt

TL1 TH1
T1 (Pi n) TR1 G e at
8- bits 8- bits

TF1

Cont rol

INT1 (Pi n)

The Gate input controls whether the Counter runs while gated by the interrupt signal or not.

TMOD : Counter/Timer Mode Register


GATE C/T M1 Timer 1 M0 GATE C/T M1 Timer 0 M0

- GATE : Permits INTx pin to enable/disable counter. - C/T : Set for counter operation, reset for timer operation. - M1, M0 : 00 : Emulate 8048 counter/timer (13-bits). 01 :16-bit counter/timer. 10 : 8-bit auto-reload mode 11 :Timer 0 = two 8-bit timers. Timer 1 Counting disabled. Timing function allowed. Can be used as Baud Rate generator.

TCON : Counter/Timer Control Register


TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

- TF1, TF0 : Overflow flags for Timer 1 and Timer 0. - TR1, TR0 : Run control bits for Timer 1 and Timer 0. Set to run, reset to hold. - IE1, IE0 : Edge flag for external interrupts 1 and 0. * Set by interrupt edge, cleared when interrupt is processed. - IT1, IT0 : Type bit for external interrupts. * Set for falling edge interrupts, reset for 0 level interrupts. * = not related to counter/timer operation.

Serial Interface
- Full duplex UART. - Four modes of operation: Synchronous serial I/O expansion. Asynchronous serial I/O with variable baud rate. Nine bit mode with variable baud rate. Nine bit mode with fixed baud rate. - 10 or 11 bit frames. - Interrupt driven or polled operation. - Registers: SCON - Serial port control register. SBUF - Read received data. - Write data to be transmitted. PCON - SMOD bit.

Serial Interface Modes of Operation


TXD and RXD are the serial output and input pins (Port 3, bits 1 and 0). Mode 0: Shift Register Mode. Serial data is transmitted/received on RXD. TXD outputs shift clock. Baud Rate is 1/12 of clock frequency. Mode 1: 10-bits transmitted or received. Start (0), 8 data bits (LSB first), and a stop bit (1). Baud Rate Clock is variable using Timer 1 overflow or external count input. Can go up to 104.2KHz (20MHz osc.). Mode 2: 11-bits transmitted or received. Start (0), 8 data bits (LSB first), programmable 9th bit, and stop bit (1). Baud Rate programmable to either 1/32 or 1/64 oscillator frequency (625KHz for 20MHz osc.). Mode 3: 11-bit mode. Baud Rate variable using Timer 1 overflow or external input. 104.2 KHz max. (20MHz osc.).

Multi-Drop Communication
Serial Communication Modes 2 and 3 allow one "Master" 8051 to control several "Slaves": The serial port can be programmed to generate an interrupt if the 9th data bit = 1. The TXD outputs of the slaves are tied together and to the RXD input of the master. The RXD inputs of the slaves are tied together and to the TXD ouput of the master. Each slave is assigned an address. Address bytes transmitted by the master have the 9th bit = 1. When the master transmits an address byte, all the slaves are interrupted. The slaves then check to see if they are being addressed or not. The Addressed slave can then carry out the master's commands.

SCON : Serial Control Register


SMO SM1 SM2 REN TB8 RB8 TI RI
- SM0, SM1 = Serial Mode: 00 = Mode 0 : Shift register I/O expansion. 01 = Mode 1 : 8-bit UART with variable baud rate. 10 = Mode 2 : 9-bit UART with fixed baud rate. 11 = Mode 3 : 9-bit UART with variable baud rate. - SM2 : Mode 0 : Not used. Mode 1 : 1 = Ignore bytes with no stop bit. Mode 2,3 : 0 = Set receive interrupt (RI) on all bytes. : 1 = Set RI on bytes where bit 9 = 1. - REN = Enables receiver. - TB8 = Ninth bit transmitted (in modes 2 and 3). - RB8 = Ninth bit received: Mode 0 : Not used. Mode 1 : Stop bit. Mode 2,3 : Ninth data bit. - TI = Transmit interrupt flag. - RI = Receive interrupt flag.

Interrupt System
- 5 Interrupt Sources (in order of priority): External Interrupt 0. Timer 0. External Interrupt 1. Timer 1. Serial Port. - Each interrupt type has a separate vector address. - Each interrupt type can be programmed to one of two priority levels. - External interrupts can be programmed for edge or level sensitivity.

IE : Interrupt Enable Register


EA ---- EA - ES - ET1 - EX1 - ET0 - EX0 ---ES ET1 EX1 ET0 EX0 : Global interrupt enable. : Serial interface. : Timer 1. : External interrupt 1. : Timer 0. : External interrupt 0. - 0 = Disabled. - 1 = Enabled.

Interrupt Vector Addresses


Source IE0 TF0 IE1 TF1 RI&TI Address 03H 0BH 13H 1BH 23H

The 8051 starts execution at 0000H after Reset.

IP: Interrupt Priority Register


------------PS PT1 PX1 PT0 PX0

- PS

: Serial interface.

- PT1 : Timer 1. - PX1 : External interrupt 1. - PT0 : Timer 0. - PX0 : External interrupt 0. - 0 = Low priority. - 1 = High priority.

8051 Addressing Modes


There are basically 5 ways of specifying source/destination operand addresses: 1. Particular On-chip Resources: This includes the Accumulator (A), the Stack Pointer (SP), the Data Pointer (DP), the Program Counter (PC), and the Carry (C). Other On-chip Registers are Memory-mapped while these have special Op-codes. 2. Immediate operands: The # sign is the designator. These are 8-bits except for DPTR contents (16bits). 3. Register operands: Designated as Rn, where n is 0..7. One of the four Register Banks is used (PSW selected). 4. Direct Operands: From 00 to FF Hex, specifies one of the internal data addresses. 5. Indirect Address: Designated as @Ri, where i is 0 or 1, uses the contents of R0 or R1 in the selected Register Bank to specify the address. Other form is @A, using Accumulator contents.

Instruction Set : Arithmetic


Mnemonics ADD ADDC SUBB Operands A, Rn A, direct A, @Ri A, #data INC DEC A Rn direct @Ri INC MUL DIV DA DPTR AB AB A Bytes/Cycles 1/1 2/1 1/1 2/1 1/1 1/1 2/1 1/1 1/2 1/4 1/4 1/1

Instruction Set : Logic (1/2)


Mnemonic ANL ORL XRL Operands A, Rn A, direct A, @Ri A, #data direct, A direct, #data C, bit C, /bit CLR CPL A C bit Bytes/Cycles 1/1 2/1 1/1 2/1 2/1 3/2 2/2 2/2 1/1 1/1 2/1

Instruction Set : Logic (2/2)


Mnemonic RL RLC RR RRC SWAP SETB CLR CPL 2/1 Operands A A A A A C bit Bytes/Cycles 1/1 1/1 1/1 1/1 1/1 1/1

Instruction Set : Data Transfer(1/3)


Mnemonic MOV Operands A, Rn A, direct A, @Ri A, #data Rn, A Rn , direct Rn, #data direct, A direct, Rn direct, direct direct, @Ri direct, #data Bytes/Cycles 1/1 2/1 1/1 2/1 1/1 2/2 2/1 2/1 2/2 3/2 2/2 3/2

Instruction Set : Data Transfer (2/3)


Mnemonic MOV Operands @Ri, A @Ri, direct @Ri, #data DPTR, #data16 C, bit bit, C MOVX A,@DPTR @DPTR,A A,@Ri @Ri,A Bytes/Cycles 1/1 2/2 2/1 3/2 2/1 2/2 1/2 1/2 1/2 1/2

Instruction Set : Branching(1/2)


Mnemonic LCALL ACALL RET RETI LJMP AJMP SJMP JMP JZ JNZ Operands addr16 addr11 addr16 addr11 rel @A+DPTR rel rel Bytes/Cycles 3/2 2/2 1/2 1/2 3/2 2/2 2/2 1/2 2/2 2/2

Instruction Set : Branching(2/2)


Mnemonic CJNE Operands A, direct, rel A, #data, rel Rn, #data, rel @Ri,#data,rel DJNZ Rn, rel direct, rel NOP JC JNC JB JNB JBC rel rel bit, rel bit, rel bit, rel Bytes/Cycles 3/2 3/2 3/2 3/2 2/2 3/2 1/1 2/2 2/2 3/2 3/2 3/2

Directions from the Core Product


Analog-toDigital Very Small Packages Low Power Low Voltage EPROM & OTP

Extended I/O

80C51

Memory 2 to 32 K

ASIC Cell Library Speed


Up to 30 MHz

EEPROM derivatives I2C Serial Bus

Philips/Signetics 8051 Family


Product Name 8031/51 8032/52 8XC751 8XC752 8XC31/51 8XCL410 80/3C851 8XC550 8XC451 8XC652 8XC52 8XC053/054 8XC562 8XC552 8XC654 8XC524 8XC528 Process ROM NMOS NMOS CEPROM CEPROM CEPROM SACMOS EEPROM CEPROM CEPROM CEPROM CEPROM CEPROM CEPROM CEPROM CEPROM CEPROM CEPROM 4K 8K 2K 2K 4K 4K 4K 4K 4K 8K 8K 8K/16k 8K 8K 16K 16K 32K RAM Pins 8-bit Ports Serial I/O Timers 40 40 24 28 40 40 40 40 68 40 40 42 68 68 40 40 40 4 4 2+3/8 2+5/8 4 4 4 4 7 4 4 4 6 6 4 4 4 UART UART I2C I2C UART I2C UART UART UART UART,I2C UART -UART UART,I2C UART,I2C UART, I2C UART,I2C Special 2 3 1 1 2 2 2 2 2 2 3 2 4 4 2 3 3 Industry Standard Industry Standard 24 Pin Skinny DIP 8-bit A/D,PWM 20,24, 30MHz LowVolt/Power (1.8 volts) 256 EEPROM 8-bit A/D, WD 7 I/O Ports 8K ROM, I2C Serial Bus Industry Standard TV Display (OSD), D/A 8-bit A/D, PWM, WD, T2 10-bit A/D, PWM, WD, T2 16K ROM, I2C Serial Bus 16K, 512 bytes, WD 32K ROM, 512 RAM, WD 128 256 64 64 128 128 128 128 128 256 256 192 256 256 256 512 512

Introduction to Embedded C
The Cx51 Optimizing C Compiler is a complete implementation of the American National Standards Institute (ANSI) standard for the C language The Cx51 Compiler is not a universal C compiler adapted for the 8051 target. It is a ground-up implementation, dedicated to generating extremely fast and compact code for the 8051 microprocessor

Super Loop Software Architecture


void main (void) { /* prepare for task X */ X_Init(); while(1) /* fro ever (super loop ) */ { X(); /* peform the task */ } } The super loop is required because we have no operation system to return to: our application will keep looping until the system power is removed.

Delay
void delay (int time) { int i,j; for (i=0; i<time; i++) for (j=0; j<400; j++); }

Variable Declare
xdata char PORTACFG _at_ 0x7F93; xdata char OUTA _at_ 0x7F96; xdata char OEA _at_ 0x7F9C; #define DISPLAYTIME 800 void delay (int time);

(For Loop)
main() { int i; PORTACFG = 0x00; OEA = 0xFF; while(1) { for(i = 1; i < 256; i<<=1) { OUTA = i; delay(DISPLAYTIME); } } }

:(For Loop)
for(i = 1; i < 256; i<<=1); // { OUTA = i; delay(DISPLAYTIME); } for(i = 1; i < 256; i<<=1) OUTA = i; delay(DISPLAYTIME); // OUTA=iDelay

While Loop
main() { int i; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { i = 1; while( i < 256) { OUTA = i; delay(DISPLAYTIME); i<<=1; } } }

dowhile
main() { int i; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { i = 1; do { OUTA = i; delay(DISPLAYTIME); i<<=1; }while( i < 256); } }

break
main() { int i = 1; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { i = 1; do { OUTA = i; delay(DISPLAYTIME); i<<=1; if(i==256) break; }while(1); } }

continue
main() { int i = 1; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { i = 1; do { if(i == 16){ i<<=1; continue; } OUTA = i; delay(DISPLAYTIME); i<<=1; if(i==256) break; }while(1); } }

if
main() { int i = 1; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { OUTA = i; delay(DISPLAYTIME); i<<=1; if( i == 256) i= 1; } }

If .. else
main() { int i = 1; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { OUTA = i; delay(DISPLAYTIME); if( i == 128) i= 1; else i<<=1; } }

switch
main() { int i = 1; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { OUTA = i; delay(DISPLAYTIME); switch(i) { case 1: i=2; break; case 2: i=4; break; case 4: i=8; break; default: i=1; break; } } }

Array
main() { int i; code char led[8]={1,2,4,8,16,32,64,128}; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { i = 0; do { OUTA = led[i]; delay(DISPLAYTIME); i++; }while(i<8); } }

Pointer
main() { int i=0; code char led[8]={1,2,4,8,16,32,64,128}; data char *pt; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { i=0; pt=led; while(i<8) { OUTA = *pt; delay(DISPLAYTIME); pt++; i++; } } }

%
main() { int i=0; code char led[8]={1,2,4,8,16,32,64,128}; PORTACFG = 0x00; // PA OEA = 0xFF; // while(1) { OUTA = led[i]; delay(DISPLAYTIME); i= (i+1) % 8; } }

Memory Areas
Program Memory Internal Data Memory External Data Memory Far Memory SFR Memory

Program Memory
Read only Up to 64K Bytes Using the code memory type specifier in the Cx51 Compiler.

Internal Data Memory


Within the 8051 CPU Read/write. Access very fast limited to 256 bytes.

Three Memory Types


The data memory specifier
First 128 bytes Direct addressing

The idata memory specifier


All 256 bytes Indirect addressing is slower than direct addressing

The bdata memory specifier


The 16 bytes of bit-addressable memory in Internal data area (20h to 2Fh)

External Data Memory


Read/write. On-chip XRAM space (several 8051) Up to 64K Bytes Memory-mapped I/O.

Two Memory Types


The xdata memory specifier
64K Byte (external data memory) Large memory model

The pdata memory type specifier


exactly one (1) page (256 bytes) of external data memory Compact memory model

Far Memory
refers to the extended address space of many new 8051 variants. uses generic 3-byte pointers to access extended memory spaces. Two Cx51 memory types
far extended RAM space const far - constants in extended ROM space

SFR Memory
128 bytes bit, byte, or word-sized registers used to control timers, counters, serial I/O, port I/O, and peripherals Three data types
sfr sfr16 sbit

sfr
SFRs are declared in the same fashion as other C variables. The only difference is that the data type specified is sfr rather than char or int. For example:
sfr P0 = 0x80; /* Port-0, address 80h */ sfr P1 = 0x90; /* Port-1, address 90h */ sfr P2 = 0xA0; /* Port-2, address 0A0h */ sfr P3 = 0xB0; /* Port-3, address 0B0h */

Sfr and ports


For example, we can send data to Port1 as follow:
unsigned char Port_data; Port_data = 0x0f; /* Port 1, address 90h */ . P1 = Port_data; /* write 00001111 to Port1 */

For example, we can read from Port 1 as follow:


unsigned char Port_data; P1 = 0xff; /* set the port to read mode */ Port_data = P1; /* read from the port */ .

sfr16
Many 8051 derivatives use two SFRs with consecutive addresses to specify 16-bit values. For example:
sfr16 T2 = 0xCC; /* Timer 2: T2L 0CCh, T2H 0CDh */ sfr16 RCAP2 = 0xCA; /* RCAP2L 0CAh, RCAP2H 0CBh */

sbit
With typical 8051 applications, it is often necessary to access individual bits within an SFR. The Cx51 Compiler makes this possible with the sbit data type which provides access to bitaddressable SFRs and other bit-addressable objects. For example: sbit EA = 0xAF;

Bitwise operator
Operator
& | ^ << >> ~

Description
Bitwiae AND Bitwise OR (inclusive OR) Bitwise XOR(exclusive OR) Left shift Right shift One`s complement

A 0 0 1 1

B 0 1 0 1

A AND B 0 0 0 1

A OR B 0 1 1 1

A XOR B 0 1 1 0

Variant 1: sfr_name ^ int_constant


This variant uses a previously declared sfr (sfr_name) as the base address for the sbit. The bit position must be a number in the 0-7 range. For example:
sfr PSW = 0xD0; sfr IE = 0xA8; sbit OV = PSW^2; sbit CY = PSW^7; sbit EA = IE^7;

Variant 2: int_constant ^ int_constant


This variant uses an integer constant as the base address for the sbit. For example:
sbit OV = 0xD0^2; sbit CY = 0xD0^7; sbit EA = 0xA8^7;

Variant 3: int_constant
This variant uses an absolute bit address for the sbit. For example:
sbit OV = 0xD2; sbit CY = 0xD7; sbit EA = 0xAF;

Memory Models
The C51 Compiler provides three memory models:
Small Model Compact Model Large Model

Small Model
In this model, all variables, by default, reside in the internal data memory of the 8051 system as if they were declared explicitly using the data memory type specifier.

Compact Model
Using the compact model, by default, all variables reside in a single page of external data memory of the 8051 systemas if they were explicitly declared using the pdata memory type specifier.

Large Model
In the large model, all variables, by default, reside in external data memory (which may be up to 64K Bytes). This is the same as if they were explicitly declared using the xdata memory type specifier.

Memory Types
Explicit Memory Types Implicit Memory Types

Explicit Memory Types

Data Types

Bit Types
The Cx51 Compiler provides a bit data type that may be used for variable declarations, argument lists, and function-return values. For example:
static bit done_flag = 0; /* bit variable */ bit testfunc ( /* bit function */ bit flag1, /* bit arguments */ bit flag2) { . . . return (0); /* bit return value */ }

Absolute Variable Location


Variables may be located at absolute memory locations in your C program source modules using the _at_ keyword. The usage for this feature is:
[memory_space] type variable_name _at_ constant;

Using the _at_ keyword


struct link { struct link idata *next; char code *test; }; struct link list idata _at_ 0x40; /* list at idata 0x40 */ char xdata text[256] _at_ 0xE000; /* array at xdata 0xE000 */ int xdata i1 _at_ 0x8000; /* int at xdata 0x8000 */ volatile char xdata IO _at_ 0xFFE8; /* xdata I/O port at 0xFFE8 */ void main ( void ){ link.next = (void *) 0; i1 = 0x1234; text [0] = 'a'; IO = 6; }

Pointers
Generic Pointers Memory-Specific Pointers

Generic Pointers
Generic pointers are declared like standard C pointers. For example:
char *s; /* string ptr */ int *numptr; /* int ptr */ long *state; /* Texas */

Memory-Specific Pointers
Memory-specific pointers always include a memory type specification in the pointer declaration and always refer to a specific memory area. For example:
char data *str; /* ptr to string in data */ int xdata *numtab; /* ptr to int(s) in xdata */ long code *powtab; /* ptr to long(s) in code */

Function Declarations
The C51 Compiler provides a number of extensions for standard C function declarations. return_type funcname ( args ) {small | compact | large} reentrant interrupt x using y

interrupt number

register bank number

Parameters and Registers

Return Values

Interrupt Functions

For example

Reentrant Functions
A reentrant function may be shared by several processes at the same time. When a reentrant function is executing, another process can interrupt the execution and then begin to execute that same reentrant function.

Preprocessor
Directives Stringize Token Pasting Predefined Macro Constants

Directives
Preprocessor directives must be the first nonwhitespace text specified on a line. All directives are prefixed with the pound or numbersign character ('#'). For example:
#pragma #include <stdio.h> #define DEBUG 1

Stringize
The stringize or number-sign operator ('#'), when used within a macro definition, converts a macro parameter into a string constant. For example:
#define stringer(x) printf (#x "\n")
stringer (text)

Token Pasting
The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example:
#define paster(n) printf ("token" #n " = %d", token##n) paster (9);

printf ("token9 = %d", token9);

Predefined Macro Constants

Interfacing C to Assembler - Global Variables


C
unsigned int bob; unsigned char jim;

ASM
EXTERN DATA(jim) MOV A,jim

Small Model Example

Examples

8051 /INT0 External Interrupt Example Program(1/2)


#include <REG52.H> unsigned char ex0_isr_counter = 0; void ex0_isr (void) interrupt 0 { ex0_isr_counter++; // Increment the count }

8051 /INT0 External Interrupt Example Program(2/2) void main (void) { IT0 = 1; // Configure interrupt 0 for falling edge on /INT0 (P3.2) EX0 = 1; // Enable EX0 Interrupt EA = 1; // Enable Global Interrupt Flag while (1) { } }

8051 Bit I/O Example Program


sfr P1 = 0x90; /* SFR for P1 */ sbit P1_0 = P1^0; /* SFR for P1.0 */ sbit P1_1 = P1^1; /* SFR for P1.1 */ void main (void) { P1_0 = 1; /* Configure P1.0 as an input */ while (1) { P1_1 = P1_0; /* Copy P1.0 to P1.1 */ } }

#include <reg52.h> #include <stdio.h> void main (void) {/*Set serial port for 9600 baud at 11.0592 MHz. Note that we use Timer 1 for the baud rate generator.*/ SCON = 0x50; TMOD |= 0x20; TH1 = 0xFA; TR1 = 1; TI = 1; PCON |= 0x80;

8051 Counter 0 Example Program(1/2)

printf ("\r\nCounter 0 Example Program\r\n"); printf ("\r\nStart toggling P3.4 (T0 input)\r\n\r\n"); /*Set Timer0 for 16-bit counter mode. Set the Timer0 Run control bit.*/ TMOD = (TMOD & 0xF0) | 0x05; TR0 = 1; /*Output the value of the counter. As you toggle P3.4, the timer/counter 0 value will increase. */ while (1) { printf ("\rCounter 0 = %2.2bX%2.2bXh", TH0, TL0); }}

8051 Counter 0 Example Program (2/2)

#include <string.h> memcpy function

8051 Memory Write Example Program (1/2)

// Include prototypes for

unsigned char idata idata_buffer [16] _at_ 0xB0; unsigned char data data_buffer [16] _at_ 0x60; unsigned char pdata pdata_buffer [16] _at_ 0xFF60; unsigned char xdata xdata_buffer [16] _at_ 0x0200;

8051 Memory Write Example Program (2/2)


void main (void){ memcpy (idata_buffer, "IDATA Buffer....", sizeof (idata_buffer)); memcpy (data_buffer, "DATA Buffer......", sizeof (data_buffer)); memcpy (pdata_buffer, "PDATA Buffer -NEVER USE :-)", sizeof (pdata_buffer)); memcpy (xdata_buffer, "XDATA Buffer....", sizeof (xdata_buffer)); while (1);}

8051 Port I/O Example Program


sfr P1 = 0x90; /* SFR definition for Port 1 */ sfr P3 = 0xB0; /* SFR definition for Port 3 */ void main (void){ unsigned char pval; /* temp variable for port values */ P1 = 0xFF; /* Setup P1 for Input */ while (1) { pval = P1; /* Read P1 into pval */ P3 = pval; /* Write pval to P3 */ }}

8051 Pulse Width Measurement Example(1/4)


#include <reg52.h> #include <stdio.h> unsigned int T0_ISR_count = 0; void T0_ISR (void) interrupt 1 { T0_ISR_count++; TF0 = 0; // Reset the interrupt request }

8051 Pulse Width Measurement Example (2/4)


void main (void){ /*Set serial port for 9600 baud at 11.0592 MHz. Note that we use Timer 1 for the baud rate generator. */ SCON = 0x50; TMOD |= 0x20; TH1 = 0xFA; TR1 = 1; TI = 1; PCON |= 0x80; printf ("\nPulse Width Example Program\n\n");

8051 Pulse Width Measurement Example (3/4)


/*Enable interrupts for timer 0*/ ET0 = 1; EA = 1; /*Set Timer0 for 16-bit interval timer mode*/ TMOD = (TMOD & 0xF0) | 0x09; while (1) { T0_ISR_count = 0; TH0 = 0; TL0 = 0; TR0 = 1; printf ("\nStart a pulse.\n");

8051 Pulse Width Measurement Example (4/4)


/* Wait for the pulse to start. Then, wait for the pulse to end. */ while (!INT0); while (INT0); /* Compute the width of the pulse one clock cycle is 1us for a standard 8051 and display it. */ printf ("The width pulse is: %ld uSec\n", (unsigned long)((TH0 << 8) | TL0 | ((unsigned long)T0_ISR_count << 16))); }}

Potrebbero piacerti anche