Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ADC DMA mode for STM32 F1, F2, F37, F4, F7 and L1 #982

Merged
merged 2 commits into from
Apr 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions examples/nucleo_f401re/adc_dma/adc_dma.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2023, Zühlke Engineering (Austria) GmbH
*
* This file is part of the modm project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

#ifndef EXAMPLE_ADCDMA_HPP
#define EXAMPLE_ADCDMA_HPP

#include <modm/platform.hpp>

template<class Adc, class DmaChannel>
class AdcDma
{
struct Dma
{
using AdcChannel =
typename DmaChannel::template RequestMapping<modm::platform::Peripheral::Adc1>::Channel;
static constexpr modm::platform::DmaBase::Request AdcRequest =
DmaChannel::template RequestMapping<modm::platform::Peripheral::Adc1>::Request;
};

public:
/**
* \brief initialize both adc and dma
* @tparam SystemClock
*/
template<class SystemClock>
static void
initialize(uintptr_t destination_ptr, size_t length,
modm::platform::DmaBase::Priority priority = modm::platform::DmaBase::Priority::Low,
modm::platform::DmaBase::CircularMode circularMode =
modm::platform::DmaBase::CircularMode::Enabled,
modm::platform::DmaBase::IrqHandler transferErrorCallback = nullptr,
modm::platform::DmaBase::IrqHandler halfCompletedCallback = nullptr,
modm::platform::DmaBase::IrqHandler completedCallback = nullptr)
{
Dma::AdcChannel::configure(
modm::platform::DmaBase::DataTransferDirection::PeripheralToMemory,
modm::platform::DmaBase::MemoryDataSize::HalfWord,
modm::platform::DmaBase::PeripheralDataSize::HalfWord,
modm::platform::DmaBase::MemoryIncrementMode::Increment,
modm::platform::DmaBase::PeripheralIncrementMode::Fixed, priority, circularMode);
Dma::AdcChannel::setPeripheralAddress(Adc::getDataRegisterAddress());
Dma::AdcChannel::setDataLength(length);
Dma::AdcChannel::setMemoryAddress(destination_ptr);

setTransferErrorCallback(transferErrorCallback);
setHalfCompletedConversionCallback(halfCompletedCallback);
setCompletedConversionCallback(completedCallback);

Dma::AdcChannel::template setPeripheralRequest<Dma::AdcRequest>();
Adc::disableDmaMode();
// Start Conversion if adc is enabled
if (Adc::getAdcEnabled())
{
Adc::enableDmaMode();
Adc::enableDmaRequests();
Dma::AdcChannel::start();
}
}

static void
setTransferErrorCallback(modm::platform::DmaBase::IrqHandler transferErrorCallback)
{
if (transferErrorCallback == nullptr) { return; }
Dma::AdcChannel::enableInterruptVector();
Dma::AdcChannel::enableInterrupt(modm::platform::DmaBase::InterruptEnable::TransferError |
modm::platform::DmaBase::InterruptEnable::DirectModeError);
Dma::AdcChannel::setTransferErrorIrqHandler(transferErrorCallback);
}

static void
setHalfCompletedConversionCallback(modm::platform::DmaBase::IrqHandler halfCompletedCallback)
{
if (halfCompletedCallback == nullptr) { return; }
Dma::AdcChannel::enableInterruptVector();
Dma::AdcChannel::enableInterrupt(modm::platform::DmaBase::InterruptEnable::HalfTransfer);
Dma::AdcChannel::setHalfTransferCompleteIrqHandler(halfCompletedCallback);
}

static void
setCompletedConversionCallback(modm::platform::DmaBase::IrqHandler completedCallback)
{
if (completedCallback == nullptr) { return; }
Dma::AdcChannel::enableInterruptVector();
Dma::AdcChannel::enableInterrupt(
modm::platform::DmaBase::InterruptEnable::TransferComplete);
Dma::AdcChannel::setTransferCompleteIrqHandler(completedCallback);
}
};

#endif // EXAMPLE_ADCDMA_HPP
88 changes: 88 additions & 0 deletions examples/nucleo_f401re/adc_dma/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright (c) 2023, Zühlke Engineering (Austria) GmbH
*
* This file is part of the modm project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

