1#include "esphome.h"
2
3class SN74HC165Component : public PollingComponent, public BinarySensor
4{
5 byte pinNum;
6 private:
7 const byte LATCH = 13; // ESP pin number that should be connected to pin 1 of 74hc165s
8 const byte DATA = 5; // ESP pin number that should be connected to pin 9 of first 74hc165
9 const byte CLOCK = 4; // ESP pin number that should be connected to pin 2 of 74hc165s
10
11 bool getBit(unsigned long x, byte n)
12 {
13 bool value = bitRead(x, n);
14 return value;
15 }
16
17 unsigned long shiftinput= 1;
18 unsigned long oldshiftinput= 0;
19
20 public:
21 SN74HC165Component (byte pin) : PollingComponent(100) { pinNum = pin; } // Change the number inside "PollingComponent(100)" to change update interval in miliseconds
22 float get_setup_priority() const override { return esphome::setup_priority::HARDWARE; }
23
24 void setup() override
25 {
26 pinMode(LATCH, OUTPUT);
27 pinMode(CLOCK, OUTPUT);
28 pinMode(DATA, INPUT);
29 digitalWrite(CLOCK, LOW);
30 digitalWrite(CLOCK, HIGH);
31 digitalWrite(LATCH, HIGH);
32 }
33
34 void update() override
35 {
36 digitalWrite(CLOCK, LOW);
37 digitalWrite(CLOCK, HIGH);
38 digitalWrite(LATCH, LOW);
39 digitalWrite(LATCH, HIGH);
40
41 shiftinput = shiftIn(DATA, CLOCK, LSBFIRST);
42 shiftinput |= shiftIn(DATA, CLOCK, LSBFIRST) << 8;
43 shiftinput |= shiftIn(DATA, CLOCK, LSBFIRST) << 16;
44 shiftinput |= shiftIn(DATA, CLOCK, LSBFIRST) << 24;
45
46 if (shiftinput != oldshiftinput)
47 {
48 publish_state(getBit(shiftinput, pinNum));
49 oldshiftinput = shiftinput;
50 }
51 }
52};