【问题标题】:How do I flip specific bits in a specific spot and carry the value to do it again later in the program如何在特定位置翻转特定位并携带该值以便稍后在程序中再次执行
【发布时间】:2021-10-11 00:14:51
【问题描述】:

我的计划是设置 PORTA= 0x0F 因此 PORTA= 00001111 然后在 if 循环中翻转 PORTC 中的符号,所以现在 PORT C 是 00001111 然后另一个 if 循环说如果 PORTC 的 0-3 = 1 然后设置 PORTC7=1 显示如 PORTC=10001111

#include <avr/io.h>
#ifdef _SIMULATE_
#include "simAVRHeader.h"
#endif

int main(void) {
    DDRA = 0x00; PORTA = 0xFF; // Configure port A's 8 pins as inputs
    DDRC = 0xFF; PORTC = 0x00; // Configure port C's 8 pins as outputs, initialize to 0s
    while (1)
{


    if(!(PINA & 0x01)){
        PORTC |= 0x01;
    }
    if(!(PINA & 0x02)){
        PORTC |= 0x02;
    }
    if(!(PINA & 0x04)){
        PORTC |= 0x04;
        }
    if(!(PINA & 0x08)){
        PORTC |= 0x08;
        }

    if(PORTC==0x0F)
    {
        PORTC |= 0x80;
    }
    

}

return 0;
}

【问题讨论】:

  • PORTA 根据代码初始化为0x11111111。你想要这个初始化然后将它设置为0x00001111。如果一次翻转PORTC 的所有 4 个最低有效位可以吗?或者你想一个一个地做,如显示的代码?
  • 我正在单独做一个测试用例,但是例如如果端口 A 是:0000 1111 那么端口 C 应该是 0000 0000
  • 如果要在对应的PORTA管脚为低电平时设置PORTC管脚,则必须写if(PINA &amp; 0x01)。不知道您为什么在其中包含!

标签: c embedded


【解决方案1】:

要启用某个位,请使用 OR (|) 与该位。

要禁用位,请使用 AND (&amp;) 与除该位之外的所有内容,使用按位非 (~)。

要更改位的值(0 到 1 或 1 到 0),请使用按位异或 (^)。

这是一个例子:

#include <stdint.h>

int main ()
{
  uint8_t bits = 0x00;
  uint8_t mask = 0x01;
  //enable bit
  bits |= mask;
  //disable bit
  bits &= ~mask;
  //flip bit
  bits ^= mask;
  //flip bit again
  bits ^= mask;
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 2012-03-28
    • 2020-01-07
    • 2021-02-27
    • 1970-01-01
    • 2012-07-21
    相关资源
    最近更新 更多