// This Example uses adc to sample 2 channels in scan mode 50 times every 0.5s and store the value
// in a buffer via dma. The adc is set to be triggered by the Timer1 compare event and then to
// sample both channels using scan mode. The compare event is triggered for a defined number of
// times by configuring the Timer1 to use one pulse mode with an repetition count. For more
// information on the timer please refer to the timer register count example. In this configuration,
// the adc sampling process is started by the cpu but handled completely by peripherals clearing CPU
// time for other tasks.

#include <modm/architecture/interface/interrupt.hpp>
#include <modm/board.hpp>
#include <modm/platform.hpp>

#include "adc_dma.hpp"
#include "timer_handler.hpp"

using namespace Board;
using namespace modm::platform;
using Adc1Dma = AdcDma<Adc1, Dma2::Channel0>;

std::array<uint16_t, 100> adc_results;
volatile bool dma_completed = false;

void
completedCallback()
{
LedD13::toggle();
dma_completed = true;
}

int
main()
{
Board::initialize();
Adc1::initialize<SystemClock>();
Dma2::enable();

// Use the logging streams to print some messages.
// Change MODM_LOG_LEVEL above to enable or disable these messages
MODM_LOG_DEBUG << "debug" << modm::endl;
MODM_LOG_INFO << "info" << modm::endl;
MODM_LOG_WARNING << "warning" << modm::endl;
MODM_LOG_ERROR << "error" << modm::endl;

LedD13::setOutput();
LedD13::reset();
advancedTimerConfig<Timer1>(adc_results.size() / 2 - 1);
chris-durand marked this conversation as resolved.
Show resolved Hide resolved
Adc1Dma::initialize<SystemClock>((uintptr_t)(&adc_results[0]), adc_results.size());
const auto c0_channel = Adc1::getPinChannel<GpioInputC0>();
const auto c1_channel = Adc1::getPinChannel<GpioInputC1>();
Adc1::connect<GpioInputC0::In10>();
Adc1::connect<GpioInputC1::In11>();
Adc1::setChannel(c0_channel, Adc1::SampleTime::Cycles3);
Adc1::addChannel(c1_channel, Adc1::SampleTime::Cycles3);
Adc1::enableScanMode();
// On STM32F4 Event0 means TIM1's channel 1 capture and compare event.
// Each controller has a different trigger mapping, check the reference
// manual to more information on the trigger mapping of yours controller.
Adc1::enableRegularConversionExternalTrigger(Adc1::ExternalTriggerPolarity::FallingEdge,
Adc1::RegularConversionExternalTrigger::Event0);
Adc1Dma::setCompletedConversionCallback(completedCallback);

adc_results.fill(0);
timerStart<Timer1>();
while (true)
{
modm::delay(0.5s);
if (!dma_completed) { continue; }
dma_completed = false;
MODM_LOG_DEBUG << "Measurements"
<< "\r" << modm::endl;
for (const uint16_t& sample : adc_results) { MODM_LOG_DEBUG << sample << ", "; }
MODM_LOG_DEBUG << "\r" << modm::endl;
adc_results.fill(0);
timerStart<Timer1>();
}

return 0;
}
12 changes: 12 additions & 0 deletions examples/nucleo_f401re/adc_dma/project.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<library>
<extends>modm:nucleo-f401re</extends>
<options>
<option name="modm:build:build.path">../../../build/nucleo_f401re/adc_dma</option>
</options>
<modules>
<module>modm:build:scons</module>
<module>modm:platform:timer:1</module>
<module>modm:platform:adc:1</module>
<module>modm:platform:dma</module>
</modules>
</library>
48 changes: 48 additions & 0 deletions examples/nucleo_f401re/adc_dma/timer_handler.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2023, Zühlke Engineering (Austria) GmbH
*
* This file is part of the modm project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

#ifndef EXAMPLE_TimerHANDLER_HPP
#define EXAMPLE_TimerHANDLER_HPP

