Sei sulla pagina 1di 14

RD2 Kit – C programming

RD2 Kit
Would you like to learn how to program the x51 and other
microcontrollers in the C language? RD2 Kit with 40 just
solved examples will help you for sure.

Start programming using the C language

One can use a lot of platforms for C programming. We have prepared the RD2 KIT for two of them: SDCC and
Keil. This Kit can help you to migrate from asm code to the C language.

Why is RD2 Kit different than others?

• Simple, cheap and easily obtainable HW.


• The micro used in the RD2 Kit is suitable for C programming.
• There are at least 40 examples demonstrating the basic principles of C programming of MCU’s
• All of the examples are made for Keil and SDCC compiler, which is availablefree of charge.
• The applications can be used with other compilers as well.
• There is a description of differences between the C compilers included.

If you are interested in our RD2 Kit, you can either build it yourself or order it from HW server.

RD2 Kit 1 / 14 www.HW.cz


RD2 Kit – C programming

40 solved examples in KEIL C and SDCC


To help you understand and study basic principles of developing circuits based on MCU applications with 8051,
there are several solved examples in C language. The examples are designed for the development kit and for
compiling with Keil C51 evaluation version and free SDCC. You should use ISP programming method to program
the RD2 MCU. There is no need to use extra hardware for programming. Everything needed is on the board of
the RD2 Kit.

There are also HEX files of the examples which were already prepared from the source codes which you can use
directly to program your RD2 Kit using the Flasher or the original FLIPprogram.

The examples are grouped by topic:

Basic programming in C for 89C51RD2:


- description of the compiling of a simple program in C language, programming the MCU using ISP

Serial Channel
- setting the 8-bit serial communication, functions for writing and reading data from the serial channel
- using standard functions of the C language: formatted input output
- easy calculator

LCD display 2 x 16 using 4-bit communication protocol


- setting up the 4-bit communication mode, LCD read/write functions
- user defined characters, text shifting and animation
- sending of the instructions to LCD
- redirecting of the standard input/output to the LCD and serial channel

Matrix keyboard 4 x 3
- function for reading, diagnostics with the output to the serial channel
- sharing of the data bus by LCD and keyboard

Interrupt system
- T2 Timer with 16-bit preloading, accessing LED in the interrupt routine
- Real Time Clock using T2 timer
- External interrupt service INT0

Watchdog Timer
- Watchdog Timer manipulation and using Watchdog in Applications
- controlled reset by the Watchdog

Timer Based Programmable Array PCA, Timer T2


- 8-bit Pulse Width Modulation
- Measuring the Pulse Length
- Programmable Pulse Generator

RD2 Kit 2 / 14 www.HW.cz


RD2 Kit – C programming

Program Flash Memory


- checking the integrity of the program code using check sum
- Calling API functions of the user defined loader for working with the FLASH
- Accessing the XAF memory (eXtra Array Flash)

EEPROM Memory
- EEPROM Memory access, reading/writing EEPROM using Serial Channel

External XRAM Data Memory


- setting up the capacity of the XRAM
- testing memory parts and accessing the XRAM using Serial Channel

Special Processor Function


- switching off the generation of the ALE signal
- Idle Mode, Power-Down Mode
- X2-Mode switching

MCU Diagnostics
- diagnostics of each block

Intermediate usage of the development tools


- Assembler instructions in C language
- compiling to user defined addresses

RD2 Kit 3 / 14 www.HW.cz


RD2 Kit – C programming

Serial Channel

Example 1.1
Create a program for communicating using the serial channel with parameters 19200, N, 8, 1. Write your own
functions for writing and reading. Test the functionality by sending a string, which is terminated by the character
00h. Also create a terminal emulation (echoes pressed char.).

Serial channel is set to mode 1, - 8bit UART. You can change the baud rate by setting the overflow value of the
timer T1 and the value of SMOD bit in the PCON register. T1 works in mode 2 with preset. The baud rate is
calculated using following equation:

2 SMOD FOSC
Baudrate = ⋅ (1)
32 12 ⋅ [256 − TH 1]
Calculating the baud rate value is automatic using a macro without parameters (defined command)
Timer1Mode1ReloadValue. The value of 9200b is used in the following examples.

There is no interrupt used for the serial channel service. Sending-receiving of data is done by subroutines called
(ser_putch(), ser_puts()), (ser_getch()).

