Search code examples
c8051keil

Configure port1 of 8051 micro-controller as input


I am writing a very simple application which allows one to change the temperature. The temperature is displayed using LEDS (BCD format)

I wrote the following code in Keil C51:

#include< REG51.h>

sbit select = P1^7;
sbit up = P1^0;
sbit down = P1^1;
int data room = 24;

void main()
{   int prog;
    P2 &=0x00;
    P1 |=0x83;
    prog = 0;
    while (1)
    {
        if(select == 1)
            prog++;
        if(prog == 1)
        {
            if(up == 1)
                room++;
            if(down == 1)
                room--;

            P2 = room;
        }
    }
}

I then complied this and obtained the Intel hex file which i then tried to simulate using the Edsim.

According to the C code the temp should change when prog=1 and when either up(p1.0) or down(p1.1) is pressed, but in the simulation it only changes when both select(p1.7) and up/down is pressed!

Why is this happening?


Solution

  • prog++ means that the value of prog increments by 1 every time that the condition select == 1 is true. This means that the condition prog == 1 is true only on the first iteration that it's incremented.

    Try changing prog++ to prog = 1.

    Edit: As per discussion in comments, if you wish to track the number of times select has gone up, you need to wait for it to be 0 again before you let prog be incremented again. For example:

    int prev = select;
    …
    if (select != prev) {
        // select has changed from its previous state
    
        prev = select;
        if (prev) {
            // select went from 0 to 1
            ++prog;
    
            if (prog == 1) {
               // code to be executed once only on the first press
            } else if (prog == 2) {
               // code to be executed once only on the second press
            } else if (prog >= 3) {
               // code to be executed once on every subsequent press
            }
        } else {
            // select went from 1 to 0
        }
    }
    
    if (prev) {
       // select is being pressed
    
       if (prog == 1) {
           // code to be executed _continuously_ while select is held down
           // (after first press only)
       }
       // ...
    }