-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
Copy pathesp32-hal-uart.c
1201 lines (1072 loc) · 39.4 KB
/
esp32-hal-uart.c
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
// Copyright 2015-2024 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "esp32-hal-uart.h"
#if SOC_UART_SUPPORTED
#include "esp32-hal.h"
#include "esp32-hal-periman.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "driver/uart.h"
#include "hal/uart_ll.h"
#include "soc/soc_caps.h"
#include "soc/uart_struct.h"
#include "soc/uart_periph.h"
#include "rom/ets_sys.h"
#include "rom/gpio.h"
#include "driver/gpio.h"
#include "hal/gpio_hal.h"
#include "esp_rom_gpio.h"
static int s_uart_debug_nr = 0; // UART number for debug output
#define REF_TICK_BAUDRATE_LIMIT 250000 // this is maximum UART badrate using REF_TICK as clock
struct uart_struct_t {
#if !CONFIG_DISABLE_HAL_LOCKS
SemaphoreHandle_t lock; // UART lock
#endif
uint8_t num; // UART number for IDF driver API
bool has_peek; // flag to indicate that there is a peek byte pending to be read
uint8_t peek_byte; // peek byte that has been read but not consumed
QueueHandle_t uart_event_queue; // export it by some uartGetEventQueue() function
// configuration data:: Arduino API typical data
int8_t _rxPin, _txPin, _ctsPin, _rtsPin; // UART GPIOs
uint32_t _baudrate, _config; // UART baudrate and config
// UART ESP32 specific data
uint16_t _rx_buffer_size, _tx_buffer_size; // UART RX and TX buffer sizes
bool _inverted; // UART inverted signal
uint8_t _rxfifo_full_thrhd; // UART RX FIFO full threshold
};
#if CONFIG_DISABLE_HAL_LOCKS
#define UART_MUTEX_LOCK()
#define UART_MUTEX_UNLOCK()
static uart_t _uart_bus_array[] = {
{0, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#if SOC_UART_HP_NUM > 1
{1, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
#if SOC_UART_HP_NUM > 2
{2, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
#if SOC_UART_HP_NUM > 3
{3, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
#if SOC_UART_HP_NUM > 4
{4, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
};
#else
#define UART_MUTEX_LOCK() \
if (uart->lock != NULL) \
do { \
} while (xSemaphoreTake(uart->lock, portMAX_DELAY) != pdPASS)
#define UART_MUTEX_UNLOCK() \
if (uart->lock != NULL) \
xSemaphoreGive(uart->lock)
static uart_t _uart_bus_array[] = {
{NULL, 0, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#if SOC_UART_HP_NUM > 1
{NULL, 1, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
#if SOC_UART_HP_NUM > 2
{NULL, 2, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
#if SOC_UART_HP_NUM > 3
{NULL, 3, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
#if SOC_UART_HP_NUM > 4
{NULL, 4, false, 0, NULL, -1, -1, -1, -1, 0, 0, 0, 0, false, 0},
#endif
};
#endif
// Negative Pin Number will keep it unmodified, thus this function can detach individual pins
// This function will also unset the pins in the Peripheral Manager and set the pin to -1 after detaching
static bool _uartDetachPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t ctsPin, int8_t rtsPin) {
if (uart_num >= SOC_UART_HP_NUM) {
log_e("Serial number is invalid, please use number from 0 to %u", SOC_UART_HP_NUM - 1);
return false;
}
// get UART information
uart_t *uart = &_uart_bus_array[uart_num];
bool retCode = true;
//log_v("detaching UART%d pins: prev,pin RX(%d,%d) TX(%d,%d) CTS(%d,%d) RTS(%d,%d)", uart_num,
// uart->_rxPin, rxPin, uart->_txPin, txPin, uart->_ctsPin, ctsPin, uart->_rtsPin, rtsPin); vTaskDelay(10);
// detaches pins and sets Peripheral Manager and UART information
if (rxPin >= 0 && uart->_rxPin == rxPin && perimanGetPinBusType(rxPin) == ESP32_BUS_TYPE_UART_RX) {
gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[rxPin], PIN_FUNC_GPIO);
// avoids causing BREAK in the UART line
if (uart->_inverted) {
esp_rom_gpio_connect_in_signal(GPIO_FUNC_IN_LOW, UART_PERIPH_SIGNAL(uart_num, SOC_UART_RX_PIN_IDX), false);
} else {
esp_rom_gpio_connect_in_signal(GPIO_FUNC_IN_HIGH, UART_PERIPH_SIGNAL(uart_num, SOC_UART_RX_PIN_IDX), false);
}
uart->_rxPin = -1; // -1 means unassigned/detached
if (!perimanClearPinBus(rxPin)) {
retCode = false;
log_e("UART%d failed to detach RX pin %d", uart_num, rxPin);
}
}
if (txPin >= 0 && uart->_txPin == txPin && perimanGetPinBusType(txPin) == ESP32_BUS_TYPE_UART_TX) {
gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[txPin], PIN_FUNC_GPIO);
esp_rom_gpio_connect_out_signal(txPin, SIG_GPIO_OUT_IDX, false, false);
uart->_txPin = -1; // -1 means unassigned/detached
if (!perimanClearPinBus(txPin)) {
retCode = false;
log_e("UART%d failed to detach TX pin %d", uart_num, txPin);
}
}
if (ctsPin >= 0 && uart->_ctsPin == ctsPin && perimanGetPinBusType(ctsPin) == ESP32_BUS_TYPE_UART_CTS) {
gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[ctsPin], PIN_FUNC_GPIO);
esp_rom_gpio_connect_in_signal(GPIO_FUNC_IN_LOW, UART_PERIPH_SIGNAL(uart_num, SOC_UART_CTS_PIN_IDX), false);
uart->_ctsPin = -1; // -1 means unassigned/detached
if (!perimanClearPinBus(ctsPin)) {
retCode = false;
log_e("UART%d failed to detach CTS pin %d", uart_num, ctsPin);
}
}
if (rtsPin >= 0 && uart->_rtsPin == rtsPin && perimanGetPinBusType(rtsPin) == ESP32_BUS_TYPE_UART_RTS) {
gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[rtsPin], PIN_FUNC_GPIO);
esp_rom_gpio_connect_out_signal(rtsPin, SIG_GPIO_OUT_IDX, false, false);
uart->_rtsPin = -1; // -1 means unassigned/detached
if (!perimanClearPinBus(rtsPin)) {
retCode = false;
log_e("UART%d failed to detach RTS pin %d", uart_num, rtsPin);
}
}
return retCode;
}
// Peripheral Manager detach callback for each specific UART PIN
static bool _uartDetachBus_RX(void *busptr) {
// sanity check - it should never happen
assert(busptr && "_uartDetachBus_RX bus NULL pointer.");
uart_t *bus = (uart_t *)busptr;
return _uartDetachPins(bus->num, bus->_rxPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
static bool _uartDetachBus_TX(void *busptr) {
// sanity check - it should never happen
assert(busptr && "_uartDetachBus_TX bus NULL pointer.");
uart_t *bus = (uart_t *)busptr;
return _uartDetachPins(bus->num, UART_PIN_NO_CHANGE, bus->_txPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
static bool _uartDetachBus_CTS(void *busptr) {
// sanity check - it should never happen
assert(busptr && "_uartDetachBus_CTS bus NULL pointer.");
uart_t *bus = (uart_t *)busptr;
return _uartDetachPins(bus->num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, bus->_ctsPin, UART_PIN_NO_CHANGE);
}
static bool _uartDetachBus_RTS(void *busptr) {
// sanity check - it should never happen
assert(busptr && "_uartDetachBus_RTS bus NULL pointer.");
uart_t *bus = (uart_t *)busptr;
return _uartDetachPins(bus->num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, bus->_rtsPin);
}
// Attach function for UART
// connects the IO Pad, set Paripheral Manager and internal UART structure data
static bool _uartAttachPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t ctsPin, int8_t rtsPin) {
if (uart_num >= SOC_UART_HP_NUM) {
log_e("Serial number is invalid, please use number from 0 to %u", SOC_UART_HP_NUM - 1);
return false;
}
// get UART information
uart_t *uart = &_uart_bus_array[uart_num];
//log_v("attaching UART%d pins: prev,new RX(%d,%d) TX(%d,%d) CTS(%d,%d) RTS(%d,%d)", uart_num,
// uart->_rxPin, rxPin, uart->_txPin, txPin, uart->_ctsPin, ctsPin, uart->_rtsPin, rtsPin); vTaskDelay(10);
bool retCode = true;
if (rxPin >= 0) {
// forces a clean detaching from a previous peripheral
if (perimanGetPinBusType(rxPin) != ESP32_BUS_TYPE_INIT) {
perimanClearPinBus(rxPin);
}
// connect RX Pad
bool ret = ESP_OK == uart_set_pin(uart->num, UART_PIN_NO_CHANGE, rxPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
if (ret) {
ret &= perimanSetPinBus(rxPin, ESP32_BUS_TYPE_UART_RX, (void *)uart, uart_num, -1);
if (ret) {
uart->_rxPin = rxPin;
}
}
if (!ret) {
log_e("UART%d failed to attach RX pin %d", uart_num, rxPin);
}
retCode &= ret;
}
if (txPin >= 0) {
// forces a clean detaching from a previous peripheral
if (perimanGetPinBusType(txPin) != ESP32_BUS_TYPE_INIT) {
perimanClearPinBus(txPin);
}
// connect TX Pad
bool ret = ESP_OK == uart_set_pin(uart->num, txPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
if (ret) {
ret &= perimanSetPinBus(txPin, ESP32_BUS_TYPE_UART_TX, (void *)uart, uart_num, -1);
if (ret) {
uart->_txPin = txPin;
}
}
if (!ret) {
log_e("UART%d failed to attach TX pin %d", uart_num, txPin);
}
retCode &= ret;
}
if (ctsPin >= 0) {
// forces a clean detaching from a previous peripheral
if (perimanGetPinBusType(ctsPin) != ESP32_BUS_TYPE_INIT) {
perimanClearPinBus(ctsPin);
}
// connect CTS Pad
bool ret = ESP_OK == uart_set_pin(uart->num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, ctsPin);
if (ret) {
ret &= perimanSetPinBus(ctsPin, ESP32_BUS_TYPE_UART_CTS, (void *)uart, uart_num, -1);
if (ret) {
uart->_ctsPin = ctsPin;
}
}
if (!ret) {
log_e("UART%d failed to attach CTS pin %d", uart_num, ctsPin);
}
retCode &= ret;
}
if (rtsPin >= 0) {
// forces a clean detaching from a previous peripheral
if (perimanGetPinBusType(rtsPin) != ESP32_BUS_TYPE_INIT) {
perimanClearPinBus(rtsPin);
}
// connect RTS Pad
bool ret = ESP_OK == uart_set_pin(uart->num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, rtsPin, UART_PIN_NO_CHANGE);
if (ret) {
ret &= perimanSetPinBus(rtsPin, ESP32_BUS_TYPE_UART_RTS, (void *)uart, uart_num, -1);
if (ret) {
uart->_rtsPin = rtsPin;
}
}
if (!ret) {
log_e("UART%d failed to attach RTS pin %d", uart_num, rtsPin);
}
retCode &= ret;
}
return retCode;
}
// just helper functions
int8_t uart_get_RxPin(uint8_t uart_num) {
return _uart_bus_array[uart_num]._rxPin;
}
int8_t uart_get_TxPin(uint8_t uart_num) {
return _uart_bus_array[uart_num]._txPin;
}
void uart_init_PeriMan(void) {
// set Peripheral Manager deInit Callback for each UART pin
perimanSetBusDeinit(ESP32_BUS_TYPE_UART_RX, _uartDetachBus_RX);
perimanSetBusDeinit(ESP32_BUS_TYPE_UART_TX, _uartDetachBus_TX);
perimanSetBusDeinit(ESP32_BUS_TYPE_UART_CTS, _uartDetachBus_CTS);
perimanSetBusDeinit(ESP32_BUS_TYPE_UART_RTS, _uartDetachBus_RTS);
}
// Routines that take care of UART events will be in the HardwareSerial Class code
void uartGetEventQueue(uart_t *uart, QueueHandle_t *q) {
// passing back NULL for the Queue pointer when UART is not initialized yet
*q = NULL;
if (uart == NULL) {
return;
}
*q = uart->uart_event_queue;
return;
}
bool uartIsDriverInstalled(uart_t *uart) {
if (uart == NULL) {
return false;
}
if (uart_is_driver_installed(uart->num)) {
return true;
}
return false;
}
// Negative Pin Number will keep it unmodified, thus this function can set individual pins
// When pins are changed, it will detach the previous one
bool uartSetPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t ctsPin, int8_t rtsPin) {
if (uart_num >= SOC_UART_HP_NUM) {
log_e("Serial number is invalid, please use number from 0 to %u", SOC_UART_HP_NUM - 1);
return false;
}
// get UART information
uart_t *uart = &_uart_bus_array[uart_num];
bool retCode = true;
UART_MUTEX_LOCK();
//log_v("setting UART%d pins: prev->new RX(%d->%d) TX(%d->%d) CTS(%d->%d) RTS(%d->%d)", uart_num,
// uart->_rxPin, rxPin, uart->_txPin, txPin, uart->_ctsPin, ctsPin, uart->_rtsPin, rtsPin); vTaskDelay(10);
// First step: detaches all previous UART pins
bool rxPinChanged = rxPin >= 0 && rxPin != uart->_rxPin;
if (rxPinChanged) {
retCode &= _uartDetachPins(uart_num, uart->_rxPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
bool txPinChanged = txPin >= 0 && txPin != uart->_txPin;
if (txPinChanged) {
retCode &= _uartDetachPins(uart_num, UART_PIN_NO_CHANGE, uart->_txPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
bool ctsPinChanged = ctsPin >= 0 && ctsPin != uart->_ctsPin;
if (ctsPinChanged) {
retCode &= _uartDetachPins(uart_num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, uart->_ctsPin, UART_PIN_NO_CHANGE);
}
bool rtsPinChanged = rtsPin >= 0 && rtsPin != uart->_rtsPin;
if (rtsPinChanged) {
retCode &= _uartDetachPins(uart_num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, uart->_rtsPin);
}
// Second step: attach all UART new pins
if (rxPinChanged) {
retCode &= _uartAttachPins(uart_num, rxPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
if (txPinChanged) {
retCode &= _uartAttachPins(uart_num, UART_PIN_NO_CHANGE, txPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
if (ctsPinChanged) {
retCode &= _uartAttachPins(uart->num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, ctsPin, UART_PIN_NO_CHANGE);
}
if (rtsPinChanged) {
retCode &= _uartAttachPins(uart->num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, rtsPin);
}
UART_MUTEX_UNLOCK();
if (!retCode) {
log_e("UART%d set pins failed.", uart_num);
}
return retCode;
}
//
bool uartSetHwFlowCtrlMode(uart_t *uart, uart_hw_flowcontrol_t mode, uint8_t threshold) {
if (uart == NULL) {
return false;
}
// IDF will issue corresponding error message when mode or threshold are wrong and prevent crashing
// IDF will check (mode > HW_FLOWCTRL_CTS_RTS || threshold >= SOC_UART_FIFO_LEN)
UART_MUTEX_LOCK();
bool retCode = (ESP_OK == uart_set_hw_flow_ctrl(uart->num, mode, threshold));
UART_MUTEX_UNLOCK();
return retCode;
}
// This helper function will return true if a new IDF UART driver needs to be restarted and false if the current one can continue its execution
bool _testUartBegin(
uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint32_t rx_buffer_size, uint32_t tx_buffer_size, bool inverted,
uint8_t rxfifo_full_thrhd
) {
if (uart_nr >= SOC_UART_HP_NUM) {
return false; // no new driver has to be installed
}
uart_t *uart = &_uart_bus_array[uart_nr];
// verify if is necessary to restart the UART driver
if (uart_is_driver_installed(uart_nr)) {
// some parameters can't be changed unless we end the UART driver
if (uart->_rx_buffer_size != rx_buffer_size || uart->_tx_buffer_size != tx_buffer_size || uart->_inverted != inverted
|| uart->_rxfifo_full_thrhd != rxfifo_full_thrhd) {
return true; // the current IDF UART driver must be terminated and a new driver shall be installed
} else {
return false; // The current IDF UART driver can continue its execution
}
} else {
return true; // no IDF UART driver is running and a new driver shall be installed
}
}
uart_t *uartBegin(
uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint32_t rx_buffer_size, uint32_t tx_buffer_size, bool inverted,
uint8_t rxfifo_full_thrhd
) {
if (uart_nr >= SOC_UART_HP_NUM) {
log_e("UART number is invalid, please use number from 0 to %u", SOC_UART_HP_NUM - 1);
return NULL; // no new driver was installed
}
uart_t *uart = &_uart_bus_array[uart_nr];
log_v("UART%d baud(%ld) Mode(%x) rxPin(%d) txPin(%d)", uart_nr, baudrate, config, rxPin, txPin);
#if !CONFIG_DISABLE_HAL_LOCKS
if (uart->lock == NULL) {
uart->lock = xSemaphoreCreateMutex();
if (uart->lock == NULL) {
log_e("HAL LOCK error.");
return NULL; // no new driver was installed
}
}
#endif
if (uart_is_driver_installed(uart_nr)) {
log_v("UART%d Driver already installed.", uart_nr);
// some parameters can't be changed unless we end the UART driver
if (uart->_rx_buffer_size != rx_buffer_size || uart->_tx_buffer_size != tx_buffer_size || uart->_inverted != inverted
|| uart->_rxfifo_full_thrhd != rxfifo_full_thrhd) {
log_v("UART%d changing buffer sizes or inverted signal or rxfifo_full_thrhd. IDF driver will be restarted", uart_nr);
uartEnd(uart_nr);
} else {
bool retCode = true;
UART_MUTEX_LOCK();
//User may just want to change some parameters, such as baudrate, data length, parity, stop bits or pins
if (uart->_baudrate != baudrate) {
if (ESP_OK != uart_set_baudrate(uart_nr, baudrate)) {
log_e("UART%d changing baudrate failed.", uart_nr);
retCode = false;
} else {
log_v("UART%d changed baudrate to %d", uart_nr, baudrate);
uart->_baudrate = baudrate;
}
}
uart_word_length_t data_bits = (config & 0xc) >> 2;
uart_parity_t parity = config & 0x3;
uart_stop_bits_t stop_bits = (config & 0x30) >> 4;
if (retCode && (uart->_config & 0xc) >> 2 != data_bits) {
if (ESP_OK != uart_set_word_length(uart_nr, data_bits)) {
log_e("UART%d changing data length failed.", uart_nr);
retCode = false;
} else {
log_v("UART%d changed data length to %d", uart_nr, data_bits + 5);
}
}
if (retCode && (uart->_config & 0x3) != parity) {
if (ESP_OK != uart_set_parity(uart_nr, parity)) {
log_e("UART%d changing parity failed.", uart_nr);
retCode = false;
} else {
log_v("UART%d changed parity to %s", uart_nr, parity == 0 ? "NONE" : parity == 2 ? "EVEN" : "ODD");
}
}
if (retCode && (uart->_config & 0xc30) >> 4 != stop_bits) {
if (ESP_OK != uart_set_stop_bits(uart_nr, stop_bits)) {
log_e("UART%d changing stop bits failed.", uart_nr);
retCode = false;
} else {
log_v("UART%d changed stop bits to %d", uart_nr, stop_bits == 3 ? 2 : 1);
}
}
if (retCode) {
uart->_config = config;
}
if (retCode && rxPin > 0 && uart->_rxPin != rxPin) {
retCode &= _uartDetachPins(uart_nr, uart->_rxPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
retCode &= _uartAttachPins(uart_nr, rxPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
if (!retCode) {
log_e("UART%d changing RX pin failed.", uart_nr);
} else {
log_v("UART%d changed RX pin to %d", uart_nr, rxPin);
}
}
if (retCode && txPin > 0 && uart->_txPin != txPin) {
retCode &= _uartDetachPins(uart_nr, UART_PIN_NO_CHANGE, uart->_txPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
retCode &= _uartAttachPins(uart_nr, UART_PIN_NO_CHANGE, txPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
if (!retCode) {
log_e("UART%d changing TX pin failed.", uart_nr);
} else {
log_v("UART%d changed TX pin to %d", uart_nr, txPin);
}
}
UART_MUTEX_UNLOCK();
if (retCode) {
// UART driver was already working, just return the uart_t structure, syaing that no new driver was installed
return uart;
}
// if we reach this point, it means that we need to restart the UART driver
uartEnd(uart_nr);
}
} else {
log_v("UART%d not installed. Starting installation", uart_nr);
}
uart_config_t uart_config;
memset(&uart_config, 0, sizeof(uart_config_t));
uart_config.flags.backup_before_sleep = false; // new flag from IDF v5.3
uart_config.data_bits = (config & 0xc) >> 2;
uart_config.parity = (config & 0x3);
uart_config.stop_bits = (config & 0x30) >> 4;
uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;
uart_config.rx_flow_ctrl_thresh = rxfifo_full_thrhd;
uart_config.baud_rate = baudrate;
// there is an issue when returning from light sleep with the C6 and H2: the uart baud rate is not restored
// therefore, uart clock source will set to XTAL for all SoC that support it. This fix solves the C6|H2 issue.
#if SOC_UART_SUPPORT_XTAL_CLK
uart_config.source_clk = UART_SCLK_XTAL; // valid for C2, S3, C3, C6, H2 and P4
#elif SOC_UART_SUPPORT_REF_TICK
if (baudrate <= REF_TICK_BAUDRATE_LIMIT) {
uart_config.source_clk = UART_SCLK_REF_TICK; // valid for ESP32, S2 - MAX supported baud rate is 250 Kbps
} else {
uart_config.source_clk = UART_SCLK_APB; // baudrate may change with the APB Frequency!
}
#else
// Default CLK Source: CLK_APB for ESP32|S2|S3|C3 -- CLK_PLL_F40M for C2 -- CLK_PLL_F48M for H2 -- CLK_PLL_F80M for C6
uart_config.source_clk = UART_SCLK_DEFAULT; // baudrate may change with the APB Frequency!
#endif
UART_MUTEX_LOCK();
bool retCode = ESP_OK == uart_driver_install(uart_nr, rx_buffer_size, tx_buffer_size, 20, &(uart->uart_event_queue), 0);
if (retCode) {
retCode &= ESP_OK == uart_param_config(uart_nr, &uart_config);
}
if (retCode) {
if (inverted) {
// invert signal for both Rx and Tx
retCode &= ESP_OK == uart_set_line_inverse(uart_nr, UART_SIGNAL_TXD_INV | UART_SIGNAL_RXD_INV);
} else {
// disable invert signal for both Rx and Tx
retCode &= ESP_OK == uart_set_line_inverse(uart_nr, UART_SIGNAL_INV_DISABLE);
}
}
// if all fine, set internal parameters
if (retCode) {
uart->_baudrate = baudrate;
uart->_config = config;
uart->_inverted = inverted;
uart->_rxfifo_full_thrhd = rxfifo_full_thrhd;
uart->_rx_buffer_size = rx_buffer_size;
uart->_tx_buffer_size = tx_buffer_size;
uart->has_peek = false;
uart->peek_byte = 0;
}
UART_MUTEX_UNLOCK();
// uartSetPins detaches previous pins if new ones are used over a previous begin()
if (retCode) {
retCode &= uartSetPins(uart_nr, rxPin, txPin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
if (!retCode) {
log_e("UART%d initialization error.", uart->num);
uartEnd(uart_nr);
uart = NULL;
} else {
uartFlush(uart);
log_v("UART%d initialization done.", uart->num);
}
return uart; // a new driver was installed
}
// This function code is under testing - for now just keep it here
void uartSetFastReading(uart_t *uart) {
if (uart == NULL) {
return;
}
UART_MUTEX_LOCK();
// override default RX IDF Driver Interrupt - no BREAK, PARITY or OVERFLOW
uart_intr_config_t uart_intr = {
.intr_enable_mask = UART_INTR_RXFIFO_FULL | UART_INTR_RXFIFO_TOUT, // only these IRQs - no BREAK, PARITY or OVERFLOW
.rx_timeout_thresh = 1,
.txfifo_empty_intr_thresh = 10,
.rxfifo_full_thresh = 2,
};
ESP_ERROR_CHECK(uart_intr_config(uart->num, &uart_intr));
UART_MUTEX_UNLOCK();
}
bool uartSetRxTimeout(uart_t *uart, uint8_t numSymbTimeout) {
if (uart == NULL) {
return false;
}
UART_MUTEX_LOCK();
bool retCode = (ESP_OK == uart_set_rx_timeout(uart->num, numSymbTimeout));
UART_MUTEX_UNLOCK();
return retCode;
}
bool uartSetRxFIFOFull(uart_t *uart, uint8_t numBytesFIFOFull) {
if (uart == NULL) {
return false;
}
UART_MUTEX_LOCK();
bool retCode = (ESP_OK == uart_set_rx_full_threshold(uart->num, numBytesFIFOFull));
UART_MUTEX_UNLOCK();
return retCode;
}
void uartEnd(uint8_t uart_num) {
if (uart_num >= SOC_UART_HP_NUM) {
log_e("Serial number is invalid, please use number from 0 to %u", SOC_UART_HP_NUM - 1);
return;
}
// get UART information
uart_t *uart = &_uart_bus_array[uart_num];
UART_MUTEX_LOCK();
_uartDetachPins(uart_num, uart->_rxPin, uart->_txPin, uart->_ctsPin, uart->_rtsPin);
if (uart_is_driver_installed(uart_num)) {
uart_driver_delete(uart_num);
}
UART_MUTEX_UNLOCK();
}
void uartSetRxInvert(uart_t *uart, bool invert) {
if (uart == NULL) {
return;
}
#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
// POTENTIAL ISSUE :: original code only set/reset rxd_inv bit
// IDF or LL set/reset the whole inv_mask!
// if (invert)
// ESP_ERROR_CHECK(uart_set_line_inverse(uart->num, UART_SIGNAL_RXD_INV));
// else
// ESP_ERROR_CHECK(uart_set_line_inverse(uart->num, UART_SIGNAL_INV_DISABLE));
#else
// this implementation is better over IDF API because it only affects RXD
// this is supported in ESP32, ESP32-S2 and ESP32-C3
uart_dev_t *hw = UART_LL_GET_HW(uart->num);
if (invert) {
hw->conf0.rxd_inv = 1;
} else {
hw->conf0.rxd_inv = 0;
}
#endif
}
uint32_t uartAvailable(uart_t *uart) {
if (uart == NULL) {
return 0;
}
UART_MUTEX_LOCK();
size_t available;
uart_get_buffered_data_len(uart->num, &available);
if (uart->has_peek) {
available++;
}
UART_MUTEX_UNLOCK();
return available;
}
uint32_t uartAvailableForWrite(uart_t *uart) {
if (uart == NULL) {
return 0;
}
UART_MUTEX_LOCK();
uint32_t available = uart_ll_get_txfifo_len(UART_LL_GET_HW(uart->num));
size_t txRingBufferAvailable = 0;
if (ESP_OK == uart_get_tx_buffer_free_size(uart->num, &txRingBufferAvailable)) {
available = txRingBufferAvailable == 0 ? available : txRingBufferAvailable;
}
UART_MUTEX_UNLOCK();
return available;
}
size_t uartReadBytes(uart_t *uart, uint8_t *buffer, size_t size, uint32_t timeout_ms) {
if (uart == NULL || size == 0 || buffer == NULL) {
return 0;
}
size_t bytes_read = 0;
UART_MUTEX_LOCK();
if (uart->has_peek) {
uart->has_peek = false;
*buffer++ = uart->peek_byte;
size--;
bytes_read = 1;
}
if (size > 0) {
int len = uart_read_bytes(uart->num, buffer, size, pdMS_TO_TICKS(timeout_ms));
if (len < 0) {
len = 0; // error reading UART
}
bytes_read += len;
}
UART_MUTEX_UNLOCK();
return bytes_read;
}
// DEPRECATED but the original code will be kepts here as future reference when a final solution
// to the UART driver is defined in the use case of reading byte by byte from UART.
uint8_t uartRead(uart_t *uart) {
if (uart == NULL) {
return 0;
}
uint8_t c = 0;
UART_MUTEX_LOCK();
if (uart->has_peek) {
uart->has_peek = false;
c = uart->peek_byte;
} else {
int len = uart_read_bytes(uart->num, &c, 1, 20 / portTICK_PERIOD_MS);
if (len <= 0) { // includes negative return from IDF in case of error
c = 0;
}
}
UART_MUTEX_UNLOCK();
return c;
}
uint8_t uartPeek(uart_t *uart) {
if (uart == NULL) {
return 0;
}
uint8_t c = 0;
UART_MUTEX_LOCK();
if (uart->has_peek) {
c = uart->peek_byte;
} else {
int len = uart_read_bytes(uart->num, &c, 1, 20 / portTICK_PERIOD_MS);
if (len <= 0) { // includes negative return from IDF in case of error
c = 0;
} else {
uart->has_peek = true;
uart->peek_byte = c;
}
}
UART_MUTEX_UNLOCK();
return c;
}
void uartWrite(uart_t *uart, uint8_t c) {
if (uart == NULL) {
return;
}
UART_MUTEX_LOCK();
uart_write_bytes(uart->num, &c, 1);
UART_MUTEX_UNLOCK();
}
void uartWriteBuf(uart_t *uart, const uint8_t *data, size_t len) {
if (uart == NULL || data == NULL || !len) {
return;
}
UART_MUTEX_LOCK();
uart_write_bytes(uart->num, data, len);
UART_MUTEX_UNLOCK();
}
void uartFlush(uart_t *uart) {
uartFlushTxOnly(uart, true);
}
void uartFlushTxOnly(uart_t *uart, bool txOnly) {
if (uart == NULL) {
return;
}
UART_MUTEX_LOCK();
while (!uart_ll_is_tx_idle(UART_LL_GET_HW(uart->num)));
if (!txOnly) {
ESP_ERROR_CHECK(uart_flush_input(uart->num));
}
UART_MUTEX_UNLOCK();
}
void uartSetBaudRate(uart_t *uart, uint32_t baud_rate) {
if (uart == NULL) {
return;
}
UART_MUTEX_LOCK();
#if !SOC_UART_SUPPORT_XTAL_CLK
soc_module_clk_t newClkSrc = baud_rate <= REF_TICK_BAUDRATE_LIMIT ? SOC_MOD_CLK_REF_TICK : SOC_MOD_CLK_APB;
uart_ll_set_sclk(UART_LL_GET_HW(uart->num), newClkSrc);
#endif
if (uart_set_baudrate(uart->num, baud_rate) == ESP_OK) {
uart->_baudrate = baud_rate;
} else {
log_e("Setting UART%d baud rate to %d has failed.", uart->num, baud_rate);
}
UART_MUTEX_UNLOCK();
}
uint32_t uartGetBaudRate(uart_t *uart) {
uint32_t baud_rate = 0;
if (uart == NULL) {
return 0;
}
UART_MUTEX_LOCK();
if (uart_get_baudrate(uart->num, &baud_rate) != ESP_OK) {
log_e("Getting UART%d baud rate has failed.", uart->num);
baud_rate = (uint32_t)-1; // return value when failed
}
UART_MUTEX_UNLOCK();
return baud_rate;
}
static void ARDUINO_ISR_ATTR uart0_write_char(char c) {
while (uart_ll_get_txfifo_len(&UART0) == 0);
uart_ll_write_txfifo(&UART0, (const uint8_t *)&c, 1);
}
#if SOC_UART_HP_NUM > 1
static void ARDUINO_ISR_ATTR uart1_write_char(char c) {
while (uart_ll_get_txfifo_len(&UART1) == 0);
uart_ll_write_txfifo(&UART1, (const uint8_t *)&c, 1);
}
#endif
#if SOC_UART_HP_NUM > 2
static void ARDUINO_ISR_ATTR uart2_write_char(char c) {
while (uart_ll_get_txfifo_len(&UART2) == 0);
uart_ll_write_txfifo(&UART2, (const uint8_t *)&c, 1);
}
#endif
#if SOC_UART_HP_NUM > 3
static void ARDUINO_ISR_ATTR uart3_write_char(char c) {
while (uart_ll_get_txfifo_len(&UART3) == 0);
uart_ll_write_txfifo(&UART3, (const uint8_t *)&c, 1);
}
#endif
#if SOC_UART_HP_NUM > 4
static void ARDUINO_ISR_ATTR uart4_write_char(char c) {
while (uart_ll_get_txfifo_len(&UART4) == 0);
uart_ll_write_txfifo(&UART4, (const uint8_t *)&c, 1);
}
#endif
void uart_install_putc() {
switch (s_uart_debug_nr) {
case 0: ets_install_putc1((void (*)(char)) & uart0_write_char); break;
#if SOC_UART_HP_NUM > 1
case 1: ets_install_putc1((void (*)(char)) & uart1_write_char); break;
#endif
#if SOC_UART_HP_NUM > 2
case 2: ets_install_putc1((void (*)(char)) & uart2_write_char); break;
#endif
#if SOC_UART_HP_NUM > 3
case 3: ets_install_putc1((void (*)(char)) & uart3_write_char); break;
#endif
#if SOC_UART_HP_NUM > 4
case 4: ets_install_putc1((void (*)(char)) & uart4_write_char); break;
#endif
default: ets_install_putc1(NULL); break;
}
ets_install_putc2(NULL);
}
// Routines that take care of UART mode in the HardwareSerial Class code
// used to set UART_MODE_RS485_HALF_DUPLEX auto RTS for TXD for ESP32 chips
bool uartSetMode(uart_t *uart, uart_mode_t mode) {
if (uart == NULL || uart->num >= SOC_UART_HP_NUM) {
return false;
}
UART_MUTEX_LOCK();
bool retCode = (ESP_OK == uart_set_mode(uart->num, mode));
UART_MUTEX_UNLOCK();
return retCode;
}
void uartSetDebug(uart_t *uart) {
if (uart == NULL || uart->num >= SOC_UART_HP_NUM) {
s_uart_debug_nr = -1;
} else {
s_uart_debug_nr = uart->num;
}
uart_install_putc();
}
int uartGetDebug() {
return s_uart_debug_nr;
}
int log_printfv(const char *format, va_list arg) {
static char loc_buf[64];
char *temp = loc_buf;
uint32_t len;
va_list copy;
va_copy(copy, arg);
len = vsnprintf(NULL, 0, format, copy);
va_end(copy);
if (len >= sizeof(loc_buf)) {
temp = (char *)malloc(len + 1);
if (temp == NULL) {
return 0;
}
}
/*
// This causes dead locks with logging in specific cases and also with C++ constructors that may send logs
#if !CONFIG_DISABLE_HAL_LOCKS
if(s_uart_debug_nr != -1 && _uart_bus_array[s_uart_debug_nr].lock){
xSemaphoreTake(_uart_bus_array[s_uart_debug_nr].lock, portMAX_DELAY);
}
#endif
*/
#if (ARDUINO_USB_CDC_ON_BOOT == 1 && ARDUINO_USB_MODE == 0) || CONFIG_IDF_TARGET_ESP32C3 \
|| ((CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32P4) && ARDUINO_USB_CDC_ON_BOOT == 1)
vsnprintf(temp, len + 1, format, arg);
ets_printf("%s", temp);
#else
int wlen = vsnprintf(temp, len + 1, format, arg);
for (int i = 0; i < wlen; i++) {
ets_write_char_uart(temp[i]);
}
#endif
/*
// This causes dead locks with logging and also with constructors that may send logs
#if !CONFIG_DISABLE_HAL_LOCKS
if(s_uart_debug_nr != -1 && _uart_bus_array[s_uart_debug_nr].lock){
xSemaphoreGive(_uart_bus_array[s_uart_debug_nr].lock);
}
#endif
*/
if (len >= sizeof(loc_buf)) {
free(temp);
}
// flushes TX - make sure that the log message is completely sent.
if (s_uart_debug_nr != -1) {
while (!uart_ll_is_tx_idle(UART_LL_GET_HW(s_uart_debug_nr)));
}
return len;
}
int log_printf(const char *format, ...) {
int len;
va_list arg;
va_start(arg, format);
len = log_printfv(format, arg);
va_end(arg);
return len;
}
static void log_print_buf_line(const uint8_t *b, size_t len, size_t total_len) {
for (size_t i = 0; i < len; i++) {
log_printf("%s0x%02x,", i ? " " : "", b[i]);
}
if (total_len > 16) {
for (size_t i = len; i < 16; i++) {
log_printf(" ");
}
log_printf(" // ");
} else {
log_printf(" // ");
}
for (size_t i = 0; i < len; i++) {
log_printf("%c", ((b[i] >= 0x20) && (b[i] < 0x80)) ? b[i] : '.');
}
log_printf("\n");
}
void log_print_buf(const uint8_t *b, size_t len) {
if (!len || !b) {
return;
}
for (size_t i = 0; i < len; i += 16) {
if (len > 16) {
log_printf("/* 0x%04X */ ", i);
}
log_print_buf_line(b + i, ((len - i) < 16) ? (len - i) : 16, len);