Interfacing displays, keypads and relays

Seven-segment and character-LCD interfacing, matrix keypad scanning and debounce, and relay drivers with flyback diodes and isolation, with relay-driver and multiplexing calculations.

Drafted with Aria, reviewed by the AiCanCode.org team. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Operators set and see machine parameters through keypads and displays, and the controller switches pumps, heaters and contactors through relays. These interfaces look simple, but wrong current calculations burn MCU pins, a missing flyback diode kills the driver transistor, and unhandled switch bounce turns one key press into five. They are standard lab experiments and standard interview questions.

Key ideas

LEDs and seven-segment displays.

  • Each segment is an LED needing a series resistor. Common cathode: all cathodes joined to ground (segment pin high = on). Common anode: anodes joined to V_CC (segment pin low = on).
  • A segment code is the byte that lights the right segments (for a common-cathode display with bits g f e d c b a, "0" = 0x3F, "1" = 0x06).
  • Multiplexing: with N digits, the segment lines are shared and only one digit's common is enabled at a time, in rotation. If every digit is refreshed faster than about 50–100 times a second, the eye sees a steady display. Each digit is lit only 1/N of the time, so the peak segment current must be about N times the desired average.
  • A digit's common pin can carry up to 8 segment currents — far more than a GPIO pin can sink — so it is switched by a transistor.

Character LCD (HD44780-type 16×2).

  • Pins: RS (0 = command, 1 = data), R/W (usually tied to write), E (enable; data is latched on its falling edge), D0–D7 or only D4–D7 in 4-bit mode, plus contrast (V0) and backlight.
  • Typical initialisation commands: 0x38 (8-bit, 2 lines, 5×8 font) or 0x28 for 4-bit mode, 0x0C (display on, cursor off), 0x06 (entry mode: increment), 0x01 (clear, takes about 1.5 ms). Set the cursor with 0x80 + address: line 1 starts at DDRAM 0x00 (command 0x80), line 2 at 0x40 (command 0xC0).
  • An I2C "backpack" (PCF8574 port expander) reduces the wiring to two lines; graphic OLED/TFT displays use I2C or SPI.

Matrix keypads.

  • A keypad with r rows and c columns has r × c keys but needs only r + c pins (a 4×4 needs 8 instead of 16).
  • Scanning: columns are inputs with pull-ups; drive one row low at a time, others high (or high-impedance), and read the columns. A low column identifies the key at that row–column crossing. Repeat for every row.
  • Debounce: contacts bounce for typically 5–20 ms. Accept a key only after it reads the same for about 20 ms, then wait for release.
  • Ghosting: pressing three keys at the corners of a rectangle makes a fourth appear pressed; diodes in series with each key prevent it.

Relays and load switching.

  • An electromechanical relay gives galvanic isolation between coil and contacts and can switch AC mains. Its coil current (tens of mA) exceeds a GPIO pin's rating, so it is driven by a transistor (or a Darlington array such as ULN2003, which has built-in clamp diodes).
  • Flyback diode across the coil (cathode to +V) is mandatory: when the transistor turns off, the coil inductance would otherwise produce a large voltage spike.
  • The base resistor is chosen to saturate the transistor: use the minimum β and overdrive by 2–5 times.
  • Contact rating must cover the load voltage, current and inrush (motors and lamps draw several times their running current at switch-on); inductive DC loads need derating.
  • An optocoupler between MCU and driver gives isolation from noisy plant grounds. Solid-state relays (SSRs) have no moving parts, switch silently and fast, often at zero crossing, but leak a little current and need heat sinking.

Connections. GPIO and bit manipulation (topic 3) drive all of these; timers (topic 4) run multiplexing and debounce; the same relay and isolation ideas appear in PLC output modules.

Formulas

Keys = r × c, Pins = r + c

  • r = rows, c = columns of a matrix keypad.

t_digit = 1 / (N × f_refresh)

  • On-time per digit (s); N = number of multiplexed digits; f_refresh = refresh rate of each digit (Hz).

I_avg = I_peak / N

  • Average segment current (A) in an N-digit multiplexed display.

R_seg = (V_CC − V_F − V_CE(sat)) / I_peak

  • Segment resistor (Ω); V_F = LED forward voltage (V); V_CE(sat) = digit-driver transistor drop (V).

I_C = V_coil / R_coil

  • Relay coil current (A); V_coil = coil supply (V); R_coil = coil resistance (Ω).

I_B = k × I_C / β_min, R_B = (V_OH − V_BE) / I_B

  • k = overdrive factor (2–5); β_min = minimum current gain; V_OH = MCU high output voltage (V); V_BE ≈ 0.7 V.

Worked examples

Example 1 (standard). A 5 V MCU drives a 12 V relay with a 400 Ω coil through an NPN transistor with β_min = 100. Use an overdrive factor of 5. Find the coil current and base resistor.

  1. I_C = V_coil / R_coil = 12 / 400 = 30 mA.
  2. I_B = k × I_C / β_min = 5 × 30 mA / 100 = 1.5 mA.
  3. R_B = (V_OH − V_BE) / I_B = (5 − 0.7) / 1.5 mA = 2.87 kΩ → choose the standard 2.7 kΩ (I_B = 1.59 mA, safely within the pin rating).
  4. Add a 1N4148/1N4007 flyback diode across the coil.

Answer: I_C = 30 mA, R_B ≈ 2.7 kΩ.