Linking the whole program is exactly the same as in the first demo program. You can use any serial Terminal to
communicate with the Kit. It must be set to 19200, N, 8, 1. In case you are controlling the PSEN by program for
ISP programming, the terminal must not control the RTS signal, otherwise the loader might be started.

Example 1.2
Replace your own functions from example 1.1 with the standard functions of C language for formatted
input/output. Use printf() function and display numerical value of the numbers, defined as unsigned char, long and
int. Use as many methods as possible. Use different types of formatting string.

We are using functions for input/output which are reading integer number as a string and automatically converting
it to the numerical value (scanf works in the opposite way).

Using standard Input/output functions is exactly the same as in programming on PC. There is implicitly suggested
usage of serial channel. There are some differences in the formatting strings, which are optimized to the x51
platform.

If you are using printf() function in SDCC you have to write your own putchar() function. (see example 2.4.)

Example 1.3
Write a program of a simple calculator which can perform +,-,/,* operations with integers. Input/output of data can
be done as you want.
Some of the standard functions known from the C language are not implemented on x51 platform so we have to
use some alternative solutions. The program of the calculator reads two numbers and then the symbol of the
mathematic operation. You can use for instance the scanf() function for reading numbers, which can be replaced
by sscanf() or atoi(). To display the result through serial channel, we use the functions created in previous
examples.

RD2 Kit 4 / 14 www.HW.cz


RD2 Kit – C programming

LCD display 2 x 16 characters in 4-bit communication mode

Example 2.1
Make a program for controlling the 2 x 16 character LCD display in 4 - bit communication mode. Pay attention to
correct initialization of the LCD and the control of the BUSY signal by the program. Write functions for sending
instructions and characters to the LCD's controller. Test the functionality of the program by sending string ending
with a 00h character to the LCD.

When using the 4 - bit communication mode, four wires are saved. On the other side, the communication protocol
is much more complicated. Display is connected to the P1 port and it uses all the pins except P1.3. P1.3 is free
and can be used as a general I/O pin.

The LCD has an HD44780 compatible controller. There are three necessary basic functions, which are at the core
of our API interface. It is the initialization of the LCD in 4 - bit mode, sending of the data to the LCD's controller
and checking the BUSY signal. Detailed description of the functions is not a part of this text. You can find it in the
datasheet of the HD44780 controller.

In several cases, there was a problem with initialization of the display after power up. The problem was solved
using the PowerOnReset() function described in example 5.2.

Example 2.2
Enhance the example 2.1. Write a function that can be used for loading user defined character sets. Write a
function for continuous text shifting. Make a simple animation using your user defined character set.

You can set up first eight characters in the character set so you can make special effects, graphic symbols,
special characters or animations. The used matrix and settings allow you to use 5x7 or 5x10 point raster.

Definitions of the characters are stored in the program code memory. It contains 64 bytes. A character is defined
by 8 bytes which are stored in the CGRAM memory one by one.

The animation consists of shifting. Suitably defined character set is shifted on the LCD from the right to the left.

Example 2.3
Display the table of instructions for controlling the display using serial channel. User should control the display by
sending instructions through the serial channel.

The program demonstrates the usage of the API interface. The instructions are displayed on the screen and the
user can easily test them and see what the instructions do.

Example 2.4
Write your own putchar() function for sending the characters to the LCD display. Create an algorithm which can
redirect the standard output (printf()) to the serial channel or to the LCD display. Test the functionality using the
printf() function.

Function printf() creates the string according to the definition string and displays the created string using the
putchar() function. Printf() implicitly uses the serial channel. In case that we have created a new putchar() function
we can redirect the output to the different device. The putchar() must be declared exactly the same way as the
original function declared in stdio.h file. There is a global variable used for defining the output device.

RD2 Kit 5 / 14 www.HW.cz


RD2 Kit – C programming

Matrix Keyboard with 4 x 3 keys

Example 3.1
Make a program for reading a matrix keyboard with 4 x 3 keys. Test the functionality by pressing all the keys one
by one and display the value of each key using the serial channel.

