Arduino shiftOut()在第1和第8位

时间:2015-06-01 12:32:59

标签: c++ binary arduino arduino-uno shift-register

所以我连接两个移位寄存器(CD4021BE用于输入,HC595N用于输出)并编写了一个小程序,打印到串行监视器按下哪些按钮,并使用unsigned char变量点亮相应的二极管。输入与shiftIn函数完美配合,但输出很奇怪。

按下按钮2-7时,一切正常。按第一个按钮可打印正确的char值但不会点亮二极管。按下第8个按钮也可以正确打印,但会点亮第1和第8个二极管。

我认为问题出在shiftOut函数的某处,但我找不到它。当使用互联网上的例子(二极管上的二进制倒计时)时,这些二极管工作得很好,所以布线很好但是我的代码似乎没有用。请告诉我我做错了什么。

// Support for HCF4021BE IC, basically any 4021 should work. The fastest way I could manage + debugging to console

#define pinLatch 8
#define pinInput 9                               //defining pins
#define pinClock 7
#define pinOutput 6

unsigned char currentByte, inputByte = 72;      //non-zero value for debug purposes

void setup() {
  Serial.begin(9600);
  pinMode(pinLatch, OUTPUT);                    //standard setup
  pinMode(pinClock, OUTPUT);
  pinMode(pinInput, INPUT);
  pinMode(pinOutput, OUTPUT);
}

void loop() {
  digitalWrite(pinLatch, 1);
  delayMicroseconds(20);                        //pulsing latch so that 4021 read inputs
  digitalWrite(pinLatch, 0);

  inputByte = shiftIn(pinInput, pinClock);      //read the byte returned by shiftIn to var
  if (currentByte != inputByte)                 //print only changes
  {
      if (inputByte != 0)
      {    
        for (int n = 0; n <= 7; n++)              //print which button is pressed        
          if (inputByte & (1 << n))               //if given n-th bit of input is true    
          {                                                                              
            Serial.print(n + 1);                  //print the number of the button (byte+1)        
            Serial.print(" ");
          }
      Serial.println();
      } else {
        Serial.println(0);
      }
  }
  currentByte = inputByte;
  shiftOut(pinOutput, pinClock, LSBFIRST, inputByte);
}

byte shiftIn(int myDataPin, int myClockPin) {

  byte myDataIn = 0;  
  for (int i = 7; i >= 0; i--)
  {
    digitalWrite(myClockPin, 0);                //pulsing the clockPin to read consequent bits/inputs of 4021
    delayMicroseconds(1);                     //the responsiveness of 4021
    if (digitalRead(myDataPin)) {               //if i-th input of 4021 is 1
      myDataIn = myDataIn |(1 << i);            //sets i-th bit of myDataIn byte to 1
    }
    digitalWrite(myClockPin, 1);
  }

  return myDataIn;
}

Code on pastebin

PS这是我在这里的第一篇文章,因为我是一名初学程序员。如果出现问题,请告诉我。)

0 个答案:

没有答案