Example 2 (GATE level). A 4-digit common-cathode seven-segment display is multiplexed from a 5 V MCU so that each digit is refreshed 100 times per second. Each segment should appear as if driven at 5 mA continuously. V_F = 2.0 V, digit-transistor V_CE(sat) = 0.2 V. Find (a) the digit time slot, (b) the segment resistor, (c) the worst-case current in one digit transistor.

  1. t_digit = 1 / (N × f_refresh) = 1 / (4 × 100) = 2.5 ms → a timer interrupt every 2.5 ms switches digits.
  2. I_peak = N × I_avg = 4 × 5 mA = 20 mA.
  3. R_seg = (5 − 2.0 − 0.2) / 20 mA = 140 Ω → choose 150 Ω, giving I_peak = 2.8 / 150 = 18.7 mA and I_avg = 4.7 mA.
  4. Worst case ("8." lit) = 8 segments × 18.7 mA = 149 mA — so each digit common needs a transistor, not a GPIO pin.

Answers: 2.5 ms; 150 Ω; ≈ 149 mA.

Common mistakes

  • Omitting the flyback diode, or fitting it the wrong way round (it then shorts the supply when the transistor turns on).
  • Driving relay coils or digit commons straight from GPIO pins.
  • Forgetting that multiplexing divides brightness by N.
  • Reading a keypad without pull-ups, so inputs float, or without debounce.
  • Writing to an HD44780 too fast after power-up or after a clear command (it needs milliseconds).
  • Choosing a relay by coil voltage only and ignoring contact current, inrush and AC vs DC rating.
  • Confusing common-anode and common-cathode segment codes (they are bitwise complements).

For GATE ME

This topic produces conceptual MCQs (number of pins for a keypad, common-anode vs common-cathode, why a flyback diode or optocoupler is used, LCD control pins) and simple numericals on relay driver base resistors, LED resistors and multiplexing timing. Practise drawing the transistor–relay–diode circuit and tracking currents through it.

Quick check

  1. How many keys and how many pins does a 4×3 matrix keypad have?
  2. Which LCD command moves the cursor to the start of line 2?
  3. What is the common-cathode segment code for "1" (bits g…a)?
  4. A 5-digit display refreshes each digit at 80 Hz. What is the digit slot?
  5. Why must the base resistor be sized with β_min rather than typical β?

Answers: 1. 12 keys, 7 pins 2. 0xC0 3. 0x06 4. 2.5 ms 5. To guarantee saturation for the worst transistor in production

Try answering each one aloud before you open it.

  1. 1.How do relays function in an industrial automation system?Concept

    Relays are electrically operated switches used in industrial automation systems to control a circuit by a separate low-power signal. They allow one circuit to switch another circuit, keeping them electrically isolated. In automation, relays are used to control high-power devices with low-power signals, enabling the automation system to manage large loads safely and efficiently. They are crucial for protecting sensitive components from high voltages and currents.

  2. 2.Why are character LCD displays commonly used in microcontroller projects?Application

    A 16×2 HD44780-type LCD is cheap, draws very little current apart from its backlight, and has a built-in controller and character generator, so the MCU only sends ASCII codes and a few commands. It connects through an 8-bit or 4-bit parallel bus with RS and E control lines (6 pins in 4-bit mode), or through an I2C backpack using just two lines. That makes it ideal for showing set-points, readings and status on simple instruments.

  3. 3.What happens if a relay is used beyond its rated current capacity?Application

    If a relay is used beyond its rated current capacity, it can overheat and potentially fail. This can lead to the contacts welding together, causing the relay to remain in a closed position even when it should be open. Such a failure can result in uncontrolled operation of the connected load, posing safety hazards and potentially damaging the equipment. It is crucial to select a relay with an appropriate current rating for the application to avoid these issues.

  4. 4.Explain how a keypad matrix is interfaced with a microcontroller.Concept

    The r rows and c columns go to r + c GPIO pins — 8 pins for a 4×4 keypad instead of 16. Typically the columns are inputs with pull-ups and the firmware drives one row low at a time while the other rows are high or high-impedance. If a column then reads low, the key at that row–column crossing is pressed. The scan repeats for every row every few milliseconds, and a key is accepted only after it reads stable for about 20 ms (debounce).

  5. 5.Why is debouncing necessary when interfacing a keypad with a microcontroller?Application

    Debouncing is necessary when interfacing a keypad with a microcontroller because mechanical switches can produce multiple transitions (bounces) when pressed or released. These bounces can be interpreted as multiple key presses by the microcontroller, leading to erroneous inputs. Debouncing techniques, such as software delays or hardware filters, are used to ensure that only a single, clean signal is registered for each key press, improving the reliability of the input system.

  6. 6.What are the advantages of using a touch screen display over a traditional keypad in industrial automation?Application

    Touch screen displays offer several advantages over traditional keypads in industrial automation. They provide a more intuitive and flexible user interface, allowing for dynamic changes in the display layout and functionality without physical modifications. Touch screens can display more information and support complex interactions, improving user experience and efficiency. They also reduce the need for multiple physical buttons, saving space and simplifying the design of control panels.

  7. 7.If a PLC is programmed to control a relay that operates a motor, what considerations should be made regarding the relay's specifications?Application

    When programming a PLC to control a relay that operates a motor, it is important to consider the relay's voltage and current ratings to ensure they match or exceed the motor's requirements. The relay should be capable of handling the motor's inrush current, which can be significantly higher than its running current. Additionally, the relay's response time should be suitable for the application's timing requirements, and it should be rated for the expected number of operations to ensure reliability and longevity.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?