Matrix keyboard is connected using seven wires. The columns are connected to the port P3.5-P3.7. The lines are
read from the port P1.4-P1.7. The columns are selected by pulling the pin (P3.5 - P3.7) low. Then, the program
reads the row inputs (P1.4-P1.7). If there was a key pressed, the corresponding pin is low. After reading the input,
next column is selected. This algorithm reads only the first pressed key. The value of the key is sent to the serial
port and displayed on the screen.

Example 3.2
Connect the rows to the Data bus used by the LCD display. Write a key-lock program with display to test the
functionality. (The user can insert a new cone).

In some applications, we are limited by the number of I/O pins of the controller. We can make following solution:
Data for LCD on the bus are valid if there is an ENABLE signal set to high. Otherwise, the bus is free and we can
use it to read data from the keyboard. The keyboard functions are enhanced with an instruction that sets the
Enable signal low if the data are read from the keyboard and the bus is not used to communicate with the LCD. If
the program is not reading from the Keyboard, all the column pins (P3.5-P3.7) are set to high. Then, the user
cannot make an error on the bus while the communicating with the LCD.

Interrupt system

Example 4.1
Write a program, which can service the interrupt of the T2 timer with a 16 - bit preload value. Set the period of
blinking with a led to 2000ms . Use the P2.0 pin as an input for increasing the period of blinking (0=increase).

T2 interrupt is recognized by setting up the TF2 bit. If there is an interrupt recognized on T2 the timer is
automatically preloaded with the preload value. The function of the T2 is independent on the program. The
preload value can be calculated using following formula:
FOSC ⋅ t
[TH 2, TL2] = 10000h − (2)
12
where t is the time in seconds, FOSC is the frequency of the crystal.

Interrupts are defined in the C language using the attribute interrupt with the interrupt number. The keyword using
selects the bank of the registers. The definition for T2 Timer follows:

static void Reload_Timer2_ISR(void) interrupt 5 using 3


{ LD1 = ~LD1; // toggle LED every 1000 ms
TF2 = 0; // clear timer 2 overflow flag
}

RD2 Kit 6 / 14 www.HW.cz


RD2 Kit – C programming

Example 4.2
Create a program of real time clock by using example 4.1. The clock output is in format HH:MM:SS and displayed
on LCD or using serial channel.

The clock accuracy depends on the time between the interrupts. The interrupt routine must be as short as
possible. It means that only several instructions are used inside the routine. Displaying the time is in the main part
of the program.

Example 4.3
Connect a button to the INT0 pin. (External interrupt pin). Make a detection of the falling edge. Display the routine
processing by changing the value of the LED.

External interrupts /INT0 and /INT1 are sensitive to low or the falling edge on the corresponding pins of the
controller. The interrupt routine is similar to the example 4.1. There are some difficulties in implementing external
interrupts. The detected value must be longer than specified in the controller datasheet. Otherwise, the detection
may not work properly.

Watchdog Timer

Example 5.1
Create a program which uses the watchdog timer. Simulate the inputs of a real application by typing the keys in
the serial terminal. If the key is pressed, the watchdog timer is reset. When no key is pressed during a period of
time, the whole controller is reset.

The watchdog timer is used to control the operation of applications. Whenever this timer overflows, the controller
is reset. The watchdog is set by writing the 1Eh and E1h values to the WDTRST register. The WDT is reset by
writing the same values to the WDTRST register. The value of WDT is incremented. You can use another counter
in WDTPRG register to increase the time of incrementation.

Example 5.2
Write a program which can read the information in the PCON register. Recognize the Power-Off bit and decide if
the controller has been switched on by Reset (using external button) or Power On. Use WDT to program a
controlled reset of the controller.

The value of the Power-Off bit is set up after switching on the power supply to the value=1. It does not depend on
resetting the controller by the external button.

RD2 Kit 7 / 14 www.HW.cz


RD2 Kit – C programming

Program Counter Array (PCA), Timer T2

Example 6.1
Create a program which uses the PCA for 8-bit Pulse Width Modulation (PWM). Set the PWM output to the P1.3
(LED diode). Change the modulation width and see the result using LED (its brightness changes).
PCA is made by 16 - bit Counter/Timer and five 16-bit comparators or latches. You can use each of them as a 16
- bit comparator (PWM, quick output mode, 16-bit timer) or a 16-bit latch (measuring pulse length).
We have to set the right module to the comparison mode. PWM works as an 8-bit counter with preset. The
register CCAPLn is loaded from CCAPHn after each overflow. You can easily change the pulse width by
changing the CCAPHn register value.

