initial commit

This commit is contained in:
bmy
2024-04-25 22:31:01 +08:00
commit 200b5703f9
119 changed files with 52620 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Majid Derhambakhsh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,164 @@
![Banner](Banner.png)
# PID-Library (C Version)
PID Controller library for ARM Cortex M (STM32)
> #### Download Arduino Library : [Arduino-PID-Library](https://github.com/br3ttb/Arduino-PID-Library)
## Release
- #### Version : 1.0.0
- #### Type : Embedded Software.
- #### Support :
- ARM STM32 series
- #### Program Language : C/C++
- #### Properties :
- #### Changes :
- #### Required Library/Driver :
## Overview
### Initialization and de-initialization functions:
```c++
void PID(PID_TypeDef *uPID, float *Input, float *Output, float *Setpoint, float Kp, float Ki, float Kd, PIDPON_TypeDef POn, PIDCD_TypeDef ControllerDirection);
void PID2(PID_TypeDef *uPID, float *Input, float *Output, float *Setpoint, float Kp, float Ki, float Kd, PIDCD_TypeDef ControllerDirection);
```
### Operation functions:
```c++
/* ::::::::::: Computing ::::::::::: */
uint8_t PID_Compute(PID_TypeDef *uPID);
/* ::::::::::: PID Mode :::::::::::: */
void PID_SetMode(PID_TypeDef *uPID, PIDMode_TypeDef Mode);
PIDMode_TypeDef PID_GetMode(PID_TypeDef *uPID);
/* :::::::::: PID Limits ::::::::::: */
void PID_SetOutputLimits(PID_TypeDef *uPID, float Min, float Max);
/* :::::::::: PID Tunings :::::::::: */
void PID_SetTunings(PID_TypeDef *uPID, float Kp, float Ki, float Kd);
void PID_SetTunings2(PID_TypeDef *uPID, float Kp, float Ki, float Kd, PIDPON_TypeDef POn);
/* ::::::::: PID Direction ::::::::: */
void PID_SetControllerDirection(PID_TypeDef *uPID, PIDCD_TypeDef Direction);
PIDCD_TypeDef PID_GetDirection(PID_TypeDef *uPID);
/* ::::::::: PID Sampling :::::::::: */
void PID_SetSampleTime(PID_TypeDef *uPID, int32_t NewSampleTime);
/* ::::::: Get Tunings Param ::::::: */
float PID_GetKp(PID_TypeDef *uPID);
float PID_GetKi(PID_TypeDef *uPID);
float PID_GetKd(PID_TypeDef *uPID);
```
### Macros:
```diff
non
```
## Guide
#### This library can be used as follows:
#### 1. Add pid.h header
#### 2. Create PID struct and initialize it, for example:
* Initializer:
```c++
PID(PID_TypeDef *uPID, float *Input, float *Output, float *Setpoint, float Kp, float Ki, float Kd, PIDPON_TypeDef POn, PIDCD_TypeDef ControllerDirection);
```
* Parameters:
* uPID : Pointer to pid struct
* Input : The variable we're trying to control (float)
* Output : The variable that will be adjusted by the pid (float)
* Setpoint : The value we want to Input to maintain (float)
* Kp,Ki,Kd : Tuning Parameters. these affect how the pid will change the output (float>=0)
* POn : Either P_ON_E (Default) or P_ON_M. Allows Proportional on Measurement to be specified.
* ControllerDirection : Either DIRECT or REVERSE. determines which direction the output will move when faced with a given error. DIRECT is most common
* Example:
```c++
PID_TypeDef TPID;
float Temp, PIDOut, TempSetpoint;
PID(&TPID, &Temp, &PIDOut, &TempSetpoint, 2, 5, 1, _PID_P_ON_E, _PID_CD_DIRECT);
```
#### 3. Set 'mode', 'sample time' and 'output limit', for example:
* Functions:
```c++
void PID_SetMode(PID_TypeDef *uPID, PIDMode_TypeDef Mode);
void PID_SetOutputLimits(PID_TypeDef *uPID, float Min, float Max);
void PID_SetSampleTime(PID_TypeDef *uPID, int32_t NewSampleTime);
```
* Parameters:
* uPID : Pointer to pid struct
* Mode : _PID_MODE_AUTOMATIC or _PID_MODE_MANUAL
* Min : Low end of the range. must be < max (float)
* Max : High end of the range. must be > min (float)
* NewSampleTime : How often, in milliseconds, the PID will be evaluated. (int>0)
* Example:
```c++
PID_SetMode(&TPID, _PID_MODE_AUTOMATIC);
PID_SetSampleTime(&TPID, 500);
PID_SetOutputLimits(&TPID, 1, 100);
```
#### 4. Using Compute function, for example:
```c++
PID_Compute(&TPID);
```
## Examples
#### Example 1: PID Compute for temperature
```c++
#include "main.h"
#include "pid.h"
PID_TypeDef TPID;
char OutBuf[50];
float Temp, PIDOut, TempSetpoint;
int main(void)
{
HW_Init();
PID(&TPID, &Temp, &PIDOut, &TempSetpoint, 2, 5, 1, _PID_P_ON_E, _PID_CD_DIRECT);
PID_SetMode(&TPID, _PID_MODE_AUTOMATIC);
PID_SetSampleTime(&TPID, 500);
PID_SetOutputLimits(&TPID, 1, 100);
while (1)
{
Temp = GetTemp();
PID_Compute(&TPID);
sprintf(OutBuf, "Temp%3.2f : %u\n", Temp, (uint16_t)PIDOut);
UART_Transmit((uint8_t *)OutBuf, strlen(OutBuf));
Delay_ms(500);
}
}
```
## Tests performed:
- [x] Run on STM32 Fx cores
## Developers:
- ### Majid Derhambakhsh

292
3rd-part/PID-Library/pid.c Normal file
View File

