Lesson 7 Four Digits 7-Segment Display

Share for us
Share on facebook
Share on twitter
Share on pinterest
Share on whatsapp

Introduction

In this lesson, we will use a four digits 7-segment display to display a number from 0 to 9999.

Components

– 1*Raspberry Pi

– 1*Breadboard

– 1*Network cable (or USB wireless network adapter)

– 1*Four Digit 7-Segment Display

– Several jumper wires

Experimental Principle

When using one digit 7-segment display, if it is common anode, we will connect common anode pin to power source; if it is common cathode, we will connect common cathode pin to GND. When using four digit 7-segment display, the common anode or common cathode pin are used to control which digit is displayed. There is only one digit working. However, based on the principle of Persistence of Vision, we can see four 7-segment display is all displaying numbers. This is because electronic scanning speed is fast and we cannot notice it.

Experimental Procedures

Step 1: Connect the circuit

                      a ~ p  ——————————-  GPIO0 ~ GPIO7

                      d1 ~ d4 —————————–  GPIO11 ~ GPIO8

Step 2: Edit and save the code(see path/Rpi_ultraKit /07_segment/segment.c)

Step 3: Compile the code

gcc  segment.c  -lwiringPi 

Step 4: Run the program

./a.out

Now, you can see the four digits segment display a number from 0 to 9999.

Code

#include <wiringPi.h>
#include <stdio.h>

#define   Bit0    8
#define   Bit1    9
#define   Bit2   10
#define   Bit3   11

unsigned char const SegCode[10] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};

unsigned char DatBuf[4] = {0,0,0,0};

int cnt = 0;

void sysInit(void)
{
 int i;

 for(i=0;i<12;i++){
  pinMode(i, OUTPUT);
  digitalWrite(i, HIGH);
 }
}

void do_cnt(void)
{
 DatBuf[0] = SegCode[cnt % 10];
 DatBuf[1] = SegCode[cnt % 100 / 10];
 DatBuf[2] = SegCode[cnt % 1000 / 100];
 DatBuf[3] = SegCode[cnt / 1000];
}

void display(void)
{
 int i;

 for(i=0;i<100;i++){
  digitalWrite(Bit0, 0);
  digitalWrite(Bit1, 1);
  digitalWrite(Bit2, 1);
  digitalWrite(Bit3, 1);
  digitalWriteByte(DatBuf[0]);

  delay(1);

  digitalWrite(Bit0, 1);
  digitalWrite(Bit1, 0);
  digitalWrite(Bit2, 1);
  digitalWrite(Bit3, 1);
  digitalWriteByte(DatBuf[1]);

  delay(1);

  digitalWrite(Bit0, 1);
  digitalWrite(Bit1, 1);
  digitalWrite(Bit2, 0);
  digitalWrite(Bit3, 1);
  digitalWriteByte(DatBuf[2]);

  delay(1);

  digitalWrite(Bit0, 1);
  digitalWrite(Bit1, 1);
  digitalWrite(Bit2, 1);
  digitalWrite(Bit3, 0);
  digitalWriteByte(DatBuf[3]);

  delay(1);
 }
 cnt++;
 if(cnt == 10000){
  cnt = 0;
 }
}

int main(void)
{
 if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
  printf("setup wiringPi failed !");
  return 1;
 }

 sysInit();

 while(1){
  do_cnt();
  display();
 }

 return 0;
}