Print rotary encoder values on 7-segment display with PIC® MCU

This is another example that shows how to interface PIC18F46K22 microcontroller with common anode 7-segment display.
This example shows how to print rotary encoder values (positive and negative) on 4-digit 7-segment display where the first digit (most left) is used for the minus sign ( – ). Here the rotary encoder is an input device and the 7-segment display is an output device.
The compiler used in this project is CCS C.

To see how to interface PIC18F46K22 microcontroller with 7-segment display (4-digit counter example), visit the following post:
Interfacing PIC18F46K22 with 7-segment display | 4-Digit counter example

Components Required:

  • PIC18F46K22 microcontroller   —->  datasheet
  • 4-digit common anode 7-segment display
  • 4 x PNP transistor  (2SA10152S90152N3906 …)
  • Rotary encoder
  • 7 x 100 ohm resistor
  • 4 x 4.7k ohm resistor
  • 5V source
  • Breadboard
  • Jumper wires

PIC18F46K22 with 7-segment display and rotary encoder circuit:
The image below shows our example circuit diagram.

PIC18F46K22 rotary encoder 7-segment display circuit

All the grounded terminals are connected together.

The rotary encoder board has 5 pins: GND, + , SW, DT (pin B or data pin) and CLK (pin A or clock pin) where:
GND is connected to circuit ground (0V)
+ is connected to +5V
SW is push button pin, not used in this example
DT is connected to PIC18F46K22 pin RB5 (#38)
CLK is connected to PIC18F46K22 pin RB4 (#37)

The 4 transistors are of the same type (PNP).

In this project the PIC18F46K22 microcontroller runs with its internal oscillator @ 8 MHz, MCLR pin is configured as an input pin.

PIC18F46K22 with 7-segment display and rotary encoder C code:
The following C code is for CCS C compiler, it was tested with version 5.051.

Since the 4 digits are multiplexed we need to refresh the display very quickly (display one digit at a time, others are off), for that I used Timer2 module (8-bit timer) interrupt with 1:16 prescaler and 1:2 postoscaler, this means Timer2 overflows every 2048 microseconds { 256/[8/(4 x 16)] = 256 x 8 = 2048 microseconds } and its interrupt occurred every 4096 microseconds (postoscaler = 2).

Timer2 module configuration is shown below (255 is the preload value):

PORTB interrupt-on-change is enabled for pins RB4 and RB5 which are respectively connected to CLK and DT pins of the rotary encoder. This interrupt detects falling and rising of the two lines:

Rest of code is described through comments.

CCS C Code:

The hardware circuit of this project should give a result similar to the one shown in the following video where Arduino UNO board is used:

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top