//多个74HC165级联,上一级Q7引脚连接下一级的Q7,最后一级的Q7连到Arduino
const byte latchPin = 9; // to latch the inputs into the registers
const byte clockPin = 13; // I choose the SCK pin
const byte dataPin = 12; // I choose the MISO pin
uint32_t oldOptionSwitch = 0; // previous state of all the inputs
const int pulseWidth = 10; // pulse width in microseconds
void setup ()
{
Serial.begin( 115200);
pinMode( clockPin, OUTPUT); // clock signal, idle LOW
pinMode( latchPin, OUTPUT); // latch (copy input into registers), idle HIGH
digitalWrite( latchPin, HIGH);
}
void loop ()
{
// Give a pulse to the parallel load latch of all 74HC165
digitalWrite( latchPin, LOW);
delayMicroseconds( pulseWidth);
digitalWrite( latchPin, HIGH);
// Reading one 74HC165 at a time and combining them into a 32 bit variable
// The last 74HC165 is at the bottom, but the switches start numbering
// at the top. So the first byte has to be shifted into the highest place.
uint32_t optionSwitch = 0;
for( int i=24; i>=0; i-=8)
{
//每执行一次ReadOne165(),时钟信号就要移动8次,所以能自动读后边的位
//另外,由于ReadOne165()中有时钟信号,所以不能直接在print()里调用它,会移到错误的位上去
//“(uint32_t) ReadOne165()”读取一个8位的数据,转换为uint32_t类型
//“<< i”8位数据向左移动i位(24、16、8、0),如11111111移动成11111111000000000000000000000000
//"optionSwitch |= "是把几次移位的数字合并成一个数
optionSwitch |= ((uint32_t) ReadOne165()) << i;
//byte bits = ReadOne165();
//Serial.println(bits, BIN);
//optionSwitch |= ((uint32_t)bits) << i;
}
//分4组输出32位数字
Serial.print("optionSwitch: ");
for(int i=0; i<32; i++){
Serial.print(bitRead(optionSwitch, i));
if((i+1)%8 == 0 && i != 31)
{
Serial.print("-");
}
}
Serial.println();
/*for( int i = 0; i<32; i++)
{
if( bitRead( optionSwitch, i) != bitRead( oldOptionSwitch,i))
{
Serial.print( "Switch ");
if( i < 10)
Serial.print( " ");
Serial.print( i);
Serial.print( " is now ");
Serial.println( bitRead( optionSwitch, i) == 0 ? "down ↓" : "up ↑");
}
}
oldOptionSwitch = optionSwitch;*/
delay( 25); // slow down the sketch to avoid switch bounce
}
//一次读8位(即一个芯片的信号)
//由于Arduino自带的shiftIn函数的时钟信号控制和74HC165不同,所以只能自己写个函数
byte ReadOne165()
{
//函数中的局部变量一旦函数执行完毕,就会被销毁,相应的内存空间会被释放。
byte ret = 0x00;
// The first one that is read is the highest bit (input D7 of the 74HC165).
for( int i=7; i>=0; i--)
{
if( digitalRead( dataPin) == HIGH)
//把对应的位设为1
bitSet( ret, i);
digitalWrite( clockPin, HIGH);
delayMicroseconds( pulseWidth);
digitalWrite( clockPin, LOW);
}
//Serial.println(ret, BIN);
return( ret);
}