Activity 4. Counter of the 1s of input PORTD

The purpose of this activity is to count the 1s of PORTD and show the result at output PORTB.

(30 minutes)


Activity 4

Step 1. The circuit is drawn in the Proteus Design Suite. In this step 8 LEDs are connected to the PORTB parallel output port and 8 switches to the PORTD input port.



Step 2. The program in C language is written.

The student must complete the following program in C language.

#include<main.h>  // This file contains the initial settings

                                // It must be in the same folder with the project

 

#byte PORTB=0xF81 // F81 Is the position or PORTB data register

                                    // at the data memory of the microcontroller

                                    // SFR Special Function Register

 

#byte PORTD=0xF83  // F83 Is the position or PORTB data register

                                      // at the data memory of the microcontroller

                                     // SFR Special Function Register

 

// ********* main program ************************

 

void main()

{                                  // Opening bracket of main

 

set_tris_b(0x00);          // PORTB is set as output port

                                     // (PORTB Direction Register = 0000 0000)

 

set_tris_d(0xff);            // PORTD is set as input port 

                                      // (PORTD Direction Register = 1111 1111)

 

 

PORTB=0b00000000;    // PORTB takes the initial value of 0000 0000

 

 

int i=0;                               // Integer varable used in the  for() { }

                   

int a;                                   // Integer varable a

while(TRUE) {                  //Endless loop(condition always true)

            a=0;

            for (i=0; i<=7; i++){

…………………………………………………………………………

Complete the program with the necessary commands

 ………………………………………………………..……………….

                                            }  // Closing bracket of for() { }

            PORTB=a;                  // PORTB takes the value of the variable a

                                                // Variable a equals the multitude of 1s of  PORTD

            }                                  // Closing bracket of while

 

}                                              // Closing bracket of main

 

Tip1. The function bit_test(PORTD,i) checks the bit i of PORTD data register. If the bit equals to 1 then the function returns the value 1. If the bit is 0, then the function returns the value 0.

Tip2. We can use the counter a=a+ bit_test(PORTD,i) to count the 1s of PORTD



Step 3. The program is compiled with the use of CCS C compiler to the microcontroller machine code. The machine code is loaded to the flash memory of the microcontroller.



Step 4. By turning ON and OFF the switches connected to PORTD we form an 8 bit number. We check that the multitude of the 1s at PORTD is shown on PORTB