Key Concepts and Implementation Details for 8051 Microcontrollers

Special Functon Register and Bit Declarations

The sfr and sbit keywords are used for declarations in 8051 microcontroller programming. sfr declares an entire special function register, while sbit declares a single bit within a register.

sfr output_port = 0xA0;
sbit indicator_bit = output_port ^ 3;

The #define preprocessor directive is also used for declarations, but its more suitable for defining hardware pins like P0, P1, P2, and P3, whereas sfr is typically used for internal hardware such as timers.

When defining device addresses, do not use an equals sign or a semicolon directly after the address.

#define EEPROM_DEVICE 0xA0    // Correct

For declaring a specific bit in a register, include the semicolon and use the caret operator.

sbit clock_line = output_port ^ 2;
sbit data_line = output_port ^ 1;

The bit data type can also be used for variables that only hold values 1 or 0.

Output Configurations: Weak Pull-Up and Open-Drain

In a weak pull-up configuration, when the output is set to 0, the switch closes, connecting the signal directly to ground, which provides strong driving capability. When set to 1, the switch opens, connecting the signal to a high potential through a pull-up resistor, resulting in weaker driving capability.

Open-drain outputs lack a pull-up resistor, featuring only a switch. Outputting 0 closes the switch to ground, while opening the switch leaves the output in a floating state.

Intrinsic Functions for Bit Manipulation

The INTRINS.H header provides functions for cyclic bit rotations. _cror_ performs a right rotation, and _crol_ performs a left rotation. Unlike the shift operators (<< and >>), which fill vacated bits with zeros, these functions perform 8-bit cyclic rotations.

Latch Operation Principles

A latch is an electronic component that stores digital signals. Its primary function is to capture and hold the state of an input signal upon a clock pulse. The output remains stable even if the input changes, until the next clock pulse arrives.

Data latching occurs when the latch signal transitions from low to high, transferring data from the shift register to the output register. During the high period of the latch signal, the latched data state is maintained. A change in the signal level will then output the data.

Input/Output Activation Considerations

For buttons connected to a port like P3, one side is grounded. Since microcontroller pins default to a high state (1) on power-up, pressing the button pulls the pin to ground (0), allowing the microcontroller to detect the press. A button configured to set the pin to 1 would not be detectable.

LEDs, as loads, require a voltage difference to illuminate. One side is typically connected to ground (GND), and the other side needs a high potential to activate.

Memory Classification

Volatile Memory Non-Volatile Memory
SRAM (Static RAM) Mask ROM
DRAM (Dynamic RAM) PROM (Programmable ROM)
EPROM (Erasable PROM)
EEPROM (Electrically Erasable PROM)
Flash Memory

Seven-Segment Display Control

A 3-to-8 decoder, such as the 138 decoder, allows control of eight output lines using only three I/O pins, reducing the number of pins required. The enable pin, often active low, activates the device. Control is achieved by converting a 3-bit binary input to a decimal value that selects the corresponding output line.

In a common-cathode seven-segment display, all LED cathodes are connected to ground. An LED lights when its anode is supplied with a high voltage (e.g., 5V), creating a potential difference. If the anode is at 0V, no potential difference exists, and the LED remains off.

For a common-anode display, all anodes are connected to a positive supply. An LED lights when its cathode is pulled to ground (0V), creating a potential difference. If the cathode is at 5V, no lighting occurs.

Timer/Counter Fundamentals

The STC89C52 microcontroller includes two 16-bit timer/counters, T0 and T1.

The TCON register is bit-addressable, allowing individual bit manipulation. Key bits include:

  • TF1 (Timer Flag): Set to 1 by hardware on overflow, cleared by hardware after CPU response.
  • TR1 (Timer Run): Controls the start and stop of the timer/counter.
  • IE1 (Interrupt Enable): Part of the interrupt enable controller.

The IE register manages interrupt sources:

  • EA (IE.7): Global interrupt enable.
  • EX0 (IE.0): External interrupt 0 enable.
  • ET0 (IE.1): Timer 0 interrupt enable.
  • EX1 (IE.2): External interrupt 1 enable.
  • ET1 (IE.3): Timer 1 interrupt enable.
  • ES (IE.4): Serial port interrupt enable.
  • ET2 (IE.5): Timer 2 interrupt enable.

To enable an interrupt, set its corresponding bit in IE and ensure EA is set to 1.

The IT bit controls external interrupt triggering: 0 for level-triggered, 1 for edge-triggered.

The TMOD register is not bit-addressable. Key bits include:

  • GATE: Timer control gate.
  • C/T: 0 for timer mode, 1 for counter mode.

Timer Calculations and Initialization

Assuming a system frequency of 12 MHz and a 12T timer clock, the timer clock frequency is 1 MHz (12 MHz / 12). Each timer tick represents 1 microsecond. For a 1-millisecond delay, the required count is 1000 ticks.

Timers are 16-bit, with values split into high (TH) and low (TL) bytes. The maximum count is 65535. To achieve a 1 ms delay, the initial value is 65535 - 1000 = 64535. In hexadecimal, this is 0xFC17, so TH0 = 0xFC and TL0 = 0x17.

void Timer0_Initialize(void) {
    TMOD &= 0xF0;
    TMOD |= 0x01;
    TL0 = 0x17;
    TH0 = 0xFC;
    TF0 = 0;
    TR0 = 1;
    ET0 = 1;
    EA = 1;
    PT0 = 0;
}

