ELIOT1 HAL
Загрузка...
Поиск...
Не найдено
hal_uart.h
См. документацию.
1
25#ifndef HAL_UART_H
26#define HAL_UART_H
27
28#include "hal_common.h"
29
33#define HAL_UART_DRIVER_VERSION (MAKE_VERSION(0, 1, 0))
34
38#ifndef UART_RETRY_TIMES
39#define UART_RETRY_TIMES 0U /* 0 - ожидание до получения значения */
40#endif /* UART_RETRY_TIMES */
41
66
82
87 UART_LSR_FlagRxError = (UART_LSR_RFE_Msk),
88 UART_LSR_FlagTxHwEmpty = (UART_LSR_TEMT_Msk),
89 UART_LSR_FlagTxSwEmpty = (UART_LSR_THRE_Msk),
90 UART_LSR_FlagRxLinebreakError = (UART_LSR_BI_Msk),
91 UART_LSR_FlagRxFrameError = (UART_LSR_FE_Msk),
92 UART_LSR_FlagRxParityError = (UART_LSR_PE_Msk),
93 UART_LSR_FlagRxOverflowError = (UART_LSR_OE_Msk),
94 UART_LSR_FlagRxReady = (UART_LSR_DR_Msk),
95};
96
104
112
122
132
142
151
159
164 uint32_t baudrate_bps;
176 /* enum uart_txfifo_watermark tx_watermark; */
177 /* enum uart_rxfifo_watermark rx_watermark; */
178 /* bool rs485_enable; */
179 /* enum uart_rs485_mode rs485_mode; */
180 /* bool rs485_de_active_state; */
181 /* bool rs485_re_active_state; */
186};
187
194 union {
195 uint8_t *rx_data;
196 uint8_t const *tx_data;
197 };
198 size_t data_size;
199};
200
201/* Объявление, описание ниже. */
202struct uart_handle;
203
207typedef void (*uart_transfer_callback_t)(UART_Type *base,
208 struct uart_handle *handle, enum uart_status status, void *user_data);
209
215 volatile const uint8_t *tx_data;
216 volatile size_t tx_data_size;
219 uint8_t *tx_ring_buffer;
221 volatile uint16_t tx_ring_buffer_head;
222 volatile uint16_t tx_ring_buffer_tail;
224 volatile uint8_t *rx_data;
225 volatile size_t rx_data_size;
228 uint8_t *rx_ring_buffer;
230 volatile uint16_t rx_ring_buffer_head;
231 volatile uint16_t rx_ring_buffer_tail;
234 void *user_data;
236 volatile uint8_t tx_state;
237 volatile uint8_t rx_state;
238};
239
240#if defined(__cplusplus)
241extern "C" {
242#endif /* __cplusplus */
243
280enum uart_status UART_Init(UART_Type *base, const struct uart_config *config,
281 uint32_t src_clock_hz);
282
292enum uart_status UART_Deinit(UART_Type *base);
293
319
336enum uart_status UART_SetBaudRate(UART_Type *base, uint32_t baudrate_bps,
337 uint32_t src_clock_hz);
338
366static inline uint32_t UART_GetStatusFlags(UART_Type *base)
367{
368 return (base->LSR & 0xFFUL);
369}
370
394static inline void UART_EnableInterrupts(UART_Type *base, uint32_t mask)
395{
396 /*
397 * Работаем только с прерываниями, зарегистрированными в
398 * @ref uart_interrupt_enable.
399 */
400 base->IER |= mask & UART_AllInterruptsEnable;
401}
402
418static inline void UART_DisableInterrupts(UART_Type *base, uint32_t mask)
419{
421 base->IER &= ~mask;
422}
423
434static inline uint32_t UART_GetEnabledInterrupts(UART_Type *base)
435{
436 return base->IER & UART_AllInterruptsEnable;
437}
438
446static inline void UART_SetRxFifoWatermark(UART_Type *base,
447 enum uart_rxfifo_watermark water)
448{
449 SET_VAL_MSK(base->FCR, UART_FCR_RT_Msk, UART_FCR_RT_Pos, water);
450}
451
459static inline void UART_SetTxFifoWatermark(UART_Type *base,
460 enum uart_txfifo_watermark water)
461{
462 SET_VAL_MSK(base->FCR, UART_FCR_TET_Msk, UART_FCR_TET_Pos, water);
463}
464
481static inline void UART_SetLoopback(UART_Type *base, bool enable)
482{
483 SET_VAL_MSK(base->MCR, UART_MCR_LOOPBACK_Msk, UART_MCR_LOOPBACK_Pos,
484 enable);
485}
486
494static inline void UART_SetIr(UART_Type *base, bool enable)
495{
496 SET_VAL_MSK(base->MCR, UART_MCR_SIRE_Msk, UART_MCR_SIRE_Pos, enable);
497}
498
506static inline void UART_SetRs485(UART_Type *base, bool enable)
507{
508 SET_VAL_MSK(base->TCR, UART_TCR_RS485_EN_Msk, UART_TCR_RS485_EN_Pos,
509 enable);
510}
511
521static inline void UART_Rs485Mode(UART_Type *base, enum uart_rs485_mode mode,
523{
524 SET_VAL_MSK(base->TCR, UART_TCR_XFER_MODE_Msk, UART_TCR_XFER_MODE_Pos,
525 mode);
526 SET_VAL_MSK(base->TCR, UART_TCR_DE_POL_Msk, UART_TCR_DE_POL_Pos, de);
527 SET_VAL_MSK(base->TCR, UART_TCR_RE_POL_Msk, UART_TCR_RE_POL_Pos, re);
528}
529
549static inline void UART_WriteByte(UART_Type *base, uint8_t data)
550{
551 /* Доступен, если LCR[7](DLAB) == 0x0. */
552 base->THR = data;
553}
554
566static inline void UART_WriteByteWait(UART_Type *base, uint8_t data)
567{
568 /* Пока есть данные в буфере передатчика. */
569 while (GET_VAL_MSK(base->LSR, UART_LSR_THRE_Msk, UART_LSR_THRE_Pos) == 0U)
570 ;
571
572 /* Доступен, если LCR[7](DLAB) == 0x0. */
573 base->THR = data;
574}
575
587static inline uint8_t UART_ReadByte(UART_Type *base)
588{
589 /* Доступен, если LCR[7](DLAB) == 0x0. */
590 return (uint8_t) base->RBR;
591}
592
604static inline uint8_t UART_ReadByteWait(UART_Type *base)
605{
606 /* Пока нет данных в приемнике. */
607 while (GET_VAL_MSK(base->LSR, UART_LSR_DR_Msk, UART_LSR_DR_Pos) == 0U);
608
609 /* Доступен, если LCR[7](DLAB) == 0x0. */
610 return (uint8_t) base->RBR;
611}
612
621static inline uint8_t UART_GetRxFifoCount(UART_Type *base)
622{
623 return (uint8_t) GET_VAL_MSK(base->TFL, UART_RFL_RFL_Msk, UART_RFL_RFL_Pos);
624}
625
634static inline uint8_t UART_GetTxFifoCount(UART_Type *base)
635{
636 return (uint8_t) GET_VAL_MSK(base->TFL, UART_TFL_TFL_Msk, UART_TFL_TFL_Pos);
637}
638
653enum uart_status UART_WriteBlocking(UART_Type *base, const uint8_t *data,
654 size_t length);
655
674enum uart_status UART_ReadBlocking(UART_Type *base, uint8_t *data,
675 size_t length);
676
712 struct uart_handle *handle, uint8_t *ring_buffer, size_t ring_buffer_size);
713
726 struct uart_handle *handle);
727
736
772 struct uart_handle *handle, struct uart_transfer *xfer,
773 size_t *received_bytes);
774
791 struct uart_handle *handle);
792
805 struct uart_handle *handle, uint32_t *count);
806
843 struct uart_handle *handle, struct uart_transfer *xfer);
844
859 struct uart_handle *handle);
860
875 struct uart_handle *handle, uint32_t *count);
876
892 struct uart_handle *handle,
893 uint8_t *tx_ring_buffer, size_t ring_buffer_size);
894
903
918enum uart_status UART_WriteTxRing(UART_Type *base, struct uart_handle *handle,
919 const uint8_t *data, size_t *length);
920
931 struct uart_handle *handle);
932
957 struct uart_handle *handle, uart_transfer_callback_t callback,
958 void *user_data);
959
968void UART_TransferHandleIRQ(UART_Type *base, struct uart_handle *handle);
969
974#if defined(__cplusplus)
975}
976#endif /* __cplusplus */
977
982#endif /* HAL_UART_H */
static uint8_t UART_ReadByteWait(UART_Type *base)
Вычитывает байт из регистра приема с ожиданием получения
Definition hal_uart.h:604
static void UART_Rs485Mode(UART_Type *base, enum uart_rs485_mode mode, enum uart_rs485_active_state de, enum uart_rs485_active_state re)
Установка режима работы RS485.
Definition hal_uart.h:521
enum uart_status UART_SetBaudRate(UART_Type *base, uint32_t baudrate_bps, uint32_t src_clock_hz)
Устанавливает скорость модуля UART.
uart_txfifo_watermark
Триггер уровня заполненности TxFIFO.
Definition hal_uart.h:126
uart_rs485_active_state
Активное сотояние линии для RS485.
Definition hal_uart.h:155
enum uart_status UART_TransferStopRingBuffer(UART_Type *base, struct uart_handle *handle)
Прерывает фоновую передачу и удаляет кольцевой буфер
enum uart_status UART_TransferStopTxRingBuffer(UART_Type *base, struct uart_handle *handle)
Отключение кольцевого буфера передатчика
static void UART_WriteByte(UART_Type *base, uint8_t data)
Записывает данные на передачу в регистр передачи
Definition hal_uart.h:549
static uint8_t UART_ReadByte(UART_Type *base)
Вычитывает байт из регистра приема
Definition hal_uart.h:587
uart_rxfifo_watermark
Триггер уровня заполненности RxFIFO.
Definition hal_uart.h:136
enum uart_status UART_ReadBlocking(UART_Type *base, uint8_t *data, size_t length)
Чтение регистра данных RX с использованием метода блокировки
enum uart_status UART_TransferCreateHandle(UART_Type *base, struct uart_handle *handle, uart_transfer_callback_t callback, void *user_data)
Инициализирует дескриптор UART.
static uint32_t UART_GetStatusFlags(UART_Type *base)
Извлекает флаги состояния UART.
Definition hal_uart.h:366
void(* uart_transfer_callback_t)(UART_Type *base, struct uart_handle *handle, enum uart_status status, void *user_data)
Сallback-функция
Definition hal_uart.h:207
static void UART_SetLoopback(UART_Type *base, bool enable)
Включение/выключение режима петли
Definition hal_uart.h:481
enum uart_status UART_Init(UART_Type *base, const struct uart_config *config, uint32_t src_clock_hz)
Инициализирует модуль UART структурой конфигурации пользователя и частотой периферии
enum uart_status UART_WriteBlocking(UART_Type *base, const uint8_t *data, size_t length)
Записывает в регистр TX с использованием метода блокировки
uart_stop_bit_count
Количество стоп-битов для UART.
Definition hal_uart.h:108
enum uart_status UART_TransferAbortReceive(UART_Type *base, struct uart_handle *handle)
Отмена приема данных по прерыванию через линейный буфер в дескрипторе
uart_data_len
Количество бит данных в передаваемом символе
Definition hal_uart.h:116
enum uart_status UART_TransferGetSendCount(UART_Type *base, struct uart_handle *handle, uint32_t *count)
Возвращает количество байтов, отправленных в шину
enum uart_status UART_TransferAbortSend(UART_Type *base, struct uart_handle *handle)
Останавливает передачу данных, управляемую прерыванием
uart_lsr_flags
Флаги состояния UART LSR.
Definition hal_uart.h:86
static void UART_WriteByteWait(UART_Type *base, uint8_t data)
Записывает данные на передачу в регистр передачи c ожиданием освобождения места
Definition hal_uart.h:566
uart_interrupt_enable
Конфигурация прерываний для UART.
Definition hal_uart.h:70
enum uart_status UART_WriteTxRing(UART_Type *base, struct uart_handle *handle, const uint8_t *data, size_t *length)
Передать линейный буфер на передачу через кольцевой буфер
size_t UART_TransferGetTxRingBufferLength(struct uart_handle *handle)
Получить количество байт данных для отправки в кольцевом Tx буфере
size_t UART_TransferGetRxRingBufferLength(struct uart_handle *handle)
Получить длину данных, принятых в кольцевом RX буфере
static uint8_t UART_GetRxFifoCount(UART_Type *base)
Получить количество байтов в RxFIFO.
Definition hal_uart.h:621
enum uart_status UART_TransferSendNonBlocking(UART_Type *base, struct uart_handle *handle, struct uart_transfer *xfer)
Передает буфер данных по прерыванию
static void UART_EnableInterrupts(UART_Type *base, uint32_t mask)
Разрешает прерывания UART в соответствии с предоставленной маской
Definition hal_uart.h:394
static void UART_SetIr(UART_Type *base, bool enable)
Включение/выключение инфракрасного режима работы
Definition hal_uart.h:494
static void UART_SetTxFifoWatermark(UART_Type *base, enum uart_txfifo_watermark water)
Устанавливает триггер уровня заполненности TxFIFO.
Definition hal_uart.h:459
enum uart_status UART_GetDefaultConfig(struct uart_config *config)
Получает структуру конфигурации по умолчанию
enum uart_status UART_Deinit(UART_Type *base)
Деинициализирует модуль UART.
enum uart_status UART_TransferReceiveNonBlocking(UART_Type *base, struct uart_handle *handle, struct uart_transfer *xfer, size_t *received_bytes)
Прием данных в асинхронном режиме (без ожидания) по прерыванию
enum uart_status UART_TransferStartTxRingBuffer(UART_Type *base, struct uart_handle *handle, uint8_t *tx_ring_buffer, size_t ring_buffer_size)
Инициализация колцевого буфера на передачу
enum uart_status UART_TransferGetReceiveCount(UART_Type *base, struct uart_handle *handle, uint32_t *count)
Возвращает количество принятых байтов
static void UART_DisableInterrupts(UART_Type *base, uint32_t mask)
Отключает прерывания UART в соответствии с предоставленной маской
Definition hal_uart.h:418
static void UART_SetRxFifoWatermark(UART_Type *base, enum uart_rxfifo_watermark water)
Устанавливает триггер уровня заполненности RxFIFO.
Definition hal_uart.h:446
static void UART_SetRs485(UART_Type *base, bool enable)
Включение/выключение RS485 режима работы
Definition hal_uart.h:506
static uint8_t UART_GetTxFifoCount(UART_Type *base)
Получить количество байтов в TxFIFO.
Definition hal_uart.h:634
uart_status
Статусы драйвера UART.
Definition hal_uart.h:45
enum uart_status UART_TransferStartRingBuffer(UART_Type *base, struct uart_handle *handle, uint8_t *ring_buffer, size_t ring_buffer_size)
Инициализация колцевого буфера на прием
void UART_TransferHandleIRQ(UART_Type *base, struct uart_handle *handle)
Функция-обработчик UART IRQ.
static uint32_t UART_GetEnabledInterrupts(UART_Type *base)
Запрос маски включенных прерываний в UART.
Definition hal_uart.h:434
uart_rs485_mode
Режим работы RS485.
Definition hal_uart.h:146
uart_parity_mode
Режимы четности UART.
Definition hal_uart.h:100
@ UART_TxFifoQuarterFull
Definition hal_uart.h:129
@ UART_TxFifoEmpty
Definition hal_uart.h:127
@ UART_TxFifoTwoChars
Definition hal_uart.h:128
@ UART_TxFifoHalfFull
Definition hal_uart.h:130
@ UART_RS485_ActiveStateHigh
Definition hal_uart.h:156
@ UART_RS485_ActiveStateLow
Definition hal_uart.h:157
@ UART_RxFifoTwoToFull
Definition hal_uart.h:140
@ UART_RxFifoHalfFull
Definition hal_uart.h:139
@ UART_RxFifoQuarterFull
Definition hal_uart.h:138
@ UART_RxFifoOneChar
Definition hal_uart.h:137
@ UART_TwoOrOneAndHalfStopBit
Definition hal_uart.h:110
@ UART_OneStopBit
Definition hal_uart.h:109
@ UART_6BitsPerChar
Definition hal_uart.h:118
@ UART_7BitsPerChar
Definition hal_uart.h:119
@ UART_5BitsPerChar
Definition hal_uart.h:117
@ UART_8BitsPerChar
Definition hal_uart.h:120
@ UART_LSR_FlagTxHwEmpty
Definition hal_uart.h:88
@ UART_LSR_FlagRxReady
Definition hal_uart.h:94
@ UART_LSR_FlagRxFrameError
Definition hal_uart.h:91
@ UART_LSR_FlagTxSwEmpty
Definition hal_uart.h:89
@ UART_LSR_FlagRxError
Definition hal_uart.h:87
@ UART_LSR_FlagRxOverflowError
Definition hal_uart.h:93
@ UART_LSR_FlagRxParityError
Definition hal_uart.h:92
@ UART_LSR_FlagRxLinebreakError
Definition hal_uart.h:90
@ UART_ThresoldInterruptEnable
Definition hal_uart.h:71
@ UART_TxInterruptEnable
Definition hal_uart.h:74
@ UART_RxLineInterruptEnable
Definition hal_uart.h:73
@ UART_ModemInterruptEnable
Definition hal_uart.h:72
@ UART_AllInterruptsEnable
Definition hal_uart.h:76
@ UART_RxInterruptEnable
Definition hal_uart.h:75
@ UART_Status_RxBusy
Definition hal_uart.h:53
@ UART_Status_Ok
Definition hal_uart.h:46
@ UART_Status_RxIdle
Definition hal_uart.h:55
@ UART_Status_RxError
Definition hal_uart.h:57
@ UART_Status_FramingError
Definition hal_uart.h:61
@ UART_Status_TxRingBufferNull
Definition hal_uart.h:64
@ UART_Status_TxError
Definition hal_uart.h:56
@ UART_Status_Fail
Definition hal_uart.h:47
@ UART_Status_NoTransferInProgress
Definition hal_uart.h:51
@ UART_Status_ReadOnly
Definition hal_uart.h:48
@ UART_Status_BaudrateNotSupport
Definition hal_uart.h:63
@ UART_Status_TxIdle
Definition hal_uart.h:54
@ UART_Status_BreakLineError
Definition hal_uart.h:60
@ UART_Status_Timeout
Definition hal_uart.h:50
@ UART_Status_TxBusy
Definition hal_uart.h:52
@ UART_Status_InvalidArgument
Definition hal_uart.h:49
@ UART_Status_ParityError
Definition hal_uart.h:62
@ UART_Status_RxRingBufferOverrun
Definition hal_uart.h:58
@ UART_Status_RxFifoBufferOverrun
Definition hal_uart.h:59
@ UART_RS485_ModeFullDuplex
Definition hal_uart.h:147
@ UART_RS485_ModeHalfDuplexAuto
Definition hal_uart.h:149
@ UART_RS485_ModeHalfDuplexManual
Definition hal_uart.h:148
@ UART_ParityOdd
Definition hal_uart.h:101
@ UART_ParityEven
Definition hal_uart.h:102
Конфигурация UART.
Definition hal_uart.h:163
bool enable_hardware_flow_control
Definition hal_uart.h:174
enum uart_parity_mode parity_mode
Definition hal_uart.h:166
bool enable_infrared
Definition hal_uart.h:173
bool enable_rxfifo
Definition hal_uart.h:170
uint32_t baudrate_bps
Definition hal_uart.h:164
enum uart_data_len bit_count_per_char
Definition hal_uart.h:169
bool enable_parity
Definition hal_uart.h:165
bool parity_manual
Definition hal_uart.h:167
bool break_line
Definition hal_uart.h:175
bool enable_loopback
Definition hal_uart.h:172
bool enable_txfifo
Definition hal_uart.h:171
enum uart_stop_bit_count stop_bit_count
Definition hal_uart.h:168
Дескриптор состояния приема/передачи для неблокирующих функций обмена
Definition hal_uart.h:214
volatile uint16_t rx_ring_buffer_tail
Definition hal_uart.h:231
volatile uint16_t tx_ring_buffer_tail
Definition hal_uart.h:222
size_t rx_data_size_all
Definition hal_uart.h:226
uart_transfer_callback_t callback
Definition hal_uart.h:233
void * user_data
Definition hal_uart.h:234
volatile const uint8_t * tx_data
Definition hal_uart.h:215
size_t tx_ring_buffer_size
Definition hal_uart.h:220
volatile uint8_t rx_state
Definition hal_uart.h:237
volatile uint8_t * rx_data
Definition hal_uart.h:224
volatile uint16_t tx_ring_buffer_head
Definition hal_uart.h:221
size_t rx_ring_buffer_size
Definition hal_uart.h:229
volatile size_t tx_data_size
Definition hal_uart.h:216
volatile uint8_t tx_state
Definition hal_uart.h:236
volatile uint16_t rx_ring_buffer_head
Definition hal_uart.h:230
uint8_t * tx_ring_buffer
Definition hal_uart.h:219
size_t tx_data_size_all
Definition hal_uart.h:217
volatile size_t rx_data_size
Definition hal_uart.h:225
uint8_t * rx_ring_buffer
Definition hal_uart.h:228
Указатель на буфер приема или передачи
Definition hal_uart.h:193
uint8_t * rx_data
Definition hal_uart.h:195
size_t data_size
Definition hal_uart.h:198
uint8_t const * tx_data
Definition hal_uart.h:196