Arduino读取红外遥控与digitalWrite邂逅

    xiaoxiao2021-03-26  13

      Arduino 读取遥控器,例子程序正常,换到自己程序,每次读取的数值总是不一样?Why?测试环境为Arduino uno和Mulie-functions Shidle,读取用的Arduino-IRremote库。   例子程序很简单,代码如下:     

    #include <IRremote.h> int RECV_PIN = 11; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { Serial.begin(9600); irrecv.enableIRIn(); // Start the receiver } void loop() { if (irrecv.decode(&results)) { Serial.println(results.value, HEX); irrecv.resume(); // Receive the next value } delay(100); }

    我的程序稍微复杂,追踪原因,发现问题出在shiftOut函数。在四位共阳数码管显示的时候,用到了下面代码:

    digitalWrite(latchPin,LOW); //将ST_CP口上面加低电平让芯片准备好接收数据 shiftOut(dataPin,clockPin,MSBFIRST,Dis_table[10]); //发送显示码 0-3 shiftOut(dataPin,clockPin,MSBFIRST,Dis_buf[i] ); //发送通值 digitalWrite(latchPin,HIGH); //将ST_CP这个针脚恢复到高电平

    看上去正常啊,为了平滑显示,这段代码放在了定时器1中。为什么调用shiftOut会影响红外读取呢?在不同管脚啊?看下shiftOut源代码,在wiring_shift.c文件中:

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) { uint8_t i; for (i = 0; i < 8; i++) { if (bitOrder == LSBFIRST) digitalWrite(dataPin, !!(val & (1 << i))); else digitalWrite(dataPin, !!(val & (1 << (7 - i)))); digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } }

    再平常不过了,继续找原因,难道digitalWrite有问题?无奈看看digitalWrite源代码,在wiring_digital.c文件里:

    void digitalWrite(uint8_t pin, uint8_t val) { uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *out; if (port == NOT_A_PIN) return; // If the pin that support PWM output, we need to turn it off // before doing a digital write. if (timer != NOT_ON_TIMER) turnOffPWM(timer); out = portOutputRegister(port); uint8_t oldSREG = SREG; cli(); if (val == LOW) { *out &= ~bit; } else { *out |= bit; } SREG = oldSREG; }

    哦,digitalWrite函数居然有个cli(),折腾我一下午。将shiftOut改写:

    #define clockOn bitSet(PORTD, 7) #define clockOff bitClear(PORTD, 7) void shiftOut1(uint8_t val) { for (char i = 7; i >= 0; i--) { bitWrite(PORTB, 0, bitRead(val, i)); clockOn; clockOff; } }

    世界总算清静了,效率也提高了许多。

    转载请注明原文地址: https://ju.6miu.com/read-650203.html

    最新回复(0)