Example 6.2
Write a program which uses PCA for measuring the pulse length. Use the temperature sensor SMT160 - 30 as a
pulse generator. Use the correct numerical formula to measure the temperature and display the value using the
LCD display.

You can easily set the latch mode interrupt, which is generated by changing the signal input value. You should
decide which type of change is the right for generating the interrupt signal. The values of the CH and CL counter
registers are written to the CCAPnH and CCAPnL registers in the same time as the interrupt is generated.

The Temperature sensor SMT160 - 30 is connected to the PCA module 0. The values of CCAP0H and CAP0L
are written to the prepared structure, which describes the pulse. The temperature is calculated using the
measured values and using following formula:
1446 ⋅ T1 − 681 ⋅ T0
t [° C] t = (3)
T1 + T0
T1 is a high and T0 is a low.
After that, the calculated value is displayed on the LCD.

Example 6.3
Write a program which uses the T2 Timer to generate pulses on the P1.0 output. Read the signal frequency using
the serial channel. Display current read and generated value on the LCD. Discuss the differences between the
values.

You have to switch the mode of T2 Timer to the 16-bit preload counter. The frequency is calculated using the
following formula (4):
FOSC
FOUT = (4)
4 ⋅ [65536 − [ RCAP 2 H , RCAP 2 L]]
Fill in the frequency into the formula and calculate the values of the RCAP2H and RCAP2L registers. There is an
error in calculating higher frequencies due to rounding of the calculated result. It means that there might be a
differences between the real frequency and the expected one.

RD2 Kit 8 / 14 www.HW.cz


RD2 Kit – C programming

Example 6.4
Timer/Counter T0, T2 - Measuring the frequency
Write a program which uses T0 Counter for counting the external pulses connected to P3.4. Use the T2 Timer as
a pulse generator with output at P1.0. The output pin P1.0 is connected to the input pin P3.4. Calculate the
frequency, the period of the measured signal and display the values using the serial port. The maximum
frequency you should connect to the P3.4 is 1/24 of the oscilator frequency. Make the measurement for
frequencies from 100Hz up to 750kHz.

Example 6.5
Program Counter Array, Timer T2 - period measurement

Create a program which uses PCA for measuring pulse lengths. Use the T2 Timer as a pulse generator with
output at P1.0 as in the previous example. Connect the generated frequency to the PCA input P1.3. Calculate the
frequency, the period of the measured signal and display the values using serial port. Make the measurement for
frequencies from 100Hz up to 10kHz.

Example 6.6
Interrupt system - Alarm
Create a program which sets four outputs after predefined time period for each output. Use the real clock timer as
in the example 4.2. Use the Real clock timer as a base timer of the application. The time settings mode is
activated by the "*" key and each alarm setting is activated by the "#" key and the number of the alarm (0 .. 3).
Display the actual value of the outputs using LCD.

Example 6.7
Timer/Counter T0, T2 - Measuring the frequency
Write a program which uses the T0 Counter for counting the external pulses connected to P3.4. Use theT2 Timer
as a pulse generator with output at P1.0. The output pin P1.0 is connected to the input pin P3.4. Calculate the
frequency, the period of the measured signal and display the values using serial port. The maximum frequency
you should connect to the P3.4 is 1/24 of the oscilator frequency. Make the measurement for frequencies from
100Hz up to 750kHz.

Example 6.8
Program Counter Array, Timer T2 - period measurement
Write a program which uses PCA for measuring the pulse length. Use the T2 Timer as a pulse generator with
output at P1.0 as in the previous example. Connect the generated frequency to the PCA input P1.3. Calculate the
frequency, the period of the measured signal and display the values using serial port. Make the measurement for
frequencies from 100Hz up to 10kHz.

RD2 Kit 9 / 14 www.HW.cz


RD2 Kit – C programming

FLASH Program Memory

Example 7.1
Write a program which checks the code integrity using check sum calculation of the continuous Flash Ram
Memory block. Use the function of RD2 - Flasher with parameter -s. The check sum algorithm is exactly the same
as in the Intel - HEX file. Use the Code Memory pointer for reading the Flash Memory.