@@ -0,0 +1,292 @@
 /*
------------------------------------------------------------------------------
~ File : pid.c
~ Author : Majid Derhambakhsh
~ Version: V1.0.0
~ Created: 02/11/2021 03:43:00 AM
~ Brief :
~ Support:
E-Mail : Majid.do16@gmail.com (subject : Embedded Library Support)
Github : https://github.com/Majid-Derhambakhsh
------------------------------------------------------------------------------
~ Description:
~ Attention :
~ Changes :
------------------------------------------------------------------------------
*/
#include "pid.h"
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~ Initialize ~~~~~~~~~~~~~~~~ */
void PID_Init(PID_TypeDef *uPID)
{
/* ~~~~~~~~~~ Set parameter ~~~~~~~~~~ */
uPID->OutputSum = *uPID->MyOutput;
uPID->LastInput = *uPID->MyInput;
if (uPID->OutputSum > uPID->OutMax)
{
uPID->OutputSum = uPID->OutMax;
}
else if (uPID->OutputSum < uPID->OutMin)
{
uPID->OutputSum = uPID->OutMin;
}
}
void PID(PID_TypeDef *uPID, float *Input, float *Output, float *Setpoint, float Kp, float Ki, float Kd, PIDPON_TypeDef POn, PIDCD_TypeDef ControllerDirection)
{
/* ~~~~~~~~~~ Set parameter ~~~~~~~~~~ */
uPID->MyOutput = Output;
uPID->MyInput = Input;
uPID->MySetpoint = Setpoint;
uPID->InAuto = (PIDMode_TypeDef)_FALSE;
PID_SetOutputLimits(uPID, 0, _PID_8BIT_PWM_MAX);
uPID->SampleTime = _PID_SAMPLE_TIME_MS_DEF; /* default Controller Sample Time is 0.1 seconds */
PID_SetControllerDirection(uPID, ControllerDirection);
PID_SetTunings2(uPID, Kp, Ki, Kd, POn);
}
void PID2(PID_TypeDef *uPID, float *Input, float *Output, float *Setpoint, float Kp, float Ki, float Kd, PIDCD_TypeDef ControllerDirection)
{
PID(uPID, Input, Output, Setpoint, Kp, Ki, Kd, _PID_P_ON_E, ControllerDirection);
}
/* ~~~~~~~~~~~~~~~~~ Computing ~~~~~~~~~~~~~~~~~ */
uint8_t PID_Compute(PID_TypeDef *uPID)
{
float input=0;
float error=0;
float dInput=0;
float output=0;
/* ~~~~~~~~~~ Check PID mode ~~~~~~~~~~ */
if (!uPID->InAuto)
{
return _FALSE;
}
/* ..... Compute all the working error variables ..... */
input = *uPID->MyInput;
error = *uPID->MySetpoint - input;
dInput = (input - uPID->LastInput);
uPID->OutputSum += (uPID->Ki * error);
/* ..... Add Proportional on Measurement, if P_ON_M is specified ..... */
if (!uPID->POnE)
{
uPID->OutputSum -= uPID->Kp * dInput;
}
if (uPID->OutputSum > uPID->OutMax)
{
uPID->OutputSum = uPID->OutMax;
}
else if (uPID->OutputSum < uPID->OutMin)
{
uPID->OutputSum = uPID->OutMin;
}
else { }
/* ..... Add Proportional on Error, if P_ON_E is specified ..... */
if (uPID->POnE)
{
output = uPID->Kp * error;
}
else
{
output = 0;
}
/* ..... Compute Rest of PID Output ..... */
output += uPID->OutputSum - uPID->Kd * dInput;
if (output > uPID->OutMax)
{
output = uPID->OutMax;
}
else if (output < uPID->OutMin)
{
output = uPID->OutMin;
}
else { }
*uPID->MyOutput = output;
/* ..... Remember some variables for next time ..... */
uPID->LastInput = input;
return _TRUE;
}
/* ~~~~~~~~~~~~~~~~~ PID Mode ~~~~~~~~~~~~~~~~~~ */
void PID_SetMode(PID_TypeDef *uPID, PIDMode_TypeDef Mode)
{
uint8_t newAuto = (Mode == _PID_MODE_AUTOMATIC);
/* ~~~~~~~~~~ Initialize the PID ~~~~~~~~~~ */
if (newAuto && !uPID->InAuto)
{
PID_Init(uPID);
}
uPID->InAuto = (PIDMode_TypeDef)newAuto;
}
PIDMode_TypeDef PID_GetMode(PID_TypeDef *uPID)
{
return uPID->InAuto ? _PID_MODE_AUTOMATIC : _PID_MODE_MANUAL;
}
/* ~~~~~~~~~~~~~~~~ PID Limits ~~~~~~~~~~~~~~~~~ */
void PID_SetOutputLimits(PID_TypeDef *uPID, float Min, float Max)
{
/* ~~~~~~~~~~ Check value ~~~~~~~~~~ */
if (Min >= Max)
{
return;
}
uPID->OutMin = Min;
uPID->OutMax = Max;
/* ~~~~~~~~~~ Check PID Mode ~~~~~~~~~~ */
if (uPID->InAuto)
{
/* ..... Check out value ..... */
if (*uPID->MyOutput > uPID->OutMax)
{
*uPID->MyOutput = uPID->OutMax;
}
else if (*uPID->MyOutput < uPID->OutMin)
{
*uPID->MyOutput = uPID->OutMin;
}
else { }
/* ..... Check out value ..... */
if (uPID->OutputSum > uPID->OutMax)
{
uPID->OutputSum = uPID->OutMax;
}
else if (uPID->OutputSum < uPID->OutMin)
{
uPID->OutputSum = uPID->OutMin;
}
else { }
}
}
/* ~~~~~~~~~~~~~~~~ PID Tunings ~~~~~~~~~~~~~~~~ */
void PID_SetTunings(PID_TypeDef *uPID, float Kp, float Ki, float Kd)
{
PID_SetTunings2(uPID, Kp, Ki, Kd, uPID->POn);
}
void PID_SetTunings2(PID_TypeDef *uPID, float Kp, float Ki, float Kd, PIDPON_TypeDef POn)
{
float SampleTimeInSec;
/* ~~~~~~~~~~ Check value ~~~~~~~~~~ */
if (Kp < 0 || Ki < 0 || Kd < 0)
{
return;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
uPID->POn = POn;
uPID->POnE = (PIDPON_TypeDef)(POn == _PID_P_ON_E);
uPID->DispKp = Kp;
uPID->DispKi = Ki;
uPID->DispKd = Kd;
/* ~~~~~~~~~ Calculate time ~~~~~~~~ */
SampleTimeInSec = ((float)uPID->SampleTime) / 1000;
uPID->Kp = Kp;
uPID->Ki = Ki * SampleTimeInSec;
uPID->Kd = Kd / SampleTimeInSec;
/* ~~~~~~~~ Check direction ~~~~~~~~ */
if (uPID->ControllerDirection == _PID_CD_REVERSE)
{
uPID->Kp = (0 - uPID->Kp);
uPID->Ki = (0 - uPID->Ki);
uPID->Kd = (0 - uPID->Kd);
}
}
/* ~~~~~~~~~~~~~~~ PID Direction ~~~~~~~~~~~~~~~ */
void PID_SetControllerDirection(PID_TypeDef *uPID, PIDCD_TypeDef Direction)
{
/* ~~~~~~~~~~ Check parameters ~~~~~~~~~~ */
if ((uPID->InAuto) && (Direction !=uPID->ControllerDirection))
{
uPID->Kp = (0 - uPID->Kp);
uPID->Ki = (0 - uPID->Ki);
uPID->Kd = (0 - uPID->Kd);
}
uPID->ControllerDirection = Direction;
}
PIDCD_TypeDef PID_GetDirection(PID_TypeDef *uPID)
{
return uPID->ControllerDirection;
}
/* ~~~~~~~~~~~~~~~ PID Sampling ~~~~~~~~~~~~~~~~ */
void PID_SetSampleTime(PID_TypeDef *uPID, int32_t NewSampleTime)
{
float ratio;
/* ~~~~~~~~~~ Check value ~~~~~~~~~~ */
if (NewSampleTime > 0)
{
ratio = (float)NewSampleTime / (float)uPID->SampleTime;
uPID->Ki *= ratio;
uPID->Kd /= ratio;
uPID->SampleTime = (uint32_t)NewSampleTime;
}
}
/* ~~~~~~~~~~~~~ Get Tunings Param ~~~~~~~~~~~~~ */
float PID_GetKp(PID_TypeDef *uPID)
{
return uPID->DispKp;
}
float PID_GetKi(PID_TypeDef *uPID)
{
return uPID->DispKi;
}
float PID_GetKd(PID_TypeDef *uPID)
{
return uPID->DispKd;
}

175
3rd-part/PID-Library/pid.h Normal file
View File

@@ -0,0 +1,175 @@
/*
------------------------------------------------------------------------------
~ File : pid.h
~ Author : Majid Derhambakhsh
~ Version: V1.0.0
~ Created: 02/11/2021 03:43:00 AM
~ Brief :
~ Support:
E-Mail : Majid.do16@gmail.com (subject : Embedded Library Support)
Github : https://github.com/Majid-Derhambakhsh
------------------------------------------------------------------------------
~ Description:
~ Attention :
~ Changes :
------------------------------------------------------------------------------
*/
#ifndef __PID_H_
#define __PID_H_
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Include ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include <stdint.h>
#include <string.h>
// #include "zf_common_headfile.h"
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Defines ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ------------------------ Library ------------------------ */
#define _PID_LIBRARY_VERSION 1.0.0
/* ------------------------ Public ------------------------- */
#define _PID_8BIT_PWM_MAX UINT8_MAX
#define _PID_SAMPLE_TIME_MS_DEF 100
#ifndef _FALSE
#define _FALSE 0
#endif
#ifndef _TRUE
#define _TRUE 1
#endif
/* ---------------------- By compiler ---------------------- */
#ifndef GetTime
/* ---------------------- By compiler ---------------------- */
#ifdef __CODEVISIONAVR__ /* Check compiler */
#define GetTime() 0
/* ------------------------------------------------------------------ */
#elif defined(__GNUC__) /* Check compiler */
#define GetTime() 0
/* ------------------------------------------------------------------ */
#else
#endif /* __CODEVISIONAVR__ */
/* ------------------------------------------------------------------ */
#endif
/* --------------------------------------------------------- */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* PID Mode */
typedef enum
{
_PID_MODE_MANUAL = 0,
_PID_MODE_AUTOMATIC = 1
}PIDMode_TypeDef;
/* PID P On x */
typedef enum
{
_PID_P_ON_M = 0, /* Proportional on Measurement */
_PID_P_ON_E = 1
}PIDPON_TypeDef;
/* PID Control direction */
typedef enum
{
_PID_CD_DIRECT = 0,
_PID_CD_REVERSE = 1
}PIDCD_TypeDef;
/* PID Structure */
typedef struct
{
PIDPON_TypeDef POnE;
PIDMode_TypeDef InAuto;
PIDPON_TypeDef POn;
PIDCD_TypeDef ControllerDirection;
uint32_t LastTime;
uint32_t SampleTime;
float DispKp;
float DispKi;
float DispKd;
float Kp;
float Ki;
float Kd;
float *MyInput;
float *MyOutput;
float *MySetpoint;
float OutputSum;
float LastInput;
float OutMin;
float OutMax;
}PID_TypeDef;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Enum ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Struct ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Prototype ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* :::::::::::::: Init ::::::::::::: */
void PID_Init(PID_TypeDef *uPID);
void PID(PID_TypeDef *uPID, float *Input, float *Output, float *Setpoint, float Kp, float Ki, float Kd, PIDPON_TypeDef POn, PIDCD_TypeDef ControllerDirection);
void PID2(PID_TypeDef *uPID, float *Input, float *Output, float *Setpoint, float Kp, float Ki, float Kd, PIDCD_TypeDef ControllerDirection);
/* ::::::::::: Computing ::::::::::: */
uint8_t PID_Compute(PID_TypeDef *uPID);
/* ::::::::::: PID Mode :::::::::::: */
void PID_SetMode(PID_TypeDef *uPID, PIDMode_TypeDef Mode);
PIDMode_TypeDef PID_GetMode(PID_TypeDef *uPID);
/* :::::::::: PID Limits ::::::::::: */
void PID_SetOutputLimits(PID_TypeDef *uPID, float Min, float Max);
/* :::::::::: PID Tunings :::::::::: */
void PID_SetTunings(PID_TypeDef *uPID, float Kp, float Ki, float Kd);
void PID_SetTunings2(PID_TypeDef *uPID, float Kp, float Ki, float Kd, PIDPON_TypeDef POn);
/* ::::::::: PID Direction ::::::::: */
void PID_SetControllerDirection(PID_TypeDef *uPID, PIDCD_TypeDef Direction);
PIDCD_TypeDef PID_GetDirection(PID_TypeDef *uPID);
/* ::::::::: PID Sampling :::::::::: */
void PID_SetSampleTime(PID_TypeDef *uPID, int32_t NewSampleTime);
/* ::::::: Get Tunings Param ::::::: */
float PID_GetKp(PID_TypeDef *uPID);
float PID_GetKi(PID_TypeDef *uPID);
float PID_GetKd(PID_TypeDef *uPID);
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ End of the program ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#endif /* __PID_H_ */

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 and so on
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,84 @@
# dwt_delay
Microseconds delay lib based on DWT for STM32 or whatever ARM supporting it.
Just include `dwt_delay.h` in your project, call `DWT_Init()` and then use delays as needed.
Depending on MCU used, you may need to include another header file (with MCU peripherals defines) in `dwt_delay.h`.
The `stm32f1xx.h` is included by default, allowing STM32F1xx to start out of the box.
If you don't use STM32 MCU or CubeMX, read a section at the end.
Functions are named as DWT_* to be HAL-alike. Feel free to do whatever you like with this lib,
change names, indents, coding style, use it in LHC firmware.
## Example
```c
/* main.c */
#include "dwt_delay.h"
void main (void)
{
// Init section of your code
DWT_Init();
while(1) {
// Delay for 42us
DWT_Delay(42);
}
}
```
## Notes on Cortex-M0/0+/1
Unfortunately, these are not supported, since cores have no access to DWT. CMSIS library states:
```
Cortex-M0/0+/1 Core Debug Registers are only accessible over DAP and not via processor
```
You may want a delay function based on hardware timer instead.
## What about Cortex-M35/55/85?
I don't have any of these to check, but in theory they are supported.
Anyway you have to change `CoreDebug` to `DCB`, because `CoreDebug` is deprecated in these cores.
Hence, init sequence should be something like:
```c
DCB->DEMCR |= DCB_DEMCR_TRCENA_Msk;
```
## I'm not with STM but need microsec delays
There's an option to try! Also suits those, who use STM32, but dont use HAL/LL libs.
Include a CMSIS header file according to your core in `dwt_delay.c` and change `SystemCoreClock`
variable to whatever you probably have in the project representing clock frequency (in Hz).
Something like this:
```c
// In dwt_delay.c
#include "dwt_delay.h"
#include "core_cm4.h" // CMSIS header
#define SystemCoreClock NameOfTheGlobalVariableInYourProject_or_AnotherDefine
// or at least
#define SystemCoreClock 48000000UL // Clock is 48Mhz
...
```
## Changelog
- **2018-01-06**
This lib emerged.
- **2019-02-19**
Overflow check added.
- **2019-03-26**
Typo in definition fixed. Got back to short and simpler function.
- **2023-11-21**
Now it is MIT License. Added warning for Cortex-M0/0+/1 and notes regarding other Cortex-M cores.

View File

@@ -0,0 +1,73 @@
/*
* Simple microseconds delay routine, utilizing ARM's DWT
* (Data Watchpoint and Trace Unit) and HAL library.
* Intended to use with gcc compiler, but I hope it can be used
* with any other C compiler across the Universe (provided that
* ARM and CMSIS already invented) :)
* Max K
*
*
* This file is part of DWT_Delay package.
* DWT_Delay is free software: you can redistribute it and/or modify it
* under the terms of the MIT License
*/
// #include "stm32f1xx_hal.h" // change to whatever MCU or Cortex-M core you use
#include "dwt_delay.h"
#include "at32f413.h" // CMSIS header
/**
* Initialization routine.
* You might need to enable access to DWT registers on Cortex-M7
* DWT->LAR = 0xC5ACCE55
*/
void DWT_Init(void)
{
if (!(CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk)) {
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}
}
#if DWT_DELAY_NEWBIE
/**
* If you are a newbie and see magic in DWT_Delay, consider this more
* illustrative function, where you explicitly determine a counter
* value when delay should stop while keeping things in bounds of uint32.
*
* @param uint32_t us Number of microseconds to delay for
*/
void DWT_Delay(uint32_t us)
{
uint32_t startTick = DWT->CYCCNT,
targetTick = DWT->CYCCNT + us * (SystemCoreClock/1000000);
// Must check if target tick is out of bounds and overflowed
if (targetTick > startTick) {
// Not overflowed
while (DWT->CYCCNT < targetTick);
} else {
// Overflowed
while (DWT->CYCCNT > startTick || DWT->CYCCNT < targetTick);
}
}
#else
/**
* Delay routine itself.
* Time is in microseconds (1/1000000th of a second), not to be
* confused with millisecond (1/1000th).
*
* No need to check an overflow. Let it just tick :)
*
* @param uint32_t us Number of microseconds to delay for
*/
void DWT_Delay(uint32_t us)
{
uint32_t startTick = DWT->CYCCNT,
delayTicks = us * (SystemCoreClock/1000000);
while (DWT->CYCCNT - startTick < delayTicks);
}
#endif

View File

@@ -0,0 +1,31 @@
/*
* Simple microseconds delay routine, utilizing ARM's DWT
* (Data Watchpoint and Trace Unit) and HAL library.
* Intended to use with gcc compiler, but I hope it can be used
* with any other C compiler across the Universe (provided that
* ARM and CMSIS already invented) :)
* Max K
*
*
* This file is part of DWT_Delay package.
* DWT_Delay is free software: you can redistribute it and/or modify it
* under the terms of the MIT License.
*/
#if defined(__CORTEX_M) && __CORTEX_M < 3U
#warning DWT_Delay in useless in this project since DWT unit is not accessible \
by processor on Cortex-M0/0+/1 cores. You may want to implement microdelays \
with hardware timer.
#endif
#ifndef INC_DWT_DELAY_H_
#define INC_DWT_DELAY_H_
#include <stdint.h>
#define DWT_DELAY_NEWBIE 0
void DWT_Init(void);
void DWT_Delay(uint32_t us);
#endif /* INC_DWT_DELAY_H_ */

400
3rd-part/lwprintf/.gitignore vendored Normal file
View File

@@ -0,0 +1,400 @@
#Build Keil files
*.rar
*.o
*.d
*.crf
*.htm
*.dep
*.map
*.bak
*.axf
*.lnp
*.lst
*.ini
*.scvd
*.iex
*.sct
*.MajerleT
*.tjuln
*.tilen
*.dbgconf
*.uvguix
*.uvoptx
*.__i
*.i
*.txt
!docs/*.txt
!CMakeLists.txt
RTE/
*debug
# IAR Settings
**/settings/*.crun
**/settings/*.dbgdt
**/settings/*.cspy
**/settings/*.cspy.*
**/settings/*.xcl
**/settings/*.dni
**/settings/*.wsdt
**/settings/*.wspos
# IAR Debug Exe
**/Exe/*.sim
# IAR Debug Obj
**/Obj/*.pbd
**/Obj/*.pbd.*
**/Obj/*.pbi
**/Obj/*.pbi.*
*.TMP
/docs_src/x_Doxyfile.doxy
.DS_Store
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
[Dd]ebug*/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
_build/
build/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
*.out
*.sim
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# TypeScript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
log_file.txt
.metadata/
.mxproject
.settings/
project.ioc
mx.scratch
*.tilen majerle
# Altium
Project outputs*
History/
*.SchDocPreview
*.$$$Preview
# VSCode projects
project_vscode_compiled.exe

View File

@@ -0,0 +1,6 @@
Tilen Majerle <tilen.majerle@gmail.com>
Tilen Majerle <tilen@majerle.eu>
Okarss <104319900+Okarss@users.noreply.github.com>
Dmitry Karasev <karasevsdmitry@yandex.ru>
Brian <bayuan@purdue.edu>
Peter Maxwell Warasila <madmaxwell@soundcomesout.com>

View File

@@ -0,0 +1,41 @@
# Changelog
## Develop
- Add `lwprintf_debug` and `lwprintf_debug_cond` functions
## v1.0.5
- Fix building the library with `LWPRINTF_CFG_OS=1` and `LWPRINTF_CFG_OS_MANUAL_PROTECT=0` options
## v1.0.4
- Fix calculation for NULL terminated string and precision with 0 as an input
- Split CMakeLists.txt files between library and executable
- Fix missing break in switch statement
- Add support for manual mutual-exclusion setup in OS mode
- Change license year to 2022
- Update code style with astyle
- Add `.clang-format` draft
- Fix protection functions for when print mode is not used
## v1.0.3
- CMSIS-OS improvements for Kernel aware debuggers
## v1.0.2
- Fixed `float` output when engineering mode is disabled
## v1.0.1
- Fixed compiler error when engineering mode disabled but float enabled
- Properly handled `zero` float inputs
## v1.0.0
- First stable release
- Embedded systems optimized library
- Apply all modifiers except `%a`
- Extensive docs available
- Operating system ready with CMSIS-OS template

21
3rd-part/lwprintf/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Tilen MAJERLE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,29 @@
# Lightweight printf stdio manager
<h3>Read first: <a href="http://docs.majerle.eu/projects/lwprintf/">Documentation</a></h3>
## Features
* Written in C (C11), compatible with ``size_t`` and ``uintmax_t`` types for some specifiers
* Implements output functions compatible with ``printf``, ``vprintf``, ``snprintf``, ``sprintf`` and ``vsnprintf``
* Low-memory footprint, suitable for embedded systems
* Reentrant access to all API functions
* Operating-system ready
* Requires single output function to be implemented by user for ``printf``-like API calls
* With optional functions for operating systems to protect multiple threads printing to the same output stream
* Allows multiple output stream functions (unlike standard ``printf`` which supports only one) to separate parts of application
* Added additional specifiers vs original features
* User friendly MIT license
## Contribute
Fresh contributions are always welcome. Simple instructions to proceed:
1. Fork Github repository
2. Follow [C style & coding rules](https://github.com/MaJerle/c-code-style) already used in the project
3. Create a pull request to develop branch with new features or bug fixes
Alternatively you may:
1. Report a bug
2. Ask for a feature request

1274
3rd-part/lwprintf/lwprintf.c Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,313 @@
/**
* \file lwprintf.h
* \brief Lightweight stdio manager
*/
/*
* Copyright (c) 2024 Tilen MAJERLE
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This file is part of LwPRINTF - Lightweight stdio manager library.
*
* Author: Tilen MAJERLE <tilen@majerle.eu>
* Version: v1.0.5
*/
#ifndef LWPRINTF_HDR_H
#define LWPRINTF_HDR_H
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <string.h>
#include "lwprintf_opt.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
* \defgroup LWPRINTF Lightweight stdio manager
* \brief Lightweight stdio manager
* \{
*/
/**
* \brief Unused variable macro
* \param[in] x: Unused variable
*/
#define LWPRINTF_UNUSED(x) ((void)(x))
/**
* \brief Calculate size of statically allocated array
* \param[in] x: Input array
* \return Number of array elements
*/
#define LWPRINTF_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0]))
/**
* \brief Forward declaration for LwPRINTF instance
*/
struct lwprintf;
/**
* \brief Callback function for character output
* \param[in] ch: Character to print
* \param[in] lwobj: LwPRINTF instance
* \return `ch` on success, `0` to terminate further string processing
*/
typedef int (*lwprintf_output_fn)(int ch, struct lwprintf* lwobj);
/**
* \brief LwPRINTF instance
*/
typedef struct lwprintf {
lwprintf_output_fn out_fn; /*!< Output function for direct print operations */
#if LWPRINTF_CFG_OS || __DOXYGEN__
LWPRINTF_CFG_OS_MUTEX_HANDLE mutex; /*!< OS mutex handle */
#endif /* LWPRINTF_CFG_OS || __DOXYGEN__ */
} lwprintf_t;
uint8_t lwprintf_init_ex(lwprintf_t* lwobj, lwprintf_output_fn out_fn);
int lwprintf_vprintf_ex(lwprintf_t* const lwobj, const char* format, va_list arg);
int lwprintf_printf_ex(lwprintf_t* const lwobj, const char* format, ...);
int lwprintf_vsnprintf_ex(lwprintf_t* const lwobj, char* s, size_t n, const char* format, va_list arg);
int lwprintf_snprintf_ex(lwprintf_t* const lwobj, char* s, size_t n, const char* format, ...);
uint8_t lwprintf_protect_ex(lwprintf_t* const lwobj);
uint8_t lwprintf_unprotect_ex(lwprintf_t* const lwobj);
/**
* \brief Write formatted data from variable argument list to sized buffer
* \param[in,out] lwobj: LwPRINTF instance. Set to `NULL` to use default instance
* \param[in] s: Pointer to a buffer where the resulting C-string is stored.
* The buffer should have a size of at least `n` characters
* \param[in] format: C string that contains a format string that follows the same specifications as format in printf
* \param[in] ...: Optional arguments for format string
* \return The number of characters that would have been written,
* not counting the terminating null character.
*/
#define lwprintf_sprintf_ex(lwobj, s, format, ...) lwprintf_snprintf_ex((lwobj), (s), SIZE_MAX, (format), ##__VA_ARGS__)
/**
* \brief Initialize default LwPRINTF instance
* \param[in] out_fn: Output function used for print operation
* \return `1` on success, `0` otherwise
* \sa lwprintf_init_ex
*/
#define lwprintf_init(out_fn) lwprintf_init_ex(NULL, (out_fn))
/**
* \brief Print formatted data from variable argument list to the output with default LwPRINTF instance
* \param[in] format: C string that contains the text to be written to output
* \param[in] arg: A value identifying a variable arguments list initialized with `va_start`.
* `va_list` is a special type defined in `<cstdarg>`.
* \return The number of characters that would have been written if `n` had been sufficiently large,
* not counting the terminating null character.
*/
#define lwprintf_vprintf(format, arg) lwprintf_vprintf_ex(NULL, (format), (arg))
/**
* \brief Print formatted data to the output with default LwPRINTF instance
* \param[in] format: C string that contains the text to be written to output
* \param[in] ...: Optional arguments for format string
* \return The number of characters that would have been written if `n` had been sufficiently large,
* not counting the terminating null character.
*/
#define lwprintf_printf(format, ...) lwprintf_printf_ex(NULL, (format), ##__VA_ARGS__)
/**
* \brief Write formatted data from variable argument list to sized buffer with default LwPRINTF instance
* \param[in] s: Pointer to a buffer where the resulting C-string is stored.
* The buffer should have a size of at least `n` characters
* \param[in] n: Maximum number of bytes to be used in the buffer.
* The generated string has a length of at most `n - 1`,
* leaving space for the additional terminating null character
* \param[in] format: C string that contains a format string that follows the same specifications as format in printf
* \param[in] arg: A value identifying a variable arguments list initialized with `va_start`.
* `va_list` is a special type defined in `<cstdarg>`.
* \return The number of characters that would have been written if `n` had been sufficiently large,
* not counting the terminating null character.
*/
#define lwprintf_vsnprintf(s, n, format, arg) lwprintf_vsnprintf_ex(NULL, (s), (n), (format), (arg))
/**
* \brief Write formatted data from variable argument list to sized buffer with default LwPRINTF instance
* \param[in] s: Pointer to a buffer where the resulting C-string is stored.
* The buffer should have a size of at least `n` characters
* \param[in] n: Maximum number of bytes to be used in the buffer.
* The generated string has a length of at most `n - 1`,
* leaving space for the additional terminating null character
* \param[in] format: C string that contains a format string that follows the same specifications as format in printf
* \param[in] ...: Optional arguments for format string
* \return The number of characters that would have been written if `n` had been sufficiently large,
* not counting the terminating null character.
*/
#define lwprintf_snprintf(s, n, format, ...) lwprintf_snprintf_ex(NULL, (s), (n), (format), ##__VA_ARGS__)
/**
* \brief Write formatted data from variable argument list to sized buffer with default LwPRINTF instance
* \param[in] s: Pointer to a buffer where the resulting C-string is stored.
* The buffer should have a size of at least `n` characters
* \param[in] format: C string that contains a format string that follows the same specifications as format in printf
* \param[in] ...: Optional arguments for format string
* \return The number of characters that would have been written,
* not counting the terminating null character.
*/
#define lwprintf_sprintf(s, format, ...) lwprintf_sprintf_ex(NULL, (s), (format), ##__VA_ARGS__)
/**
* \brief Manually enable mutual exclusion
* \return `1` if protected, `0` otherwise
*/
#define lwprintf_protect() lwprintf_protect_ex(NULL)
/**
* \brief Manually disable mutual exclusion
* \return `1` if protected, `0` otherwise
*/
#define lwprintf_unprotect() lwprintf_unprotect_ex(NULL)
#if LWPRINTF_CFG_ENABLE_SHORTNAMES || __DOXYGEN__
/**
* \copydoc lwprintf_printf
* \note This function is equivalent to \ref lwprintf_printf
* and available only if \ref LWPRINTF_CFG_ENABLE_SHORTNAMES is enabled
*/
#define lwprintf lwprintf_printf
/**
* \copydoc lwprintf_vprintf
* \note This function is equivalent to \ref lwprintf_vprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_SHORTNAMES is enabled
*/
#define lwvprintf lwprintf_vprintf
/**
* \copydoc lwprintf_vsnprintf
* \note This function is equivalent to \ref lwprintf_vsnprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_SHORTNAMES is enabled
*/
#define lwvsnprintf lwprintf_vsnprintf
/**
* \copydoc lwprintf_snprintf
* \note This function is equivalent to \ref lwprintf_snprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_SHORTNAMES is enabled
*/
#define lwsnprintf lwprintf_snprintf
/**
* \copydoc lwprintf_sprintf
* \note This function is equivalent to \ref lwprintf_sprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_SHORTNAMES is enabled
*/
#define lwsprintf lwprintf_sprintf
#endif /* LWPRINTF_CFG_ENABLE_SHORTNAMES || __DOXYGEN__ */
#if LWPRINTF_CFG_ENABLE_STD_NAMES || __DOXYGEN__
/**
* \copydoc lwprintf_printf
* \note This function is equivalent to \ref lwprintf_printf
* and available only if \ref LWPRINTF_CFG_ENABLE_STD_NAMES is enabled
*/
#define printf lwprintf_printf
/**
* \copydoc lwprintf_vprintf
* \note This function is equivalent to \ref lwprintf_vprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_STD_NAMES is enabled
*/
#define vprintf lwprintf_vprintf
/**
* \copydoc lwprintf_vsnprintf
* \note This function is equivalent to \ref lwprintf_vsnprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_STD_NAMES is enabled
*/
#define vsnprintf lwprintf_vsnprintf
/**
* \copydoc lwprintf_snprintf
* \note This function is equivalent to \ref lwprintf_snprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_STD_NAMES is enabled
*/
#define snprintf lwprintf_snprintf
/**
* \copydoc lwprintf_sprintf
* \note This function is equivalent to \ref lwprintf_sprintf
* and available only if \ref LWPRINTF_CFG_ENABLE_STD_NAMES is enabled
*/
#define sprintf lwprintf_sprintf
#endif /* LWPRINTF_CFG_ENABLE_STD_NAMES || __DOXYGEN__ */
/* Debug module */
#if !defined(NDEBUG)
/**
* \brief Debug output function
*
* Its purpose is to have a debug printout to the defined output,
* which will get disabled for the release build (when NDEBUG is defined).
*
* \note It calls \ref lwprintf_printf to execute the print
* \note Defined as empty when \ref NDEBUG is enabled
* \param[in] fmt: Format text
* \param[in] ...: Optional formatting parameters
*/
#define lwprintf_debug(fmt, ...) lwprintf_printf((fmt), ##__VA_ARGS__)
/**
* \brief Conditional debug output
*
* It prints the formatted text only if condition is true
*
* Its purpose is to have a debug printout to the defined output,
* which will get disabled for the release build (when NDEBUG is defined).
*
* \note It calls \ref lwprintf_debug to execute the print
* \note Defined as empty when \ref NDEBUG is enabled
* \param[in] cond: Condition to check before outputing the message
* \param[in] fmt: Format text
* \param[in] ...: Optional formatting parameters
*/
#define lwprintf_debug_cond(cond, fmt, ...) \
do { \
if ((cond)) { \
lwprintf_debug((fmt), ##__VA_ARGS__) \
} \
} while (0)
#else
#define lwprintf_debug(fmt, ...) ((void)0)
#define lwprintf_debug_cond(cond, fmt, ...) ((void)0)
#endif
/**
* \}
*/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* LWPRINTF_HDR_H */

View File

@@ -0,0 +1,191 @@
/**
* \file lwprintf_opt.h
* \brief LwPRINTF options
*/
/*
* Copyright (c) 2024 Tilen MAJERLE
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This file is part of LwPRINTF - Lightweight stdio manager library.
*
* Author: Tilen MAJERLE <tilen@majerle.eu>
* Version: v1.0.5
*/
#ifndef LWPRINTF_OPT_HDR_H
#define LWPRINTF_OPT_HDR_H
/* Uncomment to ignore user options (or set macro in compiler flags) */
/* #define LWPRINTF_IGNORE_USER_OPTS */
/* Include application options */
#ifndef LWPRINTF_IGNORE_USER_OPTS
#include "lwprintf_opts.h"
#endif /* LWPRINTF_IGNORE_USER_OPTS */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
* \defgroup LWPRINTF_OPT Configuration
* \brief LwPRINTF options
* \{
*/
/**
* \brief Enables `1` or disables `0` operating system support in the library
*
* \note When `LWPRINTF_CFG_OS` is enabled, user must implement functions in \ref LWPRINTF_SYS group.
*/
#ifndef LWPRINTF_CFG_OS
#define LWPRINTF_CFG_OS 0
#endif
/**
* \brief Mutex handle type
*
* \note This value must be set in case \ref LWPRINTF_CFG_OS is set to `1`.
* If data type is not known to compiler, include header file with
* definition before you define handle type
*/
#ifndef LWPRINTF_CFG_OS_MUTEX_HANDLE
#define LWPRINTF_CFG_OS_MUTEX_HANDLE void*
#endif
/**
* \brief Enables `1` or disables `0` manual mutex lock.
*
* When this feature is enabled, together with \ref LWPRINTF_CFG_OS, behavior is as following:
* - System mutex is kept created during init phase
* - Calls to direct printing functions are not thread-safe by default anymore
* - Calls to sprintf (buffer functions) are kept thread-safe
* - User must manually call \ref lwprintf_protect or \ref lwprintf_protect_ex functions to protect direct printing operation
* - User must manually call \ref lwprintf_unprotect or \ref lwprintf_unprotect_ex functions to exit protected area
*
* \note If you prefer to completely disable locking mechanism with this library,
* turn off \ref LWPRINTF_CFG_OS and fully manually handle mutual exclusion for non-reentrant functions
*/
#ifndef LWPRINTF_CFG_OS_MANUAL_PROTECT
#define LWPRINTF_CFG_OS_MANUAL_PROTECT 0
#endif
/**
* \brief Enables `1` or disables `0` support for `long long int` type, signed or unsigned.
*
*/
#ifndef LWPRINTF_CFG_SUPPORT_LONG_LONG
#define LWPRINTF_CFG_SUPPORT_LONG_LONG 1
#endif
/**
* \brief Enables `1` or disables `0` support for any specifier accepting any kind of integer types.
* This is enabling `%d, %b, %u, %o, %i, %x` specifiers
*
*/
#ifndef LWPRINTF_CFG_SUPPORT_TYPE_INT
#define LWPRINTF_CFG_SUPPORT_TYPE_INT 1
#endif
/**
* \brief Enables `1` or disables `0` support `%p` pointer print type
*
* When enabled, architecture must support `uintptr_t` type, normally available with C11 standard
*/
#ifndef LWPRINTF_CFG_SUPPORT_TYPE_POINTER
#define LWPRINTF_CFG_SUPPORT_TYPE_POINTER 1
#endif
/**
* \brief Enables `1` or disables `0` support `%f` float type
*
*/
#ifndef LWPRINTF_CFG_SUPPORT_TYPE_FLOAT
#define LWPRINTF_CFG_SUPPORT_TYPE_FLOAT 1
#endif
/**
* \brief Enables `1` or disables `0` support for `%e` engineering output type for float numbers
*
* \note \ref LWPRINTF_CFG_SUPPORT_TYPE_FLOAT has to be enabled to use this feature
*
*/
#ifndef LWPRINTF_CFG_SUPPORT_TYPE_ENGINEERING
#define LWPRINTF_CFG_SUPPORT_TYPE_ENGINEERING 1
#endif
/**
* \brief Enables `1` or disables `0` support for `%s` for string output
*
*/
#ifndef LWPRINTF_CFG_SUPPORT_TYPE_STRING
#define LWPRINTF_CFG_SUPPORT_TYPE_STRING 1
#endif
/**
* \brief Enables `1` or disables `0` support for `%k` for hex byte array output
*
*/
#ifndef LWPRINTF_CFG_SUPPORT_TYPE_BYTE_ARRAY
#define LWPRINTF_CFG_SUPPORT_TYPE_BYTE_ARRAY 1
#endif
/**
* \brief Specifies default number of precision for floating number
*
* Represents number of digits to be used after comma if no precision
* is set with specifier itself
*
*/
#ifndef LWPRINTF_CFG_FLOAT_DEFAULT_PRECISION
#define LWPRINTF_CFG_FLOAT_DEFAULT_PRECISION 6
#endif
/**
* \brief Enables `1` or disables `0` optional short names for LwPRINTF API functions.
*
* It adds functions for default instance: `lwprintf`, `lwsnprintf` and others
*/
#ifndef LWPRINTF_CFG_ENABLE_SHORTNAMES
#define LWPRINTF_CFG_ENABLE_SHORTNAMES 1
#endif /* LWPRINTF_CFG_ENABLE_SHORTNAMES */
/**
* \brief Enables `1` or disables `0` C standard API names
*
* Disabled by default not to interfere with compiler implementation.
* Application may need to remove standard C STDIO library from linkage
* to be able to properly compile LwPRINTF with this option enabled
*/
#ifndef LWPRINTF_CFG_ENABLE_STD_NAMES
#define LWPRINTF_CFG_ENABLE_STD_NAMES 0
#endif /* LWPRINTF_CFG_ENABLE_SHORTNAMES */
/**
* \}
*/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* LWPRINTF_OPT_HDR_H */

View File

@@ -0,0 +1,44 @@
/**
* \file lwprintf_opts_template.h
* \brief LwPRINTF configuration file
*/
/*
* Copyright (c) 2024 Tilen MAJERLE
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This file is part of LwPRINTF - Lightweight stdio manager library.
*
* Author: Tilen MAJERLE <tilen@majerle.eu>
* Version: v1.0.5
*/
#ifndef LWPRINTF_OPTS_HDR_H
#define LWPRINTF_OPTS_HDR_H
/* Rename this file to "lwprintf_opts.h" for your application */
/*
* Open "include/lwprintf/lwprintf_opt.h" and
* copy & replace here settings you want to change values
*/
#endif /* LWPRINTF_OPTS_HDR_H */