chore: New module/serial API (#3055)

* WiP: new module interface

* WiP: softserial timer DMA

* WiP: setup() and send() in one step

and remove methods specific to internal or external module

* fixes and extra port config

* horus targets

* module ports have moved

* T8 support (only internal module)

* fix nv14

* stupid GCC....

* disable BT

* remove nv14 telem driver

* remove old aux serial driver

* Move module buffers out of pulses.h

* Soft serial fixes and PXX1 support

* Fixed PPM module output

* Fixed CLI

* compilation fixes

* Ported bluetooth and flysky gimbal to new serial driver

* Re-enable soft-serial RX

* fixes and cleanup

* nv14 fixes

* Fix flysky gimbals

* Ghost module

* 16 bytes of RAM

* Remove getByte from module API

* Ghost cleanup

* fix: _half_duplex_input() must be called after usart init

* WiP

* more cleanup

* Remove board specific settings from PXX1 / PXX2 drivers

* A bit of PXX2 header cleanup

* Add support for OVER8 and ONEBIT

* Add some support for inverters (NV14 / EL18)

* Support NV14 power fixes in generic board

* Fix polarity handling

* Fix RX DMA

* Fix mixer not running

* Add soft-serial polarity control

* Quick fix for telemetry polling while module port is changed

* Fix bootloader DEBUG

* Fix MPM telemetry

* Fix pulse start

* DSM2 soft-serial fallback

* DSMP async module restart

* Fix CRSF LUA upstream

* Remove global variable telemetryProtocol

* Use HAL/LL constants

* Fix various issue with AFHDS3 and NV14/EL18 internal module

* Fixed S.PORT unit tests

* fix: update widx after writing at current index

* fix: init error condition

* Fix: possible infinite loop in _find_port()

* Add support for bidir S.PORT init

* Add support for "getLastByte" in HW serial driver

* PXX1: Add support for S.PORT based on IDLE callback

* Fix rebase error

* Fix softserial _rx_fifo_push()

* Add softserial support for waitForTxCompleted()

* Fix MPM flashing (internal / external)

* Fixed external MPM

* Activate RX DMA on internal module

Seems to work with serial passthrough without issues, at least on the L3R PRO.

* Fix softserial DMA on stdlcd F4 targets

* Add softserial support for 32bit timers (mostly TIM2)

* More precise soft-serial

* Fix MPM update using inverters & HW uart

* Raise S.PORT DMA/USART IRQ prio to achieve faster switching to input

* Remove useless delays

* Fix flashing external ELRS module

* Added a retry mechanism for FrSky S.PORT update

* Remove useless enableRx()

* External FrSky modules are all flashed via S.PORT

* Remove power management unit update

This was only used on the first batch of X-lite.
This commit is contained in:
Raphael Coeffic
2023-02-09 19:44:32 +10:00
committed by GitHub
parent d80adc6c4d
commit 72193eda82
189 changed files with 7960 additions and 8364 deletions
+2 -1
View File
@@ -204,6 +204,7 @@ if(PXX2)
set(PULSES_SRC
${PULSES_SRC}
pxx2.cpp
pxx2_ota.cpp
)
endif()
@@ -302,7 +303,7 @@ set(FIRMWARE_TARGET_SRC
${FIRMWARE_TARGET_SRC}
keys_driver.cpp
diskio.cpp
telemetry_driver.cpp
# telemetry_driver.cpp
)
set(PULSES_SRC
@@ -38,6 +38,9 @@ set(FIRMWARE_TARGET_SRC ${FIRMWARE_TARGET_SRC}
../common/arm/stm32/usbd_hid_joystick.c
../common/arm/stm32/stm32_hal.cpp
../common/arm/stm32/stm32_i2c_driver.cpp
../common/arm/stm32/stm32_serial_driver.cpp
../common/arm/stm32/stm32_softserial_driver.cpp
../common/arm/stm32/module_timer_driver.cpp
)
if(IMU)
@@ -49,9 +52,9 @@ if(IMU)
endif()
if(AUX_SERIAL OR AUX2_SERIAL)
set(FIRMWARE_TARGET_SRC ${FIRMWARE_TARGET_SRC}
../common/arm/stm32/aux_serial_driver.cpp
)
# set(FIRMWARE_TARGET_SRC ${FIRMWARE_TARGET_SRC}
# ../common/arm/stm32/aux_serial_driver.cpp
# )
if(AUX_SERIAL)
add_definitions(-DAUX_SERIAL)
endif()
@@ -1,292 +0,0 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "stm32_hal_ll.h"
#include "stm32_usart_driver.h"
#include "aux_serial_driver.h"
#include "board.h"
#include "fifo.h"
#include "dmafifo.h"
#include "debug.h"
#define AUX_SERIAL_TX_BUFFER 512
#if defined(SDRAM)
#define AUX_SERIAL_RX_BUFFER 512
#else
#define AUX_SERIAL_RX_BUFFER 32
#endif
typedef Fifo<uint8_t, AUX_SERIAL_TX_BUFFER> TxFifo;
typedef DMAFifo<AUX_SERIAL_RX_BUFFER> RxFifo;
struct SerialState
{
TxFifo* txFifo;
RxFifo* rxFifo;
const stm32_usart_t* usart;
};
static void* aux_serial_init(const SerialState* st, const etx_serial_init* params)
{
stm32_usart_init(st->usart, params);
if (params->rx_enable && st->usart->rxDMA) {
stm32_usart_init_rx_dma(st->usart, st->rxFifo->buffer(), st->rxFifo->size());
st->rxFifo->clear();
}
return (void*)st;
}
static void aux_serial_putc(void* ctx, uint8_t c)
{
// When sending single bytes,
// send is based on IRQ, so that this
// only enables the corresponding IRQ
auto st = (const SerialState*)ctx;
if (st->txFifo->isFull()) return;
st->txFifo->push(c);
stm32_usart_enable_tx_irq(st->usart);
}
static void aux_serial_send_buffer(void* ctx, const uint8_t* data, uint8_t size)
{
auto st = (const SerialState*)ctx;
if (st->usart->txDMA) {
stm32_usart_send_buffer(st->usart, data, size);
return;
}
while(size > 0) {
aux_serial_putc(ctx, *data++);
size--;
}
}
static void aux_wait_tx_completed(void* ctx)
{
// TODO
(void)ctx;
}
static int aux_get_byte(void* ctx, uint8_t* data)
{
auto st = (const SerialState*)ctx;
if (!st->rxFifo) return -1;
return st->rxFifo->pop(*data);
}
void aux_serial_deinit(void* ctx)
{
auto st = (const SerialState*)ctx;
stm32_usart_deinit(st->usart);
}
#if defined(AUX_SERIAL)
static TxFifo auxSerialTxFifo;
static RxFifo auxSerialRxFifo __DMA (AUX_SERIAL_DMA_Stream_RX);
static const LL_GPIO_InitTypeDef auxUSARTPinInit = {
.Pin = AUX_SERIAL_GPIO_PIN_TX | AUX_SERIAL_GPIO_PIN_RX,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_LOW,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
.Pull = LL_GPIO_PULL_UP,
.Alternate = AUX_SERIAL_GPIO_AF_LL,
};
#if !defined(AUX_SERIAL_DMA_TX)
#define AUX_SERIAL_DMA_TX nullptr
#define AUX_SERIAL_DMA_Stream_TX nullptr
#define AUX_SERIAL_DMA_Stream_TX_LL 0
#define AUX_SERIAL_DMA_Channel_TX 0
#endif
static const stm32_usart_t auxUSART = {
.USARTx = AUX_SERIAL_USART,
.GPIOx = AUX_SERIAL_GPIO,
.pinInit = &auxUSARTPinInit,
.IRQn = AUX_SERIAL_USART_IRQn,
.IRQ_Prio = 7, // TODO: define constant
.txDMA = AUX_SERIAL_DMA_TX,
.txDMA_Stream = AUX_SERIAL_DMA_Stream_TX_LL,
.txDMA_Channel = AUX_SERIAL_DMA_Channel_TX,
.rxDMA = AUX_SERIAL_DMA_RX,
.rxDMA_Stream = AUX_SERIAL_DMA_Stream_RX_LL,
.rxDMA_Channel = AUX_SERIAL_DMA_Channel_RX,
};
static const SerialState auxSerialState = {
.txFifo = &auxSerialTxFifo,
.rxFifo = &auxSerialRxFifo,
.usart = &auxUSART,
};
// TODO: grab context to get buffer
static uint8_t auxSerialOnSend(uint8_t* data)
{
return auxSerialTxFifo.pop(*data);
}
// TODO: add to state
static etx_serial_callbacks_t auxSerialCb = {
.on_send = auxSerialOnSend,
.on_receive = nullptr,
.on_error = nullptr,
};
static void* auxSerialInit(const etx_serial_init* params)
{
return aux_serial_init(&auxSerialState, params);
}
static void (*aux1RxCb)(uint8_t*, uint32_t);
static void aux1_on_rx_byte(uint8_t data)
{
if (aux1RxCb) aux1RxCb(&data, 1);
}
static void aux1SetRxCb(void*, void (*cb)(uint8_t*, uint32_t))
{
aux1RxCb = cb;
if (aux1RxCb) {
auxSerialCb.on_receive = aux1_on_rx_byte;
stm32_usart_deinit_rx_dma(&auxUSART);
} else {
auxSerialCb.on_receive = nullptr;
}
}
const etx_serial_driver_t AuxSerialDriver = {
.init = auxSerialInit,
.deinit = aux_serial_deinit,
.sendByte = aux_serial_putc,
.sendBuffer = aux_serial_send_buffer,
.waitForTxCompleted = aux_wait_tx_completed,
.getByte = aux_get_byte,
.getBaudrate = nullptr,
.setReceiveCb = aux1SetRxCb,
.setBaudrateCb = nullptr,
};
extern "C" void AUX_SERIAL_USART_IRQHandler(void)
{
DEBUG_INTERRUPT(INT_SER2);
stm32_usart_isr(&auxUSART, &auxSerialCb);
}
#endif // AUX_SERIAL
#if defined(AUX2_SERIAL)
static TxFifo aux2SerialTxFifo;
static RxFifo aux2SerialRxFifo __DMA (AUX2_SERIAL_DMA_Stream_RX);
static const LL_GPIO_InitTypeDef aux2USARTPinInit = {
.Pin = AUX2_SERIAL_GPIO_PIN_TX | AUX2_SERIAL_GPIO_PIN_RX,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_LOW,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
.Pull = LL_GPIO_PULL_UP,
.Alternate = AUX2_SERIAL_GPIO_AF_LL,
};
static const stm32_usart_t aux2USART = {
.USARTx = AUX2_SERIAL_USART,
.GPIOx = AUX2_SERIAL_GPIO,
.pinInit = &aux2USARTPinInit,
.IRQn = AUX2_SERIAL_USART_IRQn,
.IRQ_Prio = 7, // TODO: define constant
.txDMA = nullptr,
.txDMA_Stream = 0,
.txDMA_Channel = 0,
.rxDMA = AUX2_SERIAL_DMA_RX,
.rxDMA_Stream = AUX2_SERIAL_DMA_Stream_RX_LL,
.rxDMA_Channel = AUX2_SERIAL_DMA_Channel_RX,
};
static const SerialState aux2SerialState = {
.txFifo = &aux2SerialTxFifo,
.rxFifo = &aux2SerialRxFifo,
.usart = &aux2USART,
};
static uint8_t aux2SerialOnSend(uint8_t* data)
{
return aux2SerialTxFifo.pop(*data);
}
static etx_serial_callbacks_t aux2SerialCb = {
.on_send = aux2SerialOnSend,
.on_receive = nullptr,
.on_error = nullptr,
};
static void* aux2SerialInit(const etx_serial_init* params)
{
return aux_serial_init(&aux2SerialState, params);
}
static void (*aux2RxCb)(uint8_t*, uint32_t);
static void aux2_on_rx_byte(uint8_t data)
{
if (aux2RxCb) aux2RxCb(&data, 1);
}
static void aux2SetRxCb(void*, void (*cb)(uint8_t*, uint32_t))
{
aux2RxCb = cb;
if (aux2RxCb) {
aux2SerialCb.on_receive = aux2_on_rx_byte;
stm32_usart_deinit_rx_dma(&aux2USART);
} else {
aux2SerialCb.on_receive = nullptr;
}
}
extern "C" void AUX2_SERIAL_USART_IRQHandler(void)
{
DEBUG_INTERRUPT(INT_SER2);
stm32_usart_isr(&aux2USART, &aux2SerialCb);
}
const etx_serial_driver_t Aux2SerialDriver = {
.init = aux2SerialInit,
.deinit = aux_serial_deinit,
.sendByte = aux_serial_putc,
.sendBuffer = aux_serial_send_buffer,
.waitForTxCompleted = aux_wait_tx_completed,
.getByte = aux_get_byte,
.getBaudrate = nullptr,
.setReceiveCb = aux2SetRxCb,
.setBaudrateCb = nullptr,
};
#endif // AUX2_SERIAL
@@ -1,33 +0,0 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <stdint.h>
#include "hal/serial_driver.h"
#if defined(AUX_SERIAL)
extern const etx_serial_driver_t AuxSerialDriver;
#endif
#if defined(AUX2_SERIAL)
extern const etx_serial_driver_t Aux2SerialDriver;
#endif
@@ -19,107 +19,100 @@
* GNU General Public License for more details.
*/
#include "bluetooth_driver.h"
#include "stm32_hal_ll.h"
#include "board.h"
#include "debug.h"
#if !defined(BOOT)
#include "fifo.h"
#include "stm32_serial_driver.h"
Fifo<uint8_t, BT_TX_FIFO_SIZE> btTxFifo;
Fifo<uint8_t, BT_RX_FIFO_SIZE> btRxFifo;
#define BT_USART_IRQ_PRIORITY 6
static const stm32_usart_t btUSART = {
.USARTx = BT_USART,
.GPIOx = BT_USART_GPIO,
.GPIO_Pin = BT_TX_GPIO_PIN | BT_RX_GPIO_PIN,
.IRQn = BT_USART_IRQn,
.IRQ_Prio = BT_USART_IRQ_PRIORITY,
.txDMA = nullptr,
.txDMA_Stream = 0,
.txDMA_Channel = 0,
.rxDMA = nullptr,
.rxDMA_Stream = 0,
.rxDMA_Channel = 0,
};
DEFINE_STM32_SERIAL_PORT(BTModule, btUSART, BT_RX_FIFO_SIZE, BT_TX_FIFO_SIZE);
#if defined(BLUETOOTH_PROBE)
volatile uint8_t btChipPresent = 0;
#endif
enum BluetoothWriteState
{
BLUETOOTH_WRITE_IDLE,
#if defined(BT_BRTS_GPIO_PIN)
BLUETOOTH_WRITE_INIT,
#endif
BLUETOOTH_WRITING,
#if defined(BT_BRTS_GPIO_PIN)
BLUETOOTH_WRITE_DONE
#else
BLUETOOTH_WRITE_DONE = BLUETOOTH_WRITE_IDLE
#endif
};
volatile uint8_t bluetoothWriteState = BLUETOOTH_WRITE_IDLE;
// const etx_serial_driver_t* _bt_usart_drv = nullptr;
void* _bt_usart_ctx = nullptr;
#endif
void bluetoothInit(uint32_t baudrate, bool enable)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = BT_EN_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(BT_EN_GPIO, &GPIO_InitStructure);
LL_GPIO_InitTypeDef pinInit;
LL_GPIO_StructInit(&pinInit);
#if defined(BT_BRTS_GPIO_PIN)
GPIO_InitStructure.GPIO_Pin = BT_BRTS_GPIO_PIN;
GPIO_Init(BT_BRTS_GPIO, &GPIO_InitStructure);
GPIO_SetBits(BT_BRTS_GPIO, BT_BRTS_GPIO_PIN);
#endif
pinInit.Pin = BT_EN_GPIO_PIN;
pinInit.Mode = LL_GPIO_MODE_OUTPUT;
pinInit.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
pinInit.Pull = LL_GPIO_PULL_NO;
#if defined(BT_BCTS_GPIO_PIN)
GPIO_InitStructure.GPIO_Pin = BT_BCTS_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_Init(BT_BCTS_GPIO, &GPIO_InitStructure);
#endif
LL_GPIO_Init(BT_EN_GPIO, &pinInit);
#if !defined(BOOT)
GPIO_PinAFConfig(BT_USART_GPIO, BT_TX_GPIO_PinSource, BT_GPIO_AF);
GPIO_PinAFConfig(BT_USART_GPIO, BT_RX_GPIO_PinSource, BT_GPIO_AF);
etx_serial_init cfg = {
.baudrate = baudrate,
.encoding = ETX_Encoding_8N1,
.direction = ETX_Dir_TX_RX,
.polarity = ETX_Pol_Normal,
};
GPIO_InitStructure.GPIO_Pin = BT_TX_GPIO_PIN | BT_RX_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(BT_USART_GPIO, &GPIO_InitStructure);
USART_DeInit(BT_USART);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = baudrate;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(BT_USART, &USART_InitStructure);
USART_Cmd(BT_USART, ENABLE);
USART_ITConfig(BT_USART, USART_IT_RXNE, ENABLE);
NVIC_SetPriority(BT_USART_IRQn, 6);
NVIC_EnableIRQ(BT_USART_IRQn);
bluetoothWriteState = BLUETOOTH_WRITE_IDLE;
btRxFifo.clear();
btTxFifo.clear();
if (!_bt_usart_ctx) {
auto hw_def = REF_STM32_SERIAL_PORT(BTModule);
_bt_usart_ctx = STM32SerialDriver.init(hw_def, &cfg);
} else {
STM32SerialDriver.setBaudrate(_bt_usart_ctx, baudrate);
}
#endif
if (enable)
GPIO_ResetBits(BT_EN_GPIO, BT_EN_GPIO_PIN);
else
GPIO_SetBits(BT_EN_GPIO, BT_EN_GPIO_PIN);
if (enable) {
LL_GPIO_ResetOutputPin(BT_EN_GPIO, BT_EN_GPIO_PIN);
} else {
LL_GPIO_SetOutputPin(BT_EN_GPIO, BT_EN_GPIO_PIN);
}
}
#if !defined(BOOT)
void bluetoothDisable()
{
GPIO_SetBits(BT_EN_GPIO, BT_EN_GPIO_PIN); // close bluetooth (recent modules will go to bootloader mode)
USART_ITConfig(BT_USART, USART_IT_RXNE, DISABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = BT_RX_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_Init(BT_USART_GPIO, &GPIO_InitStructure);
USART_DeInit(BT_USART);
// close bluetooth (recent modules will go to bootloader mode)
LL_GPIO_SetOutputPin(BT_EN_GPIO, BT_EN_GPIO_PIN);
if (_bt_usart_ctx) {
STM32SerialDriver.deinit(_bt_usart_ctx);
}
}
// @Cliff
// ISR is handled by the serial driver,
// however, it is unclear at this point
// how the detection should be implemented.
// Maybe setting a temporary callback on
// the interface, or trying to pull some data.
//
// Also, it is quite unclear why we would need
// to disable sending when the TX buffer is exahausted.
// The serial driver does take care of that but does not
// set any particular piece of state that could be queried
// to deduct the state of this TX buffer.
#if _OBSOLETE_
extern "C" void BT_USART_IRQHandler(void)
{
DEBUG_INTERRUPT(INT_BLUETOOTH);
@@ -144,38 +137,30 @@ extern "C" void BT_USART_IRQHandler(void)
}
else {
USART_ITConfig(BT_USART, USART_IT_TXE, DISABLE);
// => BLUETOOTH_WRITE_IDLE
bluetoothWriteState = BLUETOOTH_WRITE_DONE;
}
}
}
#endif
void bluetoothWriteWakeup()
void bluetoothWrite(const void* buffer, uint32_t len)
{
if (bluetoothWriteState == BLUETOOTH_WRITE_IDLE) {
if (!btTxFifo.isEmpty()) {
#if defined(BT_BRTS_GPIO_PIN)
bluetoothWriteState = BLUETOOTH_WRITE_INIT;
GPIO_ResetBits(BT_BRTS_GPIO, BT_BRTS_GPIO_PIN);
#else
bluetoothWriteState = BLUETOOTH_WRITING;
USART_ITConfig(BT_USART, USART_IT_TXE, ENABLE);
#endif
}
}
#if defined(BT_BRTS_GPIO_PIN)
else if (bluetoothWriteState == BLUETOOTH_WRITE_INIT) {
bluetoothWriteState = BLUETOOTH_WRITING;
USART_ITConfig(BT_USART, USART_IT_TXE, ENABLE);
}
else if (bluetoothWriteState == BLUETOOTH_WRITE_DONE) {
bluetoothWriteState = BLUETOOTH_WRITE_IDLE;
GPIO_SetBits(BT_BRTS_GPIO, BT_BRTS_GPIO_PIN);
}
#endif
if (!_bt_usart_ctx) return;
STM32SerialDriver.sendBuffer(_bt_usart_ctx, (const uint8_t*)buffer, len);
}
int bluetoothRead(uint8_t* data)
{
if (!_bt_usart_ctx) return 0;
return STM32SerialDriver.getByte(_bt_usart_ctx, data);
}
uint8_t bluetoothIsWriting(void)
{
return bluetoothWriteState != BLUETOOTH_WRITE_IDLE;
if (!_bt_usart_ctx)
return false;
return STM32SerialDriver.txCompleted(_bt_usart_ctx);
}
#endif // !BOOT
@@ -0,0 +1,52 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#pragma once
#include "hal/serial_driver.h"
// BT driver
#define BLUETOOTH_BOOTLOADER_BAUDRATE 230400
#define BLUETOOTH_DEFAULT_BAUDRATE 115200
#if defined(PCBX9E)
#define BLUETOOTH_FACTORY_BAUDRATE 9600
#else
#define BLUETOOTH_FACTORY_BAUDRATE 57600
#endif
#define BT_TX_FIFO_SIZE 64
#define BT_RX_FIFO_SIZE 256
void bluetoothInit(uint32_t baudrate, bool enable);
void bluetoothWrite(const void* buffer, uint32_t length);
int bluetoothRead(uint8_t* data);
uint8_t bluetoothIsWriting();
void bluetoothDisable();
#if defined(PCBX9LITES) || defined(PCBX7ACCESS)
#define IS_BLUETOOTH_CHIP_PRESENT() (true)
#elif defined(PCBX9LITE)
#define IS_BLUETOOTH_CHIP_PRESENT() (false)
#elif defined(BLUETOOTH_PROBE) && !defined(SIMU)
extern volatile uint8_t btChipPresent;
#define IS_BLUETOOTH_CHIP_PRESENT() (btChipPresent)
#else
#define IS_BLUETOOTH_CHIP_PRESENT() (true)
#endif
@@ -47,7 +47,6 @@
#include "stm32f4xx_spi.h"
#include "stm32f4xx_pwr.h"
#include "stm32f4xx_dma.h"
#include "stm32f4xx_usart.h"
#include "stm32f4xx_flash.h"
#include "stm32f4xx_dbgmcu.h"
#include "misc.h"
@@ -62,7 +61,6 @@
#include "stm32f2xx_spi.h"
#include "stm32f2xx_pwr.h"
#include "stm32f2xx_dma.h"
#include "stm32f2xx_usart.h"
#include "stm32f2xx_flash.h"
#include "stm32f2xx_dbgmcu.h"
#include "misc.h"
@@ -35,6 +35,8 @@ set(BOOTLOADER_SRC
../usb_driver.cpp
../flash_driver.cpp
../stm32_exti_driver.cpp
../stm32_serial_driver.cpp
../stm32_usart_driver.cpp
init.c
boot.cpp
bin_files.cpp
@@ -89,18 +91,12 @@ if(PCB STREQUAL X10 OR PCB STREQUAL X12S OR PCB STREQUAL NV14)
)
endif()
if(PCB STREQUAL NV14)
set(BOOTLOADER_SRC
${BOOTLOADER_SRC}
../../../../../targets/${TARGET_DIR}/extmodule_helper.cpp
)
endif()
if(DEBUG)
set(BOOTLOADER_SRC
${BOOTLOADER_SRC}
../../../../../serial.cpp
../../../../../targets/common/arm/stm32/aux_serial_driver.cpp
../../../../../boards/generic_stm32/aux_ports.cpp
../../../../../targets/common/arm/stm32/stm32_serial_driver.cpp
../../../../../targets/common/arm/stm32/stm32_usart_driver.cpp
)
endif()
@@ -19,6 +19,11 @@
* GNU General Public License for more details.
*/
#if defined(BLUETOOTH)
#include "bluetooth_driver.h"
#include "stm32_serial_driver.h"
#endif
#include "board.h"
#include "boot.h"
#include "bin_files.h"
@@ -240,14 +245,15 @@ void bootloaderInitApp()
keysInit();
#if defined(SWSERIALPOWER)
#if defined(AUX_SERIAL)
void set_aux_pwr(uint8_t on);
set_aux_pwr(0);
#endif
#if defined(AUX2_SERIAL)
void set_aux2_pwr(uint8_t on);
set_aux2_pwr(0);
#endif
// TODO: replace with proper serial port query...
// #if defined(AUX_SERIAL)
// void set_aux_pwr(uint8_t on);
// set_aux_pwr(0);
// #endif
// #if defined(AUX2_SERIAL)
// void set_aux2_pwr(uint8_t on);
// set_aux2_pwr(0);
// #endif
#endif
// wait a bit for the inputs to stabilize...
@@ -20,24 +20,26 @@
*/
#include "extmodule_driver.h"
#include "stm32_pulse_driver.h"
#include "hal.h"
#include "board.h"
#include "timers_driver.h"
static const stm32_pulse_timer_t extmoduleTimer = {
static stm32_pulse_dma_tc_cb_t _ext_timer_DMA_TC_Callback;
const stm32_pulse_timer_t extmoduleTimer = {
.GPIOx = EXTMODULE_TX_GPIO,
.GPIO_Pin = EXTMODULE_TX_GPIO_PIN,
.GPIO_Alternate = EXTMODULE_TIMER_TX_GPIO_AF,
.TIMx = EXTMODULE_TIMER,
.TIM_Prescaler = __LL_TIM_CALC_PSC(EXTMODULE_TIMER_FREQ, 2000000),
.TIM_Freq = EXTMODULE_TIMER_FREQ,
.TIM_Channel = EXTMODULE_TIMER_Channel,
.TIM_IRQn = EXTMODULE_TIMER_IRQn,
.DMAx = EXTMODULE_TIMER_DMA,
.DMA_Stream = EXTMODULE_TIMER_DMA_STREAM_LL,
.DMA_Channel = EXTMODULE_TIMER_DMA_CHANNEL,
.DMA_IRQn = EXTMODULE_TIMER_DMA_STREAM_IRQn,
.DMA_TC_CallbackPtr = &_ext_timer_DMA_TC_Callback,
};
// Make sure the timer channel is supported
@@ -65,126 +67,3 @@ extern "C" void EXTMODULE_TIMER_IRQHandler()
{
stm32_pulse_tim_update_isr(&extmoduleTimer);
}
void extmoduleStop()
{
EXTERNAL_MODULE_OFF();
stm32_pulse_deinit(&extmoduleTimer);
}
static void config_ppm_output(uint16_t ppm_delay, bool polarity)
{
// PPM generation principle:
//
// Hardware timer in PWM mode is used for PPM generation
// Output is OFF if CNT<CCR1(delay) and ON if bigger
// CCR1 register defines duration of pulse length and is constant
// AAR register defines duration of each pulse, it is
// updated after every pulse in Update interrupt handler.
stm32_pulse_config_output(&extmoduleTimer, !polarity, LL_TIM_OCMODE_FORCED_INACTIVE,
ppm_delay * 2);
}
void extmodulePpmStart(uint16_t ppm_delay, bool polarity)
{
EXTERNAL_MODULE_ON();
stm32_pulse_init(&extmoduleTimer);
config_ppm_output(ppm_delay, polarity);
}
void extmoduleSendNextFramePpm(void* pulses, uint16_t length,
uint16_t ppm_delay, bool polarity)
{
if (!stm32_pulse_if_not_running_disable(&extmoduleTimer))
return;
// Set polarity
stm32_pulse_set_polarity(&extmoduleTimer, !polarity);
// Start DMA request and re-enable timer
stm32_pulse_start_dma_req(&extmoduleTimer, pulses, length,
LL_TIM_OCMODE_PWM1, ppm_delay * 2);
}
#if defined(PXX1)
void extmodulePxx1PulsesStart()
{
EXTERNAL_MODULE_ON();
stm32_pulse_config_output(&extmoduleTimer, false, LL_TIM_OCMODE_PWM1, 9 * 2);
stm32_pulse_init(&extmoduleTimer);
}
void extmoduleSendNextFramePxx1(const void* pulses, uint16_t length)
{
if (!stm32_pulse_if_not_running_disable(&extmoduleTimer)) return;
// Start DMA request and re-enable timer
stm32_pulse_start_dma_req(&extmoduleTimer, pulses, length, LL_TIM_OCMODE_PWM1,
9 * 2);
}
#endif
// TODO: polarity?
void extmoduleSerialStart()
{
EXTERNAL_MODULE_ON();
stm32_pulse_init(&extmoduleTimer);
stm32_pulse_config_output(&extmoduleTimer, true, LL_TIM_OCMODE_TOGGLE, 0);
}
void extmoduleSendNextFrameSoftSerial(const void* pulses, uint16_t length, bool polarity)
{
if (!stm32_pulse_if_not_running_disable(&extmoduleTimer))
return;
// Set polarity
stm32_pulse_set_polarity(&extmoduleTimer, polarity);
// Start DMA request and re-enable timer
stm32_pulse_start_dma_req(&extmoduleTimer, pulses, length, LL_TIM_OCMODE_TOGGLE, 0);
}
void extmoduleInitTxPin()
{
LL_GPIO_InitTypeDef pinInit;
LL_GPIO_StructInit(&pinInit);
pinInit.Pin = extmoduleTimer.GPIO_Pin;
pinInit.Mode = LL_GPIO_MODE_OUTPUT;
pinInit.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
pinInit.Pull = LL_GPIO_PULL_UP;
LL_GPIO_Init(extmoduleTimer.GPIOx, &pinInit);
}
// Delay based byte sending @ 57600 bps
void extmoduleSendInvertedByte(uint8_t byte)
{
uint16_t time;
uint32_t i;
__disable_irq();
time = getTmr2MHz();
LL_GPIO_SetOutputPin(EXTMODULE_TX_GPIO, EXTMODULE_TX_GPIO_PIN);
while ((uint16_t) (getTmr2MHz() - time) < 34) {
// wait
}
time += 34;
for (i = 0; i < 8; i++) {
if (byte & 1) {
LL_GPIO_ResetOutputPin(EXTMODULE_TX_GPIO, EXTMODULE_TX_GPIO_PIN);
}
else {
LL_GPIO_SetOutputPin(EXTMODULE_TX_GPIO, EXTMODULE_TX_GPIO_PIN);
}
byte >>= 1 ;
while ((uint16_t) (getTmr2MHz() - time) < 35) {
// wait
}
time += 35 ;
}
LL_GPIO_ResetOutputPin(EXTMODULE_TX_GPIO, EXTMODULE_TX_GPIO_PIN);
__enable_irq(); // No need to wait for the stop bit to complete
while ((uint16_t) (getTmr2MHz() - time) < 34) {
// wait
}
}
@@ -23,23 +23,6 @@
#include <stdint.h>
void extmoduleStop();
void extmodulePpmStart(uint16_t ppm_delay, bool polarity);
#include "stm32_pulse_driver.h"
#if defined(PXX1)
void extmodulePxx1PulsesStart();
void extmoduleSendNextFramePxx1(const void* pulses, uint16_t length);
#endif
// Soft serial on PPM pin
void extmoduleSerialStart();
void extmoduleSendNextFramePpm(void* pulses, uint16_t length,
uint16_t ppm_delay, bool polarity);
void extmoduleSendNextFrameSoftSerial(const void* pulses, uint16_t length,
bool polarity = true);
// Bitbang serial
void extmoduleInitTxPin();
void extmoduleSendInvertedByte(uint8_t byte);
extern const stm32_pulse_timer_t extmoduleTimer;
@@ -1,210 +0,0 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "stm32_hal_ll.h"
#include "stm32_usart_driver.h"
#include "extmodule_serial_driver.h"
#include "board.h"
#if defined(EXTMODULE_USART)
struct RxFifo {
uint8_t* buf;
uint16_t size;
uint16_t widx;
uint16_t ridx;
};
struct ExtmoduleCtx {
RxFifo rxFifo;
const stm32_usart_t* usart;
};
static etx_serial_callbacks_t extmodule_callbacks = {
nullptr, nullptr, nullptr
};
static void _fifo_clear(const stm32_usart_t* usart, RxFifo& fifo)
{
if (usart->rxDMA) {
auto dma_len = LL_DMA_GetDataLength(usart->rxDMA, usart->rxDMA_Stream);
fifo.ridx = fifo.size - dma_len;
} else {
fifo.widx = fifo.ridx = 0;
}
}
static int _fifo_get_byte(const stm32_usart_t* usart, RxFifo& fifo, uint8_t* data)
{
if (usart->rxDMA) {
auto DMAx = usart->rxDMA;
auto stream = usart->rxDMA_Stream;
// DMA stream enabled?
if (!LL_DMA_IsEnabledStream(DMAx, stream)) return 0;
// Anything to read?
auto dma_len = LL_DMA_GetDataLength(DMAx, stream);
if (fifo.size - dma_len == fifo.ridx) return 0;
} else {
if (fifo.ridx == fifo.widx) return 0;
}
*data = fifo.buf[fifo.ridx];
fifo.ridx = (fifo.ridx + 1) & (fifo.size - 1);
return 1;
}
static const LL_GPIO_InitTypeDef extmoduleUSART_PinDef = {
.Pin = EXTMODULE_TX_GPIO_PIN | EXTMODULE_RX_GPIO_PIN,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_LOW,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
.Pull = LL_GPIO_PULL_UP,
.Alternate = EXTMODULE_USART_GPIO_AF_LL,
};
static const stm32_usart_t extmoduleUSART = {
.USARTx = EXTMODULE_USART,
.GPIOx = EXTMODULE_TX_GPIO,
.pinInit = &extmoduleUSART_PinDef,
.IRQn = EXTMODULE_USART_IRQn,
.IRQ_Prio = EXTMODULE_USART_IRQ_PRIORITY,
.txDMA = EXTMODULE_USART_TX_DMA,
.txDMA_Stream = EXTMODULE_USART_TX_DMA_STREAM_LL,
.txDMA_Channel = EXTMODULE_USART_TX_DMA_CHANNEL,
.rxDMA = EXTMODULE_USART_TX_DMA,
.rxDMA_Stream = EXTMODULE_USART_RX_DMA_STREAM_LL,
.rxDMA_Channel = EXTMODULE_USART_RX_DMA_CHANNEL,
};
static uint8_t _rx_buffer[INTMODULE_FIFO_SIZE] __DMA;
static ExtmoduleCtx extmoduleCtx = {
.rxFifo = { _rx_buffer, sizeof(_rx_buffer), 0, 0 },
.usart = &extmoduleUSART,
};
static void* extmoduleSerialInit(const etx_serial_init* params)
{
if (!params) return nullptr;
extmodule_callbacks.on_receive = nullptr;
extmodule_callbacks.on_error = nullptr;
// UART config
auto usart = extmoduleCtx.usart;
stm32_usart_init(usart, params);
auto& fifo = extmoduleCtx.rxFifo;
if (params->rx_enable && usart->rxDMA) {
stm32_usart_init_rx_dma(usart, fifo.buf, fifo.size);
}
_fifo_clear(usart, fifo);
return (void*)&extmoduleCtx;
}
void extmoduleSerialStop(void* ctx)
{
auto modCtx = (ExtmoduleCtx*)ctx;
stm32_usart_deinit(modCtx->usart);
// reset callbacks
extmodule_callbacks.on_receive = nullptr;
extmodule_callbacks.on_error = nullptr;
}
static void extmoduleSerialSendByte(void* ctx, uint8_t byte)
{
auto modCtx = (ExtmoduleCtx*)ctx;
stm32_usart_send_byte(modCtx->usart, byte);
}
static void extmoduleSerialSendBuffer(void* ctx, const uint8_t * data, uint8_t size)
{
auto modCtx = (ExtmoduleCtx*)ctx;
if (size == 0) return;
stm32_usart_send_buffer(modCtx->usart, data, size);
}
static void extmoduleSerialWaitForTxCompleted(void* ctx)
{
auto modCtx = (ExtmoduleCtx*)ctx;
stm32_usart_wait_for_tx_dma(modCtx->usart);
}
static int extmoduleSerialGetByte(void* ctx, uint8_t* data)
{
auto modCtx = (ExtmoduleCtx*)ctx;
return _fifo_get_byte(modCtx->usart, modCtx->rxFifo, data);
}
static void extmoduleSerialClearRxBuffer(void* ctx)
{
auto modCtx = (ExtmoduleCtx*)ctx;
_fifo_clear(modCtx->usart, modCtx->rxFifo);
}
static const etx_serial_driver_t extmoduleSerialDriver = {
.init = extmoduleSerialInit,
.deinit = extmoduleSerialStop,
.sendByte = extmoduleSerialSendByte,
.sendBuffer = extmoduleSerialSendBuffer,
.waitForTxCompleted = extmoduleSerialWaitForTxCompleted,
.getByte = extmoduleSerialGetByte,
.clearRxBuffer = extmoduleSerialClearRxBuffer,
.getBaudrate = nullptr,
.setReceiveCb = nullptr,
.setBaudrateCb = nullptr,
};
constexpr const etx_serial_driver_t* _default_driver = &extmoduleSerialDriver;
// IRQ based RX/TX: probably obsolete now
extern "C" void EXTMODULE_USART_IRQHandler(void)
{
stm32_usart_isr(extmoduleCtx.usart, &extmodule_callbacks);
}
#else
constexpr const etx_serial_driver_t* _default_driver = nullptr;
#endif // defined(EXTMODULE_USART)
const etx_serial_driver_t* _extmodule_driver = _default_driver;
void extmoduleSetSerialPort(const etx_serial_driver_t* drv)
{
if (drv) {
_extmodule_driver = drv;
} else {
_extmodule_driver = _default_driver;
}
}
const etx_serial_driver_t* extmoduleGetSerialPort()
{
return _extmodule_driver;
}
@@ -54,7 +54,6 @@ add_library(stm32_stdperiph OBJECT EXCLUDE_FROM_ALL
${STM32_STDPERIPH_DIR}/src/stm32f2xx_spi.c
${STM32_STDPERIPH_DIR}/src/stm32f2xx_dma.c
${STM32_STDPERIPH_DIR}/src/stm32f2xx_pwr.c
${STM32_STDPERIPH_DIR}/src/stm32f2xx_usart.c
${STM32_STDPERIPH_DIR}/src/stm32f2xx_adc.c
)
@@ -53,7 +53,6 @@ set(STM32_STDPERIPH_SRC
${STM32_STDPERIPH_DIR}/src/stm32f4xx_spi.c
${STM32_STDPERIPH_DIR}/src/stm32f4xx_dma.c
${STM32_STDPERIPH_DIR}/src/stm32f4xx_pwr.c
${STM32_STDPERIPH_DIR}/src/stm32f4xx_usart.c
${STM32_STDPERIPH_DIR}/src/stm32f4xx_adc.c
${STM32_STDPERIPH_DIR}/src/stm32f4xx_flash.c
)
@@ -0,0 +1,190 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "flysky_gimbal_driver.h"
#include "stm32_serial_driver.h"
#include "delays_driver.h"
#include "hal.h"
#include "crc.h"
#include <string.h>
static const stm32_usart_t fsUSART = {
.USARTx = FLYSKY_HALL_SERIAL_USART,
.GPIOx = FLYSKY_HALL_SERIAL_GPIO,
.GPIO_Pin = FLYSKY_HALL_SERIAL_RX_GPIO_PIN,
.IRQn = FLYSKY_HALL_SERIAL_USART_IRQn,
.IRQ_Prio = 6,
.txDMA = nullptr,
.txDMA_Stream = 0,
.txDMA_Channel = 0,
.rxDMA = FLYSKY_HALL_SERIAL_DMA,
.rxDMA_Stream = FLYSKY_HALL_DMA_Stream_RX,
.rxDMA_Channel = FLYSKY_HALL_DMA_Channel,
};
DEFINE_STM32_SERIAL_PORT(FSGimbal, fsUSART, HALLSTICK_BUFF_SIZE, 0);
static STRUCT_HALL HallProtocol = { 0 };
signed short hall_raw_values[FLYSKY_HALL_CHANNEL_COUNT];
unsigned short hall_adc_values[FLYSKY_HALL_CHANNEL_COUNT];
static void* _fs_usart_ctx = nullptr;
uint16_t get_flysky_hall_adc_value(uint8_t ch)
{
if (ch >= FLYSKY_HALL_CHANNEL_COUNT) {
return 0;
}
return 2 * FLYSKY_OFFSET_VALUE - hall_adc_values[ch];
}
static int _fs_get_byte(uint8_t* data)
{
return STM32SerialDriver.getByte(_fs_usart_ctx, data);
}
static void _fs_parse(STRUCT_HALL *hallBuffer, unsigned char ch)
{
switch (hallBuffer->status) {
case GET_START:
if (FLYSKY_HALL_PROTOLO_HEAD == ch) {
hallBuffer->head = FLYSKY_HALL_PROTOLO_HEAD;
hallBuffer->status = GET_ID;
hallBuffer->msg_OK = 0;
}
break;
case GET_ID:
hallBuffer->hallID.ID = ch;
hallBuffer->status = GET_LENGTH;
break;
case GET_LENGTH:
hallBuffer->length = ch;
hallBuffer->dataIndex = 0;
hallBuffer->status = GET_DATA;
if (0 == hallBuffer->length) {
hallBuffer->status = GET_CHECKSUM;
hallBuffer->checkSum = 0;
}
break;
case GET_DATA:
hallBuffer->data[hallBuffer->dataIndex++] = ch;
if (hallBuffer->dataIndex >= hallBuffer->length) {
hallBuffer->checkSum = 0;
hallBuffer->dataIndex = 0;
hallBuffer->status = GET_STATE;
}
break;
case GET_STATE:
hallBuffer->checkSum = 0;
hallBuffer->dataIndex = 0;
hallBuffer->status = GET_CHECKSUM;
// fall through!
case GET_CHECKSUM:
hallBuffer->checkSum |= ch << ((hallBuffer->dataIndex++) * 8);
if (hallBuffer->dataIndex >= 2) {
hallBuffer->dataIndex = 0;
hallBuffer->status = CHECKSUM;
// fall through!
} else {
break;
}
case CHECKSUM:
if (hallBuffer->checkSum ==
crc16(CRC_1021, &hallBuffer->head, hallBuffer->length + 3, 0xffff)) {
hallBuffer->msg_OK = 1;
}
hallBuffer->status = GET_START;
break;
}
}
static volatile bool _fs_gimbal_detected;
static void flysky_gimbal_loop()
{
uint8_t byte;
while(_fs_get_byte(&byte))
{
HallProtocol.index++;
_fs_parse(&HallProtocol, byte);
if ( HallProtocol.msg_OK )
{
HallProtocol.msg_OK = 0;
HallProtocol.stickState = HallProtocol.data[HallProtocol.length - 1];
switch ( HallProtocol.hallID.hall_Id.receiverID )
{
case TRANSFER_DIR_TXMCU:
if(HallProtocol.hallID.hall_Id.packetID == FLYSKY_HALL_RESP_TYPE_VALUES) {
memcpy(hall_raw_values, HallProtocol.data, sizeof(hall_raw_values));
for ( uint8_t channel = 0; channel < 4; channel++ )
{
hall_adc_values[channel] = FLYSKY_OFFSET_VALUE + hall_raw_values[channel];
}
}
break;
}
_fs_gimbal_detected = true;
}
}
}
static void flysky_gimbal_deinit()
{
STM32SerialDriver.deinit(_fs_usart_ctx);
}
bool flysky_gimbal_init()
{
etx_serial_init cfg = {
.baudrate = FLYSKY_HALL_BAUDRATE,
.encoding = ETX_Encoding_8N1,
.direction = ETX_Dir_RX,
.polarity = ETX_Pol_Normal,
};
_fs_gimbal_detected = false;
_fs_usart_ctx = STM32SerialDriver.init(REF_STM32_SERIAL_PORT(FSGimbal), &cfg);
STM32SerialDriver.setIdleCb(_fs_usart_ctx, flysky_gimbal_loop);
// Wait 70ms for FlySky gimbals to respond. According to LA trace, minimally 23ms is required
for (uint8_t i = 0; i < 70; i++) {
delay_ms(1);
if (_fs_gimbal_detected) {
return true;
}
}
flysky_gimbal_deinit();
return false;
}
@@ -0,0 +1,120 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define HALLSTICK_BUFF_SIZE ( 512 )
#define FLYSKY_HALL_BAUDRATE ( 921600 )
#define FLYSKY_HALL_CHANNEL_COUNT ( 4 )
#define FLYSKY_OFFSET_VALUE ( 16384 )
#define FLYSKY_HALL_PROTOLO_HEAD 0x55
#define FLYSKY_HALL_RESP_TYPE_VALUES 0x0c
typedef struct
{
signed short channel[4];
unsigned char stickState;
unsigned short CRC16;
} STRUCT_CHANNEL_PACK;
typedef struct
{
unsigned char start;
unsigned char senderID:2;
unsigned char receiverID:2;
unsigned char packetID:4;
unsigned char length;
STRUCT_CHANNEL_PACK payload;
} STRUCT_HALLDATA;
typedef struct
{
unsigned char senderID:2;
unsigned char receiverID:2;
unsigned char packetID:4;
} STRUCT_HALLID;
typedef union
{
STRUCT_HALLID hall_Id;
unsigned char ID;
} STRUCT_ID;
typedef union
{
STRUCT_HALLDATA halldat;
unsigned char buffer[30];
} UNION_HALLDATA;
typedef struct
{
unsigned char head;
STRUCT_ID hallID;
unsigned char length;
unsigned char data[HALLSTICK_BUFF_SIZE];
unsigned char reserved[15];
unsigned short checkSum;
unsigned char stickState;
unsigned char startIndex;
unsigned char endIndex;
unsigned char index;
unsigned char dataIndex;
unsigned char deindex;
unsigned char completeFlg;
unsigned char status;
unsigned char recevied;
unsigned char msg_OK;
} STRUCT_HALL;
enum
{
GET_START = 0,
GET_ID,
GET_LENGTH,
GET_DATA,
GET_STATE,
GET_CHECKSUM,
CHECKSUM,
};
enum HALLSTICK_SEND_STATE_E {
HALLSTICK_SEND_STATE_IDLE,
HALLSTICK_STATE_SEND_RESET,
HALLSTICK_STATE_GET_CONFIG,
HALLSTICK_STATE_GET_FIRMWARE,
HALLSTICK_STATE_UPDATE_FW
};
enum TRANSFER_DIR_E {
TRANSFER_DIR_HALLSTICK,
TRANSFER_DIR_TXMCU,
TRANSFER_DIR_HOSTPC,
TRANSFER_DIR_RFMODULE,
};
extern signed short hall_raw_values[FLYSKY_HALL_CHANNEL_COUNT];
extern unsigned short hall_adc_values[FLYSKY_HALL_CHANNEL_COUNT];
// returns true if the gimbals were detected properly
bool flysky_gimbal_init();
@@ -32,5 +32,4 @@ struct HeartbeatCapture {
extern volatile HeartbeatCapture heartbeatCapture;
void init_intmodule_heartbeat();
void check_intmodule_heartbeat();
void stop_intmodule_heartbeat();
@@ -1,220 +0,0 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "stm32_hal_ll.h"
#include "intmodule_serial_driver.h"
#include "stm32_usart_driver.h"
#include "board.h"
#include "fifo.h"
#include "dmafifo.h"
#if defined(INTMODULE_RX_DMA)
typedef DMAFifo<INTMODULE_FIFO_SIZE> RxFifo;
static RxFifo intmoduleFifo __DMA(
__LL_DMA_GET_STREAM_INSTANCE(INTMODULE_RX_DMA, INTMODULE_RX_DMA_STREAM));
#else
typedef Fifo<uint8_t, INTMODULE_FIFO_SIZE> RxFifo;
static RxFifo intmoduleFifo;
#endif
struct IntmoduleCtx
{
RxFifo* rxFifo;
const stm32_usart_t* usart;
};
#if !defined(INTMODULE_DMA_STREAM)
static uint8_t * intmoduleTxBufferData;
static volatile uint8_t intmoduleTxBufferRemaining;
uint8_t intmoduleTxBufferSend(uint8_t* data)
{
if (intmoduleTxBufferRemaining) {
*data = *(intmoduleTxBufferData++);
intmoduleTxBufferRemaining--;
return true;
}
// buffer is empty
return false;
}
#endif
static etx_serial_callbacks_t intmodule_driver = {
#if !defined(INTMODULE_DMA_STREAM)
intmoduleTxBufferSend,
#else
nullptr,
#endif
nullptr, nullptr
};
#if !defined(INTMODULE_RX_DMA)
// TODO: move this somewhere else
static void intmoduleFifoReceive(uint8_t data)
{
intmoduleFifo.push(data);
}
#endif
static const LL_GPIO_InitTypeDef intmoduleUSART_PinDef = {
.Pin = INTMODULE_TX_GPIO_PIN | INTMODULE_RX_GPIO_PIN,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_LOW,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
.Pull = LL_GPIO_PULL_UP,
.Alternate = INTMODULE_GPIO_AF,
};
static const stm32_usart_t intmoduleUSART = {
.USARTx = INTMODULE_USART,
.GPIOx = INTMODULE_GPIO,
.pinInit = &intmoduleUSART_PinDef,
.IRQn = INTMODULE_USART_IRQn,
.IRQ_Prio = INTMODULE_USART_IRQ_PRIORITY,
#if defined(INTMODULE_DMA)
.txDMA = INTMODULE_DMA,
.txDMA_Stream = INTMODULE_DMA_STREAM,
.txDMA_Channel = INTMODULE_DMA_CHANNEL,
#else
.txDMA = nullptr,
.txDMA_Stream = 0,
.txDMA_Channel = 0,
#endif
#if defined(INTMODULE_RX_DMA)
.rxDMA = INTMODULE_RX_DMA,
.rxDMA_Stream = INTMODULE_RX_DMA_STREAM,
.rxDMA_Channel = INTMODULE_RX_DMA_CHANNEL,
#else
.rxDMA = nullptr,
.rxDMA_Stream = 0,
.rxDMA_Channel = 0,
#endif
};
static const IntmoduleCtx intmoduleCtx = {
.rxFifo = &intmoduleFifo,
.usart = &intmoduleUSART,
};
void intmoduleStop()
{
INTERNAL_MODULE_OFF();
stm32_usart_deinit(&intmoduleUSART);
// reset callbacks
intmodule_driver.on_receive = nullptr;
intmodule_driver.on_error = nullptr;
}
static void intmoduleStop(void* ctx)
{
(void)ctx;
intmoduleStop();
}
void* intmoduleSerialStart(const etx_serial_init* params)
{
if (!params) return nullptr;
// TODO: sanity check parameters
// - the UART seems to block when initialised with baudrate = 0
// init callbacks
#if !defined(INTMODULE_RX_DMA)
intmodule_driver.on_receive = intmoduleFifoReceive;
#else
intmodule_driver.on_receive = nullptr;
#endif
intmodule_driver.on_error = nullptr;
stm32_usart_init(&intmoduleUSART, params);
if (params->rx_enable && intmoduleUSART.rxDMA) {
stm32_usart_init_rx_dma(&intmoduleUSART, intmoduleFifo.buffer(), intmoduleFifo.size());
}
intmoduleCtx.rxFifo->clear();
return (void*)&intmoduleCtx;
}
#define USART_FLAG_ERRORS (USART_FLAG_ORE | USART_FLAG_NE | USART_FLAG_FE | USART_FLAG_PE)
extern "C" void INTMODULE_USART_IRQHandler(void)
{
stm32_usart_isr(&intmoduleUSART, &intmodule_driver);
}
void intmoduleSendByte(void* ctx, uint8_t byte)
{
auto modCtx = (IntmoduleCtx*)ctx;
stm32_usart_send_byte(modCtx->usart, byte);
}
void intmoduleSendBuffer(void* ctx, const uint8_t * data, uint8_t size)
{
auto modCtx = (IntmoduleCtx*)ctx;
if (size == 0)
return;
#if !defined(INTMODULE_DMA_STREAM)
intmoduleTxBufferData = (uint8_t *)data;
intmoduleTxBufferRemaining = size;
#endif
stm32_usart_send_buffer(modCtx->usart, data, size);
}
void intmoduleWaitForTxCompleted(void* ctx)
{
#if defined(INTMODULE_DMA_STREAM)
auto modCtx = (IntmoduleCtx*)ctx;
stm32_usart_wait_for_tx_dma(modCtx->usart);
#else
while (intmoduleTxBufferRemaining > 0);
#endif
}
static int intmoduleGetByte(void* ctx, uint8_t* data)
{
auto modCtx = (IntmoduleCtx*)ctx;
if (!modCtx->rxFifo) return -1;
return modCtx->rxFifo->pop(*data);
}
static void intmoduleClearRxBuffer(void* ctx)
{
auto modCtx = (IntmoduleCtx*)ctx;
if (!modCtx->rxFifo) return;
modCtx->rxFifo->clear();
}
const etx_serial_driver_t IntmoduleSerialDriver = {
.init = intmoduleSerialStart,
.deinit = intmoduleStop,
.sendByte = intmoduleSendByte,
.sendBuffer = intmoduleSendBuffer,
.waitForTxCompleted = intmoduleWaitForTxCompleted,
.getByte = intmoduleGetByte,
.clearRxBuffer = intmoduleClearRxBuffer,
.getBaudrate = nullptr,
.setReceiveCb = nullptr,
.setBaudrateCb = nullptr,
};
@@ -0,0 +1,64 @@
/*
* Copyright (C) EdgeTX
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "module_timer_driver.h"
#include "stm32_pulse_driver.h"
static void* module_timer_init(void* hw_def, const etx_timer_config_t* cfg)
{
auto timer = (const stm32_pulse_timer_t*)hw_def;
bool polarity = cfg->polarity;
uint32_t ocval = cfg->cmp_val;
uint32_t ocmode = (cfg->type == ETX_PWM) ? LL_TIM_OCMODE_PWM1 : LL_TIM_OCMODE_TOGGLE;
stm32_pulse_init(timer, 0);
stm32_pulse_config_output(timer, polarity, ocmode, ocval);
return (void*)timer;
}
static void module_timer_deinit(void* ctx)
{
auto timer = (const stm32_pulse_timer_t*)ctx;
stm32_pulse_deinit(timer);
}
static void module_timer_send(void* ctx, const etx_timer_config_t* cfg,
const void* pulses, uint16_t length)
{
auto timer = (const stm32_pulse_timer_t*)ctx;
if (!stm32_pulse_if_not_running_disable(timer)) return;
// Set polarity
stm32_pulse_set_polarity(timer, cfg->polarity);
// Start DMA request and re-enable timer
uint32_t ocmode = (cfg->type == ETX_PWM) ? LL_TIM_OCMODE_PWM1 : LL_TIM_OCMODE_TOGGLE;
uint32_t ocval = cfg->cmp_val;
stm32_pulse_start_dma_req(timer, pulses, length, ocmode, ocval);
}
const etx_timer_driver_t STM32ModuleTimerDriver = {
.init = module_timer_init,
.deinit = module_timer_deinit,
.send = module_timer_send,
};
@@ -21,9 +21,6 @@
#pragma once
#include <stdint.h>
#include "hal/serial_driver.h"
#include "hal/timer_driver.h"
#define INTMODULE_USART_IRQ_PRIORITY 6
extern const etx_serial_driver_t IntmoduleSerialDriver;
extern const etx_timer_driver_t STM32ModuleTimerDriver;
@@ -1,5 +1,5 @@
/*
* Copyright (C) EdgeTX
* Copyright (C) EdgeTx
*
* Based on code named
* opentx - https://github.com/opentx/opentx
@@ -22,12 +22,28 @@
#pragma once
#include <stdint.h>
#include "hal/serial_driver.h"
#include "stm32_hal_ll.h"
#define EXTMODULE_USART_IRQ_PRIORITY 6
inline static bool stm32_dma_check_tc_flag(DMA_TypeDef* DMAx, uint32_t DMA_Stream)
{
switch(DMA_Stream) {
case LL_DMA_STREAM_1:
if (!LL_DMA_IsActiveFlag_TC1(DMAx)) return false;
LL_DMA_ClearFlag_TC1(DMAx);
break;
case LL_DMA_STREAM_5:
if (!LL_DMA_IsActiveFlag_TC5(DMAx)) return false;
LL_DMA_ClearFlag_TC5(DMAx);
break;
case LL_DMA_STREAM_6:
if (!LL_DMA_IsActiveFlag_TC6(DMAx)) return false;
LL_DMA_ClearFlag_TC6(DMAx);
break;
case LL_DMA_STREAM_7:
if (!LL_DMA_IsActiveFlag_TC7(DMAx)) return false;
LL_DMA_ClearFlag_TC7(DMAx);
break;
}
// Use an alternative USART as external module
void extmoduleSetSerialPort(const etx_serial_driver_t* port);
// Return the serial driver to be used as external module
const etx_serial_driver_t* extmoduleGetSerialPort();
return true;
}
@@ -82,7 +82,7 @@ static bool _has_handler(stm32_exti_handler_t* _handlers, uint8_t len)
return false;
}
void stm32_exti_enable(uint32_t line, uint32_t trigger, stm32_exti_handler_t cb)
void stm32_exti_enable(uint32_t line, uint8_t trigger, stm32_exti_handler_t cb)
{
if (line > LL_EXTI_LINE_15) return;
@@ -34,7 +34,7 @@
typedef void (*stm32_exti_handler_t)();
// Set callback and enable IRQ
void stm32_exti_enable(uint32_t line, uint32_t trigger, stm32_exti_handler_t cb);
void stm32_exti_enable(uint32_t line, uint8_t trigger, stm32_exti_handler_t cb);
// Reset callback and disable IRQ if no more handlers
void stm32_exti_disable(uint32_t line);
@@ -32,6 +32,7 @@ extern "C" {
#include "STM32F4xx_HAL_Driver/Inc/stm32f4xx_ll_usart.h"
#include "STM32F4xx_HAL_Driver/Inc/stm32f4xx_ll_exti.h"
#include "STM32F4xx_HAL_Driver/Inc/stm32f4xx_ll_system.h"
#include "STM32F4xx_HAL_Driver/Inc/stm32f4xx_ll_rcc.h"
#elif defined(STM32F2)
// Workaround to prevent the other CMSIS header to be included
@@ -47,5 +48,6 @@ extern "C" {
#include "STM32F2xx_HAL_Driver/Inc/stm32f2xx_ll_usart.h"
#include "STM32F2xx_HAL_Driver/Inc/stm32f2xx_ll_exti.h"
#include "STM32F2xx_HAL_Driver/Inc/stm32f2xx_ll_system.h"
#include "STM32F2xx_HAL_Driver/Inc/stm32f2xx_ll_rcc.h"
#endif
}
@@ -20,8 +20,20 @@
*/
#include "stm32_pulse_driver.h"
#include "stm32_dma.h"
#include "definitions.h"
#include <string.h>
// 0.5uS (2Mhz)
#define STM32_DEFAULT_TIMER_FREQ 2000000
#define STM32_DEFAULT_TIMER_AUTORELOAD 65535
// TODO:
// - DMA IRQ prio configurable (now 7)
// - Timer IRQ prio configurable (now 7)
static void enable_tim_clock(TIM_TypeDef* TIMx)
{
if (TIMx == TIM1) {
@@ -37,8 +49,12 @@ static void enable_tim_clock(TIM_TypeDef* TIMx)
}
}
void stm32_pulse_init(const stm32_pulse_timer_t* tim)
void stm32_pulse_init(const stm32_pulse_timer_t* tim, uint32_t freq)
{
if (tim->DMA_TC_CallbackPtr) {
memset(tim->DMA_TC_CallbackPtr, 0, sizeof(stm32_pulse_dma_tc_cb_t));
}
LL_GPIO_InitTypeDef pinInit;
LL_GPIO_StructInit(&pinInit);
pinInit.Pin = tim->GPIO_Pin;
@@ -49,9 +65,12 @@ void stm32_pulse_init(const stm32_pulse_timer_t* tim)
LL_TIM_InitTypeDef timInit;
LL_TIM_StructInit(&timInit);
// 0.5uS (2Mhz)
timInit.Prescaler = tim->TIM_Prescaler;
timInit.Autoreload = 65535;
if (!freq) {
freq = STM32_DEFAULT_TIMER_FREQ;
}
timInit.Prescaler = __LL_TIM_CALC_PSC(tim->TIM_Freq, freq);
timInit.Autoreload = STM32_DEFAULT_TIMER_AUTORELOAD;
enable_tim_clock(tim->TIMx);
LL_TIM_Init(tim->TIMx, &timInit);
@@ -93,6 +112,11 @@ void stm32_pulse_deinit(const stm32_pulse_timer_t* tim)
if (tim->DMAx) {
LL_DMA_DeInit(tim->DMAx, tim->DMA_Stream);
}
if (tim->DMA_TC_CallbackPtr) {
memset(tim->DMA_TC_CallbackPtr, 0, sizeof(stm32_pulse_dma_tc_cb_t));
}
LL_TIM_DeInit(tim->TIMx);
disable_tim_clock(tim->TIMx);
@@ -144,7 +168,6 @@ void stm32_pulse_config_output(const stm32_pulse_timer_t* tim, bool polarity,
LL_TIM_EnableAllOutputs(tim->TIMx);
}
LL_TIM_EnableDMAReq_UPDATE(tim->TIMx);
}
void stm32_pulse_set_polarity(const stm32_pulse_timer_t* tim, bool polarity)
@@ -158,6 +181,12 @@ void stm32_pulse_set_polarity(const stm32_pulse_timer_t* tim, bool polarity)
LL_TIM_OC_SetPolarity(tim->TIMx, tim->TIM_Channel, ll_polarity);
}
bool stm32_pulse_get_polarity(const stm32_pulse_timer_t* tim)
{
return LL_TIM_OC_GetPolarity(tim->TIMx, tim->TIM_Channel) ==
LL_TIM_OCPOLARITY_HIGH;
}
// return true if stopped, false otherwise
bool stm32_pulse_if_not_running_disable(const stm32_pulse_timer_t* tim)
{
@@ -204,6 +233,16 @@ static void set_oc_mode(const stm32_pulse_timer_t* tim, uint32_t ocmode)
LL_TIM_OC_SetMode(tim->TIMx, channel, ocmode);
}
void stm32_pulse_wait_for_completed(const stm32_pulse_timer_t* tim)
{
uint32_t channel = tim->TIM_Channel;
if (channel == LL_TIM_CHANNEL_CH1N)
channel = LL_TIM_CHANNEL_CH1;
while(LL_TIM_IsEnabledCounter(tim->TIMx) &&
LL_TIM_OC_GetMode(tim->TIMx, channel) != LL_TIM_OCMODE_FORCED_INACTIVE);
}
static void force_start_level(const stm32_pulse_timer_t* tim)
{
uint32_t channel = tim->TIM_Channel;
@@ -259,48 +298,43 @@ void stm32_pulse_start_dma_req(const stm32_pulse_timer_t* tim,
// Enable TC IRQ
LL_DMA_EnableIT_TC(tim->DMAx, tim->DMA_Stream);
// Enable DMA
LL_TIM_ClearFlag_UPDATE(tim->TIMx);
LL_TIM_DisableDMAReq_UPDATE(tim->TIMx);
LL_TIM_SetCounter(tim->TIMx, 0);
// Reset counter close to overflow
if (IS_TIM_32B_COUNTER_INSTANCE(tim->TIMx)) {
LL_TIM_SetCounter(tim->TIMx, 0xFFFFFFFF);
} else {
LL_TIM_SetCounter(tim->TIMx, 0xFFFF);
}
// only on PWM (preloads the first period)
if (ocmode == LL_TIM_OCMODE_PWM1)
LL_TIM_GenerateEvent_UPDATE(tim->TIMx);
LL_TIM_EnableDMAReq_UPDATE(tim->TIMx);
LL_DMA_EnableStream(tim->DMAx, tim->DMA_Stream);
// Trigger update to effect the first DMA transation
// Trigger update to effect the first DMA transaction
// and thus load ARR with the first duration
LL_TIM_EnableDMAReq_UPDATE(tim->TIMx);
LL_TIM_GenerateEvent_UPDATE(tim->TIMx);
// start timer
force_start_level(tim);
LL_TIM_EnableCounter(tim->TIMx);
}
static bool check_and_clean_dma_tc_flag(const stm32_pulse_timer_t* tim)
{
switch(tim->DMA_Stream) {
case LL_DMA_STREAM_1:
if (!LL_DMA_IsActiveFlag_TC1(tim->DMAx)) return false;
LL_DMA_ClearFlag_TC1(tim->DMAx);
break;
case LL_DMA_STREAM_5:
if (!LL_DMA_IsActiveFlag_TC5(tim->DMAx)) return false;
LL_DMA_ClearFlag_TC5(tim->DMAx);
break;
case LL_DMA_STREAM_7:
if (!LL_DMA_IsActiveFlag_TC7(tim->DMAx)) return false;
LL_DMA_ClearFlag_TC7(tim->DMAx);
break;
}
return true;
}
void stm32_pulse_dma_tc_isr(const stm32_pulse_timer_t* tim)
{
if (!check_and_clean_dma_tc_flag(tim)) return;
if (!stm32_dma_check_tc_flag(tim->DMAx, tim->DMA_Stream))
return;
if (tim->DMA_TC_CallbackPtr) {
auto closure = tim->DMA_TC_CallbackPtr;
if (closure->cb && closure->cb(closure->ctx)) {
return;
}
}
LL_TIM_ClearFlag_UPDATE(tim->TIMx);
LL_TIM_EnableIT_UPDATE(tim->TIMx);
// PWM mode with compare value = 0 then OCxRef is held at ‘0’
set_compare_reg(tim, 0);
set_oc_mode(tim, LL_TIM_OCMODE_PWM1);
}
@@ -315,6 +349,7 @@ void stm32_pulse_tim_update_isr(const stm32_pulse_timer_t* tim)
// Halt pulses by forcing to inactive level
set_oc_mode(tim, LL_TIM_OCMODE_FORCED_INACTIVE);
LL_TIM_DisableCounter(tim->TIMx);
}
// input mode
@@ -24,6 +24,14 @@
#include <stdint.h>
#include "stm32_hal_ll.h"
struct stm32_pulse_timer_t;
typedef bool (*stm32_pulse_dma_tc_fct)(void*);
struct stm32_pulse_dma_tc_cb_t {
stm32_pulse_dma_tc_fct cb;
void* ctx;
};
struct stm32_pulse_timer_t {
GPIO_TypeDef* GPIOx;
@@ -31,7 +39,7 @@ struct stm32_pulse_timer_t {
uint32_t GPIO_Alternate;
TIM_TypeDef* TIMx;
uint16_t TIM_Prescaler;
uint32_t TIM_Freq;
uint32_t TIM_Channel;
IRQn_Type TIM_IRQn;
@@ -39,9 +47,10 @@ struct stm32_pulse_timer_t {
uint32_t DMA_Stream;
uint32_t DMA_Channel;
IRQn_Type DMA_IRQn;
stm32_pulse_dma_tc_cb_t* DMA_TC_CallbackPtr;
};
void stm32_pulse_init(const stm32_pulse_timer_t* tim);
void stm32_pulse_init(const stm32_pulse_timer_t* tim, uint32_t freq);
void stm32_pulse_deinit(const stm32_pulse_timer_t* tim);
void stm32_pulse_config_input(const stm32_pulse_timer_t* tim);
@@ -51,8 +60,12 @@ void stm32_pulse_config_output(const stm32_pulse_timer_t* tim, bool polarity,
void stm32_pulse_set_polarity(const stm32_pulse_timer_t* tim, bool polarity);
bool stm32_pulse_get_polarity(const stm32_pulse_timer_t* tim);
void stm32_pulse_set_cmp_val(const stm32_pulse_timer_t* tim, uint32_t cmp_val);
void stm32_pulse_wait_for_completed(const stm32_pulse_timer_t* tim);
// return true if it could be disabled without interrupting a pulse train, false otherwise
bool stm32_pulse_if_not_running_disable(const stm32_pulse_timer_t* tim);
@@ -0,0 +1,497 @@
/*
* Copyright (C) EdgeTx
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "stm32_serial_driver.h"
#include <string.h>
// Serial buffer state
struct stm32_buffer_state {
volatile uint32_t ridx;
volatile uint32_t widx;
};
struct stm32_send_buffer {
volatile const uint8_t* buf;
volatile uint32_t len;
};
struct stm32_serial_state {
const stm32_serial_port* sp;
stm32_buffer_state rx_buf;
union {
stm32_buffer_state tx_fifo;
stm32_send_buffer tx_buf;
} u;
etx_serial_callbacks_t callbacks;
};
enum _STM32_USART {
#if defined(USART1)
_STM32_USART1,
#endif
#if defined(USART2)
_STM32_USART2,
#endif
#if defined(USART3)
_STM32_USART3,
#endif
#if defined(UART4)
_STM32_UART4,
#endif
#if defined(USART6)
_STM32_USART6,
#endif
#if defined(UART7)
_STM32_UART7,
#endif
_STM32_MAX_UARTS
};
#define STM32_MAX_UART_PORTS _STM32_MAX_UARTS
// allocated as needed: index does not correspond
static stm32_serial_state _serial_states[STM32_MAX_UART_PORTS];
void stm32_serial_init_driver()
{
memset(_serial_states, 0, sizeof(_serial_states));
}
// Serial context to be used in callbacks
// defined in this driver
static volatile stm32_serial_state* _isr_state;
static uint8_t _on_send_fifo(uint8_t* data)
{
auto st = _isr_state;
auto& buf_st = st->u.tx_fifo;
if (buf_st.ridx == buf_st.widx)
return 0;
const auto& tx_buf = st->sp->tx_buffer;
auto buf = tx_buf.buffer;
*data = buf[buf_st.ridx];
auto buf_len = tx_buf.length;
buf_st.ridx = (buf_st.ridx + 1) & (buf_len - 1);
return 1;
}
static uint8_t _on_send_single_buffer(uint8_t* data)
{
auto sb = &_isr_state->u.tx_buf;
if (!sb->len) return 0;
*data = *(sb->buf++);
sb->len--;
return 1;
}
static inline void _usart_isr_handler(_STM32_USART n)
{
auto st = &(_serial_states[n]);
// This tricks is necessary for now to allow
// callbacks to use the serial context while
// keeping the callbacks re-entrant
auto old_st = _isr_state;
_isr_state = st;
stm32_usart_isr(st->sp->usart, &st->callbacks);
_isr_state = old_st;
}
#define DEFINE_USART_IRQ(usart) \
extern "C" void usart ## _IRQHandler(void) \
{ \
_usart_isr_handler(_STM32_ ## usart); \
}
#if defined (USART1)
DEFINE_USART_IRQ(USART1);
#endif
#if defined (USART2)
DEFINE_USART_IRQ(USART2);
#endif
#if defined (USART3)
DEFINE_USART_IRQ(USART3);
#endif
#if defined (UART4)
DEFINE_USART_IRQ(UART4);
#endif
#if defined (USART6)
DEFINE_USART_IRQ(USART6);
#endif
#if defined (UART7)
DEFINE_USART_IRQ(UART7);
#endif
static stm32_serial_state* stm32_serial_find_state(const stm32_usart_t* usart)
{
#if defined (USART1)
if (usart->USARTx == USART1) return &_serial_states[_STM32_USART1];
#endif
#if defined (USART2)
if (usart->USARTx == USART2) return &_serial_states[_STM32_USART2];
#endif
#if defined (USART3)
if (usart->USARTx == USART3) return &_serial_states[_STM32_USART3];
#endif
#if defined (UART4)
if (usart->USARTx == UART4) return &_serial_states[_STM32_UART4];
#endif
#if defined (USART6)
if (usart->USARTx == USART6) return &_serial_states[_STM32_USART6];
#endif
#if defined (UART7)
if (usart->USARTx == UART7) return &_serial_states[_STM32_UART7];
#endif
return nullptr;
}
static void stm32_serial_free_state(stm32_serial_state* st)
{
memset(st, 0, sizeof(stm32_serial_state));
}
static inline void _dma_clear(stm32_buffer_state* buf_st, uint32_t length,
DMA_TypeDef* DMAx, uint32_t stream)
{
buf_st->ridx = length - LL_DMA_GetDataLength(DMAx, stream);
}
static inline void _fifo_clear(stm32_buffer_state* buf_st)
{
buf_st->widx = buf_st->ridx = 0;
}
static inline bool _fifo_full(stm32_buffer_state* buf_st, uint32_t length)
{
return ((buf_st->widx + 1) & (length - 1)) == buf_st->ridx;
}
static inline void _fifo_push(uint8_t c, stm32_buffer_state* buf_st,
uint32_t length, uint8_t* buf)
{
buf[buf_st->widx] = c;
buf_st->widx = (buf_st->widx + 1) & (length - 1);
}
static void _on_rx_fifo(uint8_t data)
{
auto st = _isr_state;
stm32_buffer_state* buf_st = (stm32_buffer_state*)&st->rx_buf;
auto buf_len = st->sp->rx_buffer.length;
if (_fifo_full(buf_st, buf_len)) return;
auto buf = st->sp->rx_buffer.buffer;
_fifo_push(data, buf_st, buf_len, buf);
}
static void* stm32_serial_init(void* hw_def, const etx_serial_init* params)
{
// TODO: check if port is already in use
auto sp = (const stm32_serial_port*)hw_def;
if (!sp) return nullptr;
auto usart = sp->usart;
auto st = stm32_serial_find_state(usart);
if (!st || st->sp) return nullptr;
stm32_usart_init(usart, params);
st->sp = sp; // TODO: only iff init() is sucessful
if (params->direction & ETX_Dir_TX) {
// prepare for send_byte()
if (sp->tx_buffer.length > 0) {
st->callbacks.on_send = _on_send_fifo;
}
}
if (params->direction & ETX_Dir_RX) {
auto rx_buf = sp->rx_buffer.buffer;
auto buf_len = sp->rx_buffer.length;
if (usart->rxDMA) {
stm32_usart_init_rx_dma(usart, rx_buf, buf_len);
auto dma = usart->rxDMA;
auto stream = usart->rxDMA_Stream;
_dma_clear(&st->rx_buf, buf_len, dma, stream);
} else {
st->callbacks.on_receive = _on_rx_fifo;
}
}
return (void*)st;
}
static void stm32_serial_deinit(void* ctx)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
stm32_usart_deinit(st->sp->usart);
stm32_serial_free_state(st);
}
static void stm32_serial_send_byte(void* ctx, uint8_t c)
{
// When sending single bytes,
// send is based on IRQ, so that this
// only enables the corresponding IRQ
auto st = (stm32_serial_state*)ctx;
if (!st) return;
auto sp = st->sp;
auto buf_len = sp->tx_buffer.length;
if (buf_len > 0) {
auto buf_st = &st->u.tx_fifo;
auto buf = sp->tx_buffer.buffer;
if (_fifo_full(buf_st, buf_len)) return;
_fifo_push(c, buf_st, buf_len, buf);
stm32_usart_enable_tx_irq(sp->usart);
} else {
// No TX FIFO -> fall back to sync send
stm32_usart_send_byte(sp->usart, c);
}
}
#define IS_CCM_RAM(addr) (((uint32_t)(addr) & (uint32_t)0xFFF00000) == 0x10000000)
static void stm32_serial_send_buffer(void* ctx, const uint8_t* data, uint32_t size)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
// try TX DMA first
auto sp = st->sp;
auto usart = sp->usart;
if (usart->txDMA && !IS_CCM_RAM(data)) {
stm32_usart_send_buffer(usart, data, size);
return;
}
// no internal buffer: send one buffer at a time
if (!sp->tx_buffer.length) {
st->u.tx_buf.buf = data;
st->u.tx_buf.len = size;
st->callbacks.on_send = _on_send_single_buffer;
stm32_usart_enable_tx_irq(usart);
return;
}
// else stack single bytes into our internal buffer
while(size > 0) {
stm32_serial_send_byte(ctx, *data++);
size--;
}
}
static uint8_t stm32_serial_tx_completed(void* ctx)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return 1;
return stm32_usart_tx_completed(st->sp->usart);
}
static void stm32_wait_tx_completed(void* ctx)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
while(!stm32_usart_tx_completed(st->sp->usart));
}
static void stm32_enable_rx(void* ctx)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
stm32_usart_enable_rx(st->sp->usart);
}
static int stm32_serial_get_byte(void* ctx, uint8_t* data)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return -1;
auto sp = st->sp;
const auto& rx_buf = sp->rx_buffer;
auto buf_len = rx_buf.length;
if (!buf_len) return -1;
auto buf = rx_buf.buffer;
auto& buf_st = st->rx_buf;
uint32_t widx;
auto usart = sp->usart;
if (LL_USART_IsEnabledDMAReq_RX(usart->USARTx)) {
auto dma = usart->rxDMA;
auto stream = usart->rxDMA_Stream;
widx = buf_len - LL_DMA_GetDataLength(dma, stream);
} else {
widx = buf_st.widx;
}
if (buf_st.ridx == widx)
return 0;
*data = buf[buf_st.ridx];
buf_st.ridx = (buf_st.ridx + 1) & (buf_len - 1);
return 1;
}
static int stm32_serial_get_last_byte(void* ctx, uint32_t idx, uint8_t* data)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return -1;
auto sp = st->sp;
const auto& rx_buf = sp->rx_buffer;
auto buf_len = rx_buf.length;
if (!buf_len) return -1;
auto buf = rx_buf.buffer;
auto& buf_st = st->rx_buf;
uint32_t widx;
auto usart = sp->usart;
if (LL_USART_IsEnabledDMAReq_RX(usart->USARTx)) {
auto dma = usart->rxDMA;
auto stream = usart->rxDMA_Stream;
widx = buf_len - LL_DMA_GetDataLength(dma, stream);
} else {
widx = buf_st.widx;
}
// Please note that we do not check the read cursor
// so that this function might return data that
// has already been read
uint32_t ridx = (buf_len + widx - idx) & (buf_len - 1);
*data = buf[ridx];
return 1;
}
static void stm32_serial_clear_rx_buffer(void* ctx)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
auto sp = st->sp;
auto buf_st = &st->rx_buf;
auto usart = sp->usart;
if (usart->rxDMA) {
auto buf_len = sp->rx_buffer.length;
auto dma = usart->rxDMA;
auto stream = usart->rxDMA_Stream;
_dma_clear(buf_st, buf_len, dma, stream);
} else {
_fifo_clear(buf_st);
}
}
static uint32_t stm32_serial_get_baudrate(void* ctx)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return 0;
auto sp = st->sp;
auto usart = sp->usart;
return stm32_usart_get_baudrate(usart);
}
static void stm32_serial_set_baudrate(void* ctx, uint32_t baudrate)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
auto sp = st->sp;
auto usart = sp->usart;
stm32_usart_set_baudrate(usart, baudrate);
}
static void stm32_serial_hw_option(void* ctx, uint32_t option)
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
auto sp = st->sp;
auto usart = sp->usart;
stm32_usart_set_hw_option(usart, option);
}
static void stm32_serial_set_idle_cb(void* ctx, void (*on_idle)())
{
auto st = (stm32_serial_state*)ctx;
if (!st) return;
st->callbacks.on_idle = on_idle;
uint32_t enabled = (on_idle != nullptr);
stm32_usart_set_idle_irq(st->sp->usart, enabled);
}
const etx_serial_driver_t STM32SerialDriver = {
.init = stm32_serial_init,
.deinit = stm32_serial_deinit,
.sendByte = stm32_serial_send_byte,
.sendBuffer = stm32_serial_send_buffer,
.txCompleted = stm32_serial_tx_completed,
.waitForTxCompleted = stm32_wait_tx_completed,
.enableRx = stm32_enable_rx,
.getByte = stm32_serial_get_byte,
.getLastByte = stm32_serial_get_last_byte,
.clearRxBuffer = stm32_serial_clear_rx_buffer,
.getBaudrate = stm32_serial_get_baudrate,
.setBaudrate = stm32_serial_set_baudrate,
.setPolarity = nullptr,
.setHWOption = stm32_serial_hw_option,
.setReceiveCb = nullptr, // TODO
.setIdleCb = stm32_serial_set_idle_cb,
.setBaudrateCb = nullptr,
};
@@ -0,0 +1,59 @@
/*
* Copyright (C) EdgeTx
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#pragma once
#include "stm32_usart_driver.h"
#include "hal/serial_driver.h"
// __DMA
#include "definitions.h"
// Serial buffer to be defined in boards
struct stm32_serial_buffer {
uint8_t* buffer;
uint32_t length;
};
// Serial port to be defined in boards
// (the board defines a buffer as well)
//
// etx_serial_driver.init() shall be passed
// this struct cast as (void*)
//
struct stm32_serial_port {
const stm32_usart_t* usart;
const stm32_serial_buffer rx_buffer;
const stm32_serial_buffer tx_buffer;
};
extern const etx_serial_driver_t STM32SerialDriver;
#define DEFINE_STM32_SERIAL_PORT(p,usart,rx_buf_len,tx_buf_len) \
static uint8_t p ## _RXBuffer[rx_buf_len] __DMA; \
static uint8_t p ## _TXBuffer[tx_buf_len] __DMA; \
static const stm32_serial_port p ## _STM32Serial = { \
&usart, \
{ p ## _RXBuffer, rx_buf_len }, \
{ p ## _TXBuffer, tx_buf_len }, \
}
#define REF_STM32_SERIAL_PORT(p) ((void*)& p ## _STM32Serial)
@@ -0,0 +1,510 @@
/*
* Copyright (C) EdgeTx
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "stm32_softserial_driver.h"
#include "stm32_exti_driver.h"
#include <string.h>
// constant TX bitlen, timer frequency is computed
// to reach the required baudrate
#define BITLEN 16
// RX state
static uint8_t rxBitCount;
static uint8_t rxByte;
// RX FIFO
static volatile uint8_t rxRidx;
static volatile uint8_t rxWidx;
static uint8_t *rxBuffer;
static uint32_t rxBufLen;
static const stm32_softserial_rx_port* _softserialPort;
static void _softserial_exti()
{
if (rxBitCount == 0) {
// enable timer counter
auto TIMx = _softserialPort->TIMx;
LL_TIM_SetAutoReload(TIMx, (BITLEN + BITLEN/2) - 1);
LL_TIM_EnableCounter(TIMx);
// disable start bit interrupt
LL_EXTI_DisableIT_0_31(_softserialPort->EXTI_Line);
}
}
static inline void _rx_fifo_clear()
{
rxWidx = 0;
rxRidx = 0;
}
static void _softserial_init_rx(const stm32_softserial_rx_port* port,
const etx_serial_init* params)
{
rxBitCount = 0;
rxBuffer = port->buffer.buffer;
rxBufLen = port->buffer.length;
_rx_fifo_clear();
// configure bit sample timer
LL_TIM_InitTypeDef timInit;
LL_TIM_StructInit(&timInit);
uint32_t freq = params->baudrate * 16;
if (!freq) return;
timInit.Prescaler = __LL_TIM_CALC_PSC(port->TIM_Freq, freq);
// TODO: enable_tim_clock(port->TIMx);
LL_TIM_Init(port->TIMx, &timInit);
LL_TIM_ClearFlag_UPDATE(port->TIMx);
LL_TIM_EnableIT_UPDATE(port->TIMx);
NVIC_SetPriority(port->TIM_IRQn, 0);
NVIC_EnableIRQ(port->TIM_IRQn);
LL_GPIO_InitTypeDef pinInit;
LL_GPIO_StructInit(&pinInit);
if (port->dir_GPIOx) {
pinInit.Pin = port->dir_Pin;
pinInit.Mode = LL_GPIO_MODE_OUTPUT;
LL_GPIO_Init(port->dir_GPIOx, &pinInit);
if (!port->dir_Input) {
LL_GPIO_ResetOutputPin(port->dir_GPIOx, port->dir_Pin);
} else {
LL_GPIO_SetOutputPin(port->dir_GPIOx, port->dir_Pin);
}
}
pinInit.Pin = port->GPIO_Pin;
pinInit.Mode = LL_GPIO_MODE_INPUT;
pinInit.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
pinInit.Pull = LL_GPIO_PULL_DOWN;
LL_GPIO_Init(port->GPIOx, &pinInit);
// Connect EXTI line to TELEMETRY RX pin
LL_SYSCFG_SetEXTISource(port->EXTI_Port, port->EXTI_SysLine);
// Configure EXTI for raising edge (start bit; assuming inverted serial)
_softserialPort = port;
stm32_exti_enable(port->EXTI_Line, LL_EXTI_TRIGGER_RISING, _softserial_exti);
}
static void _softserial_deinit_gpio(const stm32_softserial_rx_port* port)
{
// Reconfigure pin as input
LL_GPIO_InitTypeDef pinInit;
LL_GPIO_StructInit(&pinInit);
pinInit.Pin = port->GPIO_Pin;
pinInit.Mode = LL_GPIO_MODE_INPUT;
LL_GPIO_Init(port->GPIOx, &pinInit);
}
static void _softserial_deinit_rx(const stm32_softserial_rx_port* port)
{
stm32_exti_disable(port->EXTI_Line);
NVIC_DisableIRQ(port->TIM_IRQn);
LL_TIM_DeInit(port->TIMx);
}
static void* stm32_softserial_rx_init(void* hw_def, const etx_serial_init* params)
{
auto port = (const stm32_softserial_rx_port*)hw_def;
_softserial_init_rx(port, params);
return hw_def;
}
static void stm32_softserial_rx_deinit(void* ctx)
{
auto port = (const stm32_softserial_rx_port*)ctx;
if (port == _softserialPort) {
_softserial_deinit_rx(port);
}
_softserial_deinit_gpio(port);
_softserialPort = nullptr;
}
static inline bool _rx_fifo_full()
{
return ((rxWidx + 1) & (rxBufLen - 1)) == rxRidx;
}
static inline void _rx_fifo_push(uint8_t c)
{
rxBuffer[rxWidx] = c;
rxWidx = (rxWidx + 1) & (rxBufLen - 1);
}
static int stm32_softserial_rx_get_byte(void* ctx, uint8_t* data)
{
if (rxWidx == rxRidx) return 0;
*data = rxBuffer[rxRidx];
rxRidx = (rxRidx + 1) & (rxBufLen - 1);
return 1;
}
void stm32_softserial_rx_timer_isr(const stm32_softserial_rx_port* port)
{
auto TIMx = port->TIMx;
LL_TIM_ClearFlag_UPDATE(TIMx);
if (rxBitCount < 8) {
if (rxBitCount == 0) {
LL_TIM_SetAutoReload(TIMx, BITLEN - 1);
rxByte = 0;
}
else {
rxByte >>= 1;
}
if (LL_GPIO_IsInputPinSet(port->GPIOx, port->GPIO_Pin) == 0)
rxByte |= 0x80;
++rxBitCount;
}
else if (rxBitCount == 8) {
if (!_rx_fifo_full()) _rx_fifo_push(rxByte);
rxBitCount = 0;
// disable timer
LL_TIM_DisableCounter(TIMx);
// re-enable start bit interrupt
LL_EXTI_EnableIT_0_31(port->EXTI_Line);
}
}
static void stm32_softserial_rx_clear_rx_buffer(void* ctx)
{
rxWidx = 0;
rxRidx = 0;
}
const etx_serial_driver_t STM32SoftSerialRxDriver = {
.init = stm32_softserial_rx_init,
.deinit = stm32_softserial_rx_deinit,
.sendByte = nullptr,
.sendBuffer = nullptr,
.waitForTxCompleted = nullptr,
.enableRx = nullptr,
.getByte = stm32_softserial_rx_get_byte,
.getLastByte = nullptr,
.clearRxBuffer = stm32_softserial_rx_clear_rx_buffer,
.getBaudrate = nullptr,
.setReceiveCb = nullptr,
.setBaudrateCb = nullptr,
};
static inline void _set_level(stm32_softserial_tx_state* st, uint8_t v)
{
*st->pulse_ptr = v - 1;
#if defined(STM32_SUPPORT_32BIT_TIMERS)
st->pulse_ptr += st->pulse_inc;
#else
++st->pulse_ptr;
#endif
}
// TODO:
// - support for different word len / stop bit(s) / parity config
// - now: only 8N1 and 8E2
//
// max 11 changes 0 10 10 10 10 P 1
static void _conv_byte_8e2(stm32_softserial_tx_state* st, uint8_t b)
{
bool lev = 0;
uint8_t parity = 1;
uint8_t len = BITLEN; // max val: 10*16 < 256
for (uint8_t i = 0; i <= 9; i++) { // 8Bits + 1Parity
bool nlev = b & 1; // lsb first
parity = parity ^ (uint8_t)nlev;
if (lev == nlev) {
len += BITLEN;
} else {
_set_level(st, len);
len = BITLEN;
lev = nlev;
}
b = (b >> 1) | 0x80; // shift in ones for stop bit and parity
if (i == 7) b = b ^ parity; // lowest bit is one from previous line
}
// enlarge the last bit to be two stop bits long
_set_level(st, len + BITLEN);
// update size
--st->serial_size;
}
static void _conv_byte_8n1(stm32_softserial_tx_state* st, uint8_t b)
{
bool lev = 0;
uint8_t len = BITLEN; // max val: 10*16 < 256
for (uint8_t i = 0; i <= 8; i++) { // 8Bits
bool nlev = b & 1; // lsb first
if (lev == nlev) {
len += BITLEN;
} else {
_set_level(st, len);
len = BITLEN;
lev = nlev;
}
b = (b >> 1) | 0x80; // shift in ones for stop bit
}
// write the last bit
_set_level(st, len);
// update size
--st->serial_size;
}
// PXX1 PWM is encoded as a PWM signal
// with a fixed ON phase of 9us and a variable OFF phase
// depending on whether the bit is SET or RESET.
//
#define PXX1_FREQ 1000000 /* 1 MHz */
#define PXX1_PWM_ON 9 /* 9us */
#define PXX1_BIT_ZERO 16 /* 0 = 16us */
#define PXX1_BIT_ONE 24 /* 1 = 24us */
static void _conv_byte_pxx1(stm32_softserial_tx_state* st, uint8_t b)
{
uint32_t bits = st->serial_size < 8 ? st->serial_size : 8;
for (uint8_t i = 0; i < bits; i++) {
// MSB first
if (b & 0x80)
_set_level(st, PXX1_BIT_ONE);
else
_set_level(st, PXX1_BIT_ZERO);
// next bit
b <<= 1;
}
st->serial_size -= bits;
}
// stm32_pulse_timer_t based TX implementation
static void* stm32_softserial_tx_init(void* hw_def, const etx_serial_init* params)
{
auto port = (const stm32_softserial_tx_port*)hw_def;
// Init state
auto st = port->st;
memset(port->st, 0, sizeof(stm32_softserial_tx_state));
bool polarity = params->polarity == ETX_Pol_Normal;
uint32_t freq = params->baudrate * 16;
uint32_t ocmode = LL_TIM_OCMODE_TOGGLE;
uint32_t cmp_val = 0;
switch(params->encoding) {
case ETX_Encoding_8N1:
st->conv_byte = _conv_byte_8n1;
break;
case ETX_Encoding_8E2:
st->conv_byte = _conv_byte_8e2;
break;
case ETX_Encoding_PXX1_PWM:
st->conv_byte = _conv_byte_pxx1;
freq = PXX1_FREQ;
polarity = false;
ocmode = LL_TIM_OCMODE_PWM1;
cmp_val = PXX1_PWM_ON;
break;
default:
return nullptr;
}
// prevent dividing by 0 in stm32_pulse_init()
if (freq == 0) return nullptr;
// Use a variable timer frequency to keep bitlen constant (16)
auto tim = port->tim;
stm32_pulse_init(tim, freq);
stm32_pulse_config_output(tim, polarity, ocmode, cmp_val);
#if defined(STM32_SUPPORT_32BIT_TIMERS)
if (IS_TIM_32B_COUNTER_INSTANCE(tim->TIMx)) {
st->pulse_inc = 2;
} else {
st->pulse_inc = 1;
}
#endif
return hw_def;
}
static void stm32_softserial_tx_deinit(void* ctx)
{
auto port = (const stm32_softserial_tx_port*)ctx;
stm32_pulse_deinit(port->tim);
}
static void stm32_softserial_tx_wait(void* ctx)
{
auto port = (const stm32_softserial_tx_port*)ctx;
auto timer = port->tim;
stm32_pulse_wait_for_completed(timer);
}
static void stm32_softserial_tx_send_buffer(void* ctx, const uint8_t* data, uint32_t size);
static void stm32_softserial_tx_send_byte(void* ctx, uint8_t byte)
{
stm32_softserial_tx_send_buffer(ctx, &byte, 1);
stm32_softserial_tx_wait(ctx);
}
static uint16_t _fill_pulses(stm32_softserial_tx_state* st)
{
st->pulse_ptr = (uint16_t*)st->pulse_buffer;
bool is_pxx1 = (st->conv_byte == _conv_byte_pxx1);
uint32_t size = st->serial_size;
// PXX1 uses a # bits rather than bytes
if (is_pxx1) {
//
size = (size + 7) / 8;
if (size > STM32_SOFTSERIAL_MAX_PULSES_TRANSITIONS / 8) // 12
size = STM32_SOFTSERIAL_MAX_PULSES_TRANSITIONS / 8; // 12
} else if (size > STM32_SOFTSERIAL_BUFFERED_PULSES) {
size = STM32_SOFTSERIAL_BUFFERED_PULSES;
}
for (uint8_t i = 0; i < size; i++) {
st->conv_byte(st, *st->serial_data++);
}
uint16_t length = st->pulse_ptr - (uint16_t*)st->pulse_buffer;
#if defined(STM32_SUPPORT_32BIT_TIMERS)
if (st->pulse_inc == 2) length >>= 1;
#endif
return length;
}
static bool stm32_softserial_tx_dma_tc_isr(void* ctx)
{
auto port = (const stm32_softserial_tx_port*)ctx;
auto tim = port->tim;
auto st = port->st;
if (!st->serial_size)
return false;
uint16_t length = _fill_pulses(st);
LL_DMA_SetDataLength(tim->DMAx, tim->DMA_Stream, length);
LL_DMA_EnableStream(tim->DMAx, tim->DMA_Stream);
return true;
}
static void stm32_softserial_tx_send_buffer(void* ctx, const uint8_t* data, uint32_t size)
{
auto port = (const stm32_softserial_tx_port*)ctx;
auto timer = port->tim;
if (!stm32_pulse_if_not_running_disable(timer))
return;
// transform serial payload into timer pulses/length
auto st = port->st;
st->serial_data = data;
st->serial_size = size;
auto length = _fill_pulses(st);
if (st->serial_size > 0 && timer->DMA_TC_CallbackPtr) {
auto closure = timer->DMA_TC_CallbackPtr;
closure->cb = stm32_softserial_tx_dma_tc_isr;
closure->ctx = ctx;
}
// Start DMA request and re-enable timer
const void* pulses = st->pulse_buffer;
// TODO: save encoding
uint32_t ocmode = LL_TIM_OCMODE_TOGGLE;
uint32_t cmp_val = 0;
// dirty hack...
if (st->conv_byte == _conv_byte_pxx1) {
ocmode = LL_TIM_OCMODE_PWM1;
cmp_val = PXX1_PWM_ON;
}
stm32_pulse_start_dma_req(timer, pulses, length, ocmode, cmp_val);
}
void stm32_softserial_set_polarity(void* ctx, uint8_t polarity)
{
auto port = (const stm32_softserial_tx_port*)ctx;
auto timer = port->tim;
stm32_pulse_set_polarity(timer, polarity);
}
const etx_serial_driver_t STM32SoftSerialTxDriver = {
.init = stm32_softserial_tx_init,
.deinit = stm32_softserial_tx_deinit,
.sendByte = stm32_softserial_tx_send_byte,
.sendBuffer = stm32_softserial_tx_send_buffer,
.txCompleted = nullptr,
.waitForTxCompleted = stm32_softserial_tx_wait,
.enableRx = nullptr, // TODO: combine with EXTI / Timer implementation? (S.PORT INV RX)
.getByte = nullptr,
.clearRxBuffer = nullptr, // TODO: same as enableRx
.getBaudrate = nullptr,
.setBaudrate = nullptr,
.setPolarity = stm32_softserial_set_polarity,
.setHWOption = nullptr,
.setReceiveCb = nullptr,
.setIdleCb = nullptr,
.setBaudrateCb = nullptr,
};
@@ -0,0 +1,107 @@
/*
* Copyright (C) EdgeTx
*
* Based on code named
* opentx - https://github.com/opentx/opentx
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "stm32_serial_driver.h"
#include "stm32_pulse_driver.h"
//
// RX soft-serial
//
// Warning: only a single instance can be
// used at the same time.
//
// etx_serial_driver.init() shall be passed
// this struct cast as (void*)
//
struct stm32_softserial_rx_port {
GPIO_TypeDef* GPIOx;
uint32_t GPIO_Pin;
TIM_TypeDef* TIMx;
uint32_t TIM_Freq;
IRQn_Type TIM_IRQn;
uint32_t EXTI_Port;
uint32_t EXTI_SysLine;
uint32_t EXTI_Line;
// Input/output direction pin
GPIO_TypeDef* dir_GPIOx;
uint32_t dir_Pin;
uint32_t dir_Input;
const stm32_serial_buffer buffer;
};
void stm32_softserial_rx_timer_isr(const stm32_softserial_rx_port* port);
extern const etx_serial_driver_t STM32SoftSerialRxDriver;
//
// TX soft-serial
//
#define STM32_SOFTSERIAL_BUFFERED_PULSES 8
// Max 12 toggles per serial byte
#define STM32_SOFTSERIAL_MAX_PULSES_TRANSITIONS \
(12 * STM32_SOFTSERIAL_BUFFERED_PULSES)
#if defined(STM32_SUPPORT_32BIT_TIMERS)
typedef uint32_t stm32_softserial_pulse_t;
#else
typedef uint16_t stm32_softserial_pulse_t;
#endif
struct stm32_softserial_tx_state;
typedef void (*stm32_softserial_conv_byte_fct)(stm32_softserial_tx_state*, uint8_t);
struct stm32_softserial_tx_state {
stm32_softserial_conv_byte_fct conv_byte;
stm32_softserial_pulse_t pulse_buffer[STM32_SOFTSERIAL_MAX_PULSES_TRANSITIONS];
uint16_t* pulse_ptr;
#if defined(STM32_SUPPORT_32BIT_TIMERS)
uint8_t pulse_inc;
#endif
const uint8_t* serial_data;
volatile uint32_t serial_size;
};
// etx_serial_driver.init() shall be passed
// this struct cast as (void*)
//
struct stm32_softserial_tx_port {
const stm32_pulse_timer_t* tim;
stm32_softserial_tx_state* st;
};
#define DEFINE_STM32_SOFTSERIAL_PORT(p,timer) \
static stm32_softserial_tx_state p ## _SoftserialState __DMA; \
static const stm32_softserial_tx_port p ## _STM32Softserial = { \
&timer, \
& p ## _SoftserialState, \
}
#define REF_STM32_SOFTSERIAL_PORT(p) ((void*)& p ## _STM32Softserial)
extern const etx_serial_driver_t STM32SoftSerialTxDriver;
@@ -19,8 +19,9 @@
* GNU General Public License for more details.
*/
#include "stm32_hal_ll.h"
#include "stm32_usart_driver.h"
#include "stm32_dma.h"
#include <string.h>
// WARNING:
@@ -51,6 +52,28 @@ static void _enable_usart_irq(const stm32_usart_t* usart)
NVIC_EnableIRQ(usart->IRQn);
}
static void _enable_tx_dma_irq(const stm32_usart_t* usart)
{
NVIC_SetPriority(usart->txDMA_IRQn, usart->txDMA_IRQ_Prio);
NVIC_EnableIRQ(usart->txDMA_IRQn);
}
static inline void _half_duplex_input(const stm32_usart_t* usart)
{
if (usart->set_input) {
usart->set_input(true);
LL_USART_EnableDirectionRx(usart->USARTx);
}
}
static inline void _half_duplex_output(const stm32_usart_t* usart)
{
if (usart->set_input) {
usart->set_input(false);
LL_USART_DisableDirectionRx(usart->USARTx);
}
}
void stm32_usart_enable_tx_irq(const stm32_usart_t* usart)
{
if (LL_USART_IsEnabledDMAReq_TX(usart->USARTx)) {
@@ -65,6 +88,19 @@ void stm32_usart_enable_tx_irq(const stm32_usart_t* usart)
LL_USART_EnableIT_TXE(usart->USARTx);
}
void stm32_usart_set_idle_irq(const stm32_usart_t* usart, uint32_t enabled)
{
if (enabled) {
LL_USART_EnableIT_IDLE(usart->USARTx);
_enable_usart_irq(usart);
} else {
LL_USART_DisableIT_IDLE(usart->USARTx);
// Let's assume the port will be disabled soon
// and we don't need to figure out whether or
// not the IRQ needs to be disabled
}
}
static void enable_usart_clock(USART_TypeDef* USARTx)
{
if (USARTx == USART1) {
@@ -106,15 +142,39 @@ static void disable_usart_clock(USART_TypeDef* USARTx)
}
void stm32_usart_init_rx_dma(const stm32_usart_t* usart, void* buffer, uint32_t length)
static uint32_t _get_pin_speed(uint32_t baudrate)
{
// 1 Mbps and above
if (baudrate >= 1000000) {
return LL_GPIO_SPEED_FREQ_VERY_HIGH;
}
// 400kbps and above
else if (baudrate >= 400000) {
return LL_GPIO_SPEED_FREQ_HIGH;
}
// under 400kbps
return LL_GPIO_SPEED_FREQ_LOW;
}
static uint32_t _get_usart_af(USART_TypeDef* USARTx)
{
if (USARTx == USART1 || USARTx == USART2 || USARTx == USART3) {
return LL_GPIO_AF_7;
} else {
return LL_GPIO_AF_8;
}
}
void stm32_usart_init_rx_dma(const stm32_usart_t* usart, const void* buffer, uint32_t length)
{
if (!usart->rxDMA) return;
// Disable IRQ based RX
LL_USART_DisableIT_RXNE(usart->USARTx);
// In case TX DMA is used, disable the ISR completely
if (usart->txDMA) {
// In case TX DMA is used and IDLE IRQ is not, disable the ISR completely
if (usart->txDMA && !LL_USART_IsEnabledIT_IDLE(usart->USARTx)) {
NVIC_DisableIRQ(usart->IRQn);
}
@@ -151,69 +211,90 @@ void stm32_usart_deinit_rx_dma(const stm32_usart_t* usart)
}
}
// TODO: probably needs to be a separate API on the serial driver
//
// - USART_OneBitMethodCmd(TELEMETRY_USART, ENABLE);
// OBSOLETE:
// - asymmetric bitrates for half-duplex (GHOST)
// - ??? ability to switch RX DMA OFF ??? (-> X12S)
//
void stm32_usart_init(const stm32_usart_t* usart, const etx_serial_init* params)
{
enable_usart_clock(usart->USARTx);
LL_USART_DeInit(usart->USARTx);
LL_GPIO_Init(usart->GPIOx, (LL_GPIO_InitTypeDef*)usart->pinInit);
// TODO: enable GPIO clock
LL_GPIO_InitTypeDef pinInit;
LL_GPIO_StructInit(&pinInit);
pinInit.Pin = usart->GPIO_Pin;
pinInit.Mode = LL_GPIO_MODE_ALTERNATE;
pinInit.Speed = _get_pin_speed(params->baudrate);
pinInit.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
pinInit.Pull = LL_GPIO_PULL_UP;
pinInit.Alternate = _get_usart_af(usart->USARTx);
LL_GPIO_Init(usart->GPIOx, &pinInit);
LL_USART_InitTypeDef usartInit;
LL_USART_StructInit(&usartInit);
usartInit.BaudRate = params->baudrate;
usartInit.Parity = LL_USART_PARITY_NONE;
usartInit.DataWidth = LL_USART_DATAWIDTH_8B;
uint32_t parity = LL_USART_PARITY_NONE;
switch(params->parity){
case ETX_Parity_None:
parity = LL_USART_PARITY_NONE;
break;
case ETX_Parity_Even:
parity = LL_USART_PARITY_EVEN;
break;
case ETX_Parity_Odd:
parity = LL_USART_PARITY_ODD;
break;
}
usartInit.Parity = parity;
switch(params->encoding){
uint16_t stop_bits = LL_USART_STOPBITS_1;
switch(params->stop_bits) {
case ETX_StopBits_One:
stop_bits = LL_USART_STOPBITS_1;
break;
case ETX_StopBits_OneAndHalf:
stop_bits = LL_USART_STOPBITS_1_5;
break;
case ETX_StopBits_Two:
stop_bits = LL_USART_STOPBITS_2;
break;
}
usartInit.StopBits = stop_bits;
case ETX_Encoding_8E2:
usartInit.Parity = LL_USART_PARITY_EVEN;
usartInit.StopBits = LL_USART_STOPBITS_2;
usartInit.DataWidth = LL_USART_DATAWIDTH_9B;
break;
if (params->word_length == ETX_WordLength_9) {
usartInit.DataWidth = LL_USART_DATAWIDTH_9B;
} else {
usartInit.DataWidth = LL_USART_DATAWIDTH_8B;
case ETX_Encoding_8N1:
break;
default:
// TODO: return some error
return;
}
usartInit.HardwareFlowControl = LL_USART_HWCONTROL_NONE;
usartInit.TransferDirection = LL_USART_DIRECTION_TX_RX;
usartInit.TransferDirection = LL_USART_DIRECTION_NONE;
if (params->direction & ETX_Dir_RX)
usartInit.TransferDirection |= LL_USART_DIRECTION_RX;
if (params->direction & ETX_Dir_TX)
usartInit.TransferDirection |= LL_USART_DIRECTION_TX;
LL_USART_Init(usart->USARTx, &usartInit);
LL_USART_Enable(usart->USARTx);
// Enable TX DMA request
if (usart->txDMA) {
LL_USART_EnableDMAReq_TX(usart->USARTx);
if (params->direction & ETX_Dir_TX) {
// Enable TX DMA request
if (usart->txDMA) {
LL_USART_EnableDMAReq_TX(usart->USARTx);
// 2-wire half-duplex: setup TX DMA IRQ
if (usart->set_input && (int32_t)(usart->txDMA_IRQn) >= 0) {
_enable_tx_dma_irq(usart);
}
}
}
// Enable RX IRQ
if (params->rx_enable) {
if (params->direction & ETX_Dir_RX) {
// IRQ based RX
LL_USART_EnableIT_RXNE(usart->USARTx);
// half-duplex: start in input mode
if (usart->set_input)
_half_duplex_input(usart);
}
if (!usart->txDMA || (params->rx_enable && !usart->rxDMA)) {
if (((params->direction & ETX_Dir_TX) && !usart->txDMA) ||
LL_USART_IsEnabledIT_RXNE(usart->USARTx)) {
_enable_usart_irq(usart);
}
}
@@ -235,7 +316,8 @@ void stm32_usart_deinit(const stm32_usart_t* usart)
// Reconfigure pin as output
LL_GPIO_InitTypeDef pinInit;
memcpy(&pinInit, usart->pinInit, sizeof(LL_GPIO_InitTypeDef));
LL_GPIO_StructInit(&pinInit);
pinInit.Pin = usart->GPIO_Pin;
pinInit.Mode = LL_GPIO_MODE_OUTPUT;
pinInit.Pull = LL_GPIO_PULL_NO;
pinInit.Alternate = LL_GPIO_AF_0;
@@ -247,11 +329,22 @@ void stm32_usart_send_byte(const stm32_usart_t* usart, uint8_t byte)
{
// TODO: split into 2 steps to avoid blocking on send
while (!LL_USART_IsActiveFlag_TXE(usart->USARTx));
if (usart->set_input) {
_half_duplex_output(usart);
// switch back to input after TC
LL_USART_ClearFlag_TC(usart->USARTx);
LL_USART_EnableIT_TC(usart->USARTx);
}
LL_USART_TransmitData8(usart->USARTx, byte);
}
void stm32_usart_send_buffer(const stm32_usart_t* usart, const uint8_t * data, uint32_t size)
{
_half_duplex_output(usart);
if (usart->txDMA) {
LL_DMA_DeInit(usart->txDMA, usart->txDMA_Stream);
@@ -267,6 +360,10 @@ void stm32_usart_send_buffer(const stm32_usart_t* usart, const uint8_t * data, u
dmaInit.Priority = LL_DMA_PRIORITY_VERYHIGH; // TODO: make it configurable
LL_DMA_Init(usart->txDMA, usart->txDMA_Stream, &dmaInit);
if (usart->set_input && (int32_t)(usart->txDMA_IRQn) >= 0) {
LL_DMA_EnableIT_TC(usart->txDMA, usart->txDMA_Stream);
}
LL_DMA_EnableStream(usart->txDMA, usart->txDMA_Stream);
return;
@@ -278,6 +375,20 @@ void stm32_usart_send_buffer(const stm32_usart_t* usart, const uint8_t * data, u
}
}
uint8_t stm32_usart_tx_completed(const stm32_usart_t* usart)
{
if (LL_USART_IsEnabledDMAReq_TX(usart->USARTx)) {
// TX DMA is configured, let's check if the stream is currently enabled
if (LL_DMA_IsEnabledStream(usart->txDMA, usart->txDMA_Stream) ||
!LL_USART_IsActiveFlag_TXE(usart->USARTx))
return 0;
} else if (LL_USART_IsEnabledIT_TXE(usart->USARTx)) {
return 0;
}
return LL_USART_IsActiveFlag_TXE(usart->USARTx);
}
void stm32_usart_wait_for_tx_dma(const stm32_usart_t* usart)
{
// TODO: check if everything is properly initialised, this seems to block when
@@ -286,29 +397,133 @@ void stm32_usart_wait_for_tx_dma(const stm32_usart_t* usart)
switch(usart->txDMA_Stream) {
case LL_DMA_STREAM_1:
while (LL_DMA_IsActiveFlag_TC1(usart->txDMA));
while (!LL_DMA_IsActiveFlag_TC1(usart->txDMA));
LL_DMA_ClearFlag_TC1(usart->txDMA);
break;
case LL_DMA_STREAM_3:
while (LL_DMA_IsActiveFlag_TC3(usart->txDMA));
while (!LL_DMA_IsActiveFlag_TC3(usart->txDMA));
LL_DMA_ClearFlag_TC3(usart->txDMA);
break;
case LL_DMA_STREAM_5:
while (LL_DMA_IsActiveFlag_TC5(usart->txDMA));
while (!LL_DMA_IsActiveFlag_TC5(usart->txDMA));
LL_DMA_ClearFlag_TC5(usart->txDMA);
break;
case LL_DMA_STREAM_6:
while (LL_DMA_IsActiveFlag_TC6(usart->txDMA));
while (!LL_DMA_IsActiveFlag_TC6(usart->txDMA));
LL_DMA_ClearFlag_TC6(usart->txDMA);
break;
case LL_DMA_STREAM_7:
while (LL_DMA_IsActiveFlag_TC7(usart->txDMA));
while (!LL_DMA_IsActiveFlag_TC7(usart->txDMA));
LL_DMA_ClearFlag_TC7(usart->txDMA);
break;
}
}
}
void stm32_usart_enable_rx(const stm32_usart_t* usart)
{
_half_duplex_input(usart);
}
// from stm32f4xx_ll_usart.c
static uint32_t _get_usart_periph_clock(USART_TypeDef* USARTx)
{
uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO;
LL_RCC_ClocksTypeDef rcc_clocks;
LL_RCC_GetSystemClocksFreq(&rcc_clocks);
if (USARTx == USART1) {
periphclk = rcc_clocks.PCLK2_Frequency;
} else if (USARTx == USART2) {
periphclk = rcc_clocks.PCLK1_Frequency;
}
#if defined(USART3)
else if (USARTx == USART3) {
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* USART3 */
#if defined(USART6)
else if (USARTx == USART6) {
periphclk = rcc_clocks.PCLK2_Frequency;
}
#endif /* USART6 */
#if defined(UART4)
else if (USARTx == UART4) {
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* UART4 */
#if defined(UART5)
else if (USARTx == UART5) {
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* UART5 */
#if defined(UART7)
else if (USARTx == UART7) {
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* UART7 */
#if defined(UART8)
else if (USARTx == UART8) {
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* UART8 */
#if defined(UART9)
else if (USARTx == UART9) {
periphclk = rcc_clocks.PCLK2_Frequency;
}
#endif /* UART9 */
#if defined(UART10)
else if (USARTx == UART10) {
periphclk = rcc_clocks.PCLK2_Frequency;
}
#endif /* UART10 */
return periphclk;
}
uint32_t stm32_usart_get_baudrate(const stm32_usart_t* usart)
{
auto periphclk = _get_usart_periph_clock(usart->USARTx);
auto oversampling = LL_USART_GetOverSampling(usart->USARTx);
return LL_USART_GetBaudRate(usart->USARTx, periphclk, oversampling);
}
void stm32_usart_set_baudrate(const stm32_usart_t* usart, uint32_t baudrate)
{
auto periphclk = _get_usart_periph_clock(usart->USARTx);
auto oversampling = LL_USART_GetOverSampling(usart->USARTx);
LL_USART_SetBaudRate(usart->USARTx, periphclk, oversampling, baudrate);
// update pin speed accordingly (must be done one-by-one)
uint32_t pin_speed = _get_pin_speed(baudrate);
uint32_t pindef = usart->GPIO_Pin;
// loop borrowed from LL_GPIO_init()
uint32_t pinpos = POSITION_VAL(pindef);
uint32_t currentpin = 0;
while ((pindef >> pinpos) != 0) {
currentpin = pindef & (1 << pinpos);
if (currentpin) LL_GPIO_SetPinSpeed(usart->GPIOx, currentpin, pin_speed);
pinpos++;
}
}
void stm32_usart_set_hw_option(const stm32_usart_t* usart, uint32_t option)
{
switch(option) {
case ETX_HWOption_OVER8: {
// BRR depends on oversampling as well, so we must
// re-compute the baudrate as well.
auto baudrate = stm32_usart_get_baudrate(usart);
LL_USART_SetOverSampling(usart->USARTx, LL_USART_OVERSAMPLING_8);
stm32_usart_set_baudrate(usart, baudrate);
} break;
case ETX_HWOption_ONEBIT:
LL_USART_EnableOneBitSamp(usart->USARTx);
break;
}
}
#define USART_FLAG_ERRORS \
(LL_USART_SR_ORE | LL_USART_SR_NE | LL_USART_SR_FE | LL_USART_SR_PE)
@@ -316,6 +531,26 @@ void stm32_usart_isr(const stm32_usart_t* usart, etx_serial_callbacks_t* cb)
{
uint32_t status = LL_USART_ReadReg(usart->USARTx, SR);
// cache these first, as RXNE might clear SR
uint32_t idle = (status & LL_USART_SR_IDLE);
uint32_t txe = (status & LL_USART_SR_TXE);
// TC is only enabled with 2-wire half-duplex when TX DMA was in use
if (LL_USART_IsEnabledIT_TC(usart->USARTx) && (status & LL_USART_SR_TC)) {
// disable TC IRQ
LL_USART_DisableIT_TC(usart->USARTx);
// switch to input
_half_duplex_input(usart);
// and drain RX side first
while (status & LL_USART_SR_RXNE) {
status = LL_USART_ReadReg(usart->USARTx, DR);
status = LL_USART_ReadReg(usart->USARTx, SR);
}
}
// Receive: do it first as it is more time critical
if (LL_USART_IsEnabledIT_RXNE(usart->USARTx)) {
@@ -339,7 +574,7 @@ void stm32_usart_isr(const stm32_usart_t* usart, etx_serial_callbacks_t* cb)
}
// IRQ based send: TXE IRQ is enabled only during transfer
if (LL_USART_IsEnabledIT_TXE(usart->USARTx) && (status & LL_USART_SR_TXE)) {
if (LL_USART_IsEnabledIT_TXE(usart->USARTx) && txe) {
uint8_t data;
if (cb->on_send && cb->on_send(&data)) {
@@ -348,4 +583,27 @@ void stm32_usart_isr(const stm32_usart_t* usart, etx_serial_callbacks_t* cb)
LL_USART_DisableIT_TXE(usart->USARTx);
}
}
if (LL_USART_IsEnabledIT_IDLE(usart->USARTx) && idle) {
// SR clear sequence
status = LL_USART_ReadReg(usart->USARTx, DR);
if (cb->on_idle) cb->on_idle();
}
}
void stm32_usart_tx_dma_isr(const stm32_usart_t* usart)
{
if (!stm32_dma_check_tc_flag(usart->txDMA, usart->txDMA_Stream))
return;
auto USARTx = usart->USARTx;
// clear TC flag before enabling USART TC interrupt:
// -> TC flag will be re-triggered once the last byte which has
// just been transfered from DMA to USART will be transmitted,
// thus triggering TELEMETRY_USART_IRQHandler(), which will
// switch from output to input mode.
//
LL_USART_ClearFlag_TC(USARTx);
LL_USART_EnableIT_TC(USARTx);
}
@@ -25,12 +25,14 @@
#include "hal/serial_driver.h"
#include "stm32_hal_ll.h"
typedef void (*pin_setter_t)(uint8_t enable);
struct stm32_usart_t {
// USART defs
USART_TypeDef* USARTx;
GPIO_TypeDef* GPIOx;
const LL_GPIO_InitTypeDef* pinInit;
uint32_t GPIO_Pin;
// USART IRQ
IRQn_Type IRQn;
@@ -45,15 +47,26 @@ struct stm32_usart_t {
DMA_TypeDef* rxDMA;
uint32_t rxDMA_Stream;
uint32_t rxDMA_Channel;
// 2-wire Half-duplex settings (uses direction pin)
pin_setter_t set_input;
IRQn_Type txDMA_IRQn;
uint8_t txDMA_IRQ_Prio;
};
void stm32_usart_init(const stm32_usart_t* usart, const etx_serial_init* params);
void stm32_usart_init_rx_dma(const stm32_usart_t* usart, void* buffer, uint32_t length);
void stm32_usart_init_rx_dma(const stm32_usart_t* usart, const void* buffer, uint32_t length);
void stm32_usart_enable_tx_irq(const stm32_usart_t* usart);
void stm32_usart_set_idle_irq(const stm32_usart_t* usart, uint32_t enabled);
void stm32_usart_deinit(const stm32_usart_t* usart);
void stm32_usart_deinit_rx_dma(const stm32_usart_t* usart);
void stm32_usart_send_byte(const stm32_usart_t* usart, uint8_t byte);
void stm32_usart_send_buffer(const stm32_usart_t* usart, const uint8_t * data, uint32_t size);
uint8_t stm32_usart_tx_completed(const stm32_usart_t* usart);
void stm32_usart_wait_for_tx_dma(const stm32_usart_t* usart);
void stm32_usart_enable_rx(const stm32_usart_t* usart);
uint32_t stm32_usart_get_baudrate(const stm32_usart_t* usart);
void stm32_usart_set_baudrate(const stm32_usart_t* usart, uint32_t baudrate);
void stm32_usart_set_hw_option(const stm32_usart_t* usart, uint32_t option);
void stm32_usart_isr(const stm32_usart_t* usart, etx_serial_callbacks_t* cb);
void stm32_usart_tx_dma_isr(const stm32_usart_t* usart);
@@ -21,8 +21,6 @@
#include "opentx.h"
extern void flysky_hall_stick_loop( void );
// Start TIMER at 2000000Hz
void init2MhzTimer()
{
@@ -32,10 +30,10 @@ void init2MhzTimer()
TIMER_2MHz_TIMER->CR1 = TIM_CR1_CEN;
}
// Start TIMER at 1000Hz
void init1msTimer()
// Start TIMER at 200Hz
void init5msTimer()
{
INTERRUPT_xMS_TIMER->ARR = 999; // 1mS in uS
INTERRUPT_xMS_TIMER->ARR = 4999; // 5mS in uS
INTERRUPT_xMS_TIMER->PSC = (PERI1_FREQUENCY * TIMER_MULT_APB1) / 1000000 - 1; // 1uS
INTERRUPT_xMS_TIMER->CCER = 0;
INTERRUPT_xMS_TIMER->CCMR1 = 0;
@@ -46,7 +44,7 @@ void init1msTimer()
NVIC_SetPriority(INTERRUPT_xMS_IRQn, 4);
}
void stop1msTimer()
void stop5msTimer()
{
INTERRUPT_xMS_TIMER->CR1 = 0; // stop timer
NVIC_DisableIRQ(INTERRUPT_xMS_IRQn);
@@ -59,33 +57,20 @@ void watchdogSuspend(uint32_t timeout)
watchdogTimeout = timeout;
}
void interrupt1ms()
static void interrupt5ms()
{
static uint8_t pre_scale; // Used to get 10 Hz counter
++pre_scale;
// 1 ms loop
#if not defined(SIMU) && (defined(RADIO_FAMILY_T16) || defined(PCBNV14))
if (globalData.flyskygimbals)
{
flysky_hall_stick_loop();
}
#endif
// 5ms loop
if (pre_scale == 5 || pre_scale == 10) {
#if defined(HAPTIC)
DEBUG_TIMER_START(debugTimerHaptic);
HAPTIC_HEARTBEAT();
DEBUG_TIMER_STOP(debugTimerHaptic);
DEBUG_TIMER_START(debugTimerHaptic);
HAPTIC_HEARTBEAT();
DEBUG_TIMER_STOP(debugTimerHaptic);
#endif
}
// 10ms loop
if (pre_scale == 10) {
pre_scale = 0;
if (pre_scale & 1) {
if (watchdogTimeout) {
watchdogTimeout -= 1;
WDG_RESET(); // Retrigger hardware watchdog
@@ -101,6 +86,6 @@ void interrupt1ms()
extern "C" void INTERRUPT_xMS_IRQHandler()
{
INTERRUPT_xMS_TIMER->SR &= ~TIM_SR_UIF;
interrupt1ms();
DEBUG_INTERRUPT(INT_1MS);
interrupt5ms();
DEBUG_INTERRUPT(INT_5MS);
}
@@ -31,8 +31,8 @@ uint16_t getTmr2MHz();
#include "hal.h"
void init2MhzTimer();
void init1msTimer();
void stop1msTimer();
void init5msTimer();
void stop5msTimer();
static inline uint16_t getTmr2MHz() { return TIMER_2MHz_TIMER->CNT; }
@@ -143,7 +143,7 @@ static void _init_trainer_capture(const stm32_pulse_timer_t* tim)
_trainer_timer = tim;
_trainer_timer_isr = trainer_in_isr;
stm32_pulse_init(tim);
stm32_pulse_init(tim, 0);
stm32_pulse_config_input(tim);
switch (tim->TIM_Channel) {
@@ -171,13 +171,14 @@ static const stm32_pulse_timer_t trainerOutputTimer = {
.GPIO_Pin = TRAINER_OUT_GPIO_PIN,
.GPIO_Alternate = TRAINER_GPIO_AF,
.TIMx = TRAINER_TIMER,
.TIM_Prescaler = __LL_TIM_CALC_PSC(TRAINER_TIMER_FREQ, 2000000),
.TIM_Freq = TRAINER_TIMER_FREQ,
.TIM_Channel = TRAINER_OUT_TIMER_Channel,
.TIM_IRQn = TRAINER_TIMER_IRQn,
.DMAx = nullptr,
.DMA_Stream = 0,
.DMA_Channel = 0,
.DMA_IRQn = (IRQn_Type)0,
.DMA_TC_CallbackPtr = nullptr,
};
static void trainerSendNextFrame()
@@ -228,7 +229,7 @@ void init_trainer_ppm()
_trainer_timer = &trainerOutputTimer;
_trainer_timer_isr = trainer_out_isr;
stm32_pulse_init(&trainerOutputTimer);
stm32_pulse_init(&trainerOutputTimer, 0);
stm32_pulse_config_output(&trainerOutputTimer, GET_TRAINER_PPM_POLARITY(),
LL_TIM_OCMODE_PWM1, GET_TRAINER_PPM_DELAY() * 2);
@@ -248,13 +249,14 @@ static const stm32_pulse_timer_t trainerInputTimer = {
.GPIO_Pin = TRAINER_IN_GPIO_PIN,
.GPIO_Alternate = TRAINER_GPIO_AF,
.TIMx = TRAINER_TIMER,
.TIM_Prescaler = __LL_TIM_CALC_PSC(TRAINER_TIMER_FREQ, 2000000),
.TIM_Freq = TRAINER_TIMER_FREQ,
.TIM_Channel = TRAINER_IN_TIMER_Channel,
.TIM_IRQn = TRAINER_TIMER_IRQn,
.DMAx = nullptr,
.DMA_Stream = 0,
.DMA_Channel = 0,
.DMA_IRQn = (IRQn_Type)0,
.DMA_TC_CallbackPtr = nullptr,
};
void init_trainer_capture()
@@ -309,13 +311,14 @@ static const stm32_pulse_timer_t trainerModuleTimer = {
.GPIO_Pin = TRAINER_MODULE_CPPM_GPIO_PIN,
.GPIO_Alternate = TRAINER_MODULE_CPPM_GPIO_AF,
.TIMx = TRAINER_MODULE_CPPM_TIMER,
.TIM_Prescaler = __LL_TIM_CALC_PSC(TRAINER_MODULE_CPPM_FREQ, 2000000),
.TIM_Freq = TRAINER_MODULE_CPPM_FREQ,
.TIM_Channel = TRAINER_MODULE_CPPM_TIMER_Channel,
.TIM_IRQn = TRAINER_MODULE_CPPM_TIMER_IRQn,
.DMAx = nullptr,
.DMA_Stream = 0,
.DMA_Channel = 0,
.DMA_IRQn = (IRQn_Type)0,
.DMA_TC_CallbackPtr = nullptr,
};
void init_trainer_module_cppm()
@@ -344,38 +347,39 @@ extern "C" void TRAINER_MODULE_CPPM_TIMER_IRQHandler()
const etx_serial_init sbusTrainerParams = {
.baudrate = SBUS_BAUDRATE,
.parity = ETX_Parity_Even,
.stop_bits = ETX_StopBits_Two,
.word_length = ETX_WordLength_9,
.rx_enable = true,
.encoding = ETX_Encoding_8E2,
.direction = ETX_Dir_RX,
.polarity = ETX_Pol_Normal,
};
// external module has a full-duplex USART
#if defined(EXTMODULE_USART)
#include "extmodule_serial_driver.h"
// external module may have a full-duplex USART
#if defined(EXTMODULE_USART) || defined(CONFIGURABLE_MODULE_PORT)
static void* sbus_trainer_ctx = nullptr;
#include "hal/module_port.h"
static etx_module_state_t* sbus_trainer_mod_st = nullptr;
void init_trainer_module_sbus()
{
auto serial_driver = extmoduleGetSerialPort();
sbus_trainer_ctx = serial_driver->init(&sbusTrainerParams);
if (sbus_trainer_mod_st) return;
sbus_trainer_mod_st = modulePortInitSerial(EXTERNAL_MODULE, ETX_MOD_PORT_UART,
&sbusTrainerParams);
}
void stop_trainer_module_sbus()
{
auto serial_driver = extmoduleGetSerialPort();
auto ctx = sbus_trainer_ctx;
if (ctx) {
sbus_trainer_ctx = nullptr;
serial_driver->deinit(ctx);
}
if (!sbus_trainer_mod_st) return;
modulePortDeInit(sbus_trainer_mod_st);
}
int trainerModuleSbusGetByte(uint8_t* data)
{
auto serial_driver = extmoduleGetSerialPort();
auto ctx = sbus_trainer_ctx;
if (!sbus_trainer_mod_st) return 0;
auto serial_driver = modulePortGetSerialDrv(sbus_trainer_mod_st->rx);
auto ctx = modulePortGetCtx(sbus_trainer_mod_st->rx);
if (ctx) {
return serial_driver->getByte(ctx, data);
}
@@ -384,21 +388,12 @@ int trainerModuleSbusGetByte(uint8_t* data)
}
#elif defined(TRAINER_MODULE_SBUS_USART)
#include "stm32_usart_driver.h"
static const LL_GPIO_InitTypeDef sbus_trainer_USART_PinDef = {
.Pin = TRAINER_MODULE_SBUS_GPIO_PIN,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_LOW,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
.Pull = LL_GPIO_PULL_UP,
.Alternate = TRAINER_MODULE_SBUS_GPIO_AF,
};
#include "stm32_serial_driver.h"
static const stm32_usart_t sbus_trainer_USART = {
.USARTx = TRAINER_MODULE_SBUS_USART,
.GPIOx = TRAINER_MODULE_SBUS_GPIO,
.pinInit = &sbus_trainer_USART_PinDef,
.GPIO_Pin = TRAINER_MODULE_SBUS_GPIO_PIN,
.IRQn = (IRQn_Type)-1,
.IRQ_Prio = 0,
.txDMA = nullptr,
@@ -409,23 +404,25 @@ static const stm32_usart_t sbus_trainer_USART = {
.rxDMA_Channel = TRAINER_MODULE_SBUS_DMA_CHANNEL,
};
static DMAFifo<32> sbus_trainer_fifo __DMA (TRAINER_MODULE_SBUS_DMA_STREAM);
DEFINE_STM32_SERIAL_PORT(SbusTrainer, sbus_trainer_USART, 32, 0);
static void* _sbus_trainer_ctx = nullptr;
void init_trainer_module_sbus()
{
stm32_usart_init(&sbus_trainer_USART, &sbusTrainerParams);
stm32_usart_init_rx_dma(&sbus_trainer_USART, sbus_trainer_fifo.buffer(),
sbus_trainer_fifo.size());
_sbus_trainer_ctx = STM32SerialDriver.init(REF_STM32_SERIAL_PORT(SbusTrainer),
&sbusTrainerParams);
}
void stop_trainer_module_sbus()
{
stm32_usart_deinit(&sbus_trainer_USART);
STM32SerialDriver.deinit(_sbus_trainer_ctx);
_sbus_trainer_ctx = nullptr;
}
int trainerModuleSbusGetByte(uint8_t* data)
{
return sbus_trainer_fifo.pop(*data);
return STM32SerialDriver.getByte(_sbus_trainer_ctx, data);
}
#else
@@ -296,8 +296,14 @@ void usbSerialSetBaudRateCb(void*, void (*cb)(uint32_t))
// ctrlLineStateCb = cb;
// }
static void* usbSerialInit(void*, const etx_serial_init*)
{
// always succeeds
return (void*)1;
}
static const etx_serial_driver_t usbSerialDriver = {
.init = nullptr,
.init = usbSerialInit,
.deinit = nullptr,
.sendByte = usbSerialPutc,
.sendBuffer = nullptr,
@@ -313,6 +319,7 @@ const etx_serial_port_t UsbSerialPort = {
"USB-VCP",
&usbSerialDriver,
nullptr,
nullptr,
};
// /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/