You can use the RD2 - flasher program for calculating the check sum of the continuous Flash Ram Memory. The
result is stored directly after the last address of the calculated block. The Ram content is correct if the sum of all
bytes in the controlled block plus check sum is equal to zero.

There is an optimalization in C language for 8051 platforms for working with pointers. The programmer can select
the memory where the pointer is stored and the memory where is pointer really pointing. The definition of the
pointer stored in the internal memory and pointing to the program memory is defined as follows:

Keil C51 unsigned char code *data ptr;


SDCC code unsigned char *data ptr;

Example 7.2
Write a program for communication with the FLASH memory loader using the API interface. Display all the
accessible information, such as the Manufacturer ID, ID1, ID2, ... using serial port.

API interface is described in more details in the T89c51RD2 datasheet on pages 61 to 63. If you want to use API
functions, you have to fill in the R1, DPH, DPL, ACC registers and call the function at the address FFF0h. It was
necessary to write the parameter passing solution in assembler. This program is linked and called from the main
part of the program in C language.

The conversion and passing of parameters is different in the different development kits. We have used the
following trick: We wrote a C function which has an input and output parameters exactly the same as the planned
function in asm language. Then, we have compiled the C function, and the result is the C function in asm code.
That's it. Now we can add the asm code to the compiled C function as we need.

Example 7.3
Write a program which accesses directly the XAF Memory (eXtra Array Flash). Display the accessible information
using the serial channel as in the previous example 7.2.
The capacity of XAF memory is 128 B and it is totally separated from the Program Memory. XAF contains the
information which is used during ISP mode of programming. This information can be read by calling an API
function of the loader (as in example 7.2) or by accessing the FLASH Memory directly. Reading and writing is
controlled by the FCON register. The address of the information in XAF memory is specified in the T89c51RD2
datasheet on pages 68 and 69.

RD2 Kit 10 / 14 www.HW.cz


RD2 Kit – C programming

EEPROM Memory

Example 8.1
Write a program which works with the integrated EEPROM Memory. Write a function for reading and writing data
to the EEPROM memory. Display the data which EEPROM contains using serial port and a simple memory
browser.
Integrated EEPROM memory is accessible from 0000h to 07FFh and overlaps with the external XRAM memory.
The EEPROM is selected with the EEE bit in EECON register. Then, you can access the EEPROM using the
MOVX instruction. The timing of the internal EEPROM operations is controlled by EETIM and it depends on the
used crystal. The data are written to the memory byte by byte if they are in one page, or the entire page (64B) can
be written. The writing operation is started after storing the 50h and A0h values into the EECON register. The
signal EEBUSY is set to one after the operation of writing ends.

Comment: The errata sheet of T89c51RD2 says, that the writing process must be at least three times longer.
Only then are the data stored in the EEPROM memory reliably.

External Data Memory XRAM

Example 9.1
Create a program which works with the internal on-chip XRAM memory. Set the real size of the accessible XRAM
memory. Test each memory byte and address decoder wires. Display the data contained in the XRAM using
serial port and a simple memory browser.

