ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
as3935.cpp
Go to the documentation of this file.
1#include "as3935.h"
2#include "esphome/core/log.h"
3
4namespace esphome::as3935 {
5
6ESPHOME_LOG_TAG(TAG, "as3935");
7
9 this->irq_pin_->setup();
10 LOG_PIN(" IRQ Pin: ", this->irq_pin_);
11
12 // Write properties to sensor
13 this->write_indoor(this->indoor_);
14 this->write_noise_level(this->noise_level_);
15 this->write_watchdog_threshold(this->watchdog_threshold_);
16 this->write_spike_rejection(this->spike_rejection_);
17 this->write_lightning_threshold(this->lightning_threshold_);
18 this->write_mask_disturber(this->mask_disturber_);
19 this->write_div_ratio(this->div_ratio_);
20 this->write_capacitance(this->capacitance_);
21
22 // Handle setting up tuning or auto-calibration
23 if (this->tune_antenna_) {
24 ESP_LOGCONFIG(TAG, " Antenna tuning: ENABLED - lightning detection will not function in this mode");
25 this->tune_antenna();
26 } else if (this->calibration_) {
27 this->calibrate_oscillator();
28 }
29}
30
31void AS3935Component::dump_config() {
32 ESP_LOGCONFIG(TAG, "AS3935:");
33 LOG_PIN(" Interrupt Pin: ", this->irq_pin_);
34#ifdef USE_BINARY_SENSOR
35 LOG_BINARY_SENSOR(" ", "Thunder alert", this->thunder_alert_binary_sensor_);
36#endif
37#ifdef USE_SENSOR
38 LOG_SENSOR(" ", "Distance", this->distance_sensor_);
39 LOG_SENSOR(" ", "Lightning energy", this->energy_sensor_);
40#endif
41}
42
43void AS3935Component::loop() {
44 if (!this->irq_pin_->digital_read())
45 return;
46
47 uint8_t int_value = this->read_interrupt_register_();
48 if (int_value == NOISE_INT) {
49 ESP_LOGI(TAG, "Noise was detected - try increasing the noise level value!");
50 } else if (int_value == DISTURBER_INT) {
51 ESP_LOGI(TAG, "Disturber was detected - try increasing the spike rejection value!");
52 } else if (int_value == LIGHTNING_INT) {
53 ESP_LOGI(TAG, "Lightning has been detected!");
54#ifdef USE_BINARY_SENSOR
55 if (this->thunder_alert_binary_sensor_ != nullptr) {
56 this->thunder_alert_binary_sensor_->publish_state(true);
57 this->set_timeout(10, [this]() { this->thunder_alert_binary_sensor_->publish_state(false); });
58 }
59#endif
60#ifdef USE_SENSOR
61 uint8_t distance = this->get_distance_to_storm_();
62 PUBLISH_STATE(this->distance_sensor_, distance);
63
64 uint32_t energy = this->get_lightning_energy_();
65 PUBLISH_STATE(this->energy_sensor_, energy);
66#endif
67 }
68}
69
70void AS3935Component::write_indoor(bool indoor) {
71 ESP_LOGV(TAG, "Setting indoor to %d", indoor);
72 if (indoor) {
74 } else {
76 }
77}
78// REG0x01, bits[3:0], manufacturer default: 0010 (2).
79// This setting determines the threshold for events that trigger the
80// IRQ Pin.
81void AS3935Component::write_watchdog_threshold(uint8_t watchdog_threshold) {
82 ESP_LOGV(TAG, "Setting watchdog sensitivity to %d", watchdog_threshold);
83 if ((watchdog_threshold < 1) || (watchdog_threshold > 10)) // 10 is the max sensitivity setting
84 return;
85 this->write_register(THRESHOLD, THRESH_MASK, watchdog_threshold, 0);
86}
87
88// REG0x01, bits [6:4], manufacturer default: 010 (2).
89// The noise floor level is compared to a known reference voltage. If this
90// level is exceeded the chip will issue an interrupt to the IRQ pin,
91// broadcasting that it can not operate properly due to noise (INT_NH).
92// Check datasheet for specific noise level tolerances when setting this register.
93void AS3935Component::write_noise_level(uint8_t noise_level) {
94 ESP_LOGV(TAG, "Setting noise level to %d", noise_level);
95 if ((noise_level < 1) || (noise_level > 7))
96 return;
97
98 this->write_register(THRESHOLD, NOISE_FLOOR_MASK, noise_level, 4);
99}
100// REG0x02, bits [3:0], manufacturer default: 0010 (2).
101// This setting, like the watchdog threshold, can help determine between false
102// events and actual lightning. The shape of the spike is analyzed during the
103// chip's signal validation routine. Increasing this value increases robustness
104// at the cost of sensitivity to distant events.
105void AS3935Component::write_spike_rejection(uint8_t spike_rejection) {
106 ESP_LOGV(TAG, "Setting spike rejection to %d", spike_rejection);
107 if ((spike_rejection < 1) || (spike_rejection > 11))
108 return;
109
110 this->write_register(LIGHTNING_REG, SPIKE_MASK, spike_rejection, 0);
111}
112// REG0x02, bits [5:4], manufacturer default: 0 (single lightning strike).
113// The number of lightning events before IRQ is set high. 15 minutes is The
114// window of time before the number of detected lightning events is reset.
115// The number of lightning strikes can be set to 1,5,9, or 16.
116void AS3935Component::write_lightning_threshold(uint8_t lightning_threshold) {
117 ESP_LOGV(TAG, "Setting lightning threshold to %d", lightning_threshold);
118 switch (lightning_threshold) {
119 case 1:
120 this->write_register(LIGHTNING_REG, ((1 << 5) | (1 << 4)), 0, 4); // Demonstrative
121 break;
122 case 5:
123 this->write_register(LIGHTNING_REG, ((1 << 5) | (1 << 4)), 1, 4);
124 break;
125 case 9:
126 this->write_register(LIGHTNING_REG, ((1 << 5) | (1 << 4)), 1, 5);
127 break;
128 case 16:
129 this->write_register(LIGHTNING_REG, ((1 << 5) | (1 << 4)), 3, 4);
130 break;
131 default:
132 return;
133 }
134}
135// REG0x03, bit [5], manufacturer default: 0.
136// This setting will return whether or not disturbers trigger the IRQ Pin.
137void AS3935Component::write_mask_disturber(bool enabled) {
138 ESP_LOGV(TAG, "Setting mask disturber to %d", enabled);
139 if (enabled) {
140 this->write_register(INT_MASK_ANT, (1 << 5), 1, 5);
141 } else {
142 this->write_register(INT_MASK_ANT, (1 << 5), 0, 5);
143 }
144}
145// REG0x03, bit [7:6], manufacturer default: 0 (16 division ratio).
146// The antenna is designed to resonate at 500kHz and so can be tuned with the
147// following setting. The accuracy of the antenna must be within 3.5 percent of
148// that value for proper signal validation and distance estimation.
149void AS3935Component::write_div_ratio(uint8_t div_ratio) {
150 ESP_LOGV(TAG, "Setting div ratio to %d", div_ratio);
151 switch (div_ratio) {
152 case 16:
153 this->write_register(INT_MASK_ANT, ((1 << 7) | (1 << 6)), 0, 6);
154 break;
155 case 22:
156 this->write_register(INT_MASK_ANT, ((1 << 7) | (1 << 6)), 1, 6);
157 break;
158 case 64:
159 this->write_register(INT_MASK_ANT, ((1 << 7) | (1 << 6)), 1, 7);
160 break;
161 case 128:
162 this->write_register(INT_MASK_ANT, ((1 << 7) | (1 << 6)), 3, 6);
163 break;
164 default:
165 return;
166 }
167}
168// REG0x08, bits [3:0], manufacturer default: 0.
169// This setting will add capacitance to the series RLC antenna on the product
170// to help tune its resonance. The datasheet specifies being within 3.5 percent
171// of 500kHz to get optimal lightning detection and distance sensing.
172// It's possible to add up to 120pF in steps of 8pF to the antenna.
173void AS3935Component::write_capacitance(uint8_t capacitance) {
174 ESP_LOGV(TAG, "Setting tune cap to %d pF", capacitance * 8);
175 this->write_register(FREQ_DISP_IRQ, CAP_MASK, capacitance, 0);
176}
177
178// REG0x03, bits [3:0], manufacturer default: 0.
179// When there is an event that exceeds the watchdog threshold, the register is written
180// with the type of event. This consists of two messages: INT_D (disturber detected) and
181// INT_L (Lightning detected). A third interrupt INT_NH (noise level too HIGH)
182// indicates that the noise level has been exceeded and will persist until the
183// noise has ended. Events are active HIGH. There is a one second window of time to
184// read the interrupt register after lightning is detected, and 1.5 after
185// disturber.
187 // A 2ms delay is added to allow for the memory register to be populated
188 // after the interrupt pin goes HIGH. See "Interrupt Management" in
189 // datasheet.
190 ESP_LOGV(TAG, "Calling read_interrupt_register_");
191 delay(2);
192 return this->read_register_(INT_MASK_ANT, INT_MASK);
193}
194
195// REG0x02, bit [6], manufacturer default: 1.
196// This register clears the number of lightning strikes that has been read in
197// the last 15 minute block.
199 // Write high, then low, then high to clear.
200 ESP_LOGV(TAG, "Calling clear_statistics_");
201 this->write_register(LIGHTNING_REG, (1 << 6), 1, 6);
202 this->write_register(LIGHTNING_REG, (1 << 6), 0, 6);
203 this->write_register(LIGHTNING_REG, (1 << 6), 1, 6);
204}
205
206// REG0x07, bit [5:0], manufacturer default: 0.
207// This register holds the distance to the front of the storm and not the
208// distance to a lightning strike.
210 ESP_LOGV(TAG, "Calling get_distance_to_storm_");
212}
213
215 ESP_LOGV(TAG, "Calling get_lightning_energy_");
216 uint32_t pure_light = 0; // Variable for lightning energy which is just a pure number.
217 uint32_t temp = 0;
218 // Temp variable for lightning energy.
220 // Temporary Value is large enough to handle a shift of 16 bits.
221 pure_light = temp << 16;
222 temp = this->read_register(ENERGY_LIGHT_MSB);
223 // Temporary value is large enough to handle a shift of 8 bits.
224 pure_light |= temp << 8;
225 // No shift here, directly OR'ed into pure_light variable.
226 temp = this->read_register(ENERGY_LIGHT_LSB);
227 pure_light |= temp;
228 return pure_light;
229}
230
231// REG0x03, bit [7:6], manufacturer default: 0 (16 division ratio).
232// This function returns the current division ratio of the resonance frequency.
233// The antenna resonance frequency should be within 3.5 percent of 500kHz, and
234// so when modifying the resonance frequency with the internal capacitors
235// (tuneCap()) it's important to keep in mind that the displayed frequency on
236// the IRQ pin is divided by this number.
237uint8_t AS3935Component::read_div_ratio() {
238 ESP_LOGV(TAG, "Calling read_div_ratio");
239 uint8_t reg_val = this->read_register_(INT_MASK_ANT, DIV_MASK);
240 reg_val >>= 6; // Front of the line.
241
242 if (reg_val == 0) {
243 return 16;
244 } else if (reg_val == 1) {
245 return 32;
246 } else if (reg_val == 2) {
247 return 64;
248 } else if (reg_val == 3) {
249 return 128;
250 }
251 ESP_LOGW(TAG, "Unknown response received for div_ratio");
252 return 0;
253}
254
255uint8_t AS3935Component::read_capacitance() {
256 ESP_LOGV(TAG, "Calling read_capacitance");
257 uint8_t reg_val = this->read_register_(FREQ_DISP_IRQ, CAP_MASK) * 8;
258 return (reg_val);
259}
260
261// REG0x08, bits [5,6,7], manufacturer default: 0.
262// This will send the frequency of the oscillators to the IRQ pin.
263// _osc 1, bit[5] = TRCO - System RCO at 32.768kHz
264// _osc 2, bit[6] = SRCO - Timer RCO Oscillators 1.1MHz
265// _osc 3, bit[7] = LCO - Frequency of the Antenna
266void AS3935Component::display_oscillator(bool state, uint8_t osc) {
267 if ((osc < 1) || (osc > 3))
268 return;
269
270 this->write_register(FREQ_DISP_IRQ, OSC_MASK, state, 4 + osc);
271}
272
273// REG0x3D, bits[7:0]
274// This function calibrates both internal oscillators The oscillators are tuned
275// based on the resonance frequency of the antenna and so it should be trimmed
276// before the calibration is done.
277bool AS3935Component::calibrate_oscillator() {
278 ESP_LOGI(TAG, "Starting oscillators calibration");
279 this->write_register(CALIB_RCO, WIPE_ALL, DIRECT_COMMAND, 0); // Send command to calibrate the oscillators
280
281 this->display_oscillator(true, 2);
282 delay(2); // Give time for the internal oscillators to start up.
283 this->display_oscillator(false, 2);
284
285 // Check it they were calibrated successfully.
286 uint8_t reg_val_srco = this->read_register_(CALIB_SRCO, CALIB_MASK_NOK);
287 uint8_t reg_val_trco = this->read_register_(CALIB_TRCO, CALIB_MASK_NOK);
288
289 // reg_val_srco &= CALIB_MASK;
290 // reg_val_srco >>= 6;
291 // reg_val_trco &= CALIB_MASK;
292 // reg_val_trco >>= 6;
293 if (!reg_val_srco && !reg_val_trco) { // Zero upon success
294 ESP_LOGI(TAG, "Calibration was succesful");
295 return true;
296 } else {
297 ESP_LOGW(TAG, "Calibration was NOT succesful");
298 return false;
299 }
300}
301
302void AS3935Component::tune_antenna() {
303 uint8_t div_ratio = this->read_div_ratio();
304 uint8_t tune_val = this->read_capacitance();
305 ESP_LOGI(TAG,
306 "Starting antenna tuning\n"
307 " Division Ratio is set to: %d\n"
308 " Internal Capacitor is set to: %d\n"
309 " Displaying oscillator on INT pin. Measure its frequency - multiply value by Division Ratio",
310 div_ratio, tune_val);
311 this->display_oscillator(true, ANTFREQ);
312}
313
314uint8_t AS3935Component::read_register_(uint8_t reg, uint8_t mask) {
315 uint8_t value = this->read_register(reg);
316 value &= (~mask);
317 return value;
318}
319
320} // namespace esphome::as3935
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
virtual void setup()=0
virtual bool digital_read()=0
virtual uint8_t read_register(uint8_t reg)=0
virtual void write_register(uint8_t reg, uint8_t mask, uint8_t bits, uint8_t start_position)=0
uint8_t read_register_(uint8_t reg, uint8_t mask)
Definition as3935.cpp:314
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "as3935")
@ ENERGY_LIGHT_MMSB
Definition as3935.h:25
uint32_t value
Definition hal.cpp:41
void HOT delay(uint32_t ms)
Definition hal.cpp:85
static void uint32_t