#include <modm/architecture/interface/interrupt.hpp>
#include <modm/board.hpp>
#include <modm/platform.hpp>

#include "adc_dma.hpp"

using namespace Board;
using namespace modm::platform;
using namespace std::chrono_literals;

template<class Timer>
void
advancedTimerConfig(uint8_t repetitionCount)
{
Timer::enable();
Timer::setMode(Timer::Mode::UpCounter, Timer::SlaveMode::Disabled,
Timer::SlaveModeTrigger::Internal0, Timer::MasterMode::Update, true);
Timer::setPrescaler(84);
Timer::setOverflow(9999);
Timer::setRepetitionCount(repetitionCount);

Timer::enableOutput();
Timer::configureOutputChannel(1, Timer::OutputCompareMode::Pwm, 999, Timer::PinState::Enable);
}

template<class Timer>
static void
timerStart()
{
Timer::applyAndReset();
Timer::start();
}


#endif // EXAMPLE_TimerHANDLER_HPP
97 changes: 94 additions & 3 deletions src/modm/platform/adc/stm32/adc.hpp.in
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,44 @@ public:
%% endif
};

%% if target["family"] not in ["f1", "f3"]
enum class ExternalTriggerPolarity
{
NoTriggerDetection = 0x0u,
RisingEdge = 0x1u,
FallingEdge = 0x2u,
RisingAndFallingEdge = 0x3u,
};
%%endif

/**
* Enum mapping all events on a external trigger converter.
* The source mapped to each event varies on controller family,
* refer to the ADC external trigger section on reference manual
* of your controller for more information
*/
enum class RegularConversionExternalTrigger
{
Event0 = 0x0u,
Event1 = 0x1u,
Event2 = 0x2u,
Event3 = 0x3u,
Event4 = 0x4u,
Event5 = 0x5u,
Event6 = 0x6u,
Event7 = 0x7u,
%% if target["family"] not in ["f1", "f3"]
Event8 = 0x8u,
Event9 = 0x9u,
Event10 = 0xAu,
Event11 = 0xBu,
Event12 = 0xCu,
Event13 = 0xDu,
Event14 = 0xEu,
Event15 = 0xFu,
%% endif
};

/**
* Possible interrupts.
*
Expand Down Expand Up @@ -201,6 +239,9 @@ public:
static void
initialize();

static inline void
enable();

static inline void
disable();

Expand All @@ -225,7 +266,6 @@ public:
static inline uint16_t
getValue();


static inline uint16_t
readChannel(Channel channel);

Expand Down Expand Up @@ -271,14 +311,12 @@ public:
static inline Channel
getChannel();


static inline void
enableFreeRunningMode();

static inline void
disableFreeRunningMode();


static inline void
setLeftAdjustResult();

Expand Down Expand Up @@ -370,6 +408,59 @@ public:
static inline void
acknowledgeInterruptFlags(const InterruptFlag_t flags);

static inline uintptr_t
getDataRegisterAddress();

%% if target["family"] in ["f1","f3"]
static inline void
enableRegularConversionExternalTrigger(
RegularConversionExternalTrigger regularConversionExternalTrigger);

%%endif
%%if target["family"] not in ["f1","f3"]
static inline void
enableRegularConversionExternalTrigger(
ExternalTriggerPolarity externalTriggerPolarity,
RegularConversionExternalTrigger regularConversionExternalTrigger);

%%endif

/**
* Enable Dma mode for the ADC
*/
static inline void
enableDmaMode();

/**
* Disable Dma mode for the ADC
*/
static inline void
disableDmaMode();

/**
* get if adc is enabled
* @return true if ADC_CR2_ADON bit is set, false otherwise
*/
static inline bool
getAdcEnabled();

%% if target["family"] not in ["f1","f3"]
/**
* enable DMA selection for the ADC. If this is enabled DMA
* requests are issued as long as data are converted and
* the adc has dma enabled
*/
static inline void
enableDmaRequests();

/**
* disable dma selection for the ADC. If this is disabled
* no new DMA requests are issued after last transfer
*/
static inline void
disableDmaRequests();

%%endif
/**
* Enables scan mode
*/
Expand Down
Loading