用MPLAB XC8模拟PIC16F877A,按键复位故障端口


void main(void) { 
TRISB=0x07; 
PORTB=0x00; 
TRISD=0x00; 
PORTD=0x00;  
while(1) 
{ 
if(RB0)  // when RB0 is high
{ 
__delay_ms(100);
PORTD++;    // PORTD increments, PORTD outputs to a LED
__delay_ms(100); 
} 
if(RB2) //when RB2 is high
{
__delay_ms(100);
PORTD = 0x00; // reset PORTD to 0
break;
} 
} 
} 

RB2变高时,我使用上面的代码试图重置PORTD。我在MPLAB中设置了我的刺激,当点击时向RD0RD2发送20ms的脉冲高信号,并观察PORTD的SFR值。

RD2应该在设置为高时清除PORTD,但当我观察PORTD的SFR值时,PORTD总是先递增,然后在第二次单击时变为0。

假设PORTD的SFR值为3,当RB0为高时,PORTD增加到4,当RD2为高时,它应该回到零,但它变为5,然后如果RD2再次为高则变为零。

如何修改我的代码,使RD2立即重置PORTD

if(RB0) // when RB0 is high 
{ 
PORTD++; //Post increment 
}

if(RB2) //when RB2 is high
{

PORTD = 0x00; 
// Since ypu used post increment first PORTD will increment by 1 and then 
it will be assigned 0

} 

如何修改我的代码,以便RD2立即重置PORTD?

解决方案:使用预增量或PORTD=PORTD+1;

最新更新