-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathESP32_RC_motor_tester.ino
More file actions
829 lines (708 loc) · 25.7 KB
/
Copy pathESP32_RC_motor_tester.ino
File metadata and controls
829 lines (708 loc) · 25.7 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
//Rx servo reader library : https : //github.com/rewegit/esp32-rmt-pwm-reader
#include <esp32-rmt-pwm-reader.h>
// #include "esp32-rmt-pwm-reader.h" // if the lib is located directly in the project directory
// init channels and pins
uint8_t pins[] = { 32 }; // desired input pins
int numberOfChannels = sizeof(pins) / sizeof(uint8_t);
#include <WiFiClient.h>
#include <TelnetStream.h>
#include "driver/adc.h"
#include <esp_wifi.h>
#include <esp_bt.h>
#include <esp_task_wdt.h>
//1 seconds WDT
#define WDT_TIMEOUT 1
int nbTimeout = 0;
int timeOut = 0;
int nbAlarm = 0;
long bootTime;
//Json
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
String displayStatus = "Initializing";
//OLED
#define OLED
#ifdef OLED
#define OLED_SCL_PIN 5
#define OLED_SDA_PIN 17
#include "SSD1306.h"
SSD1306 display(0x3c, OLED_SDA_PIN, OLED_SCL_PIN); // for 0.96" 128x64 LCD display ; i2c ADDR & SDA, SCL
#endif
String displayDebug;
//Radio Rx
int throttle = -1;
int opMode = 0; //0 manual, 1 autoStep, 2 auto sweep, 3 stop
int minThrottle = 0;
int maxThrottle = 500;
float currentThrottle = 0;
int sweepDuration = 3000; //5s duration for half an automatic mode
int refreshDelay;
float refreshStep;
long refreshTimeOut = 0;
// ESC output, PWM at 50Hz
#define ESC_PIN 33 // GPIO for ESC output
#include <ESP32Servo.h> //https://docs.arduino.cc/libraries/esp32servo/
Servo myESC; // create servo object to control an ESC
//sensors selection
#define HAS_HX711 //uncomment for weighing rain gauge
//#define HAS_DS18B20 //uncomment for DS18B20 temperature sensor
#define HAS_SPEED_SENSOR //uncomment for propeller speed sensor
float temperature = 0;
int smooth = 10; //acquire smooth*values for each ADC
float Vin = 0.; //input Voltage (lipo battery voltage)
float prevVin = 0;
float current = 0.; //lipo battery current
float prevCurrent = 0;
float RPM = 0;
#define VIN_PIN 39 //ADC pin for lipo voltage measurement
#define CUR_PIN 36 //ADC pin for lipo current measurement
int zeroCurrent = 0; //ADC value on the hall sensor when current is null
#define FILTER_SAMPLES 5000 // 1 = no filtering (faster single acquisition but noise on the hall sensor),
#define REJECT_RATIO 40 //points to reject % left and right before averaging (if filter sample >1)
float smoothArray[FILTER_SAMPLES]; // array for holding raw sensor values for current sensor
//temperature sensor
#define ONE_WIRE_BUS 13 // Data wire is plugged into pin 13 on the ESP32
#ifdef HAS_DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature tempScale1(&oneWire); // Pass our oneWire reference to Dallas Temperature.
#endif
//scale (propeller thrust)
#define PIN_CLOCK 19 //output to generate clock on Hx711
#define PIN_DOUT 23 //input Dout from Hx711
long calibZero = 0; //No load sensor Output
long calib = 130968; //sensor output - calibZero for Weight calibration --> will be auto calibrated later
int calibWeight = 1000; //weight at which calibration is done --> expressed in grams.
float AverageWeight = 0;
float CurrentRawWeight = 0;
//speed sensor
#define TAC_PIN 27 //IR sensor acting as tachometer
int tops = 0; //nb tops when propeller rotates
long hallTimeout; //to debounce
int speedSensorMeasuringTime; //to compute RPM
#define NB_BLADES 2 // 2 tops for a normal 2 blades propeller
#define LED_PIN 22
//Preferences
#include <Preferences.h>
Preferences preferences;
//touchpad
touch_pad_t touchPin;
int threshold = 40; //Threshold value for touchpads pins
void callback() {
//placeholder callback function
}
boolean TouchWake = false;
//WifiManager
#include <DNSServer.h>
#include <WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
//flag for saving data
bool shouldSaveConfig = false;
bool touch3detected = false; //touch3 used to launch WifiManager (hold it while reseting)
bool touch2detected = false; //touch2 used to calibrate loadcell with known weight (hold it while reseting)
//callback notifying us of the need to save config
void saveConfigCallback() {
Serial.println("Should save config");
shouldSaveConfig = true;
}
String ssid = "";
String password = "";
boolean hasWifiCredentials = false;
//#define W_DEBUG //debug Wifi and firebase
//#define G_DEBUG //debug GCM serveur
//#define DEBUG_OUT
//#define xDEBUG
//#define xxDEBUG
//#define UDP_DEBUG
//#define DEBUG
//#define TEST
#define PREFERENCES_DEBUG
//#define DEBUG_TELNET
//#define RAW_WEIGHT_DEBUG
//#define DEBUG_TEMPERATURE
//#define DEBUG_W
//#define DEBUG_VIN //debug voltage measurement, useful to calibrate
//#define DEBUG_CURRENT //debug current measurement, useful to calibrate
//#define DEBUG_RPM
//UDP --------------
unsigned int localPort = 5000; // local port to listen on
char packetBuffer[64]; //buffer to hold incoming packet
char AndroidConnected = 0;
long Timeout;
String device = "RCmotorTester";
String theMAC = "";
WiFiUDP Udp;
long LastUDPnotification;
//end UDP-----------
#ifdef HAS_SPEED_SENSOR
void IRAM_ATTR hall_ISR() //hall sensor interrupt routine (will only count tops)
{
//if ((millis() - hallTimeout) > 10) //leave commented : no need to debounce
{
//hallTimeout = millis();
tops++;
//Serial.println( tops); //MUST comment this line to avoid crashes
}
}
#endif
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Serial.begin(115200);
// init Rx channels
pwm_reader_init(pins, numberOfChannels);
pwm_set_channel_pulse_neutral(0, 1000); // throttle neutral is set to "zero"
// here you can change channel defaults values before reading (if needed)
// e.g. pwm_set_channel_pulse_min() /max/neutral
// e.g. set auto_zero/auto_min_max for channel 0-2
// for (int ch = 0; ch < 3; ch++) {
// pwm_set_auto_zero(ch, true); // set channel to auto zero
// pwm_set_auto_min_max(ch, true); // set channel to auto min/max calibration
// }
// begin reading
esp_err_t err = pwm_reader_begin();
if (err != ESP_OK) {
Serial.printf("begin() err: %i", err);
} else {
Serial.println("***************");
Serial.println("program started");
Serial.println("***************");
Serial.println(" ");
}
// ESC PWM
// Allow allocation of all timers
ESP32PWM::allocateTimer(0);
ESP32PWM::allocateTimer(1);
ESP32PWM::allocateTimer(2);
ESP32PWM::allocateTimer(3);
myESC.setPeriodHertz(50); // standard 50 hz servo
myESC.attach(ESC_PIN, 1000, 2000); // attaches the ESC on pin 33 to the servo object
// using default min/max of 1000us and 2000us
// for an accurate 0 to 180 sweep
myESC.write(0); //be sure the motor is stopped (servo at 0 "angle value")
//Preferences
preferences.begin("RC_motor_tester", false);
//preferences.clear(); // Remove all preferences under the opened namespace
//preferences.remove("counter"); // remove the counter key only
calibWeight = preferences.getInt("calibWeight", 1000); //by default calibration of load cell is done with 1kg load attached to the propeller
calib = preferences.getLong("calib", -222444); // value for a milk pack ~1000g (surepeesed when calibration done on the android App)
ssid = preferences.getString("ssid", ""); // Get the ssid value, if the key does not exist, return a default value of ""
password = preferences.getString("password", "");
#ifdef PREFERENCES_DEBUG
Serial.println("_________________");
Serial.println("read preferences :");
Serial.print("calib HX711 : ");
Serial.println(calib);
Serial.print("calib weight (g) : ");
Serial.println(calibWeight);
Serial.println("_________________");
#endif
//preferences.end(); // Close the Preferences
#ifdef OLED
display.init();
display.flipScreenVertically();
display.setFont(ArialMT_Plain_10);
displayLCD();
#endif
if (ftouchRead(T3) < threshold) touch3detected = true; //detect touchpad for CONFIG_PIN
// //connect to WiFi
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//reset settings - for testing
//wifiManager.resetSettings();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
wifiManager.setTimeout(300);
if (touch3detected) //then launch WifiManager : touch the Touch3 pin GPIO15 , reset the ESP32 then release the touch pin a Wifi Access point will pop up
{
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//here "JP RCMotorTester"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.startConfigPortal("JP RCMotorTester")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(5000);
}
}
delay(2000);
// //save the custom WifiManager's parameters if needed
if (shouldSaveConfig) {
Serial.println("saving Wifi credentials ");
//read updated parameters
preferences.putString("password", WiFi.psk());
preferences.putString("ssid", WiFi.SSID());
delay(2000);
ESP.restart();
delay(5000);
}
//connect to WiFi
WiFi.begin(ssid.c_str(), password.c_str());
long start = millis();
hasWifiCredentials = false;
while ((WiFi.status() != WL_CONNECTED) && (millis() - start < 20000)) {
delay(500);
Serial.print(".");
}
if (WiFi.status() == WL_CONNECTED) hasWifiCredentials = true;
//if you get here you may be connected to the WiFi
Serial.print("connected to Wifi: ");
Serial.println(hasWifiCredentials);
//if (hasWifiCredentials) //don't block the prog if no wifi...it could work with only OLED display
{
TelnetStream.begin(); //used to debug over telnet
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
//Start UDP
Udp.begin(localPort);
}
Serial.println(" ");
Serial.println("start decoding and monitoring sensors : \n");
//delay(3000);
//Serial.println("Configuring WDT...");
// esp_task_wdt_init(WDT_TIMEOUT, true); //enable panic so ESP32 restarts
// esp_task_wdt_add(NULL); //add current thread to WDT watch
bootTime = millis();
//scale init
#ifdef HAS_HX711
pinMode(PIN_CLOCK, OUTPUT); // initialize digital pin 4 as an output.(clock)
digitalWrite(PIN_CLOCK, HIGH);
delayMicroseconds(100); //be sure to go into sleep mode if > 60µs
digitalWrite(PIN_CLOCK, LOW); //exit sleep mode*/
pinMode(PIN_DOUT, INPUT); // initialize digital pin 5 as an input.(data Out)
GetRawWeight();
calibZero = CurrentRawWeight; // during boot the motor doesn't spin = no thrust on the propeller
//preferences.putLong("calibZero", calibZero); // no need to store it: computed during each boot and used during loop
#ifdef DEBUG_W
Serial.print("calibZero raw value = ");
Serial.println(calibZero);
#endif
#endif //HAS_HX711
//speed IR sensor
#ifdef HAS_SPEED_SENSOR
#ifdef DEBUG
Serial.println("speed sensor enabled");
#endif
pinMode(TAC_PIN, INPUT_PULLUP);
attachInterrupt(TAC_PIN, hall_ISR, FALLING); //will count tops on Anemometer hall Sensor
hallTimeout = millis();
tops = 0;
speedSensorMeasuringTime = millis();
#endif
#ifdef HAS_DS18B20
int kk;
tempScale1.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups the delay giving the IC more time to process the temperature measurement
for (int i = 0; i < 2; i++) { //read twice to warm up
tempScale1.requestTemperatures(); //needed as first reading may be stuck to 25°
kk = tempScale1.getTempCByIndex(0);
}
#endif
//lipo voltage and current
//ADC
//analogSetClockDiv(255);
//analogReadResolution(12); // Sets the sample bits and read resolution, default is 12-bit (0 - 4095), range is 9 - 12 bits
analogSetWidth(12); // Sets the sample bits and read resolution, default is 12-bit (0 - 4095), range is 9 - 12 bits
analogSetAttenuation(ADC_11db); //Sets the input attenuation for ALL ADC inputs, default is ADC_11db, range is ADC_0db=0, ADC_2_5db=1, ADC_6db=2, ADC_11db=3
//lipo current
for (int i = 0; i < FILTER_SAMPLES; i++) {
smoothArray[i] = analogRead(CUR_PIN); //ADC smoothing the zeroCurrent delivered by the sensor (should be 2.5V)
}
zeroCurrent = medianFilter(); // we will filter the samples to keep the non noisy ones to compute zeroCurrent of the hall sensor
prevCurrent = 0;
#ifdef DEBUG_CURRENT
Serial.print("zero Current ");
Serial.println(zeroCurrent);
#endif
//lipo voltage at startup
for (int i = 0; i < 2000; i++) prevVin += analogRead(VIN_PIN); //ADC smmothing
prevVin = prevVin / 2000;
prevVin = volts(prevVin);
#ifdef DEBUG_TELNET
TelnetStream.print("start");
#endif
LastUDPnotification = millis();
}
//***********************************************************************************************************************
void loop() {
esp_task_wdt_reset(); //reset the watchdog
//*******************
//acquire all sensors
//*******************
//outside temperature sensor
#ifdef HAS_DS18B20
temperature = 0;
int i;
int kk;
for (i = 0; i < 20; i++) {
tempScale1.requestTemperatures();
temperature += tempScale1.getTempCByIndex(0);
}
temperature /= i;
#ifdef DEBUG_TEMPERATURE
Serial.print("temperature = ");
Serial.print(temperature);
Serial.println(" °C");
#endif
#endif
//lipo voltage
for (int i = 0; i < smooth; i++) Vin += analogRead(VIN_PIN); //ADC smmothing
Vin = Vin / smooth;
#ifdef DEBUG_VIN
Serial.print("Vin ");
Serial.print(Vin);
Serial.print(" / ");
#endif
Vin = volts(Vin);
if (Vin > prevVin) Vin = prevVin; //will discard positive spikes
#ifdef DEBUG_VIN
Serial.println(Vin);
#endif
//lipo current
for (int i = 0; i < smooth; i++) current += analogRead(CUR_PIN); //ADC smoothing
current = current / smooth;
#ifdef DEBUG_CURRENT
Serial.print("Current ");
Serial.print(current);
Serial.print(" / ");
#endif
current = amps(current);
if ((current) < 0) current = prevCurrent; // this will discard negative current values (spikes due to the ESC...)
prevCurrent = current;
#ifdef DEBUG_CURRENT
Serial.println(current);
#endif
//propeller thrust
#ifdef HAS_HX711
GetRawWeight(); //HX711 sensor
AverageWeight = (calibZero - CurrentRawWeight) * calibWeight / (calib);
#ifdef DEBUG
Serial.print("weight = ");
Serial.print(AverageWeight);
Serial.println(" g");
#endif
#endif //HAS_HX711
//propeller RPM
#ifdef HAS_SPEED_SENSOR
RPM = tops * 60 * 1000 / (millis() - speedSensorMeasuringTime) / NB_BLADES; // simple formula to go from blades tops to RPM
#ifdef DEBUG_RPM
Serial.print("RPM = ");
Serial.println(RPM);
#endif
tops = 0; // reset the ISR variable
speedSensorMeasuringTime = millis();
#endif
//***************************
//decoding the Radio receiver
//***************************
if (pwm_get_state_name(0) == "STABLE") // if we receive "throttle" channel then switch to manual mode
{
// Reading the actual pulse width of Throttle channel
throttle = constrain((pwm_get_rawPwm(0) - 1000), 0, 1000); //clip throttle value between 0 and 5
}
/*
int minThrottle = 0;
int maxThrottle = 500;
int currentThrottle = 0;
int sweepDuration = 5000; //5s duration for half an automatic mode
int refreshDelay;
float refreshStep;
long refreshTimeOut = 0;*/
// Do something with the pulse width... throttle
// ESC PWM
switch (opMode) {
case 0: //manual
myESC.writeMicroseconds(throttle + 1000); //replicate the throttle value
break;
case 1: //step
if ((millis() - refreshTimeOut) > refreshDelay) {
refreshTimeOut = millis();
currentThrottle += refreshStep;
refreshStep = -refreshStep;
}
throttle = currentThrottle;
myESC.writeMicroseconds(throttle + 1000); //generate the step
break;
case 2: //sweep
if ((millis() - refreshTimeOut) > refreshDelay) {
refreshTimeOut = millis();
currentThrottle += refreshStep;
if (currentThrottle >= maxThrottle) refreshStep = -refreshStep;
if (currentThrottle <= minThrottle) refreshStep = -refreshStep;
}
throttle = currentThrottle;
myESC.writeMicroseconds(throttle + 1000); //generate the step
break;
case 3: //stop
myESC.writeMicroseconds(0 + 1000); //clear the throttle value
break;
default:
// statements
break;
}
//************
// UDP process
//************
int packetSize = Udp.parsePacket(); //if there's data available, read a packet coming from Android phone
if (packetSize) {
Timeout = millis(); //rearm software watchdog
#if defined xxxDEBUG
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
#endif
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
#if defined UDP_DEBUG
Serial.print("UDP Contents: ");
Serial.println(packetBuffer);
#endif
String Res;
String test;
int i;
test = packetBuffer;
if (test == "ID") // send a reply, to the IP address and port that sent us the packet we received
{
AndroidConnected = 1;
timeOut = millis();
Res = device;
sendUDP(Res);
} else if (test.startsWith("TOPIC")) // send a reply, to the IP address and port that sent us the packet we received
{
//{"sender":"18FE349E7690","device":"WaterLeak"}
Res = WiFi.macAddress();
Res.replace(":", "");
sendUDP(Res);
}
else if (test.startsWith("{")) // decode json
{
// message = test.substring(6);
readCmd(test);
}
else if (test.startsWith("STOP")) // send a reply, to the IP address and port that sent us the packet we received
{
sendUDP("okSTOP");
}
}
//send sensors data as fast as possible (else uncomment the following line)
//if (((millis() - LastUDPnotification) > 10)) // send UDP message to Android App (no need to be connected, a simple notification, send and forget)
{
String res;
res = "{\"A\":\"" + String(current) + "\",\"V\": " + String(Vin) + ",\"W\": " + String(AverageWeight) + ",\"R\": " + String(RPM) + ",\"T\": " + String(temperature) + ",\"S\": " + String(throttle) + "}";
//LastUDPnotification = millis();
#ifdef DEBUG_TELNET
TelnetStream.println(res);
#endif
sendUDP(res); //try to send via UDP
}
#ifdef OLED
displayLCD(); //and update OLED display
#endif
if (((millis() - timeOut) > 5000) && (AndroidConnected == 1)) {
opMode = 0; //if connection with Android is lost then switch to manual mode
AndroidConnected = 0;
Serial.println("lost connection with Android phone, switch to Manual mode");
}
} //end of Loop
#ifdef OLED
void displayLCD(void) //refresh the LCD screen
{
display.clear();
display.drawString(0, 0, "current : " + (String)current + " A");
display.drawString(0, 10, "voltage : " + (String)Vin + " V");
display.drawString(0, 20, "thrust : " + (String)AverageWeight + " kg");
display.drawString(0, 30, "RPM : " + (String)RPM);
display.drawString(0, 40, "temp : " + (String)temperature + " °C");
display.display();
}
#endif
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
int ftouchRead(int gpio) // this will filter false readings of touchRead() function...
{
int val = 0;
int readVal;
for (int i = 0; i < 10; i++) {
readVal = touchRead(gpio);
val = max(val, readVal);
}
return val;
}
void sendUDP(String Res) {
char ReplyBuffer[Res.length() + 1]; // a string to send back
Res.toCharArray(ReplyBuffer, Res.length() + 1);
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.print(ReplyBuffer); //was write...
Udp.endPacket();
}
void readCmd(String test) {
if (test.startsWith("{")) //then it may contain JSON
{
StaticJsonDocument<2000> doc;
DeserializationError error = deserializeJson(doc, test);
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
Serial.println("deserializeJson() failed"); //answer with error : {"answer" : "error","detail":"decoding failed"}
sendUDP("{\"answer\" : \"error\",\"detail\":\"decoding failed\"}");
} else {
// Fetch values --> {"Cmd":"Start"}
String Cmd = doc["Cmd"];
if (Cmd == "Calib") //set high
{
String value = doc["value"];
calibWeight = value.toInt();
GetRawWeight(); //HX711 sensor
calib = calibZero - CurrentRawWeight;
Serial.print("calibration HX711... ");
Serial.println(calib);
Serial.print(" for weight (g) ");
Serial.println(calibWeight);
preferences.putLong("calib", calib);
preferences.putInt("calibWeight", calibWeight);
} else if (Cmd == "Mode") {
Serial.print("change operation mode to ");
String value = doc["value"];
opMode = value.toInt();
String minThr = doc["min"];
minThrottle = minThr.toInt();
String maxThr = doc["max"];
maxThrottle = maxThr.toInt();
Serial.print(opMode);
Serial.print(" min ");
Serial.print(minThrottle);
Serial.print(" max ");
Serial.println(maxThrottle);
switch (opMode) {
case 0: //manual
//do nothing
break;
case 1: //step
refreshStep = maxThrottle - minThrottle;
refreshDelay = sweepDuration;
currentThrottle = minThrottle;
refreshTimeOut = millis();
break;
case 2: //sweep
refreshDelay = 50; //will refresh every 50ms
refreshStep = (float)(maxThrottle - minThrottle)*refreshDelay/sweepDuration +0.5;
currentThrottle = minThrottle;
refreshTimeOut = millis();
Serial.print(" refreshStep ");
Serial.println(refreshStep);
break;
case 3: //stop
myESC.writeMicroseconds(0 + 1000); //clear the throttle value
break;
default:
// statements
break;
}
}
}
}
}
#ifdef HAS_HX711
void GetRawWeight(void) {
unsigned long RawWeight;
// wait for the chip to become ready
long startTime;
//delay(5000); //let the HX711 warm up
AverageWeight = 0;
int j = 0;
for (j = 0; j < 1; j++) {
startTime = millis();
while ((digitalRead(PIN_DOUT) == HIGH) && ((millis() - startTime) < 1000))
; //wait for data conversion ready
if ((millis() - startTime) > 1000) //or time out...
{
Serial.println("weight error");
}
RawWeight = 0;
// pulse the clock pin 24 times to read the data
for (char i = 0; i < 24; i++) {
digitalWrite(PIN_CLOCK, HIGH);
delayMicroseconds(1);
RawWeight = RawWeight << 1;
if (digitalRead(PIN_DOUT) == HIGH) RawWeight++;
digitalWrite(PIN_CLOCK, LOW);
}
// set the channel and the gain factor (A 128) for the next reading using the clock pin (one pulse)
digitalWrite(PIN_CLOCK, HIGH);
delayMicroseconds(1);
RawWeight = RawWeight ^ 0x800000;
digitalWrite(PIN_CLOCK, LOW);
AverageWeight += RawWeight;
}
//digitalWrite(PIN_CLOCK, HIGH); //to enter into power saving mode
CurrentRawWeight = AverageWeight / j;
#ifdef xRAW_WEIGHT_DEBUG
Serial.print("Raw weight : \t");
Serial.println(RawWeight);
#endif
#ifdef RAW_WEIGHT_DEBUG
Serial.print("Raw average weight : ");
Serial.println(CurrentRawWeight);
#endif
}
#endif
float mapf(float value, float fromLow, float fromHigh, float toLow, float toHigh) {
float result;
result = (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
return result;
}
float volts(float raw) //simple linear calibration...
{
return raw * 11.64 / 3780; //calib reading raw value into log
}
float amps(float raw) //simple linear calibration without substraction of the zero current (which is measured at boot time into setup)...
{
return ((zeroCurrent - raw) * 8. / 105.);
}
int medianFilter(void) {
//median filter
int raw = smoothArray[0];
if (FILTER_SAMPLES > 1) {
boolean done;
float temp;
int k, top, bottom;
done = 0; // flag to know when we're done sorting
while (done != 1) { // simple swap sort, sorts numbers from lowest to highest
done = 1;
for (int j = 0; j < (FILTER_SAMPLES - 1); j++) {
if (smoothArray[j] > smoothArray[j + 1]) { // numbers are out of order - swap
temp = smoothArray[j + 1];
smoothArray[j + 1] = smoothArray[j];
smoothArray[j] = temp;
done = 0;
}
}
}
// throw out top and bottom REJECT_RATIO % of samples - limit to throw out at least one from top and bottom
bottom = max(((FILTER_SAMPLES * REJECT_RATIO) / 100), 1);
top = min((((FILTER_SAMPLES * (100 - REJECT_RATIO)) / 100) + 1), (FILTER_SAMPLES - 1)); // the + 1 is to make up for asymmetry caused by integer rounding
k = 0;
raw = 0;
for (int j = bottom; j < top; j++) {
raw += smoothArray[j]; // total remaining indices
k++;
}
raw = raw / k; // divide by number of samples and return the value
//end median filter
}
return raw;
}