Embedded C Programming with 8051: Three Keil C51 Programs You Can Build and Check
Embedded c programming with 8051
Why does LED = 0 turn an LED on? Why does a timer configured for 50 milliseconds produce a blink that takes one second? And why does a program that compiles successfully sometimes print unreadable characters?
These are three useful questions to start Embedded C programming with 8051. Each connects a line of C to something you can see on the board. The first depends on the circuit, the second on how you count timer events, and the third on the clock that drives the serial port.
To program an 8051 in C, select the exact chip in an 8051-compatible toolchain, include its register definitions, configure the required peripheral, build a HEX file and run it in a simulator or on a programmed board. In this tutorial, you will use an AT89S52, Keil C51 and an 11.0592 MHz crystal. You will read a button, generate a timed LED output and control the LED from a serial terminal. The AT89S52 provides GPIO, hardware timers and a full-duplex UART for these exercises. microchip.com
What you will build
Program | What you do | What you should observe | What the result proves |
1. Button-controlled LED | Press and release a button connected to P1.1. | The LED on P1.0 lights while the button is held. | Your program runs, the pin mapping is correct and you understand active-low logic. |
2. Timer 0 interrupt blink | Let the board run without pressing anything. | The LED changes state about every half second. | The clock, timer configuration and interrupt path work together. |
3. UART-controlled LED | Send 1, 0 or ? from a terminal. | The board changes or reports its LED state and replies over serial. | Both UART directions work and received data controls a physical output. |
Each program is a separate main.c. Build and run them individually. The examples and expected results are worked teaching examples. They were not compiled in Keil or measured on a physical board for this article.
1. Choose the exact 8051 chip before writing code
“8051” names a family. A tutorial written for one family member can use a timer, clock setting or peripheral that behaves differently on another. Even an LED example can appear reversed if two development boards wire their LEDs differently.
The AT89S52 used here has 8 KB of in-system programmable flash, 256 bytes of internal RAM, three 16-bit timer/counters and a hardware UART. These are specifications for this chip. Check the part number printed on yours before using the examples. microchip.com
Setting | Value used throughout this guide |
Microcontroller | AT89S52 |
Compiler | Keil C51 for the 8051 family |
Header | REG52.H, using registers shared with this target |
Oscillator | 11.0592 MHz |
Timer assumption | Internal timer clock at oscillator frequency divided by 12 |
LED | P1.0, active low |
Button | P1.1, active low |
UART | P3.0/RXD and P3.1/TXD |
Terminal | 9600 baud, 8 data bits, no parity, 1 stop bit, no flow control |
Two settings are easy to confuse. Entering 11.0592 MHz in the simulator controls simulated timing. The physical board runs from its installed oscillator. Changing the project setting cannot turn a 12 MHz crystal on your board into an 11.0592 MHz crystal.
If you need to locate the pins on your package, use the Embedded Hash 8051 microcontroller pinout guide. Pinouts
2. Set up the board and Keil C51 project
For the physical labs, the simplest setup is an AT89S52 development board with a working clock, reset circuit and compatible programmer. Use the board schematic to identify existing LEDs, resistors, buttons and serial circuitry before adding connections.
Connection | Setup for this tutorial |
LED on P1.0 | Connect the LED anode to the positive supply through a suitable series resistor and its cathode to P1.0, or use an equivalent active-low onboard LED. On a 5 V training board, 1 kΩ is a practical starting resistor for a low-current indicator, subject to the LED and board specifications. |
Button on P1.1 | Connect the button between P1.1 and ground. Port 1 has an internal pull-up. The program writes 1 to the port latch before reading the input. |
Serial output | Connect board P3.1/TXD to the compatible USB-to-UART adapter’s RX input. |
Serial input | Connect adapter TX to board P3.0/RXD. Use compatible logic levels and a common ground. |
Serial connector type | Check whether your board exposes logic-level UART or an RS-232 connector with a transceiver. Use an adapter intended for the interface you actually have. |
For a 5 V board, verify that the adapter’s RX input can accept the board’s TX voltage. If the board is powered separately, the serial connection generally needs TX, RX and ground. Follow the board documentation for power connections. Port behaviour and programmable pin functions are documented in the AT89S52 datasheet. microchip.com
How to create and run an 8051 C program in Keil
- Open µVision with the C51 toolchain installed. Create a new project and select the AT89S52 target.
- Add a C source file named main.c to the source group. Paste one complete example from this guide.
- Set the target oscillator value to 11.0592 MHz for simulation and timing inspection.
- In Options for Target → Output, enable Create HEX File. Build the project and inspect the build messages.
- For simulation, start a simulator debug session and inspect the relevant port, timer or serial output. For hardware, use an AT89S52-compatible programmer to write and verify the generated HEX file.
- Reset the target and compare its behaviour with the expected result for that example. keil.com
A USB-to-UART adapter and a programmer do different jobs. The terminal adapter exchanges bytes with firmware that is already running. To install the first program on a standard AT89S52 board, use its supported programming interface. If your board has a separate loader, follow that board’s procedure.
3. Understand the C51 syntax used in the examples
You need only a few 8051-specific ideas before the first program.
C51 expression | Meaning in these labs |
#include <REG52.H> | Makes register names such as P1, TMOD, TH0, SCON and SBUF available to the program. |
sbit LED = P1^0; | Gives the name LED to bit 0 of Port 1. In a Keil sbit declaration, ^0 identifies a bit position. In an ordinary C expression, ^ means XOR. |
LED = 0; | Writes a low level to the selected output. The LED lights because of the wiring used here. |
TMOD | Selects operating modes for Timer 0 and Timer 1. The timers share this register. |
interrupt 1 | Keil C51 syntax that assigns a function to the Timer 0 interrupt vector. |
SBUF, RI, TI | Serial data register, receive flag and transmit flag used by the UART example. |
These examples use Keil C51 extensions. SDCC also supports the 8051 family, but interrupt declarations, bit-address declarations and device headers differ. If a desktop C compiler rejects sbit, first check your toolchain selection. Aivasu Tech Institute
Program 1. Control an LED with a button
Goal: Light the LED on P1.0 while the button on P1.1 is pressed. This program has no timing dependency, so it makes a good first test of the board, programmer and pin mapping.
#include <REG52.H>
sbit LED = P1^0;
sbit BUTTON = P1^1;
void main(void)
{
LED = 1; /* Active-low LED starts off. */
BUTTON = 1; /* Release P1.1 so it can be read as an input. */
while (1)
{
if (BUTTON == 0)
{
LED = 0;
}
else
{
LED = 1;
}
}
}
Why does writing zero turn the LED on?
In this circuit, the LED and resistor run from the positive supply to the microcontroller pin. Driving the pin low lets current flow through the LED into the pin. Driving it high removes the voltage difference needed to light it. That wiring is called active low.
The button uses a similar convention. Released, the input reads high. Pressed, it connects the input to ground and reads low. The AT89S52’s Port 1 pull-ups make this input arrangement possible. Port 0 behaves differently when used as general-purpose I/O, so moving the same circuit to P0 may require an external pull-up. microchip.com
Button condition | Expected P1.1 | Program writes to P1.0 | LED |
Released | 1 | 1 | Off |
Pressed and held | 0 | 0 | On |
Released again | 1 | 1 | Off |
If it fails: First replace the loop temporarily with a constant LED = 0; inside an infinite loop. If the LED still stays dark, investigate the loaded image, LED polarity, board pin and resistor path. If it lights, return to the original program and inspect P1.1. That one change separates an input problem from an output problem.
Why there is no debounce delay: This exercise follows the button’s present level. If you later change the requirement to “one press increments a counter once”, mechanical contact bounce becomes important. The counter must recognise one stable press and wait for a stable release before accepting the next press.
Program 2. Blink an LED using Timer 0 and an interrupt
Goal: Change the LED state approximately every 500 milliseconds while leaving the main loop free. Timer 0 generates an interrupt about every 50 milliseconds. After ten interrupts, the program toggles the LED.
Calculate the 8051 timer preload
For the specified AT89S52 clock configuration:
Calculation | Result |
Oscillator frequency | 11,059,200 Hz |
Timer counts per second | 11,059,200 ÷ 12 = 921,600 |
Counts required for 50 ms | 921,600 × 0.050 = 46,080 |
Starting value for a 16-bit up-counter | 65,536 − 46,080 = 19,456 |
Starting value in hexadecimal | 0x4C00 |
Values loaded into Timer 0 | TH0 = 0x4C, TL0 = 0x00 |
The counter starts at 0x4C00, counts upwards and overflows after 46,080 timer increments. This is the nominal counting interval. Interrupt entry and software reload add a small delay to the observed period. Keil’s timer application note discusses this overhead explicitly. keil.com
#include <REG52.H>
sbit LED = P1^0;
static unsigned char intervals = 0;
void timer0_isr(void) interrupt 1
{
TR0 = 0;
TH0 = 0x4C;
TL0 = 0x00;
TR0 = 1;
intervals++;
if (intervals == 10)
{
intervals = 0;
LED = !LED;
}
}
void main(void)
{
LED = 1;
TR0 = 0;
/* Preserve Timer 1 settings. Set Timer 0 to 16-bit timer mode. */
TMOD = (TMOD & 0xF0) | 0x01;
TH0 = 0x4C;
TL0 = 0x00;
TF0 = 0;
ET0 = 1; /* Enable Timer 0 interrupts. */
EA = 1; /* Enable interrupts globally. */
TR0 = 1; /* Start Timer 0. */
while (1)
{
/* Other foreground work can run here. */
}
}
What should you see?
The LED is off for about half a second, then on for about half a second. A state change occurs roughly every 500 ms. A complete on-and-off cycle takes roughly one second. If an oscilloscope shows about 1 Hz on P1.0, the result agrees with the design.
Notice why the code preserves the upper half of TMOD. Timer 0 uses the lower four bits. Timer 1 uses the upper four. If you later add UART and write TMOD = 0x01, you can accidentally erase Timer 1’s baud-rate configuration. Preserving unrelated bits makes two individually correct examples easier to combine.
What changes with a 12 MHz crystal?
With the same divide-by-12 timer clock, the timer now increments 1,000,000 times per second. A nominal 50 ms interval needs 50,000 counts. The new preload is 65,536 − 50,000 = 15,536, or 0x3CB0. Load TH0 = 0x3C and TL0 = 0xB0.
This adjustment applies to the timer example. The UART calculation also depends on oscillator frequency and must be checked separately. Moving between boards by changing only the project name is a common reason one example works while another appears broken.
Program 3. Control the LED from a serial terminal at 9600 baud
Goal: Send 1 to switch the LED on, 0 to switch it off and ? to ask for the state. This exercise is more informative than repeatedly printing “Hello”. A successful command-and-response exchange tests the PC-to-board path, the board-to-PC path and the physical output.
Use 9600 baud, 8 data bits, no parity, one stop bit and no flow control. Connect the board TX to adapter RX, board RX to adapter TX, and common ground. The program accepts individual characters and ignores carriage return and line feed.
#include <REG52.H>
sbit LED = P1^0;
static void uart_init(void)
{
TR1 = 0;
/* Timer 1: mode 2, 8-bit auto-reload. Keep Timer 0 unchanged. */
TMOD = (TMOD & 0x0F) | 0x20;
PCON &= 0x7F; /* SMOD = 0. */
SCON = 0x50; /* UART mode 1, receiver enabled. */
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
}
static void uart_write_char(char value)
{
TI = 0;
SBUF = value;
while (TI == 0)
{
/* Wait for the UART transmit flag. */
}
TI = 0;
}
static void uart_write_line(const char code *message)
{
while (*message != ‘\0’)
{
uart_write_char(*message);
message++;
}
uart_write_char(‘\r’);
uart_write_char(‘\n’);
}
void main(void)
{
unsigned char command;
LED = 1;
uart_init();
uart_write_line(“READY”);
while (1)
{
if (RI)
{
command = SBUF;
RI = 0;
switch (command)
{
case ‘1’:
LED = 0;
uart_write_line(“ON”);
break;
case ‘0’:
LED = 1;
uart_write_line(“OFF”);
break;
case ‘?’:
if (LED == 0)
{
uart_write_line(“ON”);
}
else
{
uart_write_line(“OFF”);
}
break;
case ‘\r’:
case ‘\n’:
break;
default:
uart_write_line(“USE 1 0 ?”);
break;
}
}
}
}
Why is TH1 set to 0xFD?
For this classic timer configuration, UART mode 1 uses Timer 1 overflows to generate the baud rate. With SMOD = 0, baud rate equals the Timer 1 overflow rate divided by 32. Timer 1 counts at 11,059,200 ÷ 12 = 921,600 counts per second. Starting at 0xFD gives three counts before overflow. The result is 921,600 ÷ 3 ÷ 32 = 9,600 baud. techwww.in.tu-clausthal.de
That calculation also predicts a fault. With a 12 MHz crystal and the same 0xFD reload, the result is approximately 10,417 baud, around 8.5% above 9600. If Program 1 works but the UART prints garbage on a different board, inspect the crystal marking before rewriting the transmit function.
Expected serial results
Open the terminal before resetting the board so you can see the startup message. Type one command and wait for its response.
Action | Terminal output | LED |
Reset board | READY | Off |
Send 1 | ON | On |
Send ? | ON | On |
Send 0 | OFF | Off |
Send ? | OFF | Off |
Send X | USE 1 0 ? | Previous state |
What the result tells you: Seeing READY proves that the board can transmit to the computer. It does not prove that the board can receive. If READY is readable but typing 1 does nothing, check the connection from adapter TX to P3.0/RXD, receiver enable and logic levels. If you see only the character you typed, check whether the terminal has local echo enabled.
This example uses polling and waits while sending each reply. That keeps the program easy to inspect for human-paced commands. If a computer sends a continuous stream, incoming characters can arrive before the firmware services them. A buffered, interrupt-driven receiver is the next design step for that requirement.
What 8051 memory means for your C program
The AT89S52 has 256 bytes of internal RAM. A single 100-byte buffer occupies about 39% of that total before other variables, register banks and stack use are considered. That is why an 8051 example may place fixed text in program memory instead of reserving scarce RAM for it. microchip.com
In the UART example, const char code *message tells Keil C51 that the pointer refers to characters in the code memory space. If you encounter an incompatible-pointer warning after changing the example, check where the string or buffer actually resides before adding a cast.
C51 concept | Practical use |
code | Refer to program-memory data such as constant text or lookup tables. |
data | Use directly addressable internal data memory. |
idata | Access internal data memory through indirect addressing, including upper internal RAM where supported. |
xdata | Address the external-data memory space. Available storage depends on the specific chip and board. |
volatile | Tell the compiler that a value may change outside the normal flow it can see, such as a variable updated by an interrupt and read in foreground code. |
A useful distinction: The intervals counter in Program 2 is used only inside the interrupt routine. If you later add a multi-byte time counter shared with the main loop, you have a different problem. On an 8-bit processor, foreground code can read one byte before an interrupt and another byte after it. volatile addresses compiler visibility. A consistent multi-byte snapshot also needs an appropriate synchronisation method.
Why an 8051 program works in simulation but fails on the board
A simulator can help you inspect registers, timer flags and control flow. Physical hardware adds the installed oscillator, board jumpers, LED polarity, reset circuitry, connector wiring and voltage levels. Diagnose the first observation that differs between the two environments.
Symptom | First check | What to do next |
REG52.H cannot be found or sbit is rejected | Is the project using Keil C51 for an 8051 target? | Check the selected toolchain and include configuration. |
Build succeeds but there is no HEX file | Is Create HEX File enabled? | Enable it under the target output options, rebuild and inspect the build output. keil.com |
Programmer verifies the image, but nothing happens | Does the board have power, a running clock and a released reset? | For internal program execution, check the physical EA/VPP pin configuration against the datasheet. microchip.com |
LED behaviour is reversed | Is the board LED active high or active low? | Use a constant output to establish polarity before changing the application logic. |
Button always reads low | Did the firmware release the Port 1 latch by writing 1? | Check the pin state when pressed and released, then inspect the wiring. |
LED never blinks in Program 2 | Are TR0, ET0 and the global interrupt enable set? | Inspect whether Timer 0 counts and reaches overflow. |
LED blinks at the wrong speed | Does the physical oscillator match the calculation? | Recalculate the preload and distinguish one state change from a complete cycle. |
UART prints unreadable characters | Do the crystal, reload value and terminal settings agree? | Calculate the actual baud rate before changing the application code. |
READY prints, but commands fail | Does adapter TX reach board RXD? | Verify the receive wire, common ground, compatible levels and REN. |
UART stops working after adding Timer 0 | Did a write to TMOD overwrite Timer 1’s upper nibble? | Preserve the other timer’s configuration when setting either mode. |
Two different things are called EA. The physical EA/VPP pin selects access to external or internal program memory according to the chip configuration. The EA bit in the interrupt-enable register controls global interrupts. In Program 2, EA = 1; enables interrupts. It cannot correct a miswired physical EA/VPP pin. microchip.com
How to verify that you understand the program
Once all three examples work separately, make one small change with a predictable result.
- Change the blink interval. In Program 2, change the threshold from ten timer interrupts to five. Predict the time between LED changes and the full-cycle time. The nominal answers are 250 ms and 500 ms respectively.
- Change the UART response. Add an H command that prints the available commands. Confirm that entering H leaves the current LED state unchanged.
- Combine timing and serial control. Let Timer 0 generate a heartbeat on a different LED pin while UART controls P1.0. Give each output one owner and preserve both halves of TMOD.
- Measure before adjusting. Record the crystal frequency, timer reload, predicted period and observed period. If they disagree, identify whether the error comes from the calculation, the clock source or software overhead.
If you are comparing training options in Hyderabad, ask to see this sequence on a physical board: build the program, flash it, change one register setting and measure the effect. It shows how much time learners spend working with code and hardware together. Explore hands-on embedded systems training at Embedded Hash. embeddedhash.in
Conclusion
In conclusion, this comprehensive guide has provided a deep understanding of embedded C programming with 8051 microcontrollers, enabling you to build robust systems with confidence. By mastering the concepts, techniques, and best practices outlined in this article, you are well-equipped to embark on exciting projects and create innovative embedded systems.
Throughout this guide, we explored the fundamentals of embedded C programming, from understanding the 8051 architecture to interfacing peripherals and optimizing memory usage. We delved into real-world applications, allowing you to apply your newfound knowledge to practical projects.
As technology continues to advance, embedded systems powered by the 8051 microcontroller will remain integral to numerous industries. By continually expanding your skills and staying up-to-date with emerging trends and advancements, you can remain at the forefront of this dynamic field.
FAQs on embedded C programming with 8051 microcontroller
Embedded C programming is a specialized form of programming used to develop software for embedded systems. It is important for building robust systems with the 8051 microcontroller as it allows developers to control and utilize the microcontroller’s features effectively, ensuring efficient resource management, real-time performance, and reliable operation.
While the 8051 microcontroller can be programmed using standard C language, there are certain embedded C extensions and specific guidelines that should be followed for optimizing code size, memory usage, and timing constraints. There are also specialized development tools and compilers available for embedded C programming with the 8051 microcontroller.
Choosing the right development tools involves considering factors such as the features provided, compiler efficiency, debugging capabilities, simulator support, and compatibility with the 8051 microcontroller. It is recommended to select tools that offer a comprehensive integrated development environment (IDE) with good technical support and documentation.
Designing hardware interfaces requires considering factors such as voltage levels, signal compatibility, noise suppression, power supply requirements, and proper grounding. It is crucial to develop schematics and PCB layouts that adhere to best practices and ensure reliable communication between the microcontroller and external devices or sensors.
Memory optimization techniques include reducing variable sizes, using efficient data types, applying code and data banking techniques, storing constants in ROM, and utilizing linker optimizations. Additionally, disabling unnecessary compiler optimization options, such as floating-point support, can save valuable memory resources.
Best practices for debugging embedded C programs on the 8051 microcontroller include using in-circuit emulators, hardware breakpoints, real-time debugging tools, and software debugging techniques like logging and serial communication. It is also helpful to analyze program flow, monitor variables, and use assert statements to catch errors during development.
Ensuring real-time performance involves careful task scheduling, utilizing hardware interrupts, reducing interrupt latency, optimizing code execution time, and managing system resources efficiently. Using techniques such as priority-based scheduling and interrupt-based event handling can help achieve real-time responsiveness.
Testing reliability involves unit testing of individual modules, integration testing of the overall system, stress testing, and verification against specifications. Test cases should cover both normal and exceptional scenarios, with attention to input validation, error handling, and boundary conditions.
To handle power management, it is important to design software that maximizes sleep modes, reduces unnecessary processing, optimizes timers, and minimizes power-hungry peripherals. Techniques like clock gating and power gating can help preserve energy by disabling unused components.
Yes, guidelines include writing modular and reusable code, following a consistent coding style, adding comments and documentation, using common coding guidelines like MISRA C, and leveraging software version control systems for managing code changes and collaboration.