The capacity of the on-chip XRAM memory is 1024 B. However, only 768 bytes are usable after switching on or
resetting the controller, ( due to compatibility with T87c51RD2. You can set the capacity in the AUXR register to
1024 B. The memory can be tested by writing and reading the values AAh and 55h. The access is available
through the XBYTE macro, which is used for writing and reading each byte of XRAM. You can use also similar
macros (CBYTE, DBYTE, PBYTE, XWORD, …) for accessing other memories.

RD2 Kit 11 / 14 www.HW.cz


RD2 Kit – C programming

Special Processor Functions

Example 10.1
Create a program which can switch the generating of the ALE signal on/off.

The controller contains control signals ALE and /PSEN for controlling external memory (ALE for writing the low
part of the address A0 - A7, /PSEN for reading from external data memory), /RD and /WR (for reading and writing
to/from the external data memory). The signal ALE is automaticaly generated with frequency FOSC/6. The
generation does not depend on the actual presence of the external memory. You can switch the generating of the
ALE on or off signal using the AO bit in the AUXR register. Switching it off should reduce generated noise. ALE is
then generated only when the instructions MOVX and MOVC are processed.

Example 10.2
Create a program which uses reduced power modes (Idle Mode, Power - Down Mode). Display the actual mode
using LED P1.3. (If the led is on, the program is running). Activate the reduced power mode whenever the P2.0
input is driven low.. End the r. p. mode upon pressing the button connected to /INT0 pin.

You should use the reduced power mode in applications which do not have to run all the time. T89c51RD2
contains two power down modes (Idle Mode, Power - Down Mode). The control of the modes is performed using
special bits in the PCON register. The last processed instruction before power down is the instruction which sets
the special bit in PCON and activates the Reduced Power mode. This mode ends upon incoming interrupt from
input /INT0.

Example 10.3
Write a program that services the routine of T2 interrupt with 16 - bit preload. Set the blinking period to 2000ms.
Use the P2.0 input for switching the clock multiplier (X2 - Mode ... log 0 ... increasing the period).

The settings of T2 Timer are described in example 4.1. Switching of the clock multiplier is made by the X2 bit in
the CKCON register. You should set the number of periods (6 or 12) for each peripheral for one machine cycle.

RD2 Kit 12 / 14 www.HW.cz


RD2 Kit – C programming

RD2 Kit Diagnostics

Example 11.1
Write a program which tests the functionality of each block and peripheral

Take care of following tests:

- Serial channel - reading and writing of data,


- LED connected to P1.3 output,
- Code integrity secured by check sum,
- External interrupt INT0 with button,
- LCD display 2 x 16 characters in 4 - bit mode of communication,
- Matrix keyboard 4 x 3 keys.

The listed blocks are described in detail in the previous examples. This example reminds you of some parts of the
topic and helps you make some conclusions. You can write the test routines, too and you can use them later. This
application is very useful if you are looking for a faulty part of your controller.

Intermediate usage of development tools

Example 12.1
Write a program which calculates the parity of one byte number read from serial channel. Use the parity flagfor
parity checking. If there is an odd number of ones in the accumulator, the parity is set to one. Program the usage
of accumulator in assembler code and put this code into the main function of the C language.

Keil C51
Select the source code main.c in the Project window, press the right button and select the Options
for file main.c. The displayed window contains unchecked checkboxes Generate Assembler SRC file
and Assemble SRC file. It is necessary to check these checkboxes, otherwise the program
containing the asm code is not compiled. The asm code is closed in following brackets:
#pragma asm

The asm source code

#pragma endasm
It's necessary to write all names of used libraries. You can do this in Project window where you can
insert the libraries from /C51/LIB folder. In our case, we have to enter the C51S.LIB library.

SDCC
It's very easy to put the asm code into SDCC source code. There are no modifications necessary for
compiling the source including the asm code. Just insert the asm code into following brackets and
That's it:

_asm

The asm source code

_endasm; // It's necessary to put ; at the end

Be careful if you are using asm instructions in C language. The asm code might totally change the
behaviour of the whole application so you should know what the asm code exactly does. There might
be fatal bugs in your program.

RD2 Kit 13 / 14 www.HW.cz


RD2 Kit – C programming

Example 12.2
Write a program which displays a string using serial channel. Pay attention to the Linker part of compiling the
program where the linker adds the real addresses to the relative code. Try to set the beginning address of the
program, the address where the strings are stored and so on.

Keil C51
BL511 Linker gives you full control over the linking of the program. You can specify the addresses
for each function, module, etc. Put the function (module) names with the starting addresses into
the menu Project → Options for Target …→ BL51 Locate field CODE. You have to put only
addresses, which are written, in .M51 file (symbol table). For instance we can force the beginning
of the function ser_init() to the address 900h as follows:
?PR?SER_INIT?MAIN(0900h).

SDCC
You can specify only the starting address of the program in SDCC. It's accomplished by sending
parameters --code-loc with starting address to the linker.

Conclusion
The source codes of described applications are available on the RD2 Kit CD, which is available separately in the
internet HW shop.

The CD contains also the serial code which can be used to access the database of source codes and other
examples for RD2 Kit.

Other information about this topic is available on following web sites:

- www.HW.cz - HW server : RD2 Kit developer and producer, whole project site
- www.keil.com - Keil µVision2 developer and producer, you can use the demo version for compiling
the examples
- sdcc.sourceforge.net – The home page of the SDCC project

Team of authors from the HW server

RD2 Kit 14 / 14 www.HW.cz

Potrebbero piacerti anche