-
Notifications
You must be signed in to change notification settings - Fork 4
/
2024-04-06_SofronioCoffeeRatioScale.ino
2057 lines (1900 loc) · 71.9 KB
/
2024-04-06_SofronioCoffeeRatioScale.ino
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
/*
2021-07-25 新增开机时校准,双击咖啡录入关机
2021-07-26 新增开机按住清零校准,取消双击录入关机
2021-08-02 新增开机修改sample,显示版本信息,手柄录入功能
2021-08-07 v1.1 新增手柄录入功能
2021-08-15 v1.1 去掉手柄录入(因为双头手柄含水量不一定),修复进入意式模式时未恢复参数,新增电量检测
2021-09-01 v1.2 重新加入手柄录入 修复sample不可更改bug
2021-09-03 v1.3 修复切换到意式模式直接计时问题 修复录入可能产生负值问题
2021-10-02 v1.4 修复切换到意式模式 下液计时不清零问题
2021-10-10 v1.5 修复手柄录入产生的计时问题 新增显示旋转功能
2022-02-03 v1.6 二按钮模式
2022-03-04 v1.7 流速计
2022-04-12 v1.8 优化电量显示为0时闪屏
2022-08-01 v1.9 尝试支持3.3v芯片
2022-08-06 v2.0 换用rp2040,支持无操作自动关机
2022-09-11 v2.1 支持双模式,支持六轴传感器侧放关机
2022-11-02 v2.2 使用ESP32 wemos lite,支持esp32 休眠,支持esp32电容按钮开关机,去掉5v充放一体单元,去掉了电量显示
2023-02-11 v2.3 倾斜时不开机,避免误触
bug fix: setsamplesinuse只能缩小原来config.h中的SAMPLES,不能增加。
2023-03-06 v2.4 大幅改进显示稳定性
2023-03-11 v3.0 WiFi OTA,更换字体大小
2023-06-24 v3.1 去掉WiFi功能,加入蓝牙串口,可自定义所有参数。
2023-12-11 v3.2 ESPNow无线传输参数显示
2023-12-23 v3.3 ESPNow左键开启,和蓝牙一样,加入ssd1312
2024-01-27 v3.4 加入静音后代替蜂鸣器的LED
2024-03-25 v3.5 Add early verion of English translation
2024-04-06 v4.0 Add BLE and uuid.
2024-04-28 v4.1 fix - wrong button oled indicator on rotated display
fix - "disabled weight in serial" works but "auto tare on espresso mode" doesn't
fix - when ble app connected, scale can't power off via both button down
2024-05-13 v4.2 fix - wrong map() usage. map only use long for input, not float.
todo
开机M进入菜单
//2023-02-11 关闭蜂鸣器 DONE(2023-06-25)
2023-03-06 使用enum菜单
2024-03-23 Impliment ble function using service uuid and charactoristic uuid to let other apps/devices to get the scale data, or have it tared.(done)
2024-05-05 Fix when in extration mode, screen rotated, back to pure scale, xor button indicating wrong.(done)
*/
//include
#include <Arduino.h>
#if defined(ESP8266) || defined(ESP32) || defined(AVR) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
#include <EEPROM.h>
#endif
//#include "so_config.h"
#include "so_parameter.h"
#include "so_power.h"
#include "so_gyro.h"
#include "so_display.h"
//#include "so_menu.h"
#include "so_boot_menu.h"
#include "so_declare.h"
#include "so_wifi_ota.h"
#include "so_espnow.h"
#include "so_config.h"
// #include <BluetoothSerial.h>
// BluetoothSerial SerialBT;
// #ifndef BT
// #ifdef DEBUG_BT
// #include <BluetoothSerial.h>
// BluetoothSerial SerialBT;
// #endif
// #endif
//functions 函数
//ble
// Function to calculate XOR for validation (assuming this might still be needed)
uint8_t calculateXOR(uint8_t *data, size_t len) {
uint8_t xorValue = 0x03; // Starting value for XOR as per your example
for (size_t i = 1; i < len - 1; i++) { // Start from 1 to len - 1 assuming last byte is XOR value
xorValue ^= data[i];
}
return xorValue;
}
// Encode weight into two bytes, big endian
void encodeWeight(float weight, byte &byte1, byte &byte2) {
int weightInt = (int)(weight * 10); // Convert to grams * 10
byte1 = (byte)((weightInt >> 8) & 0xFF);
byte2 = (byte)(weightInt & 0xFF);
}
// This callback will be invoked when a device connects or disconnects
class MyServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer *pServer) {
deviceConnected = true;
}
void onDisconnect(BLEServer *pServer) {
deviceConnected = false;
}
};
class MyCallbacks : public BLECharacteristicCallbacks {
uint8_t calculateChecksum(uint8_t *data, size_t len) {
uint8_t xorSum = 0;
// Iterate over each byte in the data, excluding the last one assumed to be the checksum
for (size_t i = 0; i < len - 1; i++) {
xorSum ^= data[i];
}
return xorSum;
}
// Validate the checksum of the data
bool validateChecksum(uint8_t *data, size_t len) {
if (len < 2) { // Need at least 1 byte of data and 1 byte of checksum
return false;
}
uint8_t expectedChecksum = data[len - 1];
uint8_t calculatedChecksum = calculateChecksum(data, len);
return expectedChecksum == calculatedChecksum;
}
/*
Weight received on FFF4 (0000FFF4-0000-1000-8000-00805F9B34FB)
Firmware v1.0 and v1.1 sends weight as a 7 byte message:
03CE 0000 0000 CD = 0.0 grams
03CE 0065 0000 A8 = 10.1 grams
03CE 0794 0000 5E = 194.0 grams
03CE 1B93 0000 5E = 705.9 grams
03CE 2BAC 0000 4A = 1118.0 grams
Firmware v1.2 and newer sends weight with a timestamp as a 10 byte message:
03CE 0000 010203 0000 CD = 0.0 grams - (1 minute, 2 seconds, 3 milliseconds)
03CE 0065 010204 0000 A8 = 10.1 grams - (1 minute, 2 seconds, 4 milliseconds)
03CE 0794 010205 0000 5E = 194.0 grams - (1 minute, 2 seconds, 5 milliseconds)
03CE 1B93 010206 0000 5E = 705.9 grams - (1 minute, 2 seconds, 6 milliseconds)
03CE 2BAC 010207 0000 4A = 1118.0 grams - (1 minute, 2 seconds, 7 milliseconds)
030A LED and Power
LED on [requires v1.1 firmware]
030A 0101 000009 (grams)
030A 0101 010008 (ounces)
LED off
030A 0000 000009
Power off (new in v1.2 firmware)
030A 0200 00000B
030B Timer
Timer start
030B 0300 00000B
Timer stop
030B 0000 000008
Timer zero
030B 0200 00000A
030F Tare (set weight to zero)
030F 0000 00000C
030F B900 0000B5
*/
void onWrite(BLECharacteristic *pWriteCharacteristic) {
//so Serial.print("Timer");
//so Serial.print(millis());
//so Serial.print(" onWrite counter:");
//so Serial.println(i_onWrite_counter++);
if (pWriteCharacteristic != nullptr) { // Check if the characteristic is valid
size_t len = pWriteCharacteristic->getLength(); // Get the data length
uint8_t *data = (uint8_t *)pWriteCharacteristic->getData(); // Get the data pointer
// Optionally print the received HEX for verification or debugging
//so Serial.print("Received HEX: ");
for (size_t i = 0; i < len; i++) {
if (data[i] < 0x10) { // Check if the byte is less than 0x10
//so Serial.print("0"); // Print a leading zero
}
//so Serial.print(data[i], HEX); // Print the byte in HEX
}
//so Serial.println(); // New line for readability
if (data[0] == 0x03) {
if (data[1] == 0x0F) {
if (validateChecksum(data, len)) {
//so Serial.println("Valid checksum for tare operation. Taring");
} else {
//so Serial.println("Invalid checksum for tare operation.");
}
scale.tareNoDelay();
} else if (data[1] == 0x0A) {
if (data[2] == 0x00) {
//so Serial.println("LED off detected.");
} else if (data[2] == 0x01) {
//so Serial.println("LED on detected.");
} else if (data[2] == 0x02) {
//so Serial.println("Power off detected.");
shut_down_now_nobeep();
}
} else if (data[1] == 0x0B) {
if (data[2] == 0x03) {
//so Serial.println("Timer start detected.");
stopWatch.start();
} else if (data[2] == 0x00) {
//so Serial.println("Timer stop detected.");
stopWatch.stop();
} else if (data[2] == 0x02) {
//so Serial.println("Timer zero detected.");
stopWatch.reset();
}
}
}
}
}
};
//buttons
void aceButtonHandleEvent(AceButton *button, uint8_t eventType, uint8_t buttonState) {
power_off(-1); //reset power off timer
int pin = button->getPin();
switch (eventType) {
case AceButton::kEventPressed:
//if (!deviceConnected)
buzzer.beep(1, 50);
// continue;
case AceButton::kEventReleased:
case AceButton::kEventClicked:
//buzzer.beep(1, 100);
switch (pin) {
case BUTTON_SET:
if (digitalRead(BUTTON_TARE) == LOW) {
//so Serial.print("BUTTON_SET and TARE clicked together");
//so Serial.println("Going to sleep now.");
shut_down_now_nobeep();
}
buttonSet_Clicked();
if (deviceConnected)
sendBleButton(0, 0);
Serial.println("Left button short pressed");
break;
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
case BUTTON_PLUS:
if (!deviceConnected)
buttonPlus_Clicked();
else
sendBleButton(1, 0);
//so Serial.println("Right button short pressed");
break;
case BUTTON_MINUS:
buttonMinus_Clicked();
break;
#endif
case BUTTON_TARE:
buttonTare_Clicked();
if (deviceConnected)
sendBleButton(1, 0);
Serial.println("Right button short pressed");
break;
#ifdef FIVE_BUTTON
case BUTTON_POWER:
//so Serial.println("BUTTON_POWER Clicked");
shut_down_now_nobeep();
break;
#endif //FIVE_BUTTON
}
break;
case AceButton::kEventLongPressed:
switch (pin) {
case BUTTON_SET:
if (b_f_extraction) {
//意式模式下 长按回归普通模式
//if in espresso mode, long press to go to pure weighing mode.
buzzer.beep(1, 200);
b_f_extraction = !b_f_extraction;
} else {
buzzer.beep(1, 200);
b_f_minus_container = !b_f_minus_container;
}
break;
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
case BUTTON_PLUS:
//buzzer.beep(1, 100);
break;
#endif
case BUTTON_TARE:
buzzer.beep(1, 200);
if (b_f_calibration) {
reset();
} else {
if (b_f_extraction) {
i_display_rotation = !i_display_rotation;
} else {
if (b_f_mode != 0)
b_f_mode = 0;
else
b_f_mode = 1;
// //so Serial.print("b_f_mode: ");
// //so Serial.println(b_f_mode);
EEPROM.put(i_addr_mode, b_f_mode);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
}
break;
}
break;
case AceButton::kEventRepeatPressed:
switch (pin) {
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
case BUTTON_PLUS:
buttonPlus_Clicked();
break;
case BUTTON_MINUS:
buttonMinus_Clicked();
break;
#endif
}
break;
// case AceButton::kEventDoubleClicked:
// switch (pin) {
// #ifndef FIVE_BUTTON
// case BUTTON_SET:
// //so Serial.println("BUTTON_SET Double Clicked");
// shut_down_now_nobeep();
// break;
// #endif //FIVE_BUTTON
// }
break;
}
}
void buttonSet_Clicked() {
if (millis() - t_button_pressed > 1000) {
if (b_f_calibration) {
reset();
}
// if (b_f_set_sample)
// i_sample++;
if (b_f_set_container) {
//so Serial.println("setContainerWeight()");
i_setContainerWeight = 1;
}
if (b_f_show_info)
b_f_show_info = false;
if (b_f_extraction) {
if (stopWatch.isRunning() == false) {
//进入萃取模式1s后可以操作的时钟
if (stopWatch.elapsed() == 0) {
//初始态 时钟开始
delay(500);
stopWatch.start();
//so Serial.println("时钟开始"); //timer start
}
// //so Serial.print(stopWatch.elapsed());
// //so Serial.print(" ");
// //so Serial.println("stopWatch.start();");
if (stopWatch.elapsed() > 0) {
//停止态 时钟清零
stopWatch.reset();
//so Serial.println("时钟复位"); //timer reset
}
} else {
//在计时中 按一下则结束计时 停止冲煮 (固定参数回头再说)
stopWatch.stop();
//so Serial.println("停止计时");
}
} else {
//普通模式录入粉重 切换到萃取模式
//input ground weight to the scale, and switch to extration mode.
bool newDataReady = false;
if (scale.update())
newDataReady = true;
if (newDataReady) {
f_weight_adc = scale.getData();
circularBuffer[bufferIndex] = f_weight_adc;
bufferIndex = (bufferIndex + 1) % windowLength;
// calculate moving average
f_weight_smooth = 0;
for (int i = 0; i < windowLength; i++) {
f_weight_smooth += circularBuffer[i];
}
f_weight_smooth /= windowLength;
if (f_weight_smooth >= f_displayedValue - OledTolerance && f_weight_smooth <= f_displayedValue + OledTolerance) {
// scale value is within tolerance range, do nothing
// or weight is around 0, then set to 0.
if (f_weight_smooth > -0.1 && f_weight_smooth < 0.1)
f_displayedValue = 0.0;
} else {
// scale value is outside tolerance range, update displayed value
f_displayedValue = f_weight_smooth;
// print result to serial monitor
}
if (b_f_minus_container) {
//去掉手柄重量模式
f_weight_dose = f_displayedValue - f_weight_container;
//b_f_minus_container = false;
if (f_weight_dose < 3)
f_weight_dose = f_weight_default_coffee; //不足3g 录入为默认值(20g)配合手柄模式使用
//no greater than 3 grams, then the ground weight is set to preset value. inside so_prameter.h INPUTCOFFEEPOUROVER and INPUTCOFFEEESPRESSO
} else {
if (f_weight_before_input < 3)
f_weight_dose = f_weight_default_coffee; //不足3g 录入为默认值(20g)
else
f_weight_dose = f_displayedValue;
}
initExtration();
b_f_ready_to_brew = false;
stopWatch.stop();
stopWatch.reset();
if (b_f_mode)
scale.tareNoDelay();
b_f_extraction = true;
}
}
t_button_pressed = millis();
}
}
void buttonPlus_Clicked() {
if (millis() - t_button_pressed > 1000) {
// if (b_f_set_sample) {
// //设置采样数
//set sample number.
// i_sample++;
// }
if (b_f_show_info) {
//显示信息
//show some product info
b_f_show_info = false;
}
if (b_f_extraction) {
//萃取模式
//extration mode
f_weight_dose = f_weight_dose + 0.1;
//four button version, to plus 0.1g ground weight.
} else {
//纯称重模式
//pure weighing mode
b_f_minus_container_button = !b_f_minus_container_button; //是否减去咖啡手柄重量
}
t_button_pressed = millis();
}
}
void buttonMinus_Clicked() {
if (millis() - t_button_pressed > 1000) {
// if (b_f_set_sample) {
// i_sample--;
// } else
if (b_f_show_info) {
b_f_show_info = false;
} else if (b_f_extraction) {
//萃取模式 按一下-0.1g
//four button version, to minus 0.1g ground weight.
if (f_weight_dose - 0.1 > 0)
f_weight_dose = f_weight_dose - 0.1;
} else {
if (i_decimal_precision == 1)
i_decimal_precision = 2;
else
i_decimal_precision = 1;
}
t_button_pressed = millis();
}
}
void buttonTare_Clicked() {
if (millis() - t_button_pressed > 1000) {
if (b_f_calibration) {
i_button_cal_status++;
//so Serial.print("i_button_cal_status:");
//so Serial.println(i_button_cal_status);
return;
}
if (b_f_extraction) {
if (stopWatch.isRunning())
//在计时中 按一下则结束计时 停止冲煮
//press button to stop the timer, and stop the brewing.
stopWatch.stop();
else {
//萃取模式归零
//不在计时中 重量归零 时间归零
//a tare on extracion mode.
//timer not runing, zero the scale and timer.
b_f_weight_quick_zero = true;
if (!b_f_extraction)
f_weight_dose = 0;
stopWatch.reset();
t_extraction_begin = 0;
t_extraction_first_drop = 0;
t_extraction_first_drop_num = 0;
t_extraction_last_drop = 0;
//123scale.tareNoDelay();
delay(25); //sodelay 500
scale.tareNoDelay();
}
} else if (b_f_set_container) {
delay(25); //sodelay 500
scale.tareNoDelay();
} else {
//普通归零
//a standard tare.
//f_temp_tare = f_filtered_temperature;
b_f_weight_quick_zero = true;
delay(25); //sodelay 500
scale.tareNoDelay();
}
t_button_pressed = millis();
}
}
void initExtration() {
stopWatch.reset();
t_extraction_begin = 0; //开始萃取打点
//t_ for time stamp on:
//extration begins
t_extraction_first_drop = 0; //下液第一滴打点
//first drop
t_extraction_first_drop_num = 0;
t_extraction_last_drop = 0; //下液结束打点
//last drop
tareCounter = 0; //不稳计数器
//if it's stable
t_auto_tare = 0; //自动归零打点
//auto tare time stamp
t_auto_stop = 0; //下液停止打点
//auto stop time stamp
t_scale_stable = 0; //稳定状态打点
//scale stable time stamp
t_time_out = 0; //超时打点
//time to long time stamp
t_last_weight_adc = 0; //最后一次重量输出打点
//last adc reading time stamp
}
void button_init() {
pinMode(BUTTON_SET, INPUT_PULLUP);
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
pinMode(BUTTON_PLUS, INPUT_PULLUP);
pinMode(BUTTON_MINUS, INPUT_PULLUP);
#endif
pinMode(BUTTON_TARE, INPUT_PULLUP);
#ifdef FIVE_BUTTON
pinMode(BUTTON_POWER, INPUT_PULLUP);
buttonPower.init(BUTTON_POWER);
#endif //FIVE_BUTTON
buttonSet.init(BUTTON_SET);
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
buttonPlus.init(BUTTON_PLUS);
buttonMinus.init(BUTTON_MINUS);
#endif
buttonTare.init(BUTTON_TARE);
config1.setEventHandler(aceButtonHandleEvent);
//config1.setFeature(ButtonConfig::kFeatureClick);
config1.setFeature(ButtonConfig::kFeatureLongPress);
config1.setFeature(ButtonConfig::kFeatureSuppressAfterLongPress);
config1.setFeature(ButtonConfig::kFeatureRepeatPress);
//config1.setFeature(ButtonConfig::kFeatureDoubleClick);
//config1.setFeature(ButtonConfig::kFeatureSuppressClickBeforeDoubleClick);
config1.setFeature(ButtonConfig::kFeatureSuppressAfterClick);
//config1.setFeature(ButtonConfig::kFeatureSuppressAfterDoubleClick);
config1.setRepeatPressInterval(10);
//config1.setDoubleClickDelay(DOUBLECLICK);
}
void setup() {
#ifdef ESP32
Wire.begin(I2C_SDA, I2C_SCL);
#endif
delay(50); //有些单片机会重启两次
//some soc may reset twice
Serial.begin(115200);
while (!Serial)
;
delay(200);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040) || defined(ESP32C3)
EEPROM.begin(512);
#endif
#ifdef DEBUG_BT
SerialBT.begin("soso D.R.S");
#endif
//delay(2000);
//so Serial.println("Begin!");
MPU6050_init();
#ifdef GYROFACEUP
if (gyro_z() < 8) {
//so Serial.print("gyro_z:");
//so Serial.println(gyro_z());
shut_down_now_accidentTouch();
}
#endif
#ifdef GYROFACEDOWN
if (gyro_z() > -8) {
//so Serial.print("gyro_z:");
//so Serial.println(gyro_z());
shut_down_now_accidentTouch();
}
#endif
#if defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
analogReadResolution(ADC_BIT);
#endif
button_init();
pinMode(BUZZER, OUTPUT);
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
pinMode(BUTTON_KEY, INPUT_PULLUP);
pinMode(BUTTON_DEBUG, INPUT_PULLUP);
#endif
#ifdef CHECKBATTERY
pinMode(BATTERY_LEVEL, INPUT);
pinMode(USB_LEVEL, INPUT);
#endif //CHECKBATTERY
#ifndef ESP32
#if defined(HW_SPI) || defined(SW_SPI)
pinMode(OLED_CS, OUTPUT);
pinMode(OLED_DC, OUTPUT);
pinMode(OLED_RST, OUTPUT);
digitalWrite(OLED_CS, LOW);
digitalWrite(OLED_DC, LOW);
digitalWrite(OLED_RST, HIGH);
#endif //defined(HW_SPI) || defined(SW_SPI)
#endif //ndef ESP32
EEPROM.get(i_addr_beep, b_f_beep);
buzzer.beep(1, 100);
u8g2.begin();
u8g2.enableUTF8Print();
u8g2.setContrast(255);
//char* welcome = "soso E.R.S"; //欢迎文字
//refreshOLED(welcome);
power_off(15);
#ifdef WELCOME
EEPROM.get(i_addr_welcome, str_welcome);
str_welcome.trim();
// //so Serial.print("str_welcome.length() = ");
// //so Serial.println(str_welcome.length());
// //so Serial.println(str_welcome);
#ifdef ROTATION_180
u8g2.setDisplayRotation(U8G2_R2);
#else
u8g2.setDisplayRotation(U8G2_R0);
#endif
if (str_welcome.length() == 127)
refreshOLED(WELCOME);
else
refreshOLED((char *)str_welcome.c_str(), FONT_EXTRACTION);
delay(1000);
#endif //WELCOME
stopWatch.setResolution(StopWatch::SECONDS);
stopWatch.start();
stopWatch.reset();
i_button_cal_status = 1; //校准状态归1
//calibration status goes to 1
unsigned long stabilizingtime = 500; //去皮时间(毫秒),增加可以提高去皮精确度
//taring duration. longer for better reading.
boolean _tare = true; //电子秤初始化去皮,如果不想去皮则设为false
//whether the scale will tare on start.
scale.begin();
scale.start(stabilizingtime, _tare);
EEPROM.get(INPUTCOFFEEPOUROVER_ADDRESS, INPUTCOFFEEPOUROVER);
EEPROM.get(INPUTCOFFEEESPRESSO_ADDRESS, INPUTCOFFEEESPRESSO);
EEPROM.get(i_addr_batteryCalibrationFactor, f_batteryCalibrationFactor);
Serial.print("f_batteryCalibrationFactor:");
Serial.println(f_batteryCalibrationFactor);
// //so Serial.print("INPUTCOFFEEPOUROVER:");
// //so Serial.print(INPUTCOFFEEPOUROVER);
// //so Serial.print(" INPUTCOFFEEESPRESSO:");
// //so Serial.println(INPUTCOFFEEESPRESSO);
if (isnan(f_batteryCalibrationFactor) || f_batteryCalibrationFactor < 0.9) {
f_batteryCalibrationFactor = 1.0;
EEPROM.put(i_addr_batteryCalibrationFactor, f_batteryCalibrationFactor);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
if (isnan(INPUTCOFFEEPOUROVER)) {
INPUTCOFFEEPOUROVER = 16.0;
EEPROM.put(INPUTCOFFEEPOUROVER_ADDRESS, INPUTCOFFEEPOUROVER);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
if (isnan(INPUTCOFFEEESPRESSO)) {
INPUTCOFFEEESPRESSO = 18.0;
EEPROM.put(INPUTCOFFEEESPRESSO_ADDRESS, INPUTCOFFEEESPRESSO);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
if (b_f_beep != 0 && b_f_beep != 1) {
b_f_beep = 1;
EEPROM.put(i_addr_beep, b_f_beep);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
//读取模式
EEPROM.get(i_addr_mode, b_f_mode);
// //so Serial.print("b_f_mode: ");
// //so Serial.println(b_f_mode);
if (b_f_mode > 1) {
b_f_mode = 0;
EEPROM.put(i_addr_mode, b_f_mode);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
if (b_f_mode < 0) {
b_f_mode = 0;
EEPROM.put(i_addr_mode, b_f_mode);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
//检查手柄重量合法性
//check eeprom container value is valid.
EEPROM.get(i_addr_container, f_weight_container);
if (isnan(f_weight_container)) {
f_weight_container = 0; //手柄重量为0
//保存0值
//if container is 0 grams, then save it to eeprom.
EEPROM.put(i_addr_container, f_weight_container);
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED_RP2040)
EEPROM.commit();
#endif
}
//检查校准值合法性
EEPROM.get(i_addr_calibration_value, f_calibration_value);
if (isnan(f_calibration_value)) {
b_f_calibration = true; //让按钮进入校准状态3
//put calibration to status 3
cal(); //无有效读取,进入校准模式
//eeprom calibration value is not valid, go to calibration procedure.
} else
scale.setCalFactor(f_calibration_value); //设定校准值
//检查sample值合法性
//check sample number is valid
// EEPROM.get(i_addr_sample, i_sample);
// if (isnan(i_sample)) {
// b_f_set_sample = true;
// i_sample = 0; //读取失败 默认值为3 对应sample为8
// i_sample_step = 0;
// setSample();
// }
#ifdef DEBUG
if (digitalRead(BUTTON_DEBUG) == LOW && digitalRead(BUTTON_SET) == HIGH)
b_f_debug = true;
if (digitalRead(BUTTON_DEBUG) == LOW && digitalRead(BUTTON_SET) == LOW)
b_f_debug_battery = true;
#endif //DEBUG
//重新校准
//recalibration
#ifdef CAL
if (digitalRead(BUTTON_SET) == LOW && digitalRead(BUTTON_TARE) == LOW) {
b_f_calibration = true; //让按钮进入校准状态3
//go to calibration status 3
cal(); //无有效读取,进入校准模式
//calibration value is not valid, go to calibration procedure.
}
#endif
//wifiota
#ifdef WIFI
if (digitalRead(BUTTON_SET) == LOW) {
wifiOTA();
}
#endif
#if DEBUG
//so Serial.print("digitalRead(BUTTON_SET):");
//so Serial.print(digitalRead(BUTTON_SET));
//so Serial.print("\tdigitalRead(BUTTON_SET):");
//so Serial.println(digitalRead(BUTTON_SET));
#endif
//录入手柄/接粉杯重量
//get the containter weight and save to eeprom
if (digitalRead(BUTTON_TARE) == LOW) {
b_f_set_container = true;
setContainerWeight();
}
if (digitalRead(BUTTON_SET) == LOW) {
//bluetooth serial init
//SerialBT.begin("D.R.S.");
//SerialBT.begin("Open Scale BTSerial");
setContainerWeight();
#ifdef WIFI
WiFi.mode(WIFI_STA);
// Print MAC address
//so Serial.print("MAC Address: ");
//so Serial.println(WiFi.macAddress());
// Disconnect from WiFi
WiFi.disconnect();
#endif
#ifdef ESPNOW
if (esp_now_init() == ESP_OK) {
//so Serial.println("ESPNow Init Success");
esp_now_register_recv_cb(receiveCallback);
esp_now_register_send_cb(sentCallback);
b_f_espnow = true;
} else {
//so Serial.println("ESPNow Init Failed");
// Retry InitESPNow, add a counte and then restart?
// InitESPNow();
// or Simply Restart
delay(3000);
ESP.restart();
}
#endif
} else {
//ble init
BLEDevice::init("Decent Scale");
//BLEDevice::init("Open Scale BLE");
// Create BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create BLE Service
BLEService *pService = pServer->createService(SUUID_DECENTSCALE);
pWriteCharacteristic = pService->createCharacteristic(
CUUID_DECENTSCALE_WRITE,
BLECharacteristic::PROPERTY_WRITE);
pWriteCharacteristic->setCallbacks(new MyCallbacks());
// Create BLE Characteristic for RX
pReadCharacteristic = pService->createCharacteristic(
CUUID_DECENTSCALE_READ,
BLECharacteristic::PROPERTY_READ
| BLECharacteristic::PROPERTY_NOTIFY
//| BLECharacteristic::PROPERTY_WRITE
//| BLECharacteristic::PROPERTY_INDICATE
//| BLECharacteristic::PROPERTY_BROADCAST
//| BLECharacteristic::PROPERTY_WRITE_NR
);
pReadCharacteristic->addDescriptor(new BLE2902());
pService->start();
// Start advertising
pServer->getAdvertising()->start();
//so Serial.println("Waiting for a client connection to notify...");
}
//4按键模式时显示信息
#ifndef TWO_BUTTON
if (digitalRead(BUTTON_MINUS) == LOW) {
b_f_show_info = true;
showInfo();
delay(2000);
}
#endif
//so Serial.print("Welcome: ");
if (str_welcome.length() == 127) {
//so Serial.print(WELCOME1);
} else {
//so Serial.print(str_welcome);
}
//so Serial.print("\t");
//so Serial.print(WELCOME2);
//so Serial.print("\t");
//so Serial.println(WELCOME3);
//so Serial.print("Info: ");
//so Serial.print(LINE1);
//so Serial.print("\t");
//so Serial.print(LINE2);
//so Serial.print("\t");
//so Serial.print(LINE3);
//so Serial.print("\tScale Type: ");
if (b_f_mode) {
//so Serial.println("ESPRESSO");
} else {
//so Serial.println("POUROVER");
}
//so Serial.print("Cal_Val: ");
//so Serial.print(f_calibration_value);
// //so Serial.print("\tSample[");
// //so Serial.print(i_sample);
// //so Serial.print("]: ");
// //so Serial.print(sample[i_sample]);
//so Serial.print(F("\tContainer: "));
//so Serial.print(f_weight_container);
//so Serial.print("g");
//so Serial.print(F("\tDefaultPourOver: "));
//so Serial.print(INPUTCOFFEEPOUROVER);
//so Serial.print("g");
//so Serial.print(F("\tDefaultEspresso: "));
//so Serial.print(INPUTCOFFEEESPRESSO);
//so Serial.println("g");
//so Serial.println("Button:\tSET\tTare\tPower");
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
//so Serial.println("Button:\tSET\tPlus\tMinus\tTare\tPower");
#endif
//so Serial.print("Pin:");
//so Serial.print("\t");
//so Serial.print(BUTTON_SET);
//so Serial.print("\t");
#if defined(FOUR_BUTTON) || defined(FIVE_BUTTON)
//so Serial.print(BUTTON_PLUS);
//so Serial.print("\t");
//so Serial.print(BUTTON_MINUS);
//so Serial.print("\t");
#endif
//so Serial.print(BUTTON_TARE);
//so Serial.print("\t");
//so Serial.println(GPIO_NUM_BUTTON_POWER);
//so Serial.println("Button:\tI2C_SDA\tI2C_SCK\t711SDA\t711SCK\tBUZZER");
//so Serial.print("Pin:");
//so Serial.print("\t");
//so Serial.print(I2C_SDA);
//so Serial.print("\t");
//so Serial.print(I2C_SCL);
//so Serial.print("\t");
//so Serial.print(HX711_SDA);
//so Serial.print("\t");
//so Serial.print(HX711_SCL);
//so Serial.print("\t");
//so Serial.println(BUZZER);
scale.setCalFactor(f_calibration_value); //设置偏移量
//set the calibration value
//scale.setSamplesInUse(sample[i_sample]); //设置灵敏度
scale.setSamplesInUse(1); //设置灵敏度
#ifdef CHECKBATTERY
f_up_battery = analogRead(BATTERY_LEVEL) * f_vref / (pow(2, ADC_BIT) - 1) * f_divider_factor;
t_up_battery = millis();
#endif //CHECKBATTERY
scale.tareNoDelay();
//so Serial.println("Setup complete...");
// while (!b_f_ota)
// ;
}
void pourOverScale() {
if (f_weight_dose < 3)
f_weight_dose = INPUTCOFFEEPOUROVER;
//checkBrew
if (f_displayedValue > 1 && b_f_ready_to_brew == true && b_f_weight_quick_zero == false && (millis() - t_ready_to_brew > 3000)) {
stopWatch.start();
buzzer.beep(1, 100);
b_f_ready_to_brew = false;
}
static bool newDataReady = 0;
static bool scaleStable = 0;
if (scale.update()) newDataReady = true;
if (newDataReady) {
f_weight_adc = scale.getData();
newDataReady = 0;
circularBuffer[bufferIndex] = f_weight_adc;
bufferIndex = (bufferIndex + 1) % windowLength;
// calculate moving average
f_weight_smooth = 0;
for (int i = 0; i < windowLength; i++) {
f_weight_smooth += circularBuffer[i];
}
f_weight_smooth /= windowLength;
if (f_weight_smooth >= f_displayedValue - OledTolerance && f_weight_smooth <= f_displayedValue + OledTolerance) {
// scale value is within tolerance range, do nothing
// or weight is around 0, then set to 0.
if (f_weight_smooth > -0.1 && f_weight_smooth < 0.1)
f_displayedValue = 0.0;
} else {
// scale value is outside tolerance range, update displayed value
f_displayedValue = f_weight_smooth;
// print result to serial monitor
}
if (millis() > t_flow_rate + 1000) {
f_flow_rate = f_displayedValue - f_flow_rate_last_weight;
if (f_flow_rate < 0)
f_flow_rate = 0;
dtostrf(f_flow_rate, 7, 1, c_flow_rate);
f_flow_rate_last_weight = f_displayedValue;
t_flow_rate = millis();
}
dtostrf(f_displayedValue, 7, 1, c_weight);
if (b_weight_in_serial == true) {
//so Serial.println(trim(c_weight));