3-phase PV router
Loading...
Searching...
No Matches
onewire_search.h
Go to the documentation of this file.
1
26
27#ifndef ONEWIRE_SEARCH_H
28#define ONEWIRE_SEARCH_H
29
30#include <stdint.h>
31
44template< typename Bus >
46{
47public:
48 explicit RomSearch(Bus& bus)
49 : bus{ bus }
50 {
51 }
52
61 bool next(uint8_t (&rom)[8])
62 {
63 if (lastDevice)
64 {
65 return false;
66 }
67 if (!bus.reset())
68 {
69 lastDiscrepancy = 0; // no device answers: the next search starts over
70 return false;
71 }
72 bus.write(SEARCH_ROM);
73
74 uint8_t lastZero{ 0 }; // last conflict where the 0 branch is taken, 1..64 (0: none)
75 for (uint8_t bit = 1; bit <= 64; ++bit)
76 {
77 const uint8_t idBit{ bus.read_bit() };
78 const uint8_t complementBit{ bus.read_bit() };
79 uint8_t& romByte{ rom[(bit - 1) / 8] };
80 const uint8_t mask{ static_cast< uint8_t >(1U << ((bit - 1) % 8)) };
81
82 if (idBit && complementBit)
83 {
84 // no device in the search any more: unplugged, or noise
86 return false;
87 }
88
89 bool direction{ idBit != 0 }; // no conflict: every device left has this bit
90 if (idBit == complementBit)
91 {
92 // a conflict: 1 at the last one taken as 0, 0 at a new one, as before up to there
93 direction = (bit < lastDiscrepancy) ? ((romByte & mask) != 0) : (bit == lastDiscrepancy);
94 if (!direction)
95 {
96 lastZero = bit;
97 }
98 }
99
100 romByte = static_cast< uint8_t >(direction ? (romByte | mask) : (romByte & ~mask));
101 bus.write_bit(direction ? 1 : 0); // the devices with the other bit leave the search
102 }
103
104 lastDiscrepancy = lastZero;
105 lastDevice = (0 == lastZero);
106 return true;
107 }
108
109private:
110 static constexpr uint8_t SEARCH_ROM{ 0xF0 };
111
112 Bus& bus;
113 uint8_t lastDiscrepancy{ 0 };
114 bool lastDevice{ false };
115};
116
117#endif /* ONEWIRE_SEARCH_H */
uint8_t lastDiscrepancy
RomSearch(Bus &bus)
bool next(uint8_t(&rom)[8])
Finds the next device on the bus.
static constexpr uint8_t SEARCH_ROM