解释一下有关 AVR 端口设置的代码
以下有什么作用?
PORTB = (PORTB & ~0xFC) | (b & 0xFC);
PORTD = (PORTD & ~0x30) | ((b << 4) & 0x30);
AFAIK,0xFC 是一个十六进制值。这基本上是说 11111100,因此 PORTD0-PORTD1 是输出,但其余的是输入。
该代码的完整解释是什么?
What does the following do?
PORTB = (PORTB & ~0xFC) | (b & 0xFC);
PORTD = (PORTD & ~0x30) | ((b << 4) & 0x30);
AFAIK, the 0xFC is a hex value. Is that basically saying 11111100, hence PORTD0-PORTD1 are outputs but the rest are inputs.
What would a full explanation of that code be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
分解:
选择
PORTB
的低两位。选择 b 的高 6 位。
将它们组合在一起,
PORTB
将包含 b 的高六位和PORTB
的低两位。分解:
选择 PORTD 中除了第 4 和第 5 位(从 0 开始计数)之外的所有位
将 b 视为一个位字段:
将两个部分进行或运算,
PORTD
将包含 <的第 0 位和第 1 位code>b 位于第 4 和第 5 位,其余部分为 PORTD 的原始值。Breaking it down:
Selects the lower two bits of
PORTB
.Selects the upper 6 bits of b.
ORing them together,
PORTB
will contain the upper six bits of b and the lower two bits ofPORTB
.Breaking it down:
Selects all but the 4th and 5th (counting from 0) bits of PORTD
Consider b as a field of bits:
ORing the two pieces together,
PORTD
will contain the 0th and 1st bits ofb
in its 4th and 5th bits and the original values of PORTD in the rest.第一行实际上设置端口 PB7-PB2 线的状态。首先使用
~0xFC
=0x03
屏蔽 PORTB 的当前状态,因此除 0 和 1 之外的所有位都会重置。第二步是使用 0xFC 屏蔽
b
,因此位 0 和 1 始终为 0。然后将这些值进行“或”运算。实际上,它从 b[7]..b[2] 设置 PB7-PB2,同时保持 PB1 和 PB0 的当前状态不变。请注意,PORTB 寄存器位具有不同的用途,具体取决于通过 DDRB 寄存器配置的引脚方向。对于输出引脚,它只是控制引脚状态。对于输入引脚,PORTB 控制引脚的上拉电阻。例如,如果您在引脚和地之间连接了一个按钮,则必须启用此上拉电阻 - 这样当开关打开时输入引脚不会浮动。
The first line actually sets the state of port's PB7-PB2 lines. The current state of PORTB is first masked using
~0xFC
=0x03
, so all bits, but 0 and 1, are reset.The second step is masking
b
using 0xFC, so bits 0 and 1 are always 0. Then the values are OR'ed together. Effectively, it sets PB7-PB2 from b[7]..b[2], while keeping the current state of PB1 and PB0 untouched.Note, that the PORTB register bits serve different purposes depending on the pin direction configured via the DDRB register. For output pins, it simply controls the pin state. For input pins, PORTB controls the pin's pull-up resistor. You have to enable this pull-up resistor if, for example, you have a push button connected between the pin and ground - this way the input pin is not floating when the switch is open.