0

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?

4

3 回答 3

2

prog++表示每次条件为真时,值prog加 1 。这意味着该条件仅在它增加的第一次迭代中为真。select == 1prog == 1

尝试更改prog++prog = 1.

编辑:根据评论中的讨论,如果您希望跟踪增加的次数select,您需要等待它再次为 0,然后才能prog再次增加。例如:

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)
   }
   // ...
}
于 2011-11-04T16:31:31.113 回答
2

我认为您的代码不能反映您想要它做什么。

if(select == 1)
            prog++;
        if(prog == 1)
        {

prog 最初为 0,因此 prog==1 仅在您第一次按下 select 时为真。

那时它进入 IF 并检查

if(up == 1)
                room++;
            if(down == 1)
                room--;

            P2 = room;

如果按下向上或向下,则将房间当前温度更改为 +1 或 -1。由于您使用按钮进行模拟,这意味着当您按下选择时,应该按下任何一个按钮。

然后将数据输出到P2

你需要做的是:

while (1)
{
    if(select== 1)
    {   
        P2 = room;
    }


   if(up == 1)
       room++;
   if(down == 1)
       room--; 
}

您仍然需要按选择来更新温度,然后按上/下来改变温度。如果你能让自己更清楚它是如何工作的,也许我可以提供更多帮助。

于 2011-11-04T16:44:19.420 回答
0

您应该尝试更改prog++prog = 1. 让我知道这是否有帮助!

于 2012-05-30T16:05:18.763 回答