我不允许将Arduino库(或任何库)用于此程序。如何检查引脚的输入?
我找到了两个不同的功能:
在Arduino.h中:
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
关注digitalRead回到pgmspace.h:
#define __LPM_enhanced__(addr) \
(__extension__({ \
uint16_t __addr16 = (uint16_t)(addr); \
uint8_t __result; \
__asm__ __volatile__ \
( \
"lpm %0, Z" "\n\t" \
: "=r" (__result) \
: "z" (__addr16) \
); \
__result; \
}))
对于第一个,我不知道位和值来自哪里,我根本不理解第二个。
答案 0 :(得分:1)
没有必要去实现这些实现。它非常简单如下。
当引脚0为高电平时,LED13将亮起。我在arduino上测试了这段代码
#include <avr/io.h> // Includes all the definition of register port etc
#ifndef F_CPU
#define F_CPU 16000000UL //Need to include it before <util/delay.h>
#endif //Change 16000000 with your crystal freq. In my case its 16 MHz
#include <util/delay.h> //includes delay functions delay_ms and delay_us
void setup() {
// put your setup code here, to run once:
DDRB |= 0xFF; //Configured Port B as OP
DDRD &= 0x00; //Configured Port D as IP
}
void loop() {
// put your main code here, to run repeatedly:
if (PIND&(0x01)) //to check pin0 of portD (which is Pin 0 of arduino)
PORTB |= 0xFF;
else
PORTB &= 0x00;
}
答案 1 :(得分:0)
我将假设您使用Arduino Uno,但是,一般规则适用于任何Arduino。
然后,让我们假设你想要使用数字引脚2,所以在Atmega168 / 328上使用PD2。 (PD2是PORTD引脚2的缩写)。要将其用作输入,您需要执行以下操作:
DDRD &= ~(1 << PD2);
DDRD
是端口D的数据方向寄存器。整个操作将与引脚2对应的位设置为0。
然后阅读这个引脚:
if (PIND & (1<<PD2)) {
// do something
}
另外,请检查如何操作单个位:How do you set, clear, and toggle a single bit?