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中设置了我的刺激,当点击时向RD0
或RD2
发送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;