One Digit 7-Segment Display with Loops

We will use the same wiring as before to investigate how to use a loop to simplify code. The loop will cycle through a small set of instructions until a pre-determined condition is met. For this one, we will cycle through switching on the segments of the module and then cycle through switching them off. 

  • Start a new sketch (Arduino programs are called sketches)
  • Copy and paste the code into Arduino 

_______________________________________________________________________________________________________________________________________________________________

int pinA = 2;
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;
int pinF = 7;
int pinG = 8;
int pinDP = 9;

void setup()
{
  // define pin modes
  
 pinMode(pinF,OUTPUT);
 pinMode(pinG,OUTPUT);
 pinMode(pinC,OUTPUT);
 pinMode(pinD,OUTPUT);
 pinMode(pinE,OUTPUT);
 pinMode(pinB,OUTPUT);
 pinMode(pinA,OUTPUT);
 pinMode(pinDP,OUTPUT);
}

void loop() 
{
  // loop to turn leds of seven seg ON
  
  for(int i=2;i<10;i++)
  {
    digitalWrite(i,HIGH);
    delay(250);
  }
  
  // loop to turn leds of seven seg OFF
  for(int i=2;i<10;i++)
  {
    digitalWrite(i,LOW);
    delay(250);
  }
  
  
  delay(1000);

}
_______________________________________________________________________________________________________________________________________________________________
  • Notice that the pin declarations and initialisations are the same as the previous code (because we haven’t changed the setup on the breadboard).
  • Save your file then verify and upload to the Duinotech Mega Board  (Click the icon to verify your code is correct.  If no errors, then Click the   icon to upload your code to the board)

What does the output look like on the 7-segment module? 

Notice the sequencing. The “for” loop starts at pin 2 (i=2) and changes its state to high, which lights up the segment connected to that pin. The i++ then increments the value of i by one. i.e. i=2, i+1 therefore i=3. Delay (250) is an instruction to pause for 1/4 of a second before it then checks the condition i<10, and if this is true it turns pin 3 state to high and increments i by one again. The loop stops after i=9 and pass to the next loop, which will turn the segments off sequentially. 

Modify the code to prevent the middle segment from being used. This can be achieved by using two forward slashes at the start of each unrequired line. This will identify the line as a comment that the program will ignore. 

//pinMode(pinG,OUTPUT);

//int pinG = 8;

Can you modify the code so that the second “for” loop (the one that switches the LEDs off) goes in the opposite order?