-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAS7331.cpp
More file actions
1149 lines (935 loc) · 35.6 KB
/
AS7331.cpp
File metadata and controls
1149 lines (935 loc) · 35.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file AS7331.cpp
* @brief Implementation of AS7331 UV Spectral Sensor Driver
*/
#include "AS7331.hpp"
#include <furi_hal_i2c.h>
#include <furi_hal.h>
#include <cmath> // For pow()
// Prevent compiler optimization, for debugging.
// #pragma GCC optimize("O0")
// Timeout value for I2C operations (in milliseconds)
#define AS7331_I2C_TIMEOUT 100
// Constructor
AS7331::AS7331(uint8_t i2c_address_7bit)
// Convert 7-bit to 8-bit address
: _i2c_addr_8bit(i2c_address_7bit << 1)
// Initialize to invalid mode to force first-time setup
, _deviceMode(static_cast<as7331_device_mode_t>(0x00))
, _power_down(true)
, _gain(GAIN_2)
, _integration_time(TIME_64MS)
, _enable_divider(false)
, _divider(DIV_2)
, _clock_frequency(CCLK_1_024_MHZ)
, _standby(false)
, _measurement_mode(MEASUREMENT_MODE_COMMAND) {
}
// Initialize the sensor
bool AS7331::init(const uint8_t& i2c_address_7bit) {
uint8_t detected_address_7bit = 0;
if(i2c_address_7bit == 0x0) {
// Scan I2C bus for AS7331 device
detected_address_7bit = scan_i2c_bus();
if(detected_address_7bit == 0x0) {
FURI_LOG_E(
"AS7331",
"Failed to find an AS7331 device with one of the four valid addresses on the I2C bus.");
return false;
}
} else {
if(deviceReady(i2c_address_7bit)) {
detected_address_7bit = i2c_address_7bit;
} else {
FURI_LOG_E("AS7331", "No device found at I2C address 0x%02X.", i2c_address_7bit);
return false;
}
}
// Set the I2C address (7-Bit to 8-Bit)
_i2c_addr_8bit = detected_address_7bit << 1;
// Wake up the device from power-down mode
if(!setPowerDown(false)) {
FURI_LOG_E("AS7331", "Failed to wake up the device from power-down mode.");
return false;
}
// Set the device into configuration mode
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
bool success = setDeviceMode(DEVICE_MODE_CONFIG);
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
if(!success) {
FURI_LOG_E("AS7331", "Failed to set the device into configuration mode.");
return false;
}
// Populate local configuration variables from device registers
if(!updateLocalConfig()) {
FURI_LOG_E("AS7331", "Failed to read device configuration registers.");
return false;
}
// Read the device ID
as7331_agen_reg_t deviceID;
if(!getDeviceID(deviceID)) {
FURI_LOG_E("AS7331", "Failed to read device ID.");
return false;
}
// Compare with expected Device ID
if(deviceID.byte != ExpectedAGENContent) {
FURI_LOG_E(
"AS7331",
"Device ID mismatch: expected 0x%02X, got 0x%02X.",
ExpectedAGENContent,
deviceID.byte);
return false;
}
return true;
}
// Set sensor gain (CREG1:GAIN)
bool AS7331::setGain(const as7331_gain_t& gain) {
if(gain > GAIN_1) {
FURI_LOG_E("AS7331", "Invalid gain value: %d.", gain);
return false;
}
as7331_creg1_reg_t creg1;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in configuration mode
if(!setDeviceMode(DEVICE_MODE_CONFIG)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed set device mode to configuration.");
return false;
}
// Read CREG1
if(!readRegister(RegCfgCreg1, creg1.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read CREG1 register from device.");
return false;
}
// Write new gain value
creg1.gain = gain;
if(!writeRegister(RegCfgCreg1, creg1.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to write gain value to device: %d.", creg1.gain);
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Update local config
_gain = gain;
return true;
}
// Set integration time (CREG1:TIME)
bool AS7331::setIntegrationTime(const as7331_integration_time_t& time) {
// Validate integration time value
if(time > TIME_16384MS) {
FURI_LOG_E("AS7331", "Invalid integration time value: %d.", time);
return false;
}
// Automatically set divider depending on ADC resolution to prevent overflow
// Since this voids advantages of higher integration times, remove once overflow checking is implemented.
/*
int adc_resolution;
if(time == 15) {
// Special case: Same as TIME 0
adc_resolution = 10;
} else {
adc_resolution = 10 + time;
}
if(adc_resolution > 16) {
as7331_divider_t divider = static_cast<as7331_divider_t>(adc_resolution - 17);
setDivider(divider, true);
} else if(_enable_divider) {
setDivider(DIV_2, false);
}
*/
as7331_creg1_reg_t creg1;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in configuration mode
if(!setDeviceMode(DEVICE_MODE_CONFIG)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to configuration.");
return false;
}
// Read CREG1
if(!readRegister(RegCfgCreg1, creg1.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read CREG1 register from device.");
return false;
}
// Write new integration time value
creg1.integration_time = time;
if(!writeRegister(RegCfgCreg1, creg1.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E(
"AS7331",
"Failed to write integration time value to device: %d.",
creg1.integration_time);
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Update local config
_integration_time = time;
return true;
}
// Set output divider (CREG2:DIV)
bool AS7331::setDivider(const as7331_divider_t& divider, const bool enable) {
// Validate divider value
if(divider > DIV_256) {
FURI_LOG_E("AS7331", "Invalid divider value: %d.", divider);
return false;
}
as7331_creg2_reg_t creg2;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in configuration mode
if(!setDeviceMode(DEVICE_MODE_CONFIG)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to configuration.");
return false;
}
// Read CREG2
if(!readRegister(RegCfgCreg2, creg2.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read CREG2 register from device.");
return false;
}
// Write new divider value and enable/disable it
creg2.divider = divider;
creg2.enable_divider = enable;
if(!writeRegister(RegCfgCreg2, creg2.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E(
"AS7331",
"Failed to write divider settings to device: DIV=%d, ENABLE=%d.",
creg2.divider,
creg2.enable_divider);
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Update local config
_enable_divider = enable;
_divider = divider;
return true;
}
// Set clock frequency (CREG3:CCLK)
bool AS7331::setClockFrequency(const as7331_clock_frequency_t& frequency) {
// Validate clock frequency value
if(frequency > CCLK_8_192_MHZ) {
FURI_LOG_E("AS7331", "Invalid clock frequency value: %d.", frequency);
return false;
}
as7331_creg3_reg_t creg3;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in configuration mode
if(!setDeviceMode(DEVICE_MODE_CONFIG)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to configuration.");
return false;
}
// Read CREG3
if(!readRegister(RegCfgCreg3, creg3.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read CREG3 register from device.");
return false;
}
// Write new clock frequency value
creg3.clock_frequency = frequency;
if(!writeRegister(RegCfgCreg3, creg3.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E(
"AS7331",
"Failed to write clock frequency value to device: %d.",
creg3.clock_frequency);
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Update local config
_clock_frequency = frequency;
return true;
}
// Set measurement mode (CREG3:MMODE)
bool AS7331::setMeasurementMode(const as7331_measurement_mode_t& mode) {
// Validate measurement mode value
if(mode > MEASUREMENT_MODE_SYNC_START_END) {
FURI_LOG_E("AS7331", "Invalid measurement mode value: %d.", mode);
return false;
}
as7331_creg3_reg_t creg3;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in configuration mode
if(!setDeviceMode(DEVICE_MODE_CONFIG)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to configuration.");
return false;
}
// Read CREG3
if(!readRegister(RegCfgCreg3, creg3.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read CREG3 register from device.");
return false;
}
// Write new measurement mode value
creg3.measurement_mode = mode;
if(!writeRegister(RegCfgCreg3, creg3.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E(
"AS7331", "Failed to write measurement mode to device: %d.", creg3.measurement_mode);
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Update local config
_measurement_mode = mode;
return true;
}
// Enable or disable power down state (OSR:PD)
bool AS7331::setPowerDown(const bool& power_down) {
// The power-down feature affects both operational states: configuration and measurement.
// When the power-down state is activated while the device is in a measurement cycle,
// the power-down action is only executed during the intervals between consecutive conversions.
// Power Down Current Consumption: max 1µA
// Startup Time after Power Down state: 1.2-2ms
as7331_osr_reg_t osr;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// OSR is accessible in any mode
// Read OSR register
if(!readOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read OSR register from device.");
return false;
}
// Check if the desired power down state is already set
if(osr.power_down != power_down) {
osr.power_down = power_down; // Set PD bit
// Write back the OSR register
// Local configuration (_power_down) is updated in writeOSRRegister
if(!writeOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to write power down state to device: %d.", power_down);
return false;
}
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
return true;
}
// Put the sensor in standby mode or wake it up (CREG3:SB)
bool AS7331::setStandby(const bool& standby) {
// Standby Current Consumption: max 970 µA
// Startup Time after Standby state: 4-5 µs
as7331_creg3_reg_t creg3;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in configuration mode
if(!setDeviceMode(DEVICE_MODE_CONFIG)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to configuration.");
return false;
}
// Read CREG3
if(!readRegister(RegCfgCreg3, creg3.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read CREG3 register from device.");
return false;
}
// Check if the desired standby state is already set
if(creg3.standby != standby) {
creg3.standby = standby; // Set SB bit
// Write back the CREG3 register
if(!writeRegister(RegCfgCreg3, creg3.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to write standby state to device: %d.", standby);
return false;
}
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Update local config
_standby = standby;
return true;
}
// Start the measurement (OSR:SS = 1)
bool AS7331::startMeasurement() {
as7331_osr_reg_t osr;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in measurement mode
if(!setDeviceMode(DEVICE_MODE_MEASURE)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to measurement.");
return false;
}
// Read OSR register
if(!readOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read OSR register from device.");
return false;
}
// Check if measurement is already started
if(osr.start_state != 1) {
osr.start_state = 1; // Set SS bit to start measurement
// Write back OSR register
if(!writeOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to write OSR register to start measurement.");
return false;
}
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
return true;
}
// Stop the measurement (OSR:SS = 0)
bool AS7331::stopMeasurement() {
as7331_osr_reg_t osr;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Read OSR register
if(!readOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read OSR register from device.");
return false;
}
// Check if measurement is already stopped
if(osr.start_state != 0) {
osr.start_state = 0; // Clear SS bit to stop measurement
// Write back OSR register
if(!writeOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to write OSR register to stop measurement.");
return false;
}
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
return true;
}
// Wait for measurement to complete based on conversion time
void AS7331::waitForMeasurement() {
double TCONV = getConversionTime();
if(TCONV > 0) {
// Wait for TCONV time, adding a small buffer
furi_delay_ms(static_cast<uint32_t>(TCONV * 1000) + 1); // Add 1 ms to ensure completion
}
}
// Get raw measurement results
bool AS7331::getRawResults(RawResults& rawResults) {
uint8_t buffer[6]; // Each result is 2 bytes, so 3 results * 2 bytes = 6 bytes
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in measurement mode
if(!setDeviceMode(DEVICE_MODE_MEASURE)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to measurement.");
return false;
}
// Read all measurement results in one I²C transaction
if(!readRegisters(RegMeasResultA, buffer, 6)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read measurement results from device.");
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Combine the bytes into 16-bit values (LSB first)
rawResults.uv_a = (static_cast<uint16_t>(buffer[1]) << 8) | buffer[0];
rawResults.uv_b = (static_cast<uint16_t>(buffer[3]) << 8) | buffer[2];
rawResults.uv_c = (static_cast<uint16_t>(buffer[5]) << 8) | buffer[4];
return true;
}
// Get processed measurement results with raw data
bool AS7331::getResults(Results& results, RawResults& rawResults) {
bool success = true;
// Get the raw measurement results
success &= getRawResults(rawResults);
if(!success) {
return false;
}
// Calculate FSREe for each channel
double FSREe_A = calculateFSREe(UV_A, false);
double FSREe_B = calculateFSREe(UV_B, false);
double FSREe_C = calculateFSREe(UV_C, false);
FURI_LOG_I("AS7331", "FSREe_A: %f", FSREe_B);
FURI_LOG_I("AS7331", "FSREe_B: %f", FSREe_C);
FURI_LOG_I("AS7331", "FSREe_C: %f", FSREe_C);
if(FSREe_A < 0 || FSREe_B < 0 || FSREe_C < 0) {
// Invalid FSREe calculation
return false;
}
// Adjust FSREe for clock frequency
// Since FSREe is inversely proportional to fCLK,
// we adjust FSREe by dividing by the clock frequency ratio
double fCLK_ratio = static_cast<double>(1 << _clock_frequency); // fCLK_actual / fCLK_base
FSREe_A /= fCLK_ratio;
FSREe_B /= fCLK_ratio;
FSREe_C /= fCLK_ratio;
// Get NCLK from TIME_code
uint32_t NCLK;
if(_integration_time == 15) {
NCLK = 1024;
} else if(_integration_time <= 14) {
NCLK = 1 << (10 + _integration_time);
} else {
return false; // Invalid TIME_code
}
// Adjust NCLK and FSREe for Divider if enabled
if(_enable_divider) {
int divider_factor = 1 << (_divider + 1); // Divider factor is 2^(DIV + 1)
NCLK /= divider_factor; // Adjust NCLK
// Alternatively, we could adjust MRES, but adjusting NCLK is equivalent and simpler
}
// Calculate LSB for each channel
double LSB_A = FSREe_A / NCLK;
double LSB_B = FSREe_B / NCLK;
double LSB_C = FSREe_C / NCLK;
// Calculate Ee (Irradiance in µW/cm²) for each channel
results.uv_a = rawResults.uv_a * LSB_A;
results.uv_b = rawResults.uv_b * LSB_B;
results.uv_c = rawResults.uv_c * LSB_C;
return true;
}
// Get processed measurement results
bool AS7331::getResults(Results& results) {
RawResults rawResults; // Temporary variable
return getResults(results, rawResults); // Call the core function
}
// Read temperature measurement (16-bit)
bool AS7331::getTemperature(double& temperature) {
uint16_t temperature_raw;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in measurement mode
if(!setDeviceMode(DEVICE_MODE_MEASURE)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to measurement.");
return false;
}
// Read temperature register
if(!readRegister16(RegMeasTemp, temperature_raw)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read temperature register from device.");
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Calculate temperature in Celsius (Datasheet p. 42)
temperature = temperature_raw * 0.05 - 66.9; // [°C]
return true;
}
// Check if the device is ready
bool AS7331::deviceReady(const uint8_t& i2c_address_7bit) {
uint8_t i2c_address_8bit;
if(i2c_address_7bit == 0) {
i2c_address_8bit = _i2c_addr_8bit;
} else {
i2c_address_8bit = i2c_address_7bit << 1; // Convert 7-bit to 8-bit address
}
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
bool ready = furi_hal_i2c_is_device_ready(
&furi_hal_i2c_handle_external, i2c_address_8bit, AS7331_I2C_TIMEOUT);
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
return ready;
}
// Perform a software reset (OSR:SW_RES = 1)
bool AS7331::reset() {
// Setting SW_RES to '1' triggers a software reset of the AS7331.
as7331_osr_reg_t osr;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// OSR is accessible in any mode
if(!readOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read OSR register from device.");
return false;
}
osr.software_reset = 1; // Set SW_RES bit
if(!writeOSRRegister(osr)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to write OSR register to reset device.");
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
// Update local configuration variables from device registers
_deviceMode = DEVICE_MODE_CONFIG;
if(!updateLocalConfig()) {
FURI_LOG_E("AS7331", "Failed to read device configuration registers.");
return false;
}
return true;
}
// Getter methods
// Read device ID (including mutation number)
bool AS7331::getDeviceID(as7331_agen_reg_t& deviceID) {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
if(!readRegister(RegCfgAgen, deviceID.byte)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read device ID register from device.");
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
return true;
}
// Read status register in measurement mode
bool AS7331::getStatus(as7331_osr_status_reg_t& status) {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in measurement mode
if(!setDeviceMode(DEVICE_MODE_MEASURE)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to set device mode to measurement.");
return false;
}
if(!readRegister16(RegMeasOsrStatus, status.word)) {
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
FURI_LOG_E("AS7331", "Failed to read status register from device.");
return false;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
return true;
}
// Local config getter methods
// Getter for gain code
as7331_gain_t AS7331::getGain() const {
return _gain;
}
// Getter for actual gain value
int16_t AS7331::getGainValue() const {
// Gain value is calculated using the formula: gain = 2^(11 - gain_code)
return 1 << (11 - _gain);
}
// Getter for integration time code
as7331_integration_time_t AS7331::getIntegrationTime() const {
return _integration_time;
}
// Get conversion time in seconds
double AS7331::getConversionTime() const {
// Base clock frequency is 1.024 MHz
double fCLK_base = 1.024e6; // Hz
// Actual clock frequency based on CCLK code
double fCLK = fCLK_base * (1 << _clock_frequency);
// Calculate NCLK based on TIME code
uint32_t NCLK; // Number of clock cycles within conversion time
if(_integration_time == 15) {
NCLK = 1024; // Special case: Same as TIME 0
} else if(_integration_time <= 14) {
NCLK = 1 << (10 + _integration_time);
} else {
// Invalid TIME code
return -1.0;
}
// Conversion time TCONV
double TCONV = static_cast<double>(NCLK) / fCLK; // in seconds
return TCONV;
}
// Getter for divider code
as7331_divider_t AS7331::getDivider() const {
return _divider;
}
// Getter for divider enabled state
bool AS7331::isDividerEnabled() const {
return _enable_divider;
}
// Getter for actual divider value
uint8_t AS7331::getDividerValue() const {
// Divider value is calculated using the formula: divider = 2^(1 + divider_code)
uint8_t divider_value = 1 << (1 + _divider);
return divider_value;
}
// Getter for clock frequency code
as7331_clock_frequency_t AS7331::getClockFrequency() const {
return _clock_frequency;
}
// Getter for actual clock frequency value
double AS7331::getClockFrequencyValue() const {
// Clock frequency is calculated using the formula: fCLK = 1.024 * 2^clock_frequency_code (in MHz)
uint32_t freq_multiplier = 1 << _clock_frequency; // 2^clock_frequency_code
double clock_frequency_value = 1.024 * freq_multiplier; // in MHz
return clock_frequency_value;
}
// Getter for measurement mode
as7331_measurement_mode_t AS7331::getMeasurementMode() const {
return _measurement_mode;
}
// Getter for power down state
bool AS7331::isPowerDown() const {
return _power_down;
}
// Getter for standby state
bool AS7331::isStandby() const {
return _standby;
}
// Internal helper methods
// Set the device mode
bool AS7331::setDeviceMode(const as7331_device_mode_t& mode) {
if(mode != DEVICE_MODE_CONFIG && mode != DEVICE_MODE_MEASURE) {
FURI_LOG_E("AS7331", "Invalid device mode value: %d.", mode);
return false;
}
if(_deviceMode == mode) {
return true; // Already in desired mode
}
// Read OSR register
as7331_osr_reg_t osr;
if(!readOSRRegister(osr)) {
FURI_LOG_E("AS7331", "Failed to read OSR register from device.");
return false;
}
// Set operating state (DOS bits)
osr.operating_state = mode;
// If transitioning to Measurement state, ensure power-down is disabled
if(mode == DEVICE_MODE_MEASURE) {
osr.power_down = 0;
}
// Write back OSR register
// '_deviceMode' is updated in writeOSRRegister
if(!writeOSRRegister(osr)) {
FURI_LOG_E("AS7331", "Failed to write OSR register to set device mode.");
return false;
}
return true;
}
// Read OSR register and update local config
bool AS7331::readOSRRegister(as7331_osr_reg_t& osr) {
if(!readRegister(RegCfgOsr, osr.byte)) {
FURI_LOG_E("AS7331", "Failed to read OSR Register from device.");
return false;
}
if(osr.operating_state != DEVICE_MODE_CONFIG && osr.operating_state != DEVICE_MODE_MEASURE) {
FURI_LOG_E(
"AS7331", "Invalid operating state value read from device: %d.", osr.operating_state);
return false;
}
// Update local config
_deviceMode = osr.operating_state;
_power_down = osr.power_down;
return true;
}
// Write OSR register and update local config
bool AS7331::writeOSRRegister(const as7331_osr_reg_t& osr) {
if(osr.operating_state != DEVICE_MODE_CONFIG && osr.operating_state != DEVICE_MODE_MEASURE) {
FURI_LOG_E("AS7331", "Invalid device mode value: %d.", osr.operating_state);
return false;
}
// Write back OSR register
if(!writeRegister(RegCfgOsr, osr.byte)) {
FURI_LOG_E("AS7331", "Failed to write OSR to device: %d.", osr.byte);
return false;
}
// Update local config
_deviceMode = osr.operating_state;
_power_down = osr.power_down;
return true;
}
// Generalized method to read multiple bytes from consecutive registers
bool AS7331::readRegisters(uint8_t start_register_addr, uint8_t* buffer, size_t length) {
bool success;
// Write Phase: Send the start register address, end with AwaitRestart
success = furi_hal_i2c_tx_ext(
&furi_hal_i2c_handle_external,
_i2c_addr_8bit,
false, // 7-bit address
&start_register_addr,
1,
FuriHalI2cBeginStart,
FuriHalI2cEndAwaitRestart, // Prepare for repeated start
AS7331_I2C_TIMEOUT);
if(!success) {
FURI_LOG_E("AS7331", "Failed to send start register address");
return false;
}
// Read Phase: Read the data, begin with Restart, end with Stop
success = furi_hal_i2c_rx_ext(
&furi_hal_i2c_handle_external,
_i2c_addr_8bit,
false, // 7-bit address
buffer,
length,
FuriHalI2cBeginRestart, // Repeated start
FuriHalI2cEndStop,
AS7331_I2C_TIMEOUT);
if(!success) {
FURI_LOG_E("AS7331", "Failed to read data");
return false;
}
return true;
}
// Function to read an 8-bit register
bool AS7331::readRegister(uint8_t register_addr, uint8_t& data) {
return readRegisters(register_addr, &data, 1);
}
// Function to read a 16-bit register
bool AS7331::readRegister16(uint8_t register_addr, uint16_t& data) {
uint8_t buffer[2];
bool success = readRegisters(register_addr, buffer, 2);
if(!success) {
return false;
}
// Combine the two bytes into a 16-bit value (LSB first)
data = (static_cast<uint16_t>(buffer[1]) << 8) | buffer[0];
return true;
}
// Function to write an 8-bit register
bool AS7331::writeRegister(uint8_t register_addr, const uint8_t& data) {
bool success;
uint8_t buffer[2] = {register_addr, data};
// Write the register address and data in one transaction
success = furi_hal_i2c_tx_ext(
&furi_hal_i2c_handle_external,
_i2c_addr_8bit,
false, // 7-bit address
buffer,
2,
FuriHalI2cBeginStart,
FuriHalI2cEndStop,
AS7331_I2C_TIMEOUT);
if(!success) {
FURI_LOG_E("AS7331", "Failed to write data");
return false;
}
return true;
}
// Scan I2C bus for AS7331 device
uint8_t AS7331::scan_i2c_bus() {
uint8_t addr_found = 0; // Will hold the address if found
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Iterate through possible I2C addresses
for(uint8_t addr_7bit = DefaultI2CAddr; addr_7bit <= QuaternaryI2CAddr; addr_7bit++) {
uint8_t addr_8bit = addr_7bit << 1;
// Check for device readiness
if(furi_hal_i2c_is_device_ready(
&furi_hal_i2c_handle_external, addr_8bit, AS7331_I2C_TIMEOUT)) {
addr_found = addr_7bit;
break;
}
}
furi_hal_i2c_release(&furi_hal_i2c_handle_external);
if(addr_found == 0) {
FURI_LOG_E("AS7331", "No AS7331 device found on I²C bus.");
}
return addr_found;
}
// Update local configuration variables from device registers
bool AS7331::updateLocalConfig() {
bool success = true;
as7331_creg1_reg_t creg1;
as7331_creg2_reg_t creg2;
as7331_creg3_reg_t creg3;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_external);
// Ensure we are in configuration mode
success &= setDeviceMode(DEVICE_MODE_CONFIG);
// Read configuration registers
success &= readRegister(RegCfgCreg1, creg1.byte);