Interrupt System Overview

The microcontroller supports eight interrupt sources: three timer interrupts, four external interrupts, and one serial port interrupt.

Serial Communication Methods

Serial vs. Parallel Communication

Serial Communication Transmits data one bit at a time over a single data line.
Parallel Communication Uses multiple data lines (e.g., 8, 16, 32) to transmit multiple bits simultaneously.

Communication Duplex Modes

Simplex Unidirectional communication; one device is always the transmitter, the other the receiver.
Half-Duplex Bidirectional communication, but only one direction at a time.
Full-Duplex Simultaneous bidirectional communication.

Synchronous vs. Asynchronous Communication

Synchronous Uses a clock signal to synchronize data transmission; data is sampled at clock edges.
Asynchronous No clock signal; data is framed with start and stop bits, and baud rate must be agreed upon.

Serial Port Hardware and Configuration

Simple bidirectional serial communication requires two lines: TXD (transmit) and RXD (receive), connected crosswise. For unidirectional communication, a single line suffices. Level conversion chips are needed when voltage standards differ.

The UART in STC89C52 has four modes:

  • Mode 0: Synchronous shift register.
  • Mode 1: 8-bit UART, variable baud rate (commonly used).
  • Mode 2: 9-bit UART, fixed baud rate.
  • Mode 3: 9-bit UART, variable baud rate.

Key parameters include baud rate (transmission speed), parity bit (for error checking), and stop bit (frame delimiter).

Baud rate determines the timing of data bits; mismatched baud rates between transmitter and receiver cause errors. Data frames can include address and data frames. A 9-bit format often uses the last bit for parity (odd or even) to detect errors, though it cannot identify the erroneous bit.

SBUF is the serial data buffer register, comprising separate physical registers for transmit and receive that share the same address. Writing to SBUF modifies the transmit register; reading accesses the receive register.

TI (Transmit Interrupt) and RI (Receive Interrupt) flags are set by hardware after data transmission or reception, respectively, and must be cleared by software to continue operations.

void SerialPort_Initialize() { // 4800 bps @ 11.0592 MHz
    SCON = 0x40;
    PCON &= 0x7F;
    TMOD &= 0x0F;
    TMOD |= 0x20;
    TL1 = 0xFA;
    TH1 = 0xFA;
    ET1 = 0;
    TR1 = 1;
    EA = 1;
    ES = 1;
}

LED Matrix Display Control

LED matrix displays are structurally similar to seven-segment displays but arrange LEDs in a grid. They come in common-cathode and common-anode configurations and require row-by-row or column-by-column scanning for simultaneous display.

The 74HC595 shift register converts serial data to parallel output. The SER pin inputs data one bit at a time, SERCLK shifts data through the register, and after eight cycles, RCLK latches the data to the output pins. Multiple chips can be cascaded via the QH' pin.

Pins with overbars in datasheets indicate active-low signals.

I2C Protocol Basics

I2C (Inter-Integrated Circuit) simplifies multi-device communication using two lines: SDA (data) and SCL (clock), both open-drain and pulled high with resistors (typically 4.7 kΩ).

Start and stop conditions are defined by SDA transitions while SCL is high. Data is transferred with SDA stable during SCL high periods and can change when SCL is low.

For writing a byte, the host places each bit on SDA during SCL low, then toggles SCL high for the slave to read. Reading involves the slave placing bits on SDA, with the host reading during SCL high after releasing SDA.

Device addressing includes a 7-bit address and a read/write bit. Acknowledge bits (ACK) are sent by the receiver (0 for success, 1 for failure).

EEPROM Integration with AT24C02

AT24C02 is a 256-byte EEPROM using I2C, retaining data without power. Its address is 0x50 for writing and 0x51 for reading (base address 0xA0 shifted). The WP pin enables write protection when high.

Addresses range from 0x00 to 0xFF, with 0x00-0x7F for data storage. To store a 16-bit value, split it into two bytes and write to consecutive addresses.

PWM Generation for Dimming and Motor Control

Pulse Width Modulation (PWM) generates analog-like signals by varying pulse width in inertial systems. Key parameters are frequency (1/period), duty cycle (pulse width/period), and resolution (duty cycle step size).

For a breathing LED effect, set a fixed period (e.g., 100 units) and vary the on-time within that period. A higher on-time yields brighter light.

Motor speed control uses PWM to adjust the average voltage supplied. Duty cycle directly influences speed.

unsigned char counter = 0;
if (counter >= 100) counter = 0; // Simulate modulo operation for period reset

Analog and Digital Signal Conversion

Analog signals are continuous, while digital signals are discrete (0 or 1). A/D converters bridge these domains, translating continuous voltages to digital values. D/A converters do the reverse but are less common due to PWM alternatives.

Conversion is linear; for example, 5V might map to 255, 2.5V to 127.

Infrared Remote Control Implementation

Infrared remotes use modulated 940 nm light for communication, following the NEC standard. Modulation at 38 kHz distinguishes signals from ambient infrared light. Hardware demodulation extracts the signal via a dedicated receiver.

Communication is simplex and asynchronous.

Tags: 8051 Microcontroller Embedded Systems c programming Timer/Counter serial communication

Posted on Mon, 05 Oct 2026 16:47:54 +0000 by MattAdamson