编程我的Atmega644 MCU时。为什么PORTD | = 0b00100000有效,但不是PORTD | =(PD5 << 1)?

问题描述 投票:0回答:2

我一直试图理解为什么这一行

 PORTD |= 0b00100000;

有效,但不是

PORTD |= (PD5 <<1);

我有一个连接到PD5的LED,它只为第一个命令点亮。我是否必须定义“PD5”是什么?我从来没有在我的Atmega328P上做到这一点,但现在在Atmega644它不起作用?

这是我包含的库

  #define F_CPU 1000000UL  // 1MHz internal clock
  #include <avr/io.h>
  #include <util/delay.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <avr/interrupt.h>
  #include "lcd.h"

不确定是否有什么可以引起麻烦?我错过了一些非常基本的东西吗?

c microcontroller atmega atmel
2个回答
0
投票

作业有所不同。

PORTD |= 0b00100000;

将PORT D的第5位设为1

PORTD |= (PD5 <<1);

将PORTD的第1位和第2位设置为1(PD5 == 5,PD5 << 1 == 10(0x0A),即1010二进制)

定义一些宏来打开或关闭LED,以防止每次都设置'位'

#define LEDON PORTD |= 0b00100000
#define LEDOFF PORTD &= ~0b00100000

用法示例

if ( put_led_on )
    LEDON;
else
    LEDOFF;

或者感谢您自己的研究

PORTD |= (1<<PD5);

这将把第5位设置为1


1
投票

PORTD | =(PD5 << 1);

PD5被定义为数字5.左移一位给你10,这与你想要的值无关。

另一方面,1 << PD5将给你左移1×5位的结果,这等于0b00100000 - 正是你所追求的。

© www.soinside.com 2019 - 2024. All rights reserved.