doc: renamed project

This commit is contained in:
SylvanArnold
2025-04-29 13:52:54 +02:00
committed by Sylvan Arnold
parent 244e516bd8
commit 32618389d1
985 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,537 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : C11.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : C11
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool C11_GetDir(void);
** SetDir - void C11_SetDir(bool Dir);
** SetInput - void C11_SetInput(void);
** SetOutput - void C11_SetOutput(void);
** GetVal - bool C11_GetVal(void);
** PutVal - void C11_PutVal(bool Val);
** ClrVal - void C11_ClrVal(void);
** SetVal - void C11_SetVal(void);
** NegVal - void C11_NegVal(void);
** Init - void C11_Init(void);
** Deinit - void C11_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file C11.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup C11_module C11 module documentation
** @{
*/
/* MODULE C11. */
#include "C11.h"
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if C11_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iocon.h" /* include SDK header file for I/O connection muxing */
#else /* Kinetis */
#include "fsl_port.h" /* include SDK header file for port muxing */
#endif
#endif
#include "fsl_gpio.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
#include "pins_gpio_hw_access.h"
#include "pins_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
#include "nrf_gpio.h"
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
#include "McuGPIO.h"
#else
#error "Unsupported SDK!"
#endif
#if McuLib_CONFIG_NXP_SDK_2_0_USED
static const gpio_pin_config_t C11_configOutput = {
kGPIO_DigitalOutput, /* use as output pin */
C11_CONFIG_INIT_PIN_VALUE, /* initial value */
};
static const gpio_pin_config_t C11_configInput = {
kGPIO_DigitalInput, /* use as input pin */
C11_CONFIG_INIT_PIN_VALUE, /* initial value */
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
const gpio_output_pin_user_config_t C11_OutputConfig[] = {
{
.pinName = C11_CONFIG_PIN_SYMBOL,
.config.outputLogic = C11_CONFIG_INIT_PIN_VALUE,
#if FSL_FEATURE_PORT_HAS_SLEW_RATE
.config.slewRate = kPortSlowSlewRate,
#endif
#if FSL_FEATURE_PORT_HAS_OPEN_DRAIN
.config.isOpenDrainEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH
.config.driveStrength = kPortLowDriveStrength,
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_input_pin_user_config_t C11_InputConfig[] = {
{
.pinName = C11_CONFIG_PIN_SYMBOL,
#if FSL_FEATURE_PORT_HAS_PULL_ENABLE
#if C11_CONFIG_PULL_RESISTOR==0 /* 0: no pull resistor, 1: pull-up, 2: pull-down, 3: pull-up or no pull, 4: pull-down or no pull: 4: autoselect-pull */
.config.isPullEnable = false,
#else
.config.isPullEnable = true,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PULL_SELECTION
#if C11_CONFIG_PULL_RESISTOR==1
.config.pullSelect = kPortPullUp,
#else
.config.pullSelect = kPortPullDown,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PASSIVE_FILTER
.config.isPassiveFilterEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER
.config.isDigitalFilterEnabled = true,
#endif
#if FSL_FEATURE_GPIO_HAS_INTERRUPT_VECTOR
.config.interrupt = kPortIntDisabled
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
static McuGPIO_Handle_t pin;
#endif
static bool C11_isOutput = false;
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_ClrVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#else
GPIO_PortClear(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_ClearPinOutput(C11_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_clear(C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetLow(pin);
#endif
}
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_SetVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#else
GPIO_PortSet(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinOutput(C11_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_set(C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetHigh(pin);
#endif
}
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_NegVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortToggle(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_TogglePinsOutput(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#else
GPIO_PortToggle(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_TogglePinOutput(C11_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsOutput(C11_CONFIG_PORT_NAME);
if (val&(1<<C11_CONFIG_PIN_NUMBER)) {
PINS_GPIO_WritePin(C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, 0);
} else {
PINS_GPIO_WritePin(C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, 1);
}
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_toggle(C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Toggle(pin);
#endif
}
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool C11_GetVal(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
return GPIO_PinRead(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
return GPIO_ReadPinInput(C11_CONFIG_GPIO_NAME, C11_CONFIG_PIN_NUMBER)!=0;
#else
return GPIO_PinRead(C11_CONFIG_GPIO_NAME, C11_CONFIG_PIN_NUMBER)!=0;
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
return GPIO_DRV_ReadPinInput(C11_CONFIG_PIN_SYMBOL)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
return (PINS_DRV_ReadPins(C11_CONFIG_PORT_NAME)&(1<<C11_CONFIG_PIN_NUMBER))!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
return nrf_gpio_pin_read(C11_CONFIG_PIN_NUMBER)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
return McuGPIO_GetValue(pin);
#else
return FALSE;
#endif
}
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
bool C11_GetDir(void)
{
return C11_isOutput;
}
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void C11_SetDir(bool Dir)
{
if (Dir) {
C11_SetOutput();
} else {
C11_SetInput();
}
}
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_SetInput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, &C11_configInput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(C11_CONFIG_GPIO_NAME, C11_CONFIG_PIN_NUMBER, &C11_configInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(C11_CONFIG_PIN_SYMBOL, kGpioDigitalInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(C11_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val &= ~(1<<C11_CONFIG_PIN_NUMBER); /* clear bit ==> input */
PINS_DRV_SetPinsDirection(C11_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_input(C11_CONFIG_PIN_NUMBER, NRF_GPIO_PIN_NOPULL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsInput(pin);
#endif
C11_isOutput = false;
}
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_SetOutput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, &C11_configOutput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(C11_CONFIG_GPIO_NAME, C11_CONFIG_PIN_NUMBER, &C11_configOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(C11_CONFIG_PIN_SYMBOL, kGpioDigitalOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(C11_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val |= (1<<C11_CONFIG_PIN_NUMBER); /* set bit ==> output */
PINS_DRV_SetPinsDirection(C11_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_output(C11_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsOutput(pin, false /* don't care */);
#endif
C11_isOutput = true;
}
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
void C11_PutVal(bool Val)
{
#if McuLib_CONFIG_CPU_IS_LPC
if (Val) {
GPIO_PortSet(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, 1<<C11_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(C11_CONFIG_GPIO_NAME, C11_CONFIG_PORT_NAME, 1<<C11_CONFIG_PIN_NUMBER);
}
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
if (Val) {
GPIO_SetPinsOutput(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
} else {
GPIO_ClearPinsOutput(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
}
#else
if (Val) {
GPIO_PortSet(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(C11_CONFIG_GPIO_NAME, 1<<C11_CONFIG_PIN_NUMBER);
}
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_WritePinOutput(C11_CONFIG_PIN_SYMBOL, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_DRV_WritePin(C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* NYI */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetValue(pin, Val);
#endif
}
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_Init(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if C11_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#define _IOCON_PIO_DIGITAL_EN 0x0100u /*!<@brief Enables digital function */
#define _IOCON_PIO_FUNC0 0x00u /*!<@brief Selects pin function 0 */
#define _IOCON_PIO_INV_DI 0x00u /*!<@brief Input function is not inverted */
#define _IOCON_PIO_MODE_PULLUP 0x10u /*!<@brief Selects pull-up function */
#define _IOCON_PIO_OPENDRAIN_DI 0x00u /*!<@brief Open drain is disabled */
#define _IOCON_PIO_SLEW_STANDARD 0x00u /*!<@brief Standard mode, output slew rate control is enabled */
const uint32_t port_pin_config = (/* Pin is configured as PI<portname>_<pinnumber> */
_IOCON_PIO_FUNC0 |
/* Selects pull-up function */
_IOCON_PIO_MODE_PULLUP |
/* Standard mode, output slew rate control is enabled */
_IOCON_PIO_SLEW_STANDARD |
/* Input function is not inverted */
_IOCON_PIO_INV_DI |
/* Enables digital function */
_IOCON_PIO_DIGITAL_EN |
/* Open drain is disabled */
_IOCON_PIO_OPENDRAIN_DI);
#if (McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0)
IOCON_PinMuxSet(C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, port_pin_config);
#else
IOCON_PinMuxSet(IOCON, C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, port_pin_config);
#endif
#else
PORT_SetPinMux(C11_CONFIG_PORT_NAME, C11_CONFIG_PIN_NUMBER, kPORT_MuxAsGpio); /* mux as GPIO */
#endif
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
/*! Pin Muxing not implemented */
GPIO_DRV_Init(C11_InputConfig, C11_OutputConfig);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
/* the following needs to be called in the application first:
PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr);
*/
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Config_t config;
McuGPIO_GetDefaultConfig(&config);
config.hw.pin = C11_CONFIG_PIN_NUMBER;
config.isInput = true;
pin = McuGPIO_InitGPIO(&config);
#endif
#if C11_CONFIG_INIT_PIN_DIRECTION == C11_CONFIG_INIT_PIN_DIRECTION_INPUT
C11_SetInput();
#elif C11_CONFIG_INIT_PIN_DIRECTION == C11_CONFIG_INIT_PIN_DIRECTION_OUTPUT
C11_SetOutput();
#endif
}
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_Deinit(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
pin = McuGPIO_DeinitGPIO(pin);
#endif
}
/* END C11. */
/*!
** @}
*/

View File

@@ -0,0 +1,243 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : C11.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : C11
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool C11_GetDir(void);
** SetDir - void C11_SetDir(bool Dir);
** SetInput - void C11_SetInput(void);
** SetOutput - void C11_SetOutput(void);
** GetVal - bool C11_GetVal(void);
** PutVal - void C11_PutVal(bool Val);
** ClrVal - void C11_ClrVal(void);
** SetVal - void C11_SetVal(void);
** NegVal - void C11_NegVal(void);
** Init - void C11_Init(void);
** Deinit - void C11_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file C11.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup C11_module C11 module documentation
** @{
*/
#ifndef __C11_H
#define __C11_H
/* MODULE C11. */
#include "McuLib.h" /* SDK and API used */
#include "C11config.h" /* configuration */
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h"
/* only GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF and GPIOG are currently supported */
#define C11_GPIO_IDX GPIOA_IDX /* GPIOA */
enum C11_pinNames{
C11_CONFIG_PIN_SYMBOL = GPIO_MAKE_PIN(C11_GPIO_IDX, C11_CONFIG_PIN_NUMBER),
};
extern const gpio_output_pin_user_config_t C11_OutputConfig[];
extern const gpio_input_pin_user_config_t C11_InputConfig[];
#endif
void C11_Init(void);
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_ClrVal(void);
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_SetVal(void);
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_NegVal(void);
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
bool C11_GetVal(void);
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool C11_GetDir(void);
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
void C11_SetDir(bool Dir);
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void C11_SetInput(void);
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_SetOutput(void);
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C11_PutVal(bool Val);
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
/* END C11. */
#endif
/* ifndef __C11_H */
/*!
** @}
*/

View File

@@ -0,0 +1,537 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : C21.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : C21
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool C21_GetDir(void);
** SetDir - void C21_SetDir(bool Dir);
** SetInput - void C21_SetInput(void);
** SetOutput - void C21_SetOutput(void);
** GetVal - bool C21_GetVal(void);
** PutVal - void C21_PutVal(bool Val);
** ClrVal - void C21_ClrVal(void);
** SetVal - void C21_SetVal(void);
** NegVal - void C21_NegVal(void);
** Init - void C21_Init(void);
** Deinit - void C21_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file C21.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup C21_module C21 module documentation
** @{
*/
/* MODULE C21. */
#include "C21.h"
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if C21_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iocon.h" /* include SDK header file for I/O connection muxing */
#else /* Kinetis */
#include "fsl_port.h" /* include SDK header file for port muxing */
#endif
#endif
#include "fsl_gpio.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
#include "pins_gpio_hw_access.h"
#include "pins_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
#include "nrf_gpio.h"
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
#include "McuGPIO.h"
#else
#error "Unsupported SDK!"
#endif
#if McuLib_CONFIG_NXP_SDK_2_0_USED
static const gpio_pin_config_t C21_configOutput = {
kGPIO_DigitalOutput, /* use as output pin */
C21_CONFIG_INIT_PIN_VALUE, /* initial value */
};
static const gpio_pin_config_t C21_configInput = {
kGPIO_DigitalInput, /* use as input pin */
C21_CONFIG_INIT_PIN_VALUE, /* initial value */
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
const gpio_output_pin_user_config_t C21_OutputConfig[] = {
{
.pinName = C21_CONFIG_PIN_SYMBOL,
.config.outputLogic = C21_CONFIG_INIT_PIN_VALUE,
#if FSL_FEATURE_PORT_HAS_SLEW_RATE
.config.slewRate = kPortSlowSlewRate,
#endif
#if FSL_FEATURE_PORT_HAS_OPEN_DRAIN
.config.isOpenDrainEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH
.config.driveStrength = kPortLowDriveStrength,
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_input_pin_user_config_t C21_InputConfig[] = {
{
.pinName = C21_CONFIG_PIN_SYMBOL,
#if FSL_FEATURE_PORT_HAS_PULL_ENABLE
#if C21_CONFIG_PULL_RESISTOR==0 /* 0: no pull resistor, 1: pull-up, 2: pull-down, 3: pull-up or no pull, 4: pull-down or no pull: 4: autoselect-pull */
.config.isPullEnable = false,
#else
.config.isPullEnable = true,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PULL_SELECTION
#if C21_CONFIG_PULL_RESISTOR==1
.config.pullSelect = kPortPullUp,
#else
.config.pullSelect = kPortPullDown,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PASSIVE_FILTER
.config.isPassiveFilterEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER
.config.isDigitalFilterEnabled = true,
#endif
#if FSL_FEATURE_GPIO_HAS_INTERRUPT_VECTOR
.config.interrupt = kPortIntDisabled
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
static McuGPIO_Handle_t pin;
#endif
static bool C21_isOutput = false;
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_ClrVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#else
GPIO_PortClear(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_ClearPinOutput(C21_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_clear(C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetLow(pin);
#endif
}
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_SetVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#else
GPIO_PortSet(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinOutput(C21_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_set(C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetHigh(pin);
#endif
}
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_NegVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortToggle(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_TogglePinsOutput(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#else
GPIO_PortToggle(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_TogglePinOutput(C21_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsOutput(C21_CONFIG_PORT_NAME);
if (val&(1<<C21_CONFIG_PIN_NUMBER)) {
PINS_GPIO_WritePin(C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, 0);
} else {
PINS_GPIO_WritePin(C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, 1);
}
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_toggle(C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Toggle(pin);
#endif
}
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool C21_GetVal(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
return GPIO_PinRead(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
return GPIO_ReadPinInput(C21_CONFIG_GPIO_NAME, C21_CONFIG_PIN_NUMBER)!=0;
#else
return GPIO_PinRead(C21_CONFIG_GPIO_NAME, C21_CONFIG_PIN_NUMBER)!=0;
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
return GPIO_DRV_ReadPinInput(C21_CONFIG_PIN_SYMBOL)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
return (PINS_DRV_ReadPins(C21_CONFIG_PORT_NAME)&(1<<C21_CONFIG_PIN_NUMBER))!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
return nrf_gpio_pin_read(C21_CONFIG_PIN_NUMBER)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
return McuGPIO_GetValue(pin);
#else
return FALSE;
#endif
}
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
bool C21_GetDir(void)
{
return C21_isOutput;
}
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void C21_SetDir(bool Dir)
{
if (Dir) {
C21_SetOutput();
} else {
C21_SetInput();
}
}
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_SetInput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, &C21_configInput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(C21_CONFIG_GPIO_NAME, C21_CONFIG_PIN_NUMBER, &C21_configInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(C21_CONFIG_PIN_SYMBOL, kGpioDigitalInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(C21_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val &= ~(1<<C21_CONFIG_PIN_NUMBER); /* clear bit ==> input */
PINS_DRV_SetPinsDirection(C21_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_input(C21_CONFIG_PIN_NUMBER, NRF_GPIO_PIN_NOPULL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsInput(pin);
#endif
C21_isOutput = false;
}
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_SetOutput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, &C21_configOutput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(C21_CONFIG_GPIO_NAME, C21_CONFIG_PIN_NUMBER, &C21_configOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(C21_CONFIG_PIN_SYMBOL, kGpioDigitalOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(C21_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val |= (1<<C21_CONFIG_PIN_NUMBER); /* set bit ==> output */
PINS_DRV_SetPinsDirection(C21_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_output(C21_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsOutput(pin, false /* don't care */);
#endif
C21_isOutput = true;
}
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
void C21_PutVal(bool Val)
{
#if McuLib_CONFIG_CPU_IS_LPC
if (Val) {
GPIO_PortSet(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, 1<<C21_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(C21_CONFIG_GPIO_NAME, C21_CONFIG_PORT_NAME, 1<<C21_CONFIG_PIN_NUMBER);
}
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
if (Val) {
GPIO_SetPinsOutput(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
} else {
GPIO_ClearPinsOutput(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
}
#else
if (Val) {
GPIO_PortSet(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(C21_CONFIG_GPIO_NAME, 1<<C21_CONFIG_PIN_NUMBER);
}
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_WritePinOutput(C21_CONFIG_PIN_SYMBOL, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_DRV_WritePin(C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* NYI */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetValue(pin, Val);
#endif
}
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_Init(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if C21_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#define _IOCON_PIO_DIGITAL_EN 0x0100u /*!<@brief Enables digital function */
#define _IOCON_PIO_FUNC0 0x00u /*!<@brief Selects pin function 0 */
#define _IOCON_PIO_INV_DI 0x00u /*!<@brief Input function is not inverted */
#define _IOCON_PIO_MODE_PULLUP 0x10u /*!<@brief Selects pull-up function */
#define _IOCON_PIO_OPENDRAIN_DI 0x00u /*!<@brief Open drain is disabled */
#define _IOCON_PIO_SLEW_STANDARD 0x00u /*!<@brief Standard mode, output slew rate control is enabled */
const uint32_t port_pin_config = (/* Pin is configured as PI<portname>_<pinnumber> */
_IOCON_PIO_FUNC0 |
/* Selects pull-up function */
_IOCON_PIO_MODE_PULLUP |
/* Standard mode, output slew rate control is enabled */
_IOCON_PIO_SLEW_STANDARD |
/* Input function is not inverted */
_IOCON_PIO_INV_DI |
/* Enables digital function */
_IOCON_PIO_DIGITAL_EN |
/* Open drain is disabled */
_IOCON_PIO_OPENDRAIN_DI);
#if (McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0)
IOCON_PinMuxSet(C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, port_pin_config);
#else
IOCON_PinMuxSet(IOCON, C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, port_pin_config);
#endif
#else
PORT_SetPinMux(C21_CONFIG_PORT_NAME, C21_CONFIG_PIN_NUMBER, kPORT_MuxAsGpio); /* mux as GPIO */
#endif
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
/*! Pin Muxing not implemented */
GPIO_DRV_Init(C21_InputConfig, C21_OutputConfig);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
/* the following needs to be called in the application first:
PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr);
*/
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Config_t config;
McuGPIO_GetDefaultConfig(&config);
config.hw.pin = C21_CONFIG_PIN_NUMBER;
config.isInput = true;
pin = McuGPIO_InitGPIO(&config);
#endif
#if C21_CONFIG_INIT_PIN_DIRECTION == C21_CONFIG_INIT_PIN_DIRECTION_INPUT
C21_SetInput();
#elif C21_CONFIG_INIT_PIN_DIRECTION == C21_CONFIG_INIT_PIN_DIRECTION_OUTPUT
C21_SetOutput();
#endif
}
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_Deinit(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
pin = McuGPIO_DeinitGPIO(pin);
#endif
}
/* END C21. */
/*!
** @}
*/

View File

@@ -0,0 +1,243 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : C21.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : C21
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool C21_GetDir(void);
** SetDir - void C21_SetDir(bool Dir);
** SetInput - void C21_SetInput(void);
** SetOutput - void C21_SetOutput(void);
** GetVal - bool C21_GetVal(void);
** PutVal - void C21_PutVal(bool Val);
** ClrVal - void C21_ClrVal(void);
** SetVal - void C21_SetVal(void);
** NegVal - void C21_NegVal(void);
** Init - void C21_Init(void);
** Deinit - void C21_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file C21.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup C21_module C21 module documentation
** @{
*/
#ifndef __C21_H
#define __C21_H
/* MODULE C21. */
#include "McuLib.h" /* SDK and API used */
#include "C21config.h" /* configuration */
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h"
/* only GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF and GPIOG are currently supported */
#define C21_GPIO_IDX GPIOA_IDX /* GPIOA */
enum C21_pinNames{
C21_CONFIG_PIN_SYMBOL = GPIO_MAKE_PIN(C21_GPIO_IDX, C21_CONFIG_PIN_NUMBER),
};
extern const gpio_output_pin_user_config_t C21_OutputConfig[];
extern const gpio_input_pin_user_config_t C21_InputConfig[];
#endif
void C21_Init(void);
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_ClrVal(void);
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_SetVal(void);
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_NegVal(void);
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
bool C21_GetVal(void);
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool C21_GetDir(void);
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
void C21_SetDir(bool Dir);
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void C21_SetInput(void);
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_SetOutput(void);
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void C21_PutVal(bool Val);
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
/* END C21. */
#endif
/* ifndef __C21_H */
/*!
** @}
*/

View File

@@ -0,0 +1,537 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : Clock1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : Clock1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool Clock1_GetDir(void);
** SetDir - void Clock1_SetDir(bool Dir);
** SetInput - void Clock1_SetInput(void);
** SetOutput - void Clock1_SetOutput(void);
** GetVal - bool Clock1_GetVal(void);
** PutVal - void Clock1_PutVal(bool Val);
** ClrVal - void Clock1_ClrVal(void);
** SetVal - void Clock1_SetVal(void);
** NegVal - void Clock1_NegVal(void);
** Init - void Clock1_Init(void);
** Deinit - void Clock1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file Clock1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup Clock1_module Clock1 module documentation
** @{
*/
/* MODULE Clock1. */
#include "Clock1.h"
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if Clock1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iocon.h" /* include SDK header file for I/O connection muxing */
#else /* Kinetis */
#include "fsl_port.h" /* include SDK header file for port muxing */
#endif
#endif
#include "fsl_gpio.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
#include "pins_gpio_hw_access.h"
#include "pins_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
#include "nrf_gpio.h"
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
#include "McuGPIO.h"
#else
#error "Unsupported SDK!"
#endif
#if McuLib_CONFIG_NXP_SDK_2_0_USED
static const gpio_pin_config_t Clock1_configOutput = {
kGPIO_DigitalOutput, /* use as output pin */
Clock1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
static const gpio_pin_config_t Clock1_configInput = {
kGPIO_DigitalInput, /* use as input pin */
Clock1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
const gpio_output_pin_user_config_t Clock1_OutputConfig[] = {
{
.pinName = Clock1_CONFIG_PIN_SYMBOL,
.config.outputLogic = Clock1_CONFIG_INIT_PIN_VALUE,
#if FSL_FEATURE_PORT_HAS_SLEW_RATE
.config.slewRate = kPortSlowSlewRate,
#endif
#if FSL_FEATURE_PORT_HAS_OPEN_DRAIN
.config.isOpenDrainEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH
.config.driveStrength = kPortLowDriveStrength,
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_input_pin_user_config_t Clock1_InputConfig[] = {
{
.pinName = Clock1_CONFIG_PIN_SYMBOL,
#if FSL_FEATURE_PORT_HAS_PULL_ENABLE
#if Clock1_CONFIG_PULL_RESISTOR==0 /* 0: no pull resistor, 1: pull-up, 2: pull-down, 3: pull-up or no pull, 4: pull-down or no pull: 4: autoselect-pull */
.config.isPullEnable = false,
#else
.config.isPullEnable = true,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PULL_SELECTION
#if Clock1_CONFIG_PULL_RESISTOR==1
.config.pullSelect = kPortPullUp,
#else
.config.pullSelect = kPortPullDown,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PASSIVE_FILTER
.config.isPassiveFilterEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER
.config.isDigitalFilterEnabled = true,
#endif
#if FSL_FEATURE_GPIO_HAS_INTERRUPT_VECTOR
.config.interrupt = kPortIntDisabled
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
static McuGPIO_Handle_t pin;
#endif
static bool Clock1_isOutput = false;
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_ClrVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#else
GPIO_PortClear(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_ClearPinOutput(Clock1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_clear(Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetLow(pin);
#endif
}
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_SetVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#else
GPIO_PortSet(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinOutput(Clock1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_set(Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetHigh(pin);
#endif
}
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_NegVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortToggle(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_TogglePinsOutput(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#else
GPIO_PortToggle(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_TogglePinOutput(Clock1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsOutput(Clock1_CONFIG_PORT_NAME);
if (val&(1<<Clock1_CONFIG_PIN_NUMBER)) {
PINS_GPIO_WritePin(Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, 0);
} else {
PINS_GPIO_WritePin(Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, 1);
}
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_toggle(Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Toggle(pin);
#endif
}
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool Clock1_GetVal(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
return GPIO_PinRead(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
return GPIO_ReadPinInput(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PIN_NUMBER)!=0;
#else
return GPIO_PinRead(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PIN_NUMBER)!=0;
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
return GPIO_DRV_ReadPinInput(Clock1_CONFIG_PIN_SYMBOL)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
return (PINS_DRV_ReadPins(Clock1_CONFIG_PORT_NAME)&(1<<Clock1_CONFIG_PIN_NUMBER))!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
return nrf_gpio_pin_read(Clock1_CONFIG_PIN_NUMBER)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
return McuGPIO_GetValue(pin);
#else
return FALSE;
#endif
}
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
bool Clock1_GetDir(void)
{
return Clock1_isOutput;
}
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void Clock1_SetDir(bool Dir)
{
if (Dir) {
Clock1_SetOutput();
} else {
Clock1_SetInput();
}
}
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_SetInput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, &Clock1_configInput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PIN_NUMBER, &Clock1_configInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(Clock1_CONFIG_PIN_SYMBOL, kGpioDigitalInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(Clock1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val &= ~(1<<Clock1_CONFIG_PIN_NUMBER); /* clear bit ==> input */
PINS_DRV_SetPinsDirection(Clock1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_input(Clock1_CONFIG_PIN_NUMBER, NRF_GPIO_PIN_NOPULL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsInput(pin);
#endif
Clock1_isOutput = false;
}
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_SetOutput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, &Clock1_configOutput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PIN_NUMBER, &Clock1_configOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(Clock1_CONFIG_PIN_SYMBOL, kGpioDigitalOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(Clock1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val |= (1<<Clock1_CONFIG_PIN_NUMBER); /* set bit ==> output */
PINS_DRV_SetPinsDirection(Clock1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_output(Clock1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsOutput(pin, false /* don't care */);
#endif
Clock1_isOutput = true;
}
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
void Clock1_PutVal(bool Val)
{
#if McuLib_CONFIG_CPU_IS_LPC
if (Val) {
GPIO_PortSet(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(Clock1_CONFIG_GPIO_NAME, Clock1_CONFIG_PORT_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
}
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
if (Val) {
GPIO_SetPinsOutput(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
} else {
GPIO_ClearPinsOutput(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
}
#else
if (Val) {
GPIO_PortSet(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(Clock1_CONFIG_GPIO_NAME, 1<<Clock1_CONFIG_PIN_NUMBER);
}
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_WritePinOutput(Clock1_CONFIG_PIN_SYMBOL, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_DRV_WritePin(Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* NYI */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetValue(pin, Val);
#endif
}
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_Init(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if Clock1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#define _IOCON_PIO_DIGITAL_EN 0x0100u /*!<@brief Enables digital function */
#define _IOCON_PIO_FUNC0 0x00u /*!<@brief Selects pin function 0 */
#define _IOCON_PIO_INV_DI 0x00u /*!<@brief Input function is not inverted */
#define _IOCON_PIO_MODE_PULLUP 0x10u /*!<@brief Selects pull-up function */
#define _IOCON_PIO_OPENDRAIN_DI 0x00u /*!<@brief Open drain is disabled */
#define _IOCON_PIO_SLEW_STANDARD 0x00u /*!<@brief Standard mode, output slew rate control is enabled */
const uint32_t port_pin_config = (/* Pin is configured as PI<portname>_<pinnumber> */
_IOCON_PIO_FUNC0 |
/* Selects pull-up function */
_IOCON_PIO_MODE_PULLUP |
/* Standard mode, output slew rate control is enabled */
_IOCON_PIO_SLEW_STANDARD |
/* Input function is not inverted */
_IOCON_PIO_INV_DI |
/* Enables digital function */
_IOCON_PIO_DIGITAL_EN |
/* Open drain is disabled */
_IOCON_PIO_OPENDRAIN_DI);
#if (McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0)
IOCON_PinMuxSet(Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, port_pin_config);
#else
IOCON_PinMuxSet(IOCON, Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, port_pin_config);
#endif
#else
PORT_SetPinMux(Clock1_CONFIG_PORT_NAME, Clock1_CONFIG_PIN_NUMBER, kPORT_MuxAsGpio); /* mux as GPIO */
#endif
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
/*! Pin Muxing not implemented */
GPIO_DRV_Init(Clock1_InputConfig, Clock1_OutputConfig);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
/* the following needs to be called in the application first:
PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr);
*/
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Config_t config;
McuGPIO_GetDefaultConfig(&config);
config.hw.pin = Clock1_CONFIG_PIN_NUMBER;
config.isInput = true;
pin = McuGPIO_InitGPIO(&config);
#endif
#if Clock1_CONFIG_INIT_PIN_DIRECTION == Clock1_CONFIG_INIT_PIN_DIRECTION_INPUT
Clock1_SetInput();
#elif Clock1_CONFIG_INIT_PIN_DIRECTION == Clock1_CONFIG_INIT_PIN_DIRECTION_OUTPUT
Clock1_SetOutput();
#endif
}
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_Deinit(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
pin = McuGPIO_DeinitGPIO(pin);
#endif
}
/* END Clock1. */
/*!
** @}
*/

View File

@@ -0,0 +1,243 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : Clock1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : Clock1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool Clock1_GetDir(void);
** SetDir - void Clock1_SetDir(bool Dir);
** SetInput - void Clock1_SetInput(void);
** SetOutput - void Clock1_SetOutput(void);
** GetVal - bool Clock1_GetVal(void);
** PutVal - void Clock1_PutVal(bool Val);
** ClrVal - void Clock1_ClrVal(void);
** SetVal - void Clock1_SetVal(void);
** NegVal - void Clock1_NegVal(void);
** Init - void Clock1_Init(void);
** Deinit - void Clock1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file Clock1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup Clock1_module Clock1 module documentation
** @{
*/
#ifndef __Clock1_H
#define __Clock1_H
/* MODULE Clock1. */
#include "McuLib.h" /* SDK and API used */
#include "Clock1config.h" /* configuration */
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h"
/* only GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF and GPIOG are currently supported */
#define Clock1_GPIO_IDX GPIOA_IDX /* GPIOA */
enum Clock1_pinNames{
Clock1_CONFIG_PIN_SYMBOL = GPIO_MAKE_PIN(Clock1_GPIO_IDX, Clock1_CONFIG_PIN_NUMBER),
};
extern const gpio_output_pin_user_config_t Clock1_OutputConfig[];
extern const gpio_input_pin_user_config_t Clock1_InputConfig[];
#endif
void Clock1_Init(void);
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_ClrVal(void);
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_SetVal(void);
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_NegVal(void);
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
bool Clock1_GetVal(void);
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool Clock1_GetDir(void);
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
void Clock1_SetDir(bool Dir);
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void Clock1_SetInput(void);
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_SetOutput(void);
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Clock1_PutVal(bool Val);
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
/* END Clock1. */
#endif
/* ifndef __Clock1_H */
/*!
** @}
*/

View File

@@ -0,0 +1,537 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : DQ1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : DQ1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : OneWireData
** Do Pin Muxing : no
** Init Direction : Input
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool DQ1_GetDir(void);
** SetDir - void DQ1_SetDir(bool Dir);
** SetInput - void DQ1_SetInput(void);
** SetOutput - void DQ1_SetOutput(void);
** GetVal - bool DQ1_GetVal(void);
** PutVal - void DQ1_PutVal(bool Val);
** ClrVal - void DQ1_ClrVal(void);
** SetVal - void DQ1_SetVal(void);
** NegVal - void DQ1_NegVal(void);
** Init - void DQ1_Init(void);
** Deinit - void DQ1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file DQ1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup DQ1_module DQ1 module documentation
** @{
*/
/* MODULE DQ1. */
#include "DQ1.h"
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if DQ1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iocon.h" /* include SDK header file for I/O connection muxing */
#else /* Kinetis */
#include "fsl_port.h" /* include SDK header file for port muxing */
#endif
#endif
#include "fsl_gpio.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
#include "pins_gpio_hw_access.h"
#include "pins_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
#include "nrf_gpio.h"
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
#include "McuGPIO.h"
#else
#error "Unsupported SDK!"
#endif
#if McuLib_CONFIG_NXP_SDK_2_0_USED
static const gpio_pin_config_t DQ1_configOutput = {
kGPIO_DigitalOutput, /* use as output pin */
DQ1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
static const gpio_pin_config_t DQ1_configInput = {
kGPIO_DigitalInput, /* use as input pin */
DQ1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
const gpio_output_pin_user_config_t DQ1_OutputConfig[] = {
{
.pinName = DQ1_CONFIG_PIN_SYMBOL,
.config.outputLogic = DQ1_CONFIG_INIT_PIN_VALUE,
#if FSL_FEATURE_PORT_HAS_SLEW_RATE
.config.slewRate = kPortSlowSlewRate,
#endif
#if FSL_FEATURE_PORT_HAS_OPEN_DRAIN
.config.isOpenDrainEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH
.config.driveStrength = kPortLowDriveStrength,
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_input_pin_user_config_t DQ1_InputConfig[] = {
{
.pinName = DQ1_CONFIG_PIN_SYMBOL,
#if FSL_FEATURE_PORT_HAS_PULL_ENABLE
#if DQ1_CONFIG_PULL_RESISTOR==0 /* 0: no pull resistor, 1: pull-up, 2: pull-down, 3: pull-up or no pull, 4: pull-down or no pull: 4: autoselect-pull */
.config.isPullEnable = false,
#else
.config.isPullEnable = true,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PULL_SELECTION
#if DQ1_CONFIG_PULL_RESISTOR==1
.config.pullSelect = kPortPullUp,
#else
.config.pullSelect = kPortPullDown,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PASSIVE_FILTER
.config.isPassiveFilterEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER
.config.isDigitalFilterEnabled = true,
#endif
#if FSL_FEATURE_GPIO_HAS_INTERRUPT_VECTOR
.config.interrupt = kPortIntDisabled
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
static McuGPIO_Handle_t pin;
#endif
static bool DQ1_isOutput = false;
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_ClrVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#else
GPIO_PortClear(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_ClearPinOutput(DQ1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_clear(DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetLow(pin);
#endif
}
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_SetVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#else
GPIO_PortSet(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinOutput(DQ1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_set(DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetHigh(pin);
#endif
}
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_NegVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortToggle(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_TogglePinsOutput(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#else
GPIO_PortToggle(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_TogglePinOutput(DQ1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsOutput(DQ1_CONFIG_PORT_NAME);
if (val&(1<<DQ1_CONFIG_PIN_NUMBER)) {
PINS_GPIO_WritePin(DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, 0);
} else {
PINS_GPIO_WritePin(DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, 1);
}
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_toggle(DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Toggle(pin);
#endif
}
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool DQ1_GetVal(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
return GPIO_PinRead(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
return GPIO_ReadPinInput(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PIN_NUMBER)!=0;
#else
return GPIO_PinRead(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PIN_NUMBER)!=0;
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
return GPIO_DRV_ReadPinInput(DQ1_CONFIG_PIN_SYMBOL)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
return (PINS_DRV_ReadPins(DQ1_CONFIG_PORT_NAME)&(1<<DQ1_CONFIG_PIN_NUMBER))!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
return nrf_gpio_pin_read(DQ1_CONFIG_PIN_NUMBER)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
return McuGPIO_GetValue(pin);
#else
return FALSE;
#endif
}
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
bool DQ1_GetDir(void)
{
return DQ1_isOutput;
}
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void DQ1_SetDir(bool Dir)
{
if (Dir) {
DQ1_SetOutput();
} else {
DQ1_SetInput();
}
}
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_SetInput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, &DQ1_configInput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PIN_NUMBER, &DQ1_configInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(DQ1_CONFIG_PIN_SYMBOL, kGpioDigitalInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(DQ1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val &= ~(1<<DQ1_CONFIG_PIN_NUMBER); /* clear bit ==> input */
PINS_DRV_SetPinsDirection(DQ1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_input(DQ1_CONFIG_PIN_NUMBER, NRF_GPIO_PIN_NOPULL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsInput(pin);
#endif
DQ1_isOutput = false;
}
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_SetOutput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, &DQ1_configOutput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PIN_NUMBER, &DQ1_configOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(DQ1_CONFIG_PIN_SYMBOL, kGpioDigitalOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(DQ1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val |= (1<<DQ1_CONFIG_PIN_NUMBER); /* set bit ==> output */
PINS_DRV_SetPinsDirection(DQ1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_output(DQ1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsOutput(pin, false /* don't care */);
#endif
DQ1_isOutput = true;
}
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
void DQ1_PutVal(bool Val)
{
#if McuLib_CONFIG_CPU_IS_LPC
if (Val) {
GPIO_PortSet(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(DQ1_CONFIG_GPIO_NAME, DQ1_CONFIG_PORT_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
}
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
if (Val) {
GPIO_SetPinsOutput(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
} else {
GPIO_ClearPinsOutput(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
}
#else
if (Val) {
GPIO_PortSet(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(DQ1_CONFIG_GPIO_NAME, 1<<DQ1_CONFIG_PIN_NUMBER);
}
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_WritePinOutput(DQ1_CONFIG_PIN_SYMBOL, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_DRV_WritePin(DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* NYI */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetValue(pin, Val);
#endif
}
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_Init(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if DQ1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#define _IOCON_PIO_DIGITAL_EN 0x0100u /*!<@brief Enables digital function */
#define _IOCON_PIO_FUNC0 0x00u /*!<@brief Selects pin function 0 */
#define _IOCON_PIO_INV_DI 0x00u /*!<@brief Input function is not inverted */
#define _IOCON_PIO_MODE_PULLUP 0x10u /*!<@brief Selects pull-up function */
#define _IOCON_PIO_OPENDRAIN_DI 0x00u /*!<@brief Open drain is disabled */
#define _IOCON_PIO_SLEW_STANDARD 0x00u /*!<@brief Standard mode, output slew rate control is enabled */
const uint32_t port_pin_config = (/* Pin is configured as PI<portname>_<pinnumber> */
_IOCON_PIO_FUNC0 |
/* Selects pull-up function */
_IOCON_PIO_MODE_PULLUP |
/* Standard mode, output slew rate control is enabled */
_IOCON_PIO_SLEW_STANDARD |
/* Input function is not inverted */
_IOCON_PIO_INV_DI |
/* Enables digital function */
_IOCON_PIO_DIGITAL_EN |
/* Open drain is disabled */
_IOCON_PIO_OPENDRAIN_DI);
#if (McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0)
IOCON_PinMuxSet(DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, port_pin_config);
#else
IOCON_PinMuxSet(IOCON, DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, port_pin_config);
#endif
#else
PORT_SetPinMux(DQ1_CONFIG_PORT_NAME, DQ1_CONFIG_PIN_NUMBER, kPORT_MuxAsGpio); /* mux as GPIO */
#endif
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
/*! Pin Muxing not implemented */
GPIO_DRV_Init(DQ1_InputConfig, DQ1_OutputConfig);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
/* the following needs to be called in the application first:
PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr);
*/
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Config_t config;
McuGPIO_GetDefaultConfig(&config);
config.hw.pin = DQ1_CONFIG_PIN_NUMBER;
config.isInput = true;
pin = McuGPIO_InitGPIO(&config);
#endif
#if DQ1_CONFIG_INIT_PIN_DIRECTION == DQ1_CONFIG_INIT_PIN_DIRECTION_INPUT
DQ1_SetInput();
#elif DQ1_CONFIG_INIT_PIN_DIRECTION == DQ1_CONFIG_INIT_PIN_DIRECTION_OUTPUT
DQ1_SetOutput();
#endif
}
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_Deinit(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
pin = McuGPIO_DeinitGPIO(pin);
#endif
}
/* END DQ1. */
/*!
** @}
*/

View File

@@ -0,0 +1,243 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : DQ1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : DQ1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : OneWireData
** Do Pin Muxing : no
** Init Direction : Input
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool DQ1_GetDir(void);
** SetDir - void DQ1_SetDir(bool Dir);
** SetInput - void DQ1_SetInput(void);
** SetOutput - void DQ1_SetOutput(void);
** GetVal - bool DQ1_GetVal(void);
** PutVal - void DQ1_PutVal(bool Val);
** ClrVal - void DQ1_ClrVal(void);
** SetVal - void DQ1_SetVal(void);
** NegVal - void DQ1_NegVal(void);
** Init - void DQ1_Init(void);
** Deinit - void DQ1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file DQ1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup DQ1_module DQ1 module documentation
** @{
*/
#ifndef __DQ1_H
#define __DQ1_H
/* MODULE DQ1. */
#include "McuLib.h" /* SDK and API used */
#include "DQ1config.h" /* configuration */
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h"
/* only GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF and GPIOG are currently supported */
#define DQ1_GPIO_IDX GPIOA_IDX /* GPIOA */
enum DQ1_pinNames{
DQ1_CONFIG_PIN_SYMBOL = GPIO_MAKE_PIN(DQ1_GPIO_IDX, DQ1_CONFIG_PIN_NUMBER),
};
extern const gpio_output_pin_user_config_t DQ1_OutputConfig[];
extern const gpio_input_pin_user_config_t DQ1_InputConfig[];
#endif
void DQ1_Init(void);
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_ClrVal(void);
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_SetVal(void);
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_NegVal(void);
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
bool DQ1_GetVal(void);
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool DQ1_GetDir(void);
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
void DQ1_SetDir(bool Dir);
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void DQ1_SetInput(void);
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_SetOutput(void);
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DQ1_PutVal(bool Val);
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
/* END DQ1. */
#endif
/* ifndef __DQ1_H */
/*!
** @}
*/

View File

@@ -0,0 +1,537 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : DbgRd1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : DbgRd1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 1
** Pin Symbol : OneWireDbgRead
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool DbgRd1_GetDir(void);
** SetDir - void DbgRd1_SetDir(bool Dir);
** SetInput - void DbgRd1_SetInput(void);
** SetOutput - void DbgRd1_SetOutput(void);
** GetVal - bool DbgRd1_GetVal(void);
** PutVal - void DbgRd1_PutVal(bool Val);
** ClrVal - void DbgRd1_ClrVal(void);
** SetVal - void DbgRd1_SetVal(void);
** NegVal - void DbgRd1_NegVal(void);
** Init - void DbgRd1_Init(void);
** Deinit - void DbgRd1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file DbgRd1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup DbgRd1_module DbgRd1 module documentation
** @{
*/
/* MODULE DbgRd1. */
#include "DbgRd1.h"
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if DbgRd1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iocon.h" /* include SDK header file for I/O connection muxing */
#else /* Kinetis */
#include "fsl_port.h" /* include SDK header file for port muxing */
#endif
#endif
#include "fsl_gpio.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
#include "pins_gpio_hw_access.h"
#include "pins_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
#include "nrf_gpio.h"
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
#include "McuGPIO.h"
#else
#error "Unsupported SDK!"
#endif
#if McuLib_CONFIG_NXP_SDK_2_0_USED
static const gpio_pin_config_t DbgRd1_configOutput = {
kGPIO_DigitalOutput, /* use as output pin */
DbgRd1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
static const gpio_pin_config_t DbgRd1_configInput = {
kGPIO_DigitalInput, /* use as input pin */
DbgRd1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
const gpio_output_pin_user_config_t DbgRd1_OutputConfig[] = {
{
.pinName = DbgRd1_CONFIG_PIN_SYMBOL,
.config.outputLogic = DbgRd1_CONFIG_INIT_PIN_VALUE,
#if FSL_FEATURE_PORT_HAS_SLEW_RATE
.config.slewRate = kPortSlowSlewRate,
#endif
#if FSL_FEATURE_PORT_HAS_OPEN_DRAIN
.config.isOpenDrainEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH
.config.driveStrength = kPortLowDriveStrength,
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_input_pin_user_config_t DbgRd1_InputConfig[] = {
{
.pinName = DbgRd1_CONFIG_PIN_SYMBOL,
#if FSL_FEATURE_PORT_HAS_PULL_ENABLE
#if DbgRd1_CONFIG_PULL_RESISTOR==0 /* 0: no pull resistor, 1: pull-up, 2: pull-down, 3: pull-up or no pull, 4: pull-down or no pull: 4: autoselect-pull */
.config.isPullEnable = false,
#else
.config.isPullEnable = true,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PULL_SELECTION
#if DbgRd1_CONFIG_PULL_RESISTOR==1
.config.pullSelect = kPortPullUp,
#else
.config.pullSelect = kPortPullDown,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PASSIVE_FILTER
.config.isPassiveFilterEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER
.config.isDigitalFilterEnabled = true,
#endif
#if FSL_FEATURE_GPIO_HAS_INTERRUPT_VECTOR
.config.interrupt = kPortIntDisabled
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
static McuGPIO_Handle_t pin;
#endif
static bool DbgRd1_isOutput = false;
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_ClrVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#else
GPIO_PortClear(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_ClearPinOutput(DbgRd1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_clear(DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetLow(pin);
#endif
}
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_SetVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#else
GPIO_PortSet(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinOutput(DbgRd1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_set(DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetHigh(pin);
#endif
}
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_NegVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortToggle(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_TogglePinsOutput(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#else
GPIO_PortToggle(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_TogglePinOutput(DbgRd1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsOutput(DbgRd1_CONFIG_PORT_NAME);
if (val&(1<<DbgRd1_CONFIG_PIN_NUMBER)) {
PINS_GPIO_WritePin(DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, 0);
} else {
PINS_GPIO_WritePin(DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, 1);
}
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_toggle(DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Toggle(pin);
#endif
}
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool DbgRd1_GetVal(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
return GPIO_PinRead(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
return GPIO_ReadPinInput(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PIN_NUMBER)!=0;
#else
return GPIO_PinRead(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PIN_NUMBER)!=0;
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
return GPIO_DRV_ReadPinInput(DbgRd1_CONFIG_PIN_SYMBOL)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
return (PINS_DRV_ReadPins(DbgRd1_CONFIG_PORT_NAME)&(1<<DbgRd1_CONFIG_PIN_NUMBER))!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
return nrf_gpio_pin_read(DbgRd1_CONFIG_PIN_NUMBER)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
return McuGPIO_GetValue(pin);
#else
return FALSE;
#endif
}
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
bool DbgRd1_GetDir(void)
{
return DbgRd1_isOutput;
}
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_SetDir(bool Dir)
{
if (Dir) {
DbgRd1_SetOutput();
} else {
DbgRd1_SetInput();
}
}
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_SetInput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, &DbgRd1_configInput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PIN_NUMBER, &DbgRd1_configInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(DbgRd1_CONFIG_PIN_SYMBOL, kGpioDigitalInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(DbgRd1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val &= ~(1<<DbgRd1_CONFIG_PIN_NUMBER); /* clear bit ==> input */
PINS_DRV_SetPinsDirection(DbgRd1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_input(DbgRd1_CONFIG_PIN_NUMBER, NRF_GPIO_PIN_NOPULL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsInput(pin);
#endif
DbgRd1_isOutput = false;
}
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_SetOutput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, &DbgRd1_configOutput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PIN_NUMBER, &DbgRd1_configOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(DbgRd1_CONFIG_PIN_SYMBOL, kGpioDigitalOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(DbgRd1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val |= (1<<DbgRd1_CONFIG_PIN_NUMBER); /* set bit ==> output */
PINS_DRV_SetPinsDirection(DbgRd1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_output(DbgRd1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsOutput(pin, false /* don't care */);
#endif
DbgRd1_isOutput = true;
}
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_PutVal(bool Val)
{
#if McuLib_CONFIG_CPU_IS_LPC
if (Val) {
GPIO_PortSet(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(DbgRd1_CONFIG_GPIO_NAME, DbgRd1_CONFIG_PORT_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
}
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
if (Val) {
GPIO_SetPinsOutput(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
} else {
GPIO_ClearPinsOutput(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
}
#else
if (Val) {
GPIO_PortSet(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(DbgRd1_CONFIG_GPIO_NAME, 1<<DbgRd1_CONFIG_PIN_NUMBER);
}
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_WritePinOutput(DbgRd1_CONFIG_PIN_SYMBOL, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_DRV_WritePin(DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* NYI */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetValue(pin, Val);
#endif
}
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_Init(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if DbgRd1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#define _IOCON_PIO_DIGITAL_EN 0x0100u /*!<@brief Enables digital function */
#define _IOCON_PIO_FUNC0 0x00u /*!<@brief Selects pin function 0 */
#define _IOCON_PIO_INV_DI 0x00u /*!<@brief Input function is not inverted */
#define _IOCON_PIO_MODE_PULLUP 0x10u /*!<@brief Selects pull-up function */
#define _IOCON_PIO_OPENDRAIN_DI 0x00u /*!<@brief Open drain is disabled */
#define _IOCON_PIO_SLEW_STANDARD 0x00u /*!<@brief Standard mode, output slew rate control is enabled */
const uint32_t port_pin_config = (/* Pin is configured as PI<portname>_<pinnumber> */
_IOCON_PIO_FUNC0 |
/* Selects pull-up function */
_IOCON_PIO_MODE_PULLUP |
/* Standard mode, output slew rate control is enabled */
_IOCON_PIO_SLEW_STANDARD |
/* Input function is not inverted */
_IOCON_PIO_INV_DI |
/* Enables digital function */
_IOCON_PIO_DIGITAL_EN |
/* Open drain is disabled */
_IOCON_PIO_OPENDRAIN_DI);
#if (McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0)
IOCON_PinMuxSet(DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, port_pin_config);
#else
IOCON_PinMuxSet(IOCON, DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, port_pin_config);
#endif
#else
PORT_SetPinMux(DbgRd1_CONFIG_PORT_NAME, DbgRd1_CONFIG_PIN_NUMBER, kPORT_MuxAsGpio); /* mux as GPIO */
#endif
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
/*! Pin Muxing not implemented */
GPIO_DRV_Init(DbgRd1_InputConfig, DbgRd1_OutputConfig);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
/* the following needs to be called in the application first:
PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr);
*/
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Config_t config;
McuGPIO_GetDefaultConfig(&config);
config.hw.pin = DbgRd1_CONFIG_PIN_NUMBER;
config.isInput = true;
pin = McuGPIO_InitGPIO(&config);
#endif
#if DbgRd1_CONFIG_INIT_PIN_DIRECTION == DbgRd1_CONFIG_INIT_PIN_DIRECTION_INPUT
DbgRd1_SetInput();
#elif DbgRd1_CONFIG_INIT_PIN_DIRECTION == DbgRd1_CONFIG_INIT_PIN_DIRECTION_OUTPUT
DbgRd1_SetOutput();
#endif
}
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_Deinit(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
pin = McuGPIO_DeinitGPIO(pin);
#endif
}
/* END DbgRd1. */
/*!
** @}
*/

View File

@@ -0,0 +1,243 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : DbgRd1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : DbgRd1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 1
** Pin Symbol : OneWireDbgRead
** Do Pin Muxing : no
** Init Direction : Output
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool DbgRd1_GetDir(void);
** SetDir - void DbgRd1_SetDir(bool Dir);
** SetInput - void DbgRd1_SetInput(void);
** SetOutput - void DbgRd1_SetOutput(void);
** GetVal - bool DbgRd1_GetVal(void);
** PutVal - void DbgRd1_PutVal(bool Val);
** ClrVal - void DbgRd1_ClrVal(void);
** SetVal - void DbgRd1_SetVal(void);
** NegVal - void DbgRd1_NegVal(void);
** Init - void DbgRd1_Init(void);
** Deinit - void DbgRd1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file DbgRd1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup DbgRd1_module DbgRd1 module documentation
** @{
*/
#ifndef __DbgRd1_H
#define __DbgRd1_H
/* MODULE DbgRd1. */
#include "McuLib.h" /* SDK and API used */
#include "DbgRd1config.h" /* configuration */
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h"
/* only GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF and GPIOG are currently supported */
#define DbgRd1_GPIO_IDX GPIOA_IDX /* GPIOA */
enum DbgRd1_pinNames{
DbgRd1_CONFIG_PIN_SYMBOL = GPIO_MAKE_PIN(DbgRd1_GPIO_IDX, DbgRd1_CONFIG_PIN_NUMBER),
};
extern const gpio_output_pin_user_config_t DbgRd1_OutputConfig[];
extern const gpio_input_pin_user_config_t DbgRd1_InputConfig[];
#endif
void DbgRd1_Init(void);
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_ClrVal(void);
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_SetVal(void);
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_NegVal(void);
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
bool DbgRd1_GetVal(void);
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool DbgRd1_GetDir(void);
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
void DbgRd1_SetDir(bool Dir);
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_SetInput(void);
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_SetOutput(void);
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void DbgRd1_PutVal(bool Val);
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
/* END DbgRd1. */
#endif
/* ifndef __DbgRd1_H */
/*!
** @}
*/

View File

@@ -0,0 +1,537 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : Input1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : Input1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Input
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool Input1_GetDir(void);
** SetDir - void Input1_SetDir(bool Dir);
** SetInput - void Input1_SetInput(void);
** SetOutput - void Input1_SetOutput(void);
** GetVal - bool Input1_GetVal(void);
** PutVal - void Input1_PutVal(bool Val);
** ClrVal - void Input1_ClrVal(void);
** SetVal - void Input1_SetVal(void);
** NegVal - void Input1_NegVal(void);
** Init - void Input1_Init(void);
** Deinit - void Input1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file Input1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup Input1_module Input1 module documentation
** @{
*/
/* MODULE Input1. */
#include "Input1.h"
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if Input1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iocon.h" /* include SDK header file for I/O connection muxing */
#else /* Kinetis */
#include "fsl_port.h" /* include SDK header file for port muxing */
#endif
#endif
#include "fsl_gpio.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
#include "pins_gpio_hw_access.h"
#include "pins_driver.h" /* include SDK header file for GPIO */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
#include "nrf_gpio.h"
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
#include "McuGPIO.h"
#else
#error "Unsupported SDK!"
#endif
#if McuLib_CONFIG_NXP_SDK_2_0_USED
static const gpio_pin_config_t Input1_configOutput = {
kGPIO_DigitalOutput, /* use as output pin */
Input1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
static const gpio_pin_config_t Input1_configInput = {
kGPIO_DigitalInput, /* use as input pin */
Input1_CONFIG_INIT_PIN_VALUE, /* initial value */
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
const gpio_output_pin_user_config_t Input1_OutputConfig[] = {
{
.pinName = Input1_CONFIG_PIN_SYMBOL,
.config.outputLogic = Input1_CONFIG_INIT_PIN_VALUE,
#if FSL_FEATURE_PORT_HAS_SLEW_RATE
.config.slewRate = kPortSlowSlewRate,
#endif
#if FSL_FEATURE_PORT_HAS_OPEN_DRAIN
.config.isOpenDrainEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH
.config.driveStrength = kPortLowDriveStrength,
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_input_pin_user_config_t Input1_InputConfig[] = {
{
.pinName = Input1_CONFIG_PIN_SYMBOL,
#if FSL_FEATURE_PORT_HAS_PULL_ENABLE
#if Input1_CONFIG_PULL_RESISTOR==0 /* 0: no pull resistor, 1: pull-up, 2: pull-down, 3: pull-up or no pull, 4: pull-down or no pull: 4: autoselect-pull */
.config.isPullEnable = false,
#else
.config.isPullEnable = true,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PULL_SELECTION
#if Input1_CONFIG_PULL_RESISTOR==1
.config.pullSelect = kPortPullUp,
#else
.config.pullSelect = kPortPullDown,
#endif
#endif
#if FSL_FEATURE_PORT_HAS_PASSIVE_FILTER
.config.isPassiveFilterEnabled = true,
#endif
#if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER
.config.isDigitalFilterEnabled = true,
#endif
#if FSL_FEATURE_GPIO_HAS_INTERRUPT_VECTOR
.config.interrupt = kPortIntDisabled
#endif
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
static McuGPIO_Handle_t pin;
#endif
static bool Input1_isOutput = false;
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_ClrVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#else
GPIO_PortClear(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_ClearPinOutput(Input1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_clear(Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetLow(pin);
#endif
}
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_SetVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#else
GPIO_PortSet(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinOutput(Input1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_GPIO_WritePin(Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_set(Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetHigh(pin);
#endif
}
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_NegVal(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PortToggle(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION < 250
GPIO_TogglePinsOutput(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#else
GPIO_PortToggle(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_TogglePinOutput(Input1_CONFIG_PIN_SYMBOL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsOutput(Input1_CONFIG_PORT_NAME);
if (val&(1<<Input1_CONFIG_PIN_NUMBER)) {
PINS_GPIO_WritePin(Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, 0);
} else {
PINS_GPIO_WritePin(Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, 1);
}
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_pin_toggle(Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Toggle(pin);
#endif
}
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool Input1_GetVal(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
return GPIO_PinRead(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
return GPIO_ReadPinInput(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PIN_NUMBER)!=0;
#else
return GPIO_PinRead(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PIN_NUMBER)!=0;
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
return GPIO_DRV_ReadPinInput(Input1_CONFIG_PIN_SYMBOL)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
return (PINS_DRV_ReadPins(Input1_CONFIG_PORT_NAME)&(1<<Input1_CONFIG_PIN_NUMBER))!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
return nrf_gpio_pin_read(Input1_CONFIG_PIN_NUMBER)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
return McuGPIO_GetValue(pin);
#else
return FALSE;
#endif
}
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
bool Input1_GetDir(void)
{
return Input1_isOutput;
}
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void Input1_SetDir(bool Dir)
{
if (Dir) {
Input1_SetOutput();
} else {
Input1_SetInput();
}
}
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_SetInput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, &Input1_configInput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PIN_NUMBER, &Input1_configInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(Input1_CONFIG_PIN_SYMBOL, kGpioDigitalInput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(Input1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val &= ~(1<<Input1_CONFIG_PIN_NUMBER); /* clear bit ==> input */
PINS_DRV_SetPinsDirection(Input1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_input(Input1_CONFIG_PIN_NUMBER, NRF_GPIO_PIN_NOPULL);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsInput(pin);
#endif
Input1_isOutput = false;
}
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_SetOutput(void)
{
#if McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, &Input1_configOutput);
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
GPIO_PinInit(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PIN_NUMBER, &Input1_configOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_SetPinDir(Input1_CONFIG_PIN_SYMBOL, kGpioDigitalOutput);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
pins_channel_type_t val;
val = PINS_GPIO_GetPinsDirection(Input1_CONFIG_PORT_NAME); /* bit 0: pin is input; 1: pin is output */
val |= (1<<Input1_CONFIG_PIN_NUMBER); /* set bit ==> output */
PINS_DRV_SetPinsDirection(Input1_CONFIG_PORT_NAME, val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
nrf_gpio_cfg_output(Input1_CONFIG_PIN_NUMBER);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetAsOutput(pin, false /* don't care */);
#endif
Input1_isOutput = true;
}
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
void Input1_PutVal(bool Val)
{
#if McuLib_CONFIG_CPU_IS_LPC
if (Val) {
GPIO_PortSet(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(Input1_CONFIG_GPIO_NAME, Input1_CONFIG_PORT_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
}
#elif McuLib_CONFIG_NXP_SDK_2_0_USED
#if McuLib_CONFIG_SDK_VERSION < 250
if (Val) {
GPIO_SetPinsOutput(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
} else {
GPIO_ClearPinsOutput(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
}
#else
if (Val) {
GPIO_PortSet(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
} else {
GPIO_PortClear(Input1_CONFIG_GPIO_NAME, 1<<Input1_CONFIG_PIN_NUMBER);
}
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
GPIO_DRV_WritePinOutput(Input1_CONFIG_PIN_SYMBOL, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
PINS_DRV_WritePin(Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, Val);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* NYI */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_SetValue(pin, Val);
#endif
}
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_Init(void)
{
#if McuLib_CONFIG_NXP_SDK_2_0_USED
#if Input1_CONFIG_DO_PIN_MUXING
#if McuLib_CONFIG_CPU_IS_LPC
#define _IOCON_PIO_DIGITAL_EN 0x0100u /*!<@brief Enables digital function */
#define _IOCON_PIO_FUNC0 0x00u /*!<@brief Selects pin function 0 */
#define _IOCON_PIO_INV_DI 0x00u /*!<@brief Input function is not inverted */
#define _IOCON_PIO_MODE_PULLUP 0x10u /*!<@brief Selects pull-up function */
#define _IOCON_PIO_OPENDRAIN_DI 0x00u /*!<@brief Open drain is disabled */
#define _IOCON_PIO_SLEW_STANDARD 0x00u /*!<@brief Standard mode, output slew rate control is enabled */
const uint32_t port_pin_config = (/* Pin is configured as PI<portname>_<pinnumber> */
_IOCON_PIO_FUNC0 |
/* Selects pull-up function */
_IOCON_PIO_MODE_PULLUP |
/* Standard mode, output slew rate control is enabled */
_IOCON_PIO_SLEW_STANDARD |
/* Input function is not inverted */
_IOCON_PIO_INV_DI |
/* Enables digital function */
_IOCON_PIO_DIGITAL_EN |
/* Open drain is disabled */
_IOCON_PIO_OPENDRAIN_DI);
#if (McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0)
IOCON_PinMuxSet(Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, port_pin_config);
#else
IOCON_PinMuxSet(IOCON, Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, port_pin_config);
#endif
#else
PORT_SetPinMux(Input1_CONFIG_PORT_NAME, Input1_CONFIG_PIN_NUMBER, kPORT_MuxAsGpio); /* mux as GPIO */
#endif
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
/*! Pin Muxing not implemented */
GPIO_DRV_Init(Input1_InputConfig, Input1_OutputConfig);
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_S32K
/* the following needs to be called in the application first:
PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr);
*/
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_NORDIC_NRF5
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
McuGPIO_Config_t config;
McuGPIO_GetDefaultConfig(&config);
config.hw.pin = Input1_CONFIG_PIN_NUMBER;
config.isInput = true;
pin = McuGPIO_InitGPIO(&config);
#endif
#if Input1_CONFIG_INIT_PIN_DIRECTION == Input1_CONFIG_INIT_PIN_DIRECTION_INPUT
Input1_SetInput();
#elif Input1_CONFIG_INIT_PIN_DIRECTION == Input1_CONFIG_INIT_PIN_DIRECTION_OUTPUT
Input1_SetOutput();
#endif
}
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_Deinit(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_RPI_PICO
pin = McuGPIO_DeinitGPIO(pin);
#endif
}
/* END Input1. */
/*!
** @}
*/

View File

@@ -0,0 +1,243 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : Input1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SDK_BitIO
** Version : Component 01.030, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:47, # CodeGen: 836
** Abstract :
** GPIO component usable with NXP SDK
** Settings :
** Component name : Input1
** SDK : McuLib
** GPIO Name : GPIOA
** PORT Name : PORTA
** Pin Number : 0
** Pin Symbol : LED_RED
** Do Pin Muxing : no
** Init Direction : Input
** Pull Resistor : no pull resistor
** Init Value : 0
** Contents :
** GetDir - bool Input1_GetDir(void);
** SetDir - void Input1_SetDir(bool Dir);
** SetInput - void Input1_SetInput(void);
** SetOutput - void Input1_SetOutput(void);
** GetVal - bool Input1_GetVal(void);
** PutVal - void Input1_PutVal(bool Val);
** ClrVal - void Input1_ClrVal(void);
** SetVal - void Input1_SetVal(void);
** NegVal - void Input1_NegVal(void);
** Init - void Input1_Init(void);
** Deinit - void Input1_Deinit(void);
**
** * Copyright (c) 2015-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file Input1.h
** @version 01.00
** @brief
** GPIO component usable with NXP SDK
*/
/*!
** @addtogroup Input1_module Input1 module documentation
** @{
*/
#ifndef __Input1_H
#define __Input1_H
/* MODULE Input1. */
#include "McuLib.h" /* SDK and API used */
#include "Input1config.h" /* configuration */
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_KINETIS_1_3
#include "fsl_gpio_driver.h"
/* only GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF and GPIOG are currently supported */
#define Input1_GPIO_IDX GPIOA_IDX /* GPIOA */
enum Input1_pinNames{
Input1_CONFIG_PIN_SYMBOL = GPIO_MAKE_PIN(Input1_GPIO_IDX, Input1_CONFIG_PIN_NUMBER),
};
extern const gpio_output_pin_user_config_t Input1_OutputConfig[];
extern const gpio_input_pin_user_config_t Input1_InputConfig[];
#endif
void Input1_Init(void);
/*
** ===================================================================
** Method : Init (component SDK_BitIO)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_ClrVal(void);
/*
** ===================================================================
** Method : ClrVal (component SDK_BitIO)
**
** Description :
** Clears the pin value (sets it to a low level)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_SetVal(void);
/*
** ===================================================================
** Method : SetVal (component SDK_BitIO)
**
** Description :
** Sets the pin value to a high value.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_NegVal(void);
/*
** ===================================================================
** Method : NegVal (component SDK_BitIO)
**
** Description :
** Toggles/negates the pin value
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component SDK_BitIO)
**
** Description :
** Driver de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
bool Input1_GetVal(void);
/*
** ===================================================================
** Method : GetVal (component SDK_BitIO)
**
** Description :
** Returns the pin value
** Parameters : None
** Returns :
** --- - Returns the value of the pin:
** FALSE/logical level '0' or TRUE/logical
** level '1'
** ===================================================================
*/
bool Input1_GetDir(void);
/*
** ===================================================================
** Method : GetDir (component SDK_BitIO)
**
** Description :
** Return the direction of the pin (input/output)
** Parameters : None
** Returns :
** --- - FALSE if port is input, TRUE if port is
** output
** ===================================================================
*/
void Input1_SetDir(bool Dir);
/*
** ===================================================================
** Method : SetDir (component SDK_BitIO)
**
** Description :
** Sets the direction of the pin (input or output)
** Parameters :
** NAME - DESCRIPTION
** Dir - FALSE: input, TRUE: output
** Returns : Nothing
** ===================================================================
*/
void Input1_SetInput(void);
/*
** ===================================================================
** Method : SetInput (component SDK_BitIO)
**
** Description :
** Sets the pin as input
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_SetOutput(void);
/*
** ===================================================================
** Method : SetOutput (component SDK_BitIO)
**
** Description :
** Sets the pin as output
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void Input1_PutVal(bool Val);
/*
** ===================================================================
** Method : PutVal (component SDK_BitIO)
**
** Description :
** Sets the pin value
** Parameters :
** NAME - DESCRIPTION
** Val - Value to set. FALSE/logical '0' or
** TRUE/logical '1'
** Returns : Nothing
** ===================================================================
*/
/* END Input1. */
#endif
/* ifndef __Input1_H */
/*!
** @}
*/

View File

@@ -0,0 +1,437 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : InputRB1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : RingBuffer
** Version : Component 01.054, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
** This component implements a ring buffer for different integer data type.
** Settings :
** Component name : InputRB1
** Buffer Size : 10
** Contents :
** Clear - void InputRB1_Clear(void);
** Put - uint8_t InputRB1_Put(InputRB1_ElementType elem);
** Get - uint8_t InputRB1_Get(InputRB1_ElementType *elemP);
** Peek - uint8_t InputRB1_Peek(InputRB1_BufSizeType index, InputRB1_ElementType *elemP);
** Update - uint8_t InputRB1_Update(InputRB1_BufSizeType index, InputRB1_ElementType...
** Putn - uint8_t InputRB1_Putn(InputRB1_ElementType *elem, InputRB1_BufSizeType nof);
** Getn - uint8_t InputRB1_Getn(InputRB1_ElementType *buf, InputRB1_BufSizeType nof);
** Compare - uint8_t InputRB1_Compare(InputRB1_BufSizeType index, InputRB1_ElementType...
** Delete - uint8_t InputRB1_Delete(void);
** NofElements - InputRB1_BufSizeType InputRB1_NofElements(void);
** NofFreeElements - InputRB1_BufSizeType InputRB1_NofFreeElements(void);
** Deinit - void InputRB1_Deinit(void);
** Init - void InputRB1_Init(void);
**
** * Copyright (c) 2014-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file InputRB1.h
** @version 01.00
** @brief
** This component implements a ring buffer for different integer data type.
*/
/*!
** @addtogroup InputRB1_module InputRB1 module documentation
** @{
*/
/* MODULE InputRB1. */
#include "InputRB1.h"
#if InputRB1_CONFIG_REENTRANT
#define InputRB1_DEFINE_CRITICAL() McuCriticalSection_CriticalVariable()
#define InputRB1_ENTER_CRITICAL() McuCriticalSection_EnterCritical()
#define InputRB1_EXIT_CRITICAL() McuCriticalSection_ExitCritical()
#else
#define InputRB1_DEFINE_CRITICAL() /* nothing */
#define InputRB1_ENTER_CRITICAL() /* nothing */
#define InputRB1_EXIT_CRITICAL() /* nothing */
#endif
static InputRB1_ElementType InputRB1_buffer[InputRB1_CONFIG_BUF_SIZE]; /* ring buffer */
static InputRB1_BufSizeType InputRB1_inIdx; /* input index */
static InputRB1_BufSizeType InputRB1_outIdx; /* output index */
static InputRB1_BufSizeType InputRB1_inSize; /* size data in buffer */
/*
** ===================================================================
** Method : Put (component RingBuffer)
**
** Description :
** Puts a new element into the buffer
** Parameters :
** NAME - DESCRIPTION
** elem - New element to be put into the buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Put(InputRB1_ElementType elem)
{
uint8_t res = ERR_OK;
InputRB1_DEFINE_CRITICAL();
InputRB1_ENTER_CRITICAL();
if (InputRB1_inSize==InputRB1_CONFIG_BUF_SIZE) {
res = ERR_TXFULL;
} else {
InputRB1_buffer[InputRB1_inIdx] = elem;
InputRB1_inIdx++;
if (InputRB1_inIdx==InputRB1_CONFIG_BUF_SIZE) {
InputRB1_inIdx = 0;
}
InputRB1_inSize++;
}
InputRB1_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Putn (component RingBuffer)
**
** Description :
** Put a number new element into the buffer.
** Parameters :
** NAME - DESCRIPTION
** * elem - Pointer to new elements to be put into
** the buffer
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Putn(InputRB1_ElementType *elem, InputRB1_BufSizeType nof)
{
uint8_t res = ERR_OK;
while(nof>0) {
res = InputRB1_Put(*elem);
if (res!=ERR_OK) {
break;
}
elem++; nof--;
}
return res;
}
/*
** ===================================================================
** Method : Get (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters :
** NAME - DESCRIPTION
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Get(InputRB1_ElementType *elemP)
{
uint8_t res = ERR_OK;
InputRB1_DEFINE_CRITICAL();
InputRB1_ENTER_CRITICAL();
if (InputRB1_inSize==0) {
res = ERR_RXEMPTY;
} else {
*elemP = InputRB1_buffer[InputRB1_outIdx];
InputRB1_inSize--;
InputRB1_outIdx++;
if (InputRB1_outIdx==InputRB1_CONFIG_BUF_SIZE) {
InputRB1_outIdx = 0;
}
}
InputRB1_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Getn (component RingBuffer)
**
** Description :
** Get a number elements into a buffer.
** Parameters :
** NAME - DESCRIPTION
** * buf - Pointer to buffer where to store the
** elements
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Getn(InputRB1_ElementType *buf, InputRB1_BufSizeType nof)
{
uint8_t res = ERR_OK;
while(nof>0) {
res = InputRB1_Get(buf);
if (res!=ERR_OK) {
break;
}
buf++; nof--;
}
return res;
}
/*
** ===================================================================
** Method : NofElements (component RingBuffer)
**
** Description :
** Returns the actual number of elements in the buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
InputRB1_BufSizeType InputRB1_NofElements(void)
{
return InputRB1_inSize;
}
/*
** ===================================================================
** Method : NofFreeElements (component RingBuffer)
**
** Description :
** Returns the actual number of free elements/space in the
** buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
InputRB1_BufSizeType InputRB1_NofFreeElements(void)
{
return (InputRB1_BufSizeType)(InputRB1_CONFIG_BUF_SIZE-InputRB1_inSize);
}
/*
** ===================================================================
** Method : Init (component RingBuffer)
**
** Description :
** Initializes the data structure
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void InputRB1_Init(void)
{
InputRB1_inIdx = 0;
InputRB1_outIdx = 0;
InputRB1_inSize = 0;
}
/*
** ===================================================================
** Method : Clear (component RingBuffer)
**
** Description :
** Clear (empty) the ring buffer.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void InputRB1_Clear(void)
{
InputRB1_DEFINE_CRITICAL();
InputRB1_ENTER_CRITICAL();
InputRB1_Init();
InputRB1_EXIT_CRITICAL();
}
/*
** ===================================================================
** Method : Peek (component RingBuffer)
**
** Description :
** Returns an element of the buffer without removiing it.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Peek(InputRB1_BufSizeType index, InputRB1_ElementType *elemP)
{
uint8_t res = ERR_OK;
int idx; /* index inside ring buffer */
InputRB1_DEFINE_CRITICAL();
InputRB1_ENTER_CRITICAL();
if (index>=InputRB1_CONFIG_BUF_SIZE) {
res = ERR_OVERFLOW; /* asking for an element outside of ring buffer size */
} else if (index<InputRB1_inSize) {
idx = (InputRB1_outIdx+index)%InputRB1_CONFIG_BUF_SIZE;
*elemP = InputRB1_buffer[idx];
} else { /* asking for an element which does not exist */
res = ERR_RXEMPTY;
}
InputRB1_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Compare (component RingBuffer)
**
** Description :
** Compares the elements in the buffer.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to elements to compare with
** nof - number of elements to compare
** Returns :
** --- - zero if elements are the same, -1 otherwise
** ===================================================================
*/
uint8_t InputRB1_Compare(InputRB1_BufSizeType index, InputRB1_ElementType *elemP, InputRB1_BufSizeType nof)
{
uint8_t cmpResult = 0;
uint8_t res;
InputRB1_ElementType val;
while(nof>0) {
res = InputRB1_Peek(index, &val);
if (res!=ERR_OK) { /* general failure? */
cmpResult = (uint8_t)-1; /* no match */
break;
}
if (val!=*elemP) { /* mismatch */
cmpResult = (uint8_t)-1; /* no match */
break;
}
elemP++; index++; nof--;
}
return cmpResult;
}
/*
** ===================================================================
** Method : Deinit (component RingBuffer)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/**
void InputRB1_Deinit(void)
{
** Function is implemented as macro in the header file
}
*/
/*
** ===================================================================
** Method : Delete (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Delete(void)
{
uint8_t res = ERR_OK;
InputRB1_DEFINE_CRITICAL();
InputRB1_ENTER_CRITICAL();
if (InputRB1_inSize==0) {
res = ERR_RXEMPTY;
} else {
InputRB1_inSize--;
InputRB1_outIdx++;
if (InputRB1_outIdx==InputRB1_CONFIG_BUF_SIZE) {
InputRB1_outIdx = 0;
}
}
InputRB1_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Update (component RingBuffer)
**
** Description :
** Updates the data of an element.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Update(InputRB1_BufSizeType index, InputRB1_ElementType *elemP)
{
uint8_t res = ERR_OK;
int idx; /* index inside ring buffer */
InputRB1_DEFINE_CRITICAL();
InputRB1_ENTER_CRITICAL();
if (index>=InputRB1_CONFIG_BUF_SIZE) {
res = ERR_OVERFLOW; /* asking for an element outside of ring buffer size */
} else if (index<InputRB1_inSize) {
idx = (InputRB1_outIdx+index)%InputRB1_CONFIG_BUF_SIZE;
InputRB1_buffer[idx] = *elemP; /* replace element */
} else { /* asking for an element which does not exist */
res = ERR_RXEMPTY;
}
InputRB1_EXIT_CRITICAL();
return res;
}
/* END InputRB1. */
/*!
** @}
*/

View File

@@ -0,0 +1,305 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : InputRB1.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : RingBuffer
** Version : Component 01.054, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
** This component implements a ring buffer for different integer data type.
** Settings :
** Component name : InputRB1
** Buffer Size : 10
** Contents :
** Clear - void InputRB1_Clear(void);
** Put - uint8_t InputRB1_Put(InputRB1_ElementType elem);
** Get - uint8_t InputRB1_Get(InputRB1_ElementType *elemP);
** Peek - uint8_t InputRB1_Peek(InputRB1_BufSizeType index, InputRB1_ElementType *elemP);
** Update - uint8_t InputRB1_Update(InputRB1_BufSizeType index, InputRB1_ElementType...
** Putn - uint8_t InputRB1_Putn(InputRB1_ElementType *elem, InputRB1_BufSizeType nof);
** Getn - uint8_t InputRB1_Getn(InputRB1_ElementType *buf, InputRB1_BufSizeType nof);
** Compare - uint8_t InputRB1_Compare(InputRB1_BufSizeType index, InputRB1_ElementType...
** Delete - uint8_t InputRB1_Delete(void);
** NofElements - InputRB1_BufSizeType InputRB1_NofElements(void);
** NofFreeElements - InputRB1_BufSizeType InputRB1_NofFreeElements(void);
** Deinit - void InputRB1_Deinit(void);
** Init - void InputRB1_Init(void);
**
** * Copyright (c) 2014-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file InputRB1.h
** @version 01.00
** @brief
** This component implements a ring buffer for different integer data type.
*/
/*!
** @addtogroup InputRB1_module InputRB1 module documentation
** @{
*/
#ifndef __InputRB1_H
#define __InputRB1_H
/* MODULE InputRB1. */
#include "McuLib.h" /* SDK and API used */
#include "InputRB1config.h" /* configuration */
/* Include inherited components */
#include "McuLib.h"
#include "McuCriticalSection.h"
#ifdef __cplusplus
extern "C" {
#endif
#if InputRB1_CONFIG_ELEM_SIZE==1
typedef uint8_t InputRB1_ElementType; /* type of single element */
#elif InputRB1_CONFIG_ELEM_SIZE==2
typedef uint16_t InputRB1_ElementType; /* type of single element */
#elif InputRB1_CONFIG_ELEM_SIZE==4
typedef uint32_t InputRB1_ElementType; /* type of single element */
#else
#error "illegal element type size in properties"
#endif
#if InputRB1_CONFIG_BUF_SIZE<256
typedef uint8_t InputRB1_BufSizeType; /* up to 255 elements (index 0x00..0xff) */
#else
typedef uint16_t InputRB1_BufSizeType; /* more than 255 elements, up to 2^16 */
#endif
uint8_t InputRB1_Put(InputRB1_ElementType elem);
/*
** ===================================================================
** Method : Put (component RingBuffer)
**
** Description :
** Puts a new element into the buffer
** Parameters :
** NAME - DESCRIPTION
** elem - New element to be put into the buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Get(InputRB1_ElementType *elemP);
/*
** ===================================================================
** Method : Get (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters :
** NAME - DESCRIPTION
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
InputRB1_BufSizeType InputRB1_NofElements(void);
/*
** ===================================================================
** Method : NofElements (component RingBuffer)
**
** Description :
** Returns the actual number of elements in the buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
void InputRB1_Init(void);
/*
** ===================================================================
** Method : Init (component RingBuffer)
**
** Description :
** Initializes the data structure
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
InputRB1_BufSizeType InputRB1_NofFreeElements(void);
/*
** ===================================================================
** Method : NofFreeElements (component RingBuffer)
**
** Description :
** Returns the actual number of free elements/space in the
** buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
void InputRB1_Clear(void);
/*
** ===================================================================
** Method : Clear (component RingBuffer)
**
** Description :
** Clear (empty) the ring buffer.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t InputRB1_Peek(InputRB1_BufSizeType index, InputRB1_ElementType *elemP);
/*
** ===================================================================
** Method : Peek (component RingBuffer)
**
** Description :
** Returns an element of the buffer without removiing it.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
#define InputRB1_Deinit() \
/* nothing to deinitialize */
/*
** ===================================================================
** Method : Deinit (component RingBuffer)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t InputRB1_Delete(void);
/*
** ===================================================================
** Method : Delete (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Putn(InputRB1_ElementType *elem, InputRB1_BufSizeType nof);
/*
** ===================================================================
** Method : Putn (component RingBuffer)
**
** Description :
** Put a number new element into the buffer.
** Parameters :
** NAME - DESCRIPTION
** * elem - Pointer to new elements to be put into
** the buffer
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Compare(InputRB1_BufSizeType index, InputRB1_ElementType *elemP, InputRB1_BufSizeType nof);
/*
** ===================================================================
** Method : Compare (component RingBuffer)
**
** Description :
** Compares the elements in the buffer.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to elements to compare with
** nof - number of elements to compare
** Returns :
** --- - zero if elements are the same, -1 otherwise
** ===================================================================
*/
uint8_t InputRB1_Getn(InputRB1_ElementType *buf, InputRB1_BufSizeType nof);
/*
** ===================================================================
** Method : Getn (component RingBuffer)
**
** Description :
** Get a number elements into a buffer.
** Parameters :
** NAME - DESCRIPTION
** * buf - Pointer to buffer where to store the
** elements
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t InputRB1_Update(InputRB1_BufSizeType index, InputRB1_ElementType *elemP);
/*
** ===================================================================
** Method : Update (component RingBuffer)
**
** Description :
** Updates the data of an element.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
/* END InputRB1. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __InputRB1_H */
/*!
** @}
*/

View File

@@ -0,0 +1,508 @@
see https://github.com/MarioViara/xprintfc/blob/master/LICENSE
XPrintf is provided by Mario Viara:
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
(This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.)
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
{signature of Ty Coon}, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,496 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuArmTools.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : KinetisTools
** Version : Component 01.055, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-09, 10:10, # CodeGen: 829
** Abstract :
**
** Settings :
** Component name : McuArmTools
** Utility : McuUtility
** SDK : McuLib
** Shell : Enabled
** Shell : McuShell
** Contents :
** SoftwareReset - void McuArmTools_SoftwareReset(void);
** UIDGet - uint8_t McuArmTools_UIDGet(McuArmTools_UID *uid);
** UIDSame - bool McuArmTools_UIDSame(const McuArmTools_UID *src, const McuArmTools_UID...
** UIDtoString - uint8_t McuArmTools_UIDtoString(const McuArmTools_UID *uid, uint8_t *buf,...
** GetKinetisFamilyString - McuArmTools_ConstCharPtr McuArmTools_GetKinetisFamilyString(void);
** GetPC - void* McuArmTools_GetPC(void);
** GetSP - void* McuArmTools_GetSP(void);
** SetPSP - void McuArmTools_SetPSP(void *setval);
** SetLR - void McuArmTools_SetLR(uint32_t setval);
** InitCycleCounter - void McuArmTools_InitCycleCounter(void);
** ResetCycleCounter - void McuArmTools_ResetCycleCounter(void);
** EnableCycleCounter - void McuArmTools_EnableCycleCounter(void);
** DisableCycleCounter - void McuArmTools_DisableCycleCounter(void);
** GetCycleCounter - uint32_t McuArmTools_GetCycleCounter(void);
** GetUsedMainStackSpace - uint32_t McuArmTools_GetUsedMainStackSpace(void);
** GetUnusedMainStackSpace - uint32_t McuArmTools_GetUnusedMainStackSpace(void);
** FillMainStackSpace - void McuArmTools_FillMainStackSpace(void);
** GetLinkerMainStackSize - uint32_t McuArmTools_GetLinkerMainStackSize(void);
** GetLinkerMainStackTop - McuArmTools_uint32_t_Ptr McuArmTools_GetLinkerMainStackTop(void);
** GetLinkerMainStackBase - McuArmTools_uint32_t_Ptr McuArmTools_GetLinkerMainStackBase(void);
** ParseCommand - uint8_t McuArmTools_ParseCommand(const unsigned char* cmd, bool *handled,...
** Deinit - void McuArmTools_Deinit(void);
** Init - void McuArmTools_Init(void);
**
** * Copyright (c) 2014-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuArmTools.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuArmTools_module McuArmTools module documentation
** @{
*/
#ifndef __McuArmTools_H
#define __McuArmTools_H
/* MODULE McuArmTools. */
#include "McuLib.h" /* SDK and API used */
#include "McuArmToolsconfig.h" /* configuration */
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_RPI_PICO
#include "pico/unique_id.h" /* for UID */
#include "pico/bootrom.h" /* for entering bootloader */
#endif
#include <stddef.h> /* for size_t */
#if McuArmTools_CONFIG_PARSE_COMMAND_ENABLED
#include "McuShell.h" /* Command line shell */
#endif
#ifndef __BWUserType_McuArmTools_ConstCharPtr
#define __BWUserType_McuArmTools_ConstCharPtr
typedef const uint8_t *McuArmTools_ConstCharPtr; /* Pointer to constant string */
#endif
#ifndef __BWUserType_McuArmTools_uint32_t_Ptr
#define __BWUserType_McuArmTools_uint32_t_Ptr
typedef uint32_t *McuArmTools_uint32_t_Ptr; /* Pointer to uint32_t */
#endif
#if McuLib_CONFIG_CPU_IS_ARM_CORTEX_M && McuLib_CONFIG_CORTEX_M>=3 /* only for Cortex-M3 or higher */
/* DWT (Data Watchpoint and Trace) registers, only exists on ARM Cortex with a DWT unit */
#define McuArmTools_DWT_CONTROL (*((volatile uint32_t*)0xE0001000))
/*!< DWT Control register */
#define McuArmTools_DWT_CYCCNTENA_BIT (1UL<<0)
/*!< CYCCNTENA bit in DWT_CONTROL register */
#define McuArmTools_DWT_CYCCNT (*((volatile uint32_t*)0xE0001004))
/*!< DWT Cycle Counter register */
#define McuArmTools_DEMCR (*((volatile uint32_t*)0xE000EDFC))
/*!< DEMCR: Debug Exception and Monitor Control Register */
#define McuArmTools_TRCENA_BIT (1UL<<24)
/*!< Trace enable bit in DEMCR register */
#endif
typedef struct {
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_RPI_PICO
uint8_t id[sizeof(pico_unique_board_id_t)]; /* 8 bytes, 64 bits */
#else
uint8_t id[16]; /* 128 bit ID */
#endif
} McuArmTools_UID;
typedef enum {
McuArmTools_FAMILY_K10_K12, /* K10 or K12 */
McuArmTools_FAMILY_K20_K22, /* K10 or K12 */
McuArmTools_FAMILY_K30_K11_K61, /* K30, K11 or K61 */
McuArmTools_FAMILY_K40_K21, /* K40 or K21 */
McuArmTools_FAMILY_K70, /* K70 */
McuArmTools_FAMILY_UNKONWN, /* Unknown */
McuArmTools_FAMILY_LAST /* Must be last one! */
} McuArmTools_FAMILY;
#define McuArmTools_PARSE_COMMAND_ENABLED McuArmTools_CONFIG_PARSE_COMMAND_ENABLED
/*!< set to 1 if method ParseCommand() is present, 0 otherwise */
#ifdef __cplusplus
extern "C" {
#endif
#if McuArmTools_CONFIG_PARSE_COMMAND_ENABLED
uint8_t McuArmTools_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component KinetisTools)
**
** Description :
** Shell Command Line parser. Method is only available if Shell
** is enabled in the component properties.
** Parameters :
** NAME - DESCRIPTION
** cmd - Pointer to command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** * io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
#endif
void McuArmTools_SoftwareReset(void);
/*
** ===================================================================
** Method : SoftwareReset (component KinetisTools)
**
** Description :
** Performs a reset of the device
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuArmTools_UIDGet(McuArmTools_UID *uid);
/*
** ===================================================================
** Method : UIDGet (component KinetisTools)
**
** Description :
** Return the 128bit UID of the device
** Parameters :
** NAME - DESCRIPTION
** * uid - Pointer to
** Returns :
** --- - Error code
** ===================================================================
*/
bool McuArmTools_UIDSame(const McuArmTools_UID *src, const McuArmTools_UID *dst);
/*
** ===================================================================
** Method : UIDSame (component KinetisTools)
**
** Description :
** Compares two UID
** Parameters :
** NAME - DESCRIPTION
** * src - Pointer to
** Variable_1 -
** Returns :
** --- - TRUE if the same, FALSE otherwise
** ===================================================================
*/
uint8_t McuArmTools_UIDtoString(const McuArmTools_UID *uid, uint8_t *buf, size_t bufSize);
/*
** ===================================================================
** Method : UIDtoString (component KinetisTools)
**
** Description :
** Returns the value of the UID as string
** Parameters :
** NAME - DESCRIPTION
** uid -
** * buf - Pointer to
** bufSize -
** Returns :
** --- - Error code
** ===================================================================
*/
McuArmTools_ConstCharPtr McuArmTools_GetKinetisFamilyString(void);
/*
** ===================================================================
** Method : GetKinetisFamilyString (component KinetisTools)
**
** Description :
** Determines the Kinetis Familiy based on SIM_SDID register
** Parameters : None
** Returns :
** --- - String describing the Kinetis Family
** ===================================================================
*/
void* McuArmTools_GetPC(void);
/*
** ===================================================================
** Method : GetPC (component KinetisTools)
**
** Description :
** returns the program counter
** Parameters : None
** Returns :
** --- - program counter
** ===================================================================
*/
void* McuArmTools_GetSP(void);
/*
** ===================================================================
** Method : GetSP (component KinetisTools)
**
** Description :
** returns the stack pointer
** Parameters : None
** Returns :
** --- - stack pointer
** ===================================================================
*/
void McuArmTools_SetPSP(void *setval);
/*
** ===================================================================
** Method : SetPSP (component KinetisTools)
**
** Description :
** sets the process stack pointer
** Parameters :
** NAME - DESCRIPTION
** setval - new PSP value
** Returns : Nothing
** ===================================================================
*/
void McuArmTools_SetLR(uint32_t setval);
/*
** ===================================================================
** Method : SetLR (component KinetisTools)
**
** Description :
** Sets the link register
** Parameters :
** NAME - DESCRIPTION
** setval - new LR value
** Returns : Nothing
** ===================================================================
*/
#if McuLib_CONFIG_CPU_IS_ARM_CORTEX_M && McuLib_CONFIG_CORTEX_M>=3 /* only for Cortex-M3 or higher */
#define McuArmTools_InitCycleCounter() \
McuArmTools_DEMCR |= McuArmTools_TRCENA_BIT
/*!< TRCENA: Enable trace and debug block DEMCR (Debug Exception and Monitor Control Register */
/*
** ===================================================================
** Method : InitCycleCounter (component KinetisTools)
**
** Description :
** Initializes the cycle counter, available if the core has a
** DWT (Data Watchpoint and Trace) unit, usually present on
** M3/M4/M7
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#endif
#if McuLib_CONFIG_CPU_IS_ARM_CORTEX_M && McuLib_CONFIG_CORTEX_M>=3 /* only for Cortex-M3 or higher */
#define McuArmTools_ResetCycleCounter() \
McuArmTools_DWT_CYCCNT = 0
/*!< Reset cycle counter */
/*
** ===================================================================
** Method : ResetCycleCounter (component KinetisTools)
**
** Description :
** Reset the cycle counter (set it to zero)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#endif
#if McuLib_CONFIG_CPU_IS_ARM_CORTEX_M && McuLib_CONFIG_CORTEX_M>=3 /* only for Cortex-M3 or higher */
#define McuArmTools_EnableCycleCounter() \
McuArmTools_DWT_CONTROL |= McuArmTools_DWT_CYCCNTENA_BIT
/*!< Enable cycle counter */
/*
** ===================================================================
** Method : EnableCycleCounter (component KinetisTools)
**
** Description :
** Enables counting the cycles.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#endif
#if McuLib_CONFIG_CPU_IS_ARM_CORTEX_M && McuLib_CONFIG_CORTEX_M>=3 /* only for Cortex-M3 or higher */
#define McuArmTools_DisableCycleCounter() \
McuArmTools_DWT_CONTROL &= ~McuArmTools_DWT_CYCCNTENA_BIT
/*!< Disable cycle counter */
/*
** ===================================================================
** Method : DisableCycleCounter (component KinetisTools)
**
** Description :
** Disables the cycle counter.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#endif
#if McuLib_CONFIG_CPU_IS_ARM_CORTEX_M && McuLib_CONFIG_CORTEX_M>=3 /* only for Cortex-M3 or higher */
#define McuArmTools_GetCycleCounter() \
McuArmTools_DWT_CYCCNT
/*!< Read cycle counter register */
/*
** ===================================================================
** Method : GetCycleCounter (component KinetisTools)
**
** Description :
** Return the current cycle counter value
** Parameters : None
** Returns :
** --- - cycle counter
** ===================================================================
*/
#endif
void McuArmTools_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component KinetisTools)
**
** Description :
** Driver de-initialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuArmTools_Init(void);
/*
** ===================================================================
** Method : Init (component KinetisTools)
**
** Description :
** Driver initialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint32_t McuArmTools_GetUsedMainStackSpace(void);
/*
** ===================================================================
** Method : GetUsedMainStackSpace (component KinetisTools)
**
** Description :
** Returns the used main stack space, based on the overwritten
** checking pattern.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint32_t McuArmTools_GetUnusedMainStackSpace(void);
/*
** ===================================================================
** Method : GetUnusedMainStackSpace (component KinetisTools)
**
** Description :
** Calculates the unused stack space, based on the checking
** pattern.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
void McuArmTools_FillMainStackSpace(void);
/*
** ===================================================================
** Method : FillMainStackSpace (component KinetisTools)
**
** Description :
** Fill the stack space with the checking pattern, up to the
** current MSP.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint32_t McuArmTools_GetLinkerMainStackSize(void);
/*
** ===================================================================
** Method : GetLinkerMainStackSize (component KinetisTools)
**
** Description :
** Returns the size of the main (MSP) stack size, using linker
** symbols for top (higher address) and base (lower address).
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
McuArmTools_uint32_t_Ptr McuArmTools_GetLinkerMainStackTop(void);
/*
** ===================================================================
** Method : GetLinkerMainStackTop (component KinetisTools)
**
** Description :
** Return the stack top, as set in the linker file. The stack
** grows from the top (higher address) to the base (lower
** address).
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
McuArmTools_uint32_t_Ptr McuArmTools_GetLinkerMainStackBase(void);
/*
** ===================================================================
** Method : GetLinkerMainStackBase (component KinetisTools)
**
** Description :
** Return the stack bottom, as configured in the linker file.
** The stack grows from the top (higher address) to the base
** (lower address).
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuArmTools. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuArmTools_H */
/*!
** @}
*/

View File

@@ -0,0 +1,131 @@
/*
* McuButton.c
*
* Copyright (c) 2019-2021, Erich Styger
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuLibconfig.h"
#include "McuButton.h"
#include "McuUtility.h"
#include <stdlib.h> /* memcpy */
#include <string.h> /* memset */
#include <assert.h>
#if MCUBUTTON_CONFIG_USE_FREERTOS_HEAP
#include "McuRTOS.h"
#endif
/* default configuration, used for initializing the config */
static const McuBtn_Config_t defaultConfig =
{
.isLowActive = true,
.hw = {
#if McuLib_CONFIG_NXP_SDK_USED && !McuLib_CONFIG_IS_KINETIS_KE
.gpio = NULL,
#elif McuLib_CONFIG_CPU_IS_STM32
.gpio = NULL,
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
.port = NULL,
#elif McuLib_CONFIG_CPU_IS_LPC
.port = 0,
#endif
#if McuLib_CONFIG_CPU_IS_ESP32
.pin = GPIO_NUM_NC,
#else
.pin = 0,
#endif
}
};
typedef struct {
bool isLowActive;
McuGPIO_Handle_t gpio;
} McuBtn_t;
void McuBtn_GetDefaultConfig(McuBtn_Config_t *config) {
assert(config!=NULL);
memcpy(config, &defaultConfig, sizeof(*config));
}
void McuBtn_DisablePullResistor(McuBtn_Handle_t btn) {
McuBtn_t *button;
button = (McuBtn_t*)btn;
McuGPIO_SetPullResistor(button->gpio, McuGPIO_PULL_DISABLE);
}
void McuBtn_EnablePullResistor(McuBtn_Handle_t btn) {
McuBtn_t *button;
button = (McuBtn_t*)btn;
if (button->isLowActive) {
McuGPIO_SetPullResistor(button->gpio, McuGPIO_PULL_UP);
} else {
McuGPIO_SetPullResistor(button->gpio, McuGPIO_PULL_DOWN);
}
}
bool McuBtn_IsOn(McuBtn_Handle_t btn) {
McuBtn_t *button;
assert(btn!=NULL);
button = (McuBtn_t*)btn;
if (button->isLowActive) {
return McuGPIO_IsLow(button->gpio);
} else {
return McuGPIO_IsHigh(button->gpio);
}
}
void McuBtn_GetPinStatusString(McuBtn_Handle_t btn, unsigned char *buf, size_t bufSize) {
McuBtn_t *button;
button = (McuBtn_t*)btn;
buf[0] = '\0';
McuGPIO_GetPinStatusString(button->gpio, buf, bufSize);
if (button->isLowActive) {
McuUtility_strcat(buf, bufSize, (unsigned char*)" active:L");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)" active:H");
}
}
McuBtn_Handle_t McuBtn_InitButton(McuBtn_Config_t *config) {
McuBtn_t *handle;
McuGPIO_Config_t gpioConfig;
assert(config!=NULL);
#if MCUBUTTON_CONFIG_USE_FREERTOS_HEAP
handle = (McuBtn_t*)pvPortMalloc(sizeof(McuBtn_t)); /* get a new device descriptor */
#else
handle = (McuBtn_t*)malloc(sizeof(McuBtn_t)); /* get a new device descriptor */
#endif
assert(handle!=NULL);
if (handle!=NULL) { /* if malloc failed, will return NULL pointer */
memset(handle, 0, sizeof(McuBtn_t)); /* init all fields */
handle->isLowActive = config->isLowActive;
/* create GPIO pin */
McuGPIO_GetDefaultConfig(&gpioConfig);
gpioConfig.isInput = true;
memcpy(&gpioConfig.hw, &config->hw, sizeof(gpioConfig.hw)); /* copy hardware information */
handle->gpio = McuGPIO_InitGPIO(&gpioConfig);
}
return (McuBtn_Handle_t)handle;
}
McuBtn_Handle_t McuBtn_DeinitButton(McuBtn_Handle_t button) {
assert(button!=NULL);
#if MCUBUTTON_CONFIG_USE_FREERTOS_HEAP
vPortFree(button);
#else
free(button);
#endif
return NULL;
}
void McuBtn_Deinit(void) {
}
void McuBtn_Init(void) {
}

View File

@@ -0,0 +1,51 @@
/*
* McuButton.h
*
* Copyright (c) 2019-2021, Erich Styger
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MCUBUTTON_H_
#define MCUBUTTON_H_
#include "McuButtonconfig.h"
#include <stdint.h>
#include <stdbool.h>
#include "McuLib.h"
#include "McuGPIO.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct McuButton_Dummy_s { int dummy; } McuButton_Dummy_s; /*!< using a pointer to a struct instead a pointer to void for handle, used for handle type 'safety' only */
typedef McuButton_Dummy_s *McuBtn_Handle_t; /*!< Button handle type */
typedef struct {
bool isLowActive; /* default: true */
McuGPIO_HwPin_t hw;
} McuBtn_Config_t;
void McuBtn_GetDefaultConfig(McuBtn_Config_t *config);
McuBtn_Handle_t McuBtn_InitButton(McuBtn_Config_t *config);
McuBtn_Handle_t McuBtn_DeinitButton(McuBtn_Handle_t button);
void McuBtn_DisablePullResistor(McuBtn_Handle_t btn);
void McuBtn_EnablePullResistor(McuBtn_Handle_t btn);
bool McuBtn_IsOn(McuBtn_Handle_t btn);
void McuBtn_GetPinStatusString(McuBtn_Handle_t btn, unsigned char *buf, size_t bufSize);
void McuBtn_Deinit(void);
void McuBtn_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MCUBUTTON_H_ */

View File

@@ -0,0 +1,177 @@
/**
* Copyright Ivo Gärtner
* \file
* \author Ivo Gärtner
* \copyright Ivo Gärtner
* \date 9.11.2018
* SPDX-License-Identifier: BSD-3-Clause
* See the header file for comments
*/
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include "McuCRC_CreateTable.h"
#include "McuCRC_Generator.h"
enum McuCRC_GenerateTableResult McuCRC_GenerateLookUpTable( McuCRC_Generator_t *crcGen )
{
char *formatString;
uint32_t valuesPerLine_u32, loopCounter_u32, tableEntry_u32;
FILE *outputFile;
char formatString8[] = "0x%02X";
char formatString16[] = "0x%04X";
char formatString32[] = "0x%08X";
if ( (crcGen->McuCRC_Width != 8) && (crcGen->McuCRC_Width != 16) && (crcGen->McuCRC_Width != 32) )
{
return McuCRC_TABLE_ERR_WIDTH;
}
if ( ((crcGen->McuCRC_ReflectedInput == 0) && (crcGen->McuCRC_ReflectedOutput != 0)) ||
((crcGen->McuCRC_ReflectedInput != 0) && (crcGen->McuCRC_ReflectedOutput == 0)) )
{
return McuCRC_TABLE_ERR_REFLECTED_INPUT_OUTPUT_NOT_IDENTICAL;
}
if ( (crcGen->McuCRC_Width == 8) && ( (crcGen->McuCRC_Polynomial & 0xFFFFFF00) != 0) )
{
return McuCRC_TABLE_ERR_POLYNOMIAL_TOO_LARGE_FOR_16BIT_TABLE;
}
if ( (crcGen->McuCRC_Width == 8) && ( (crcGen->McuCRC_XorOutput & 0xFFFFFF00) != 0) )
{
return McuCRC_TABLE_ERR_XOR_OUT_TOO_LARGE_FOR_16BIT_TABLE;
}
if ( (crcGen->McuCRC_Width == 16) && ( (crcGen->McuCRC_Polynomial & 0xFFFF0000) != 0) )
{
return McuCRC_TABLE_ERR_POLYNOMIAL_TOO_LARGE_FOR_16BIT_TABLE;
}
if ( (crcGen->McuCRC_Width == 16) && ( (crcGen->McuCRC_XorOutput & 0xFFFF0000) != 0) )
{
return McuCRC_TABLE_ERR_XOR_OUT_TOO_LARGE_FOR_16BIT_TABLE;
}
outputFile = fopen( McuCRC_FILENAME, "w" );
if ( outputFile == NULL )
{
return McuCRC_TABLE_ERR_FILE_OPEN;
}
fprintf(outputFile, "/*****************************************************************/\n");
fprintf(outputFile, "/* */\n");
fprintf(outputFile, "/* CRC LOOKUP TABLE */\n");
fprintf(outputFile, "/* ================ */\n");
fprintf(outputFile, "/* The following CRC lookup table was generated using program */\n");
fprintf(outputFile, "/* code which is inspired by Ross Williams' article */\n");
fprintf(outputFile, "/* \"A Painless Guide to CRC Error Detection Algorithms\". */\n");
fprintf(outputFile, "/* */\n");
fprintf(outputFile, "/* The following parameters were used: */\n");
fprintf(outputFile, "/* */\n");
fprintf(outputFile, "/* Width : %u bits */\n",
crcGen->McuCRC_Width);
if ( crcGen->McuCRC_Width == 32 ){
fprintf(outputFile, "/* Polynomial : 0x%08X */\n",
(unsigned int)crcGen->McuCRC_Polynomial);}
else if ( crcGen->McuCRC_Width == 16 ) {
fprintf(outputFile, "/* Polynomial : 0x%04X */\n",
(unsigned int)crcGen->McuCRC_Polynomial);}
else {
fprintf(outputFile, "/* Polynomial : 0x%02X */\n",
(unsigned int)crcGen->McuCRC_Polynomial);
}
if (crcGen->McuCRC_ReflectedInput == 1){
fprintf(outputFile, "/* Reflected Input : TRUE */\n");}
else {
fprintf(outputFile, "/* Reflected Input : FALSE */\n");}
if (crcGen->McuCRC_ReflectedOutput == 1){
fprintf(outputFile, "/* Reflected Output : TRUE */\n");}
else {
fprintf(outputFile, "/* Reflected Output : FALSE */\n");}
fprintf(outputFile, "/* */\n");
fprintf(outputFile, "/*****************************************************************/\n");
fprintf(outputFile, "\n");
if ( crcGen->McuCRC_Width == 32 ){
fprintf(outputFile, "uint32_t McuCRC_Table[%d] = \n{\n", McuCRC_TABLE_SIZE);
formatString = formatString32;
valuesPerLine_u32 = 4;
}
else if ( crcGen->McuCRC_Width == 16 ){
fprintf(outputFile, "uint16_t McuCRC_Table[%d] = \n{\n", McuCRC_TABLE_SIZE);
formatString = formatString16;
valuesPerLine_u32 = 8;
}
else {
fprintf(outputFile, "uint8_t McuCRC_Table[%d] = \n{\n", McuCRC_TABLE_SIZE);
formatString = formatString8;
valuesPerLine_u32 = 12;
}
for ( loopCounter_u32 = 0 ; loopCounter_u32 < McuCRC_TABLE_SIZE ; loopCounter_u32++ )
{
fprintf(outputFile, " ");
tableEntry_u32 = (uint32_t)McuCRC_CalculateTableEntry( crcGen, loopCounter_u32 );
fprintf(outputFile, formatString, tableEntry_u32 );
if ( loopCounter_u32 != (McuCRC_TABLE_SIZE - 1) )
{
fprintf(outputFile, " , ");
}
if ( ((loopCounter_u32 + 1) % valuesPerLine_u32) == 0 )
{
fprintf(outputFile, "\n");
}
}
fprintf(outputFile, "};\n");
fprintf(outputFile, "\n");
fprintf(outputFile, "/*****************************************************************/\n");
fprintf(outputFile, "/* END OF THE CRC LOOKUP TABLE */\n");
fprintf(outputFile, "/*****************************************************************/\n");
if ( fclose( outputFile ) != 0 )
{
return McuCRC_TABLE_ERR_FILE_CLOSE;
}
return McuCRC_TABLE_OK;
}
uint32_t McuCRC_CalculateTableEntry ( McuCRC_Generator_t *crcGen, uint32_t index_u32 )
{
uint32_t loopCounter_u32;
uint32_t tableEntry_u32;
uint32_t topbit_u32 = ( 1 << (crcGen->McuCRC_Width - 1) );
uint32_t inbyte_u32 = (uint32_t) index_u32;
if ( crcGen->McuCRC_ReflectedInput )
{
inbyte_u32 = McuCRC_Reflect( inbyte_u32, McuCRC_BIT_PER_BYTE );
}
tableEntry_u32 = inbyte_u32 << ( crcGen->McuCRC_Width - McuCRC_BIT_PER_BYTE );
for ( loopCounter_u32 = 0; loopCounter_u32 < McuCRC_BIT_PER_BYTE ; loopCounter_u32++)
{
if ( tableEntry_u32 & topbit_u32 )
{
tableEntry_u32 = (tableEntry_u32 << 1) ^ crcGen->McuCRC_Polynomial;
}
else
{
tableEntry_u32 = (tableEntry_u32 << 1);
}
}
if ( crcGen->McuCRC_ReflectedOutput )
{
tableEntry_u32 = McuCRC_Reflect( tableEntry_u32, crcGen->McuCRC_Width );
}
tableEntry_u32 &= crcGen->McuCRC_WidthMask;
return tableEntry_u32;
}

View File

@@ -0,0 +1,110 @@
/**
* Copyright Ivo Gärtner
* \file
* \author Ivo Gärtner
* \copyright Ivo Gärtner
* \date 9.11.2018
* SPDX-License-Identifier: BSD-3-Clause
*
* This program code does very closely rely on the example code
* of Ross Williams' article "A Painless Guide to CRC Error
* Detection Algorithms".
*
* How to use this code:
*
* These functions are only used to create a LUT for the CRC
* calculation. They are not meant to be executed on a MCU
* since they use stdlib.h and stdio.h
*
* First: Define the McuCRC_Generator_t structure, e.g. like this:
*
* McuCRC_Generator_t crcGen;
* crcGen.McuCRC_InitialValue = 0xFFFFFFFF;
* crcGen.McuCRC_Polynomial = 0x04C11DB7;
* crcGen.McuCRC_ReflectedInput = 0;
* crcGen.McuCRC_ReflectedOutput = 0;
* crcGen.McuCRC_Width = McuCRC_WIDTH_32_BIT;
* crcGen.McuCRC_XorOutput = 0xFFFFFFFF;
* crcGen.McuCRC_Table = NULL;
*
* Second: Run the McuCRC_Init function on the McuCRC_Generator_t structure:
*
* McuCRC_Init( &crcGen );
*
* Third: Run the McuCRC_GenerateLookUpTable function on the McuCRC_Generator_t structure:
*
* McuCRC_GenerateLookUpTable( &crcGen );
*
* This will create a file named as defined in McuCRC_FILENAME on your hard drive.
*
* Fourth: Copy the LUT declaration into your code and assign a pointer to the LUT
* to the McuCRC_Generator_t structure:
*
* crcGen.McuCRC_Table = (void*)McuCRC_Table;
*
* Now you can calculate crc's by using the function McuCRC_CalculateWithTableCRC32 or
* McuCRC_CalculateWithTableCRC16 if you calculated a 16 bit crc LUT, like this:
*
* uint8_t byteArray[] = {0x01, 0x01, 0x12, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5};
* crc = McuCRC_CalculateWithTableCRC32( &crcGen, byteArray, 8 );
*
* happy crc'ing
*/
#ifndef McuCRC_CREATETABLE_H_INCLUDED
#define McuCRC_CREATETABLE_H_INCLUDED
#include <stdint.h>
#include <stddef.h>
#include "McuCRC_Generator.h"
#define McuCRC_TABLE_SIZE 256
#define McuCRC_FILENAME "CrcTable.txt"
enum McuCRC_GenerateTableResult
{
McuCRC_TABLE_OK,
McuCRC_TABLE_ERR_WIDTH,
McuCRC_TABLE_ERR_REFLECTED_INPUT_OUTPUT_NOT_IDENTICAL,
McuCRC_TABLE_ERR_POLYNOMIAL_TOO_LARGE_FOR_8BIT_TABLE,
McuCRC_TABLE_ERR_XOR_OUT_TOO_LARGE_FOR_8BIT_TABLE,
McuCRC_TABLE_ERR_POLYNOMIAL_TOO_LARGE_FOR_16BIT_TABLE,
McuCRC_TABLE_ERR_XOR_OUT_TOO_LARGE_FOR_16BIT_TABLE,
McuCRC_TABLE_ERR_FILE_OPEN,
McuCRC_TABLE_ERR_FILE_CLOSE
};
/**
* \fn McuCRC_GenerateLookUpTable()
*
* \brief Calculates the LUT entries and writes it into a file
*
* This function needs the \a McuCRC_Generator_t structure to be fully defined.
* Be aware that input and output reflection MUST BE THE SAME to create a
* table (I've seen no standard CRC which has them mixed).
* If you want to have input and output reflection not identical, you should
* use the shift register implementation!
*
* The XorOut parameter does not have any impact, since the Xor'ing of the
* output is calculated within the
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \return McuCRC_GenerateTableResult Result of the crc table generation as described in \a McuCRC_GenerateTableResult
*/
enum McuCRC_GenerateTableResult McuCRC_GenerateLookUpTable( McuCRC_Generator_t *crcGen );
/**
* \fn McuCRC_CalculateTableEntry()
*
* \brief Calculates an entry for the LUT at a specific index
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \param uint32_t index_u32 Index of the table entry
* \return Table entry as uint32_t
*/
uint32_t McuCRC_CalculateTableEntry ( McuCRC_Generator_t *crcGen, uint32_t index_u32 );
#endif // McuCRC_CREATETABLE_H_INCLUDED

View File

@@ -0,0 +1,174 @@
/**
* Copyright Ivo Gärtner
* \file
* \author Ivo Gärtner
* \copyright Ivo Gärtner
* \date 9.11.2018
* SPDX-License-Identifier: BSD-3-Clause
*
* See the header file for comments
*/
#include <stdint.h>
#include <stddef.h>
#include "McuCRC_Generator.h"
void McuCRC_Init (McuCRC_Generator_t *crcGen)
{
crcGen->McuCRC_Register = crcGen->McuCRC_InitialValue;
crcGen->McuCRC_WidthMask = ( ( (1 << ( crcGen->McuCRC_Width - 1 ) ) - 1 ) << 1) | 1;
}
void McuCRC_CalculateBlock (McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length )
{
uint8_t inputData_u8;
while ( length-- )
{
inputData_u8 = *data_pu8++;
McuCRC_CalculateNextValue( crcGen, inputData_u8 );
}
}
void McuCRC_CalculateNextValue ( McuCRC_Generator_t *crcGen, uint8_t data_u8 )
{
uint32_t loopCounter_u32;
uint32_t uData_u32;
uint32_t topbit_u32;
uData_u32 = data_u8;
topbit_u32 = ( 1 << (crcGen->McuCRC_Width-1));
if ( crcGen->McuCRC_ReflectedInput )
{
uData_u32 = McuCRC_Reflect( uData_u32, McuCRC_BIT_PER_BYTE );
}
crcGen->McuCRC_Register ^= (uData_u32 << (crcGen->McuCRC_Width - McuCRC_BIT_PER_BYTE));
for ( loopCounter_u32 = 0; loopCounter_u32 < McuCRC_BIT_PER_BYTE; loopCounter_u32++)
{
if (crcGen->McuCRC_Register & topbit_u32)
{
crcGen->McuCRC_Register = (crcGen->McuCRC_Register << 1) ^ crcGen->McuCRC_Polynomial;
}
else
{
crcGen->McuCRC_Register = (crcGen->McuCRC_Register << 1);
}
crcGen->McuCRC_Register &= crcGen->McuCRC_WidthMask;
}
}
uint32_t McuCRC_GetCrcValue ( McuCRC_Generator_t *crcGen )
{
if (crcGen->McuCRC_ReflectedOutput)
{
return crcGen->McuCRC_XorOutput ^ McuCRC_Reflect( crcGen->McuCRC_Register, crcGen->McuCRC_Width );
}
else
{
return crcGen->McuCRC_XorOutput ^ crcGen->McuCRC_Register;
}
}
uint8_t McuCRC_CalculateWithTableCRC8 ( McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length )
{
uint32_t loopCounter_u32;
uint8_t crcValue_u8;
uint8_t *crcTable_au8;
crcTable_au8 = (uint8_t*)crcGen->McuCRC_Table;
crcValue_u8 = crcGen->McuCRC_InitialValue;
for ( loopCounter_u32 = 0 ; loopCounter_u32 < length ; loopCounter_u32++ )
{
crcValue_u8 = crcTable_au8[( crcValue_u8 ^ (data_pu8[loopCounter_u32])) & 0xFF];
}
crcValue_u8 ^= crcGen->McuCRC_XorOutput;
return crcValue_u8;
}
uint16_t McuCRC_CalculateWithTableCRC16 ( McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length )
{
uint32_t loopCounter_u32;
uint16_t crcValue_u16;
uint16_t *crcTable_au16;
crcTable_au16 = (uint16_t*)crcGen->McuCRC_Table;
crcValue_u16 = crcGen->McuCRC_InitialValue;
if ( (crcGen->McuCRC_ReflectedInput == 0) && (crcGen->McuCRC_ReflectedOutput == 0) )
{
for ( loopCounter_u32 = 0 ; loopCounter_u32 < length ; loopCounter_u32++ )
{
crcValue_u16 = crcTable_au16[((crcValue_u16 >> 8) ^ (data_pu8[loopCounter_u32])) & 0xFF] ^ (crcValue_u16 << McuCRC_BIT_PER_BYTE);
}
}
else if ( (crcGen->McuCRC_ReflectedInput == 1) && (crcGen->McuCRC_ReflectedOutput == 1) )
{
for ( loopCounter_u32 = 0 ; loopCounter_u32 < length ; loopCounter_u32++ )
{
crcValue_u16 = crcTable_au16[(crcValue_u16 ^ (data_pu8[loopCounter_u32])) & 0xFF] ^ (crcValue_u16 >> McuCRC_BIT_PER_BYTE);
}
}
crcValue_u16 ^= crcGen->McuCRC_XorOutput;
return crcValue_u16;
}
uint32_t McuCRC_CalculateWithTableCRC32 ( McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length )
{
uint32_t loopCounter_u32;
uint32_t crcValue_u32;
uint32_t *crcTable_au32;
crcTable_au32 = (uint32_t*)crcGen->McuCRC_Table;
crcValue_u32 = crcGen->McuCRC_InitialValue;
if ( (crcGen->McuCRC_ReflectedInput == 0) && (crcGen->McuCRC_ReflectedOutput == 0) )
{
for ( loopCounter_u32 = 0 ; loopCounter_u32 < length ; loopCounter_u32++ )
{
crcValue_u32 = crcTable_au32[((crcValue_u32 >> 24) ^ (data_pu8[loopCounter_u32])) & 0xFF] ^ (crcValue_u32 << McuCRC_BIT_PER_BYTE);
}
}
else if ( (crcGen->McuCRC_ReflectedInput == 1) && (crcGen->McuCRC_ReflectedOutput == 1) )
{
for ( loopCounter_u32 = 0 ; loopCounter_u32 < length ; loopCounter_u32++ )
{
crcValue_u32 = crcTable_au32[(crcValue_u32 ^ (data_pu8[loopCounter_u32])) & 0xFF] ^ (crcValue_u32 >> McuCRC_BIT_PER_BYTE);
}
}
crcValue_u32 ^= crcGen->McuCRC_XorOutput;
return crcValue_u32;
}
uint32_t McuCRC_Reflect ( uint32_t value_u32, uint32_t noOfBits_u32)
{
uint32_t loopCounter_u32, temp_u32;
temp_u32 = value_u32;
for ( loopCounter_u32 = 0 ; loopCounter_u32 < noOfBits_u32 ; loopCounter_u32++ )
{
if (temp_u32 & 1)
{
value_u32 |= ( 1 << ( (noOfBits_u32 - 1) - loopCounter_u32 ) );
}
else
{
value_u32 &= ~( 1 << ( (noOfBits_u32 - 1) - loopCounter_u32 ) );
}
temp_u32 = (temp_u32 >> 1);
}
return value_u32;
}

View File

@@ -0,0 +1,173 @@
/**
* Copyright Ivo Gärtner
* \file
* \author Ivo Gärtner
* \copyright Ivo Gärtner
* \date 9.11.2018
* SPDX-License-Identifier: BSD-3-Clause
*
* This program code does very closely rely on the example code
* of Ross Williams' article "A Painless Guide to CRC Error
* Detection Algorithms".
*
*
* How to use this code:
*
* First: Define the McuCRC_Generator_t structure, e.g. like this:
*
* McuCRC_Generator_t crcGen;
* crcGen.McuCRC_InitialValue = 0xFFFFFFFF;
* crcGen.McuCRC_Polynomial = 0x04C11DB7;
* crcGen.McuCRC_ReflectedInput = 0;
* crcGen.McuCRC_ReflectedOutput = 0;
* crcGen.McuCRC_Width = McuCRC_WIDTH_32_BIT;
* crcGen.McuCRC_XorOutput = 0xFFFFFFFF;
* crcGen.McuCRC_Table = NULL;
*
* Second: Run the McuCRC_Init function on the McuCRC_Generator_t structure:
*
* McuCRC_Init( &crcGen );
*
* Third: For the shift register implementation call McuCRC_CalculateBlock() and then McuCRC_GetCrcValue(), e.g. like this:
*
* uint32_t crc;
* uint8_t byteArray[] = {0x01, 0x01, 0x12, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5};
*
* McuCRC_CalculateBlock( &crcGen, byteArray, 8 );
* crc = McuCRC_GetCrcValue( &crcGen );
*
* Or for the LUT implementation call McuCRC_CalculateWithTableCRC32(), or the 8 / 16 bit versions of it, like this:
*
* crc = McuCRC_CalculateWithTableCRC8( &crcGen, byteArray, 8 );
*
*
* happy crc'ing
*/
#ifndef McuCRC_GENERATOR_H_INCLUDED
#define McuCRC_GENERATOR_H_INCLUDED
#include <stdint.h>
#include <stddef.h>
#define McuCRC_BIT_PER_BYTE 8
enum McuCRC_WIDTH_BITS
{
McuCRC_WIDTH_8_BIT = 8,
McuCRC_WIDTH_16_BIT = 16,
McuCRC_WIDTH_32_BIT = 32
};
typedef struct
{
enum McuCRC_WIDTH_BITS McuCRC_Width; /**< PARAMETER: Width of the CRC in bits - 16 or 32 */
uint32_t McuCRC_Polynomial; /**< PARAMETER: The CRC algorithm's polynomial */
uint32_t McuCRC_InitialValue; /**< PARAMETER: Initial register value */
uint32_t McuCRC_ReflectedInput; /**< PARAMETER: Reflect input - 0: no, >=1: yes */
uint32_t McuCRC_ReflectedOutput; /**< PARAMETER: Reflect output - 0: no, >=1: yes */
uint32_t McuCRC_XorOutput; /**< PARAMETER: XOR this to the output of the CRC calculation */
uint32_t McuCRC_WidthMask; /**< CONTEXT: Mask for the crc width */
uint32_t McuCRC_Register; /**< CONTEXT: Storage for the crc value */
void *McuCRC_Table; /**< PARAMETER: Pointer to a LUT if no shift register implementation is used */
} McuCRC_Generator_t;
/**
* \fn McuCRC_Init()
*
* \brief Sets the initial value of the crc calculation and calculates the width mask
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
*/
void McuCRC_Init ( McuCRC_Generator_t *crcGen );
/**
* \fn McuCRC_CalculateBlock()
*
* \brief Calculates a crc from a block of data (uint8_t array)
*
* This function calculates the crc but does not Xor the output. To get the
* Xor'd output use the function \a McuCRC_GetCrcValue() which returns the Xor'd
* crc value.
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \param uint8_t *data_pu8 Pointer to the data to be crc'd
* \param size_t length Number of bytes in the data array
*/
void McuCRC_CalculateBlock (McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length );
/**
* \fn McuCRC_CalculateNextValue()
*
* \brief Calculates the crc of one byte in a data stream
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \param uint8_t data_u8 Byte to be crc'd
*
*/
void McuCRC_CalculateNextValue ( McuCRC_Generator_t *crcGen, uint8_t data_u8 );
/**
* \fn McuCRC_GetCrcValue()
*
* \brief Returns you the Xor'd crc
*
* When you ran the functions \a McuCRC_CalculateBlock or \a McuCRC_CalculateNextValue over
* the data which you want to CRC, this function Xor's the calculated crc and returns
* this Xor'd value.
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \return The value in crcGen->McuCRC_Register XOR^d with the crcGen->McuCRC_XorOut parameter
*/
uint32_t McuCRC_GetCrcValue ( McuCRC_Generator_t *crcGen );
/**
* \fn McuCRC_CalculateWithTableCRC32()
*
* \brief Calculates a 32 bit crc of a byte array using a LUT
*
* The LUT used for this function can be calculated using the function \a McuCRC_GenerateLookUpTable()
* The pointer the LUT has to be casted to (void*)
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \return The calculated crc, XOR^d with the crcGen->McuCRC_XorOut parameter
*/
uint32_t McuCRC_CalculateWithTableCRC32 ( McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length );
/**
* \fn McuCRC_CalculateWithTableCRC16()
*
* \brief Calculates a 16 bit crc of a byte array using a LUT
*
* The LUT used for this function can be calculated using the function \a McuCRC_GenerateLookUpTable()
* The pointer the LUT has to be casted to (void*)
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \return The calculated crc, XOR^d with the crcGen->McuCRC_XorOut parameter
*/
uint16_t McuCRC_CalculateWithTableCRC16 ( McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length );
/**
* \fn McuCRC_CalculateWithTableCRC8()
*
* \brief Calculates a 8 bit crc of a byte array using a LUT
*
* The LUT used for this function can be calculated using the function \a McuCRC_GenerateLookUpTable()
* The pointer the LUT has to be casted to (void*)
*
* \param McuCRC_Generator_t *crcGen Pointer to a \a McuCRC_Generator_t structure
* \return The calculated crc, XOR^d with the crcGen->McuCRC_XorOut parameter
*/
uint8_t McuCRC_CalculateWithTableCRC8 ( McuCRC_Generator_t *crcGen, uint8_t *data_pu8, size_t length );
/**
* \fn McuCRC_Reflect()
*
* \brief Returns the bottom \a noOfBits_u32 bits of \a value_u32 in revered order
*
* \param uint32_t value_u32 Value on which to perform the bit reversal
* \param uint32_t noOfBits_u32 Number of bits to reverse
*/
uint32_t McuCRC_Reflect ( uint32_t value_u32, uint32_t noOfBits_u32);
#endif // McuCRC_GENERATOR_H_INCLUDED

View File

@@ -0,0 +1,59 @@
SPDX-License-Identifier: BSD-3-Clause
This file contains common CRC algorithm configurations
The value "Check" is the reference output if the ASCII string "123456789" is CRC'd
Common 8 bit CRC's
Algorithm Check Poly Init RefIn RefOut XorOut
CRC-8 0xF4 0x07 0x00 false false 0x00
CRC-8/CDMA2000 0xDA 0x9B 0xFF false false 0x00
CRC-8/DARC 0x15 0x39 0x00 true true 0x00
CRC-8/DVB-S2 0xBC 0xD5 0x00 false false 0x00
CRC-8/EBU 0x97 0x1D 0xFF true true 0x00
CRC-8/I-CODE 0x7E 0x1D 0xFD false false 0x00
CRC-8/ITU 0xA1 0x07 0x00 false false 0x55
CRC-8/MAXIM 0xA1 0x31 0x00 true true 0x00
CRC-8/ROHC 0xD0 0x07 0xFF true true 0x00
CRC-8/WCDMA 0x25 0x9B 0x00 true true 0x00
Common 16 bit CRC's
Algorithm Check Poly Init RefIn RefOut XorOut
CRC-16/CCITT-FALSE 0x29B1 0x1021 0xFFFF false false 0x0000
CRC-16/ARC 0xBB3D 0x8005 0x0000 true true 0x0000
CRC-16/AUG-CCITT 0xE5CC 0x1021 0x1D0F false false 0x0000
CRC-16/BUYPASS 0xFEE8 0x8005 0x0000 false false 0x0000
CRC-16/CDMA2000 0x4C06 0xC867 0xFFFF false false 0x0000
CRC-16/DDS-110 0x9ECF 0x8005 0x800D false false 0x0000
CRC-16/DECT-R 0x007E 0x0589 0x0000 false false 0x0001
CRC-16/DECT-X 0x007F 0x0589 0x0000 false false 0x0000
CRC-16/DNP 0xEA82 0x3D65 0x0000 true true 0xFFFF
CRC-16/EN-13757 0xC2B7 0x3D65 0x0000 false false 0xFFFF
CRC-16/GENIBUS 0xD64E 0x1021 0xFFFF false false 0xFFFF
CRC-16/MAXIM 0x44C2 0x8005 0x0000 true true 0xFFFF
CRC-16/MCRF4XX 0x6F91 0x1021 0xFFFF true true 0x0000
CRC-16/RIELLO 0x63D0 0x1021 0xB2AA true true 0x0000
CRC-16/T10-DIF 0xD0DB 0x8BB7 0x0000 false false 0x0000
CRC-16/TELEDISK 0x0FB3 0xA097 0x0000 false false 0x0000
CRC-16/TMS37157 0x26B1 0x1021 0x89EC true true 0x0000
CRC-16/USB 0xB4C8 0x8005 0xFFFF true true 0xFFFF
CRC-A 0xBF05 0x1021 0xC6C6 true true 0x0000
CRC-16/KERMIT 0x2189 0x1021 0x0000 true true 0x0000
CRC-16/MODBUS 0x4B37 0x8005 0xFFFF true true 0x0000
CRC-16/X-25 0x906E 0x1021 0xFFFF true true 0xFFFF
CRC-16/XMODEM 0x31C3 0x1021 0x0000 false false 0x0000
Common 32 bit CRC's
Algorithm Check Poly Init RefIn RefOut XorOut
CRC-32 0xCBF43926 0x04C11DB7 0xFFFFFFFF true true 0xFFFFFFFF
CRC-32/BZIP2 0xFC891918 0x04C11DB7 0xFFFFFFFF false false 0xFFFFFFFF
CRC-32C 0xE3069283 0x1EDC6F41 0xFFFFFFFF true true 0xFFFFFFFF
CRC-32D 0x87315576 0xA833982B 0xFFFFFFFF true true 0xFFFFFFFF
CRC-32/MPEG-2 0x0376E6E7 0x04C11DB7 0xFFFFFFFF false false 0x00000000
CRC-32/POSIX 0x765E7680 0x04C11DB7 0x00000000 false false 0xFFFFFFFF
CRC-32Q 0x3010BF7F 0x814141AB 0x00000000 false false 0x00000000
CRC-32/JAMCRC 0x340BC6D9 0x04C11DB7 0xFFFFFFFF true true 0x00000000
CRC-32/XFER 0xBD0BE338 0x000000AF 0x00000000 false false 0x00000000

View File

@@ -0,0 +1,236 @@
/*!
* Copyright (c) 2024, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*
* \brief Implementation of the McuCoverage module.
*/
#include "McuCoverage.h"
#if McuCoverage_CONFIG_IS_ENABLED
#include "McuLib.h"
#include <stdint.h>
#include <stdio.h>
#include "McuLog.h"
#if McuLib_CONFIG_SDK_USE_FREERTOS
#include "McuRTOS.h"
#endif
#include <gcov.h>
int McuCoverage_Check(void) {
FILE *file = NULL;
/*
* Creating a file without absolute path.
* With J-Link and MCUXpresso IDE 11.4.1, this file gets created in the IDE installation directory (C:\NXP\MCUXpressoIDE_11.4.1_6260\ide).
* Where the file gets created (current directory of the semihosting process on the host) really depends on the probe firmware and is non-standard.
* See as well:
* https://developer.arm.com/documentation/dui0058/d/semihosting/semihosting-swis/sys-open--0x01-?lang=en
*/
file = fopen ("gcov_text.txt", "w"); /* on RP2040, file is present in project root folder. If using external gdb server: in the current directory of the GDB server */
if (file!=NULL) {
fputs("hello world with file I/O\r\n", file);
fclose(file);
} else {
return 0; /* failed */
}
file = fopen ("c:\\tmp\\test.txt", "w");
if (file!=NULL) {
fputs("hello world with file I/O\r\n", file);
(void)fwrite("hello\r\n", sizeof("hello\r\n")-1, 1, file);
fclose(file);
return 1; /* ok */
}
return 0; /* failed */
}
void McuCoverage_Deinit(void) {
/* nothing needed */
}
/* call the coverage initializers if not done by startup code */
void McuCoverage_Init(void) {
#if McuCoverage_CONFIG_USE_FREESTANDING
/* In a freestanding environment, we use custom hooks to write data. The constructors/destructors are *not* used,
* instead we rely on the .gcov_info in the binary.
*/
#else
#if McuLib_CONFIG_CPU_IS_RPxxxx
/* constructor calls for coverage already done in C:\Raspy\pico\pico-sdk\src\rp2_common\pico_runtime/runtime.c */
#else
void (**p)(void);
extern uint32_t __init_array_start, __init_array_end; /* linker defined symbols, array of function pointers */
uint32_t beg = (uint32_t)&__init_array_start;
uint32_t end = (uint32_t)&__init_array_end;
while(beg<end) {
p = (void(**)(void))beg; /* get function pointer */
(*p)(); /* call constructor */
beg += sizeof(p); /* next pointer */
}
#endif
#endif
}
/* custom exit function */
void exit_(int i) {
for(;;) {}
}
/* see https://gcc.gnu.org/onlinedocs/gcc/Freestanding-Environments.html#Tutorial */
#if McuCoverage_CONFIG_USE_FREESTANDING
static McuCoverage_OutputCharFct_t OutputCharFct = NULL;
void McuCoverage_OutputString(const unsigned char *str) {
if (OutputCharFct==NULL) {
return;
}
while(*str!='\0') {
OutputCharFct(*str);
str++;
}
}
void McuCoverage_SetOuputCharCallback(McuCoverage_OutputCharFct_t callback) {
OutputCharFct = callback;
}
/* The start and end symbols are provided by the linker script. We use the
array notation to avoid issues with a potential small-data area. */
/* Use the following in the linker file:
.gcov_info:
{
PROVIDE (__gcov_info_start = .);
KEEP (*(.gcov_info))
PROVIDE (__gcov_info_end = .);
} > FLASH
Additionally, set the following compiler option:
-fprofile-info-section
See https://github.com/gcc-mirror/gcc/blob/master/libgcc/gcov.h
*/
extern const struct gcov_info *const __gcov_info_start[];
extern const struct gcov_info *const __gcov_info_end[];
static const unsigned char a = 'a';
/* each 8bit binary data value c gets encoded into two characters, each in rang 'a'-'p' (p is 'a'+16):
buf[0]: 'a' + LowNibble(c)
buf[1]: 'a' + HighNibble(c)
*/
static inline unsigned char *encode(unsigned char c, unsigned char buf[2]) {
buf[0] = a + c % 16;
buf[1] = a + (c / 16) % 16;
return buf;
}
#if 0
/* The application reads a character stream encoded by encode() from stdin,
decodes it, and writes the decoded characters to stdout. Characters other
than the 16 characters 'a' to 'p' are ignored. */
static int can_decode(unsigned char c) {
return (unsigned char)(c - a) < 16;
}
/* application which reads from stdin a previously encoded data stream and decodes it to stdout. */
void application_decode(void) {
int first = 1;
int i;
unsigned char c;
while ((i = fgetc(stdin)) != EOF) {
unsigned char x = (unsigned char)i;
if (can_decode (x)) {
if (first) {
c = x - a;
} else {
fputc (c + 16 * (x - a), stdout);
}
first = !first;
} else {
first = 1;
}
}
}
#endif
/* This function shall produce a reliable in order byte stream to transfer the
gcov information from the target to the host system. */
static void dump(const void *d, unsigned n, void *arg) {
(void)arg;
const unsigned char *c = d;
unsigned char buf[2];
for(unsigned int i = 0; i<n; i++) {
if (OutputCharFct!=NULL) {
encode(c[i], buf);
OutputCharFct(buf[0]);
OutputCharFct(buf[1]);
}
}
}
/* The filename is serialized to a gcfn data stream by the
__gcov_filename_to_gcfn() function. The gcfn data is used by the
"merge-stream" subcommand of the "gcov-tool" to figure out the filename
associated with the gcov information. */
static void filename(const char *f, void *arg) {
__gcov_filename_to_gcfn(f, dump, arg);
}
/* The __gcov_info_to_gcda() function may have to allocate memory under
certain conditions. Simply try it out if it is needed for your application
or not. */
static void *allocate(unsigned length, void *arg) {
(void)arg;
void *p;
#if McuLib_CONFIG_SDK_USE_FREERTOS
p = pvPortMalloc(length);
#else
p = malloc (length);
#endif
if (p==NULL) {
McuLog_fatal("malloc failed");
for(;;) {} /* error */
}
}
/* Dump the gcov information of all translation units. */
static void dump_gcov_info (void) {
const struct gcov_info *const *info = __gcov_info_start;
const struct gcov_info *const *end = __gcov_info_end;
__asm__ ("" : "+r" (info)); /* Obfuscate variable to prevent compiler optimizations. */
while (info != end) { /* iterate through all infos (or modules instrumented) */
void *arg = NULL;
__gcov_info_to_gcda(*info, filename, dump, allocate, arg); /* write record*/
if (OutputCharFct!=NULL) { /* each record is terminated with a newline character */
OutputCharFct('\n');
}
info++;
}
}
#endif /* McuCoverage_CONFIG_USE_FREESTANDING */
void McuCoverage_WriteFiles(void) {
#if McuCoverage_CONFIG_USE_FREESTANDING
dump_gcov_info();
#else
#if __GNUC__ < 11
// void __gcov_flush(void); /* internal gcov function to write data */
__gcov_flush(); /* __gcov_flush() has been removed in the libraries for GCC11 */
#else
// void __gcov_dump(void); /* from GCC11 on, __gcov_flush() has been replaced by __gcov_dump() */
__gcov_dump(); /* from GCC11 on, use __gcov_dump() */
#endif
#endif
}
#endif /* #if McuCoverage_CONFIG_IS_ENABLED */

View File

@@ -0,0 +1,63 @@
/*!
* Copyright (c) 2024, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*
* \brief Header file for the McuCoverage module.
* It helps collecting coverage information for gcov (GNU Coverage).
*/
#ifndef MCUCOVERAGE_H_
#define MCUCOVERAGE_H_
#include "McuCoverageconfig.h"
#if McuCoverage_CONFIG_IS_ENABLED
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Test function to verify file I/O needed for gcov information generation.
* \return 1 if file I/O does work, 0 otherwise
*/
int McuCoverage_Check(void);
/*!
* \brief Type of callback used for output data in freestanding mode.
*/
typedef void (*McuCoverage_OutputCharFct_t)(unsigned char);
/*!
* \brief Set an output callback to write a coverage byte or character
*/
void McuCoverage_SetOuputCharCallback(McuCoverage_OutputCharFct_t callback);
/*!
* \brief Write a string using the McuCoverage_OutputCharFct_t callback
*/
void McuCoverage_OutputString(const unsigned char *str);
/*!
* \brief Flush and write the coverage information collected so far
*/
void McuCoverage_WriteFiles(void);
/*!
\brief Module de-initialization
*/
void McuCoverage_Deinit(void);
/*!
* \brief Initialize the coverage information/constructors. Need to call this at the start of main().
*/
void McuCoverage_Init(void);
#endif /* McuCoverage_CONFIG_IS_ENABLED */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MCUCOVERAGE_H_ */

View File

@@ -0,0 +1,151 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuCriticalSection.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : CriticalSection
** Version : Component 01.015, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2021-08-20, 16:02, # CodeGen: 747
** Abstract :
**
** Settings :
** Component name : McuCriticalSection
** SDK : McuLib
** Use Processor Expert Default : no
** Use FreeRTOS : no
** Contents :
** CriticalVariable - void McuCriticalSection_CriticalVariable(void);
** EnterCritical - void McuCriticalSection_EnterCritical(void);
** ExitCritical - void McuCriticalSection_ExitCritical(void);
** Deinit - void McuCriticalSection_Deinit(void);
** Init - void McuCriticalSection_Init(void);
**
** * Copyright (c) 2014-2021, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuCriticalSection.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuCriticalSection_module McuCriticalSection module documentation
** @{
*/
/* MODULE McuCriticalSection. */
#include "McuCriticalSection.h"
/*
** ===================================================================
** Method : CriticalVariable (component CriticalSection)
**
** Description :
** Defines a variable if necessary. This is a macro.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/*
void McuCriticalSection_CriticalVariable(void)
{
*** Implemented as macro in the header file McuCriticalSection.h
}
*/
/*
** ===================================================================
** Method : EnterCritical (component CriticalSection)
**
** Description :
** Enters a critical section
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/*
void McuCriticalSection_EnterCritical(void)
{
*** Implemented as macro in the header file McuCriticalSection.h
}
*/
/*
** ===================================================================
** Method : ExitCritical (component CriticalSection)
**
** Description :
** Exits a critical section
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/*
void McuCriticalSection_ExitCritical(void)
{
*** Implemented as macro in the header file McuCriticalSection.h
}
*/
/*
** ===================================================================
** Method : Deinit (component CriticalSection)
**
** Description :
** Driver de-initialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuCriticalSection_Deinit(void)
{
/* nothing needed */
}
/*
** ===================================================================
** Method : Init (component CriticalSection)
**
** Description :
** driver initialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuCriticalSection_Init(void)
{
/* nothing needed */
}
/* END McuCriticalSection. */
/*!
** @}
*/

View File

@@ -0,0 +1,221 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuCriticalSection.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : CriticalSection
** Version : Component 01.015, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2021-11-25, 06:25, # CodeGen: 749
** Abstract :
**
** Settings :
** Component name : McuCriticalSection
** SDK : McuLib
** Use Processor Expert Default : no
** Use FreeRTOS : no
** Contents :
** CriticalVariable - void McuCriticalSection_CriticalVariable(void);
** EnterCritical - void McuCriticalSection_EnterCritical(void);
** ExitCritical - void McuCriticalSection_ExitCritical(void);
** Deinit - void McuCriticalSection_Deinit(void);
** Init - void McuCriticalSection_Init(void);
**
** * Copyright (c) 2014-2021, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuCriticalSection.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuCriticalSection_module McuCriticalSection module documentation
** @{
*/
#ifndef __McuCriticalSection_H
#define __McuCriticalSection_H
/* MODULE McuCriticalSection. */
#include "McuLib.h" /* SDK and API used */
#include "McuCriticalSectionconfig.h" /* configuration */
/* other includes needed */
#if McuCriticalSection_CONFIG_USE_RTOS_CRITICAL_SECTION
#if McuLib_CONFIG_CPU_IS_ESP32
#include "freertos/FreeRTOS.h"
#include "freertos/task.h" /* FreeRTOS header file for taskENTER_CRITICAL() and taskEXIT_CRITICAL() macros */
#else
#include "FreeRTOS.h"
#include "task.h" /* FreeRTOS header file for taskENTER_CRITICAL() and taskEXIT_CRITICAL() macros */
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* workaround macros for wrong EnterCritical()/ExitCritical() in the low level drivers. */
#define McuCriticalSection_CriticalVariableDrv() \
McuCriticalSection_CriticalVariable()
#define McuCriticalSection_EnterCriticalDrv() \
McuCriticalSection_EnterCritical()
#define McuCriticalSection_ExitCriticalDrv() \
McuCriticalSection_ExitCritical()
#ifdef __HIWARE__
#pragma MESSAGE DISABLE C3303 /* C3303 Implicit concatenation of strings */
#endif
#if McuCriticalSection_CONFIG_USE_PEX_DEFAULT
#define McuCriticalSection_CriticalVariable() /* nothing needed */
#elif McuCriticalSection_CONFIG_USE_RTOS_CRITICAL_SECTION
#define McuCriticalSection_CriticalVariable() /* nothing needed */
#elif McuCriticalSection_CONFIG_USE_CUSTOM_CRITICAL_SECTION
#if McuLib_CONFIG_CPU_IS_RISC_V
#define McuCriticalSection_CriticalVariable() /* nothing needed */
#else
#define McuCriticalSection_CriticalVariable() uint8_t cpuSR; /* variable to store current status */
#endif
#endif
/*
** ===================================================================
** Method : CriticalVariable (component CriticalSection)
**
** Description :
** Defines a variable if necessary. This is a macro.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#if McuCriticalSection_CONFIG_USE_PEX_DEFAULT
#define McuCriticalSection_EnterCritical() EnterCritical()
#elif McuCriticalSection_CONFIG_USE_RTOS_CRITICAL_SECTION
#define McuCriticalSection_EnterCritical() taskENTER_CRITICAL_FROM_ISR() /* FreeRTOS critical section inside interrupt */
#elif McuCriticalSection_CONFIG_USE_CUSTOM_CRITICAL_SECTION
#if McuLib_CONFIG_CPU_IS_RISC_V
#define McuCriticalSection_EnterCritical() \
do { \
__asm volatile( "csrc mstatus, 8" ); /* Disable interrupts */ \
} while(0)
#elif McuLib_CONFIG_CPU_IS_ARM_CORTEX_M
#define McuCriticalSection_EnterCritical() \
do { \
/*lint -save -esym(529,cpuSR) Symbol 'cpuSR' not subsequently referenced. */\
__asm ( \
"mrs r0, PRIMASK \n\t" \
"cpsid i \n\t" \
"strb r0, %[output] \n\t" \
: [output] "=m" (cpuSR) :: "r0"); \
__asm ("" ::: "memory"); \
/*lint -restore Symbol 'cpuSR' not subsequently referenced. */\
} while(0)
#endif
#endif
/*
** ===================================================================
** Method : EnterCritical (component CriticalSection)
**
** Description :
** Enters a critical section
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#if McuCriticalSection_CONFIG_USE_PEX_DEFAULT
#define McuCriticalSection_ExitCritical() ExitCritical()
#elif McuCriticalSection_CONFIG_USE_RTOS_CRITICAL_SECTION
#define McuCriticalSection_ExitCritical() taskEXIT_CRITICAL_FROM_ISR(0) /* FreeRTOS critical section inside interrupt */
#elif McuCriticalSection_CONFIG_USE_CUSTOM_CRITICAL_SECTION
#if McuLib_CONFIG_CPU_IS_RISC_V
#define McuCriticalSection_ExitCritical() \
do { \
__asm volatile( "csrs mstatus, 8" ); /* Enable interrupts */ \
} while(0)
#elif McuLib_CONFIG_CPU_IS_ARM_CORTEX_M
#define McuCriticalSection_ExitCritical() \
do{ \
__asm ( \
"ldrb r0, %[input] \n\t" \
"msr PRIMASK,r0 \n\t" \
::[input] "m" (cpuSR) : "r0"); \
} while(0)
#endif
#endif
/*
** ===================================================================
** Method : ExitCritical (component CriticalSection)
**
** Description :
** Exits a critical section
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuCriticalSection_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component CriticalSection)
**
** Description :
** Driver de-initialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuCriticalSection_Init(void);
/*
** ===================================================================
** Method : Init (component CriticalSection)
**
** Description :
** driver initialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/* END McuCriticalSection. */
#ifdef __cplusplus
}
#endif
#endif
/* ifndef __McuCriticalSection_H */
/*!
** @}
*/

View File

@@ -0,0 +1,868 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuDS18B20.h
** CDE edition : Community
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : DS18B20
** Version : Component 01.020, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
This is a component for the Maxim DS18B20 1-Wire temperature sensor.
** Settings :
** Component Name : McuDS18B20
** Temperature Reading : Auto
** Connection mode : One slave
** One Wire : McuOneWire
** SDK : McuLib
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** ReadRom - uint8_t McuDS18B20_ReadRom(uint8_t sensor_index);
** GetRomCode - uint8_t McuDS18B20_GetRomCode(uint8_t sensor_index, uint8_t **romCodePtr);
** isBusy - bool McuDS18B20_isBusy(void);
** StartConversion - uint8_t McuDS18B20_StartConversion(uint8_t sensor_index);
** ReadTemperature - uint8_t McuDS18B20_ReadTemperature(uint8_t sensor_index);
** GetTemperatureRaw - uint8_t McuDS18B20_GetTemperatureRaw(uint16_t sensor_index, uint32_t *raw);
** GetTemperatureFloat - uint8_t McuDS18B20_GetTemperatureFloat(uint8_t sensor_index, float...
** ReadResolution - uint8_t McuDS18B20_ReadResolution(uint8_t sensor_index);
** SetResolution - uint8_t McuDS18B20_SetResolution(uint8_t sensor_index, DS18B20_ResolutionBits...
** SearchAndAssignROMCodes - uint8_t McuDS18B20_SearchAndAssignROMCodes(void);
** ParseCommand - uint8_t McuDS18B20_ParseCommand(const unsigned char* cmd, bool *handled,...
** Init - void McuDS18B20_Init(void);
** Deinit - void McuDS18B20_Deinit(void);
**
** * Copyright (c) Original implementation: Omar Isa<73> Pinales Ayala, 2014, all rights reserved.
** * Updated and maintained by Erich Styger, 2014-2020
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuDS18B20.h
** @version 01.00
** @brief
**
This is a component for the Maxim DS18B20 1-Wire temperature sensor.
*/
/*!
** @addtogroup McuDS18B20_module McuDS18B20 module documentation
** @{
*/
/* MODULE McuDS18B20. */
#include "McuDS18B20.h"
#include <string.h>
#include "McuOneWire.h" /* interface to 1-Wire */
#include "McuUtility.h"
#include "McuWait.h"
/* Events */
enum {
EV_NOTHING,
EV_INIT,
EV_NO_BUSY,
EV_READ_ROM,
EV_READ_TEMP,
EV_READ_TEMP_ALL
};
/* Rom commands */
#define RC_READ_ROM 0x33
#define RC_MATCH_ROM 0x55
#define RC_SKIP_ROM 0xCC
#define RC_RELEASE 0xFF
/* Function commands */
#define FC_CONVERT_T 0x44
#define FC_WRITE_SCRATCHPAD 0x4E
#define FC_READ_SCRATCHPAD 0xBE
#define FC_COPY_SCRATCHPAD 0x48
/* configuration byte */
#define DS18B20_CONFIG_SHIFT_R0 (5) /* R0 in configuration byte starts at bit 0 */
#define DS18B20_CONFIG_ONE_MASK (0x1F) /* bit 0 to bit 4 are one in configuration byte */
#define DS18B20_NOF_SCRATCHPAD_BYTES (9) /* number of bytes in scratchpad */
typedef struct {
int32_t Temperature;
uint8_t Rom[DS18B20_ROM_CODE_SIZE]; /* family code (0x28), ROM code (6 bytes), CRC (1 byte) */
DS18B20_ResolutionBits resolution; /* DS18B20_ResolutionBits */
} Sensor_t;
struct {
int32 Value;
uint8 Data[10];
#if McuDS18B20_CONFIG_MULTIPLE_BUS_DEVICES
uint8 WorkSensor;
unsigned MaxResolution:2;
#endif
unsigned Busy:1;
} Device;
/* conversion time based on resolution */
static const uint16 ConvTime[4] = {
94, /* DS18B20_RESOLUTION_BITS_9: 93.75 ms */
188, /* DS18B20_RESOLUTION_BITS_10: 187.5 ms */
375, /* DS18B20_RESOLUTION_BITS_11: 375 ms */
750 /* DS18B20_RESOLUTION_BITS_12: 750 ms */
};
static Sensor_t Sensor[McuDS18B20_CONFIG_NUMBER_OF_SENSORS];
static uint8_t McuDS18B20_ReadScratchpad(uint8_t sensor_index, uint8_t data[DS18B20_NOF_SCRATCHPAD_BYTES]) {
uint8_t res;
if(Device.Busy) {
return ERR_BUSY;
}
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#else
(void)sensor_index; /* not used */
#endif
Device.Busy = TRUE;
McuOneWire_SendReset();
#if McuDS18B20_CONFIG_MULTIPLE_BUS_DEVICES
McuOneWire_SendByte(RC_MATCH_ROM);
McuOneWire_SendBytes(Sensor[sensor_index].Rom, sizeof(Sensor[sensor_index].Rom));
#else /* single device on the bus, can skip ROM code */
McuOneWire_SendByte(RC_SKIP_ROM);
#endif
McuOneWire_SendByte(FC_READ_SCRATCHPAD);
McuOneWire_Receive(DS18B20_NOF_SCRATCHPAD_BYTES);
McuOneWire_SendByte(0xFF);
Device.Busy = FALSE;
/* extract data */
res = McuOneWire_GetBytes(&data[0], DS18B20_NOF_SCRATCHPAD_BYTES); /* scratchpad with 9 bytes */
if (res!=ERR_OK) {
return res; /* failed getting data */
}
/* check CRC */
if (McuOneWire_CalcCRC(&data[0], 8)!=data[8]) { /* last byte is CRC */
return ERR_CRC; /* CRC error */
}
return ERR_OK;
}
#if McuDS18B20_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
uint8_t buf[48];
uint8_t res;
float temp;
int i;
McuShell_SendStatusStr((unsigned char*)"McuDS18B20", (unsigned char*)"\r\n", io->stdOut);
#if McuDS18B20_CONFIG_READ_AUTO
McuShell_SendStatusStr((unsigned char*)" mode", (unsigned char*)"auto: conversion reads temperature\r\n", io->stdOut);
#else
McuShell_SendStatusStr((unsigned char*)" mode", (unsigned char*)"read: start conversion, then read temperature\r\n", io->stdOut);
#endif
#if McuDS18B20_CONFIG_MULTIPLE_BUS_DEVICES
McuShell_SendStatusStr((unsigned char*)" multiple", (unsigned char*)"yes\r\n", io->stdOut);
#else
McuShell_SendStatusStr((unsigned char*)" multiple", (unsigned char*)"no\r\n", io->stdOut);
#endif
McuUtility_Num8uToStr(buf, sizeof(buf), McuDS18B20_CONFIG_NUMBER_OF_SENSORS);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" sensors", buf, io->stdOut);
for(i=0;i<McuDS18B20_CONFIG_NUMBER_OF_SENSORS;i++) {
/* ROM Code */
McuUtility_Num8uToStr(buf, sizeof(buf), i); /* sensor number */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)": ");
if (Sensor[i].Rom[0]==0) { /* unknown Rom code? Try to read it from the device */
res = McuDS18B20_ReadRom(i); /* only one device on the bus: issue READROM command */
} else {
res = ERR_OK; /* do not read the ROM code from the bus, use the stored ROM values */
}
if (res==ERR_OK) {
buf[0] = '\0';
McuOneWire_strcatRomCode(buf, sizeof(buf), Sensor[i].Rom);
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"ERROR (");
McuUtility_strcatNum8u(buf, sizeof(buf), res);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)")");
}
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" ROM code", buf, io->stdOut);
/* resolution */
McuUtility_Num8uToStr(buf, sizeof(buf), i); /* sensor number */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)": ");
switch(Sensor[i].resolution) {
case DS18B20_RESOLUTION_BITS_9: McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"9 bits (93.75 ms conversion time)\r\n"); break;
case DS18B20_RESOLUTION_BITS_10: McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"10 bits (187.5 ms conversion time)\r\n"); break;
case DS18B20_RESOLUTION_BITS_11: McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"11 bits (375 ms conversion time)\r\n"); break;
case DS18B20_RESOLUTION_BITS_12: McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"12 bits (750 ms conversion time)\r\n"); break;
default: McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"UNKNOWN bits\r\n"); break;
} /* switch */
McuShell_SendStatusStr((unsigned char*)" resolution", buf, io->stdOut);
/* Temperature */
res = McuDS18B20_StartConversion(i);
if (res==ERR_OK) {
McuUtility_Num8uToStr(buf, sizeof(buf), i); /* sensor number */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)": ");
#if McuDS18B20_CONFIG_READ_AUTO
res = ERR_OK; /* in auto mode, temperature already has been read from sensor during StartConversion() */
#else
McuWait_WaitOSms(ConvTime[Sensor[i].resolution]);
res = McuDS18B20_ReadTemperature(i);
#endif
if (res==ERR_OK) {
res = McuDS18B20_GetTemperatureFloat(i, &temp);
if (res==ERR_OK) {
McuUtility_strcatNumFloat(buf, sizeof(buf), temp, 4);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"<EFBFBD>C");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"ERROR (");
McuUtility_strcatNum8u(buf, sizeof(buf), res);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)")");
}
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"ERROR (");
McuUtility_strcatNum8u(buf, sizeof(buf), res);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)")");
}
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR (");
McuUtility_strcatNum8u(buf, sizeof(buf), res);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)")");
}
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" temperature", buf, io->stdOut);
} /* for */
return ERR_OK;
}
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"McuDS18B20", (unsigned char*)"Group of McuDS18B20 commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" search", (unsigned char*)"Search for DS18B20 devices on the bus and assign ROM code\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" set res <idx> <bits>", (unsigned char*)"Set sensor resolution to (9, 10, 11, 12) bits\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" read res <idx>", (unsigned char*)"Read sensor resolution\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" start conv <idx>", (unsigned char*)"Start temperature conversion\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" read temp <idx>", (unsigned char*)"Read sensor temperature\r\n", io->stdOut);
return ERR_OK;
}
#endif /* McuDS18B20_CONFIG_PARSE_COMMAND_ENABLED */
/*
** ===================================================================
** Method : ParseCommand (component DS18B20)
**
** Description :
** Shell Command Line parser. Method is only available if Shell
** is enabled in the component properties.
** Parameters :
** NAME - DESCRIPTION
** cmd - command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuDS18B20_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io)
{
#if McuDS18B20_CONFIG_PARSE_COMMAND_ENABLED
uint8_t res = ERR_OK;
const unsigned char *p;
uint8_t sensorNr;
float temperature;
uint8_t buf[32];
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP) == 0
|| McuUtility_strcmp((char*)cmd, "McuDS18B20 help") == 0)
{
*handled = TRUE;
return PrintHelp(io);
} else if ( (McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0)
|| (McuUtility_strcmp((char*)cmd, "McuDS18B20 status") == 0)
)
{
*handled = TRUE;
res = PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, "McuDS18B20 start conv ", sizeof("McuDS18B20 start conv ")-1) == 0) {
*handled = TRUE;
p = cmd + sizeof("McuDS18B20 start conv ")-1;
if (McuUtility_ScanDecimal8uNumber(&p, &sensorNr)==ERR_OK) {
if (McuDS18B20_StartConversion(sensorNr)!=ERR_OK) {
McuShell_SendStr((unsigned char*)"Failed starting conversion!\r\n", io->stdErr);
res = ERR_FAILED;
}
} else {
McuShell_SendStr((unsigned char*)"Wrong sensor index\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, "McuDS18B20 set res ", sizeof("McuDS18B20 set res ")-1) == 0) {
DS18B20_ResolutionBits resolution;
uint8_t resol;
*handled = TRUE;
p = cmd + sizeof("McuDS18B20 set res ")-1;
if ( McuUtility_ScanDecimal8uNumber(&p, &sensorNr)==ERR_OK
&& McuUtility_ScanDecimal8uNumber(&p, &resol)==ERR_OK
&& resol>=9 && resol<=12
)
{
switch(resol) {
case 9: resolution = DS18B20_RESOLUTION_BITS_9; break;
case 10: resolution = DS18B20_RESOLUTION_BITS_10; break;
case 11: resolution = DS18B20_RESOLUTION_BITS_11; break;
case 12: resolution = DS18B20_RESOLUTION_BITS_12; break;
default: resolution = DS18B20_RESOLUTION_BITS_12; break;
}
if (McuDS18B20_SetResolution(sensorNr, resolution)!=ERR_OK) {
McuShell_SendStr((unsigned char*)"Failed starting conversion!\r\n", io->stdErr);
res = ERR_FAILED;
}
} else {
McuShell_SendStr((unsigned char*)"Wrong sensor index or resolution!\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, "McuDS18B20 read res ", sizeof("McuDS18B20 read res ")-1) == 0) {
*handled = TRUE;
p = cmd + sizeof("McuDS18B20 read res ")-1;
if (McuUtility_ScanDecimal8uNumber(&p, &sensorNr)==ERR_OK) {
if (McuDS18B20_ReadResolution(sensorNr)!=ERR_OK) {
McuShell_SendStr((unsigned char*)"Failed reading resolution\r\n", io->stdErr);
res = ERR_FAILED;
} else {
switch(Sensor[sensorNr].resolution) {
case DS18B20_RESOLUTION_BITS_9: McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"9 bits\r\n"); break;
case DS18B20_RESOLUTION_BITS_10: McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"10 bits\r\n"); break;
case DS18B20_RESOLUTION_BITS_11: McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"11 bits\r\n"); break;
case DS18B20_RESOLUTION_BITS_12: McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"12 bits\r\n"); break;
default: McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"UNKNOWN bits\r\n"); break;
} /* switch */
McuShell_SendStr(buf, io->stdOut);
res = ERR_OK;
}
} else {
McuShell_SendStr((unsigned char*)"Wrong sensor index\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, "McuDS18B20 read temp ", sizeof("McuDS18B20 read temp ")-1) == 0) {
*handled = TRUE;
p = cmd + sizeof("McuDS18B20 read temp ")-1;
if (McuUtility_ScanDecimal8uNumber(&p, &sensorNr)==ERR_OK) {
if (McuDS18B20_ReadTemperature(sensorNr)!=ERR_OK) {
McuShell_SendStr((unsigned char*)"Failed reading temperature!\r\n", io->stdErr);
res = ERR_FAILED;
} else {
if (McuDS18B20_GetTemperatureFloat(sensorNr, &temperature)!=ERR_OK) {
McuShell_SendStr((unsigned char*)"Failed getting temperature!\r\n", io->stdErr);
res = ERR_FAILED;
} else {
buf[0] = '\0';
McuUtility_strcatNumFloat(buf, sizeof(buf), temperature, 4);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"<EFBFBD>C\r\n");
McuShell_SendStr(buf, io->stdOut);
res = ERR_OK;
}
}
} else {
McuShell_SendStr((unsigned char*)"Wrong sensor index\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strcmp((char*)cmd, "McuDS18B20 search")==0) {
uint8_t rom[McuOneWire_ROM_CODE_SIZE];
bool found;
int i, nofFound = 0;
*handled = TRUE;
McuOneWire_ResetSearch(); /* reset search fields */
McuOneWire_TargetSearch(DS18B20_FAMILY_CODE); /* only search for DS18B20 */
do {
found = McuOneWire_Search(&rom[0], TRUE);
if (found) {
buf[0] = '\0';
(void)McuOneWire_strcatRomCode(buf, sizeof(buf), &rom[0]);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStr(buf, io->stdOut);
/* store ROM code in device list */
for(i=0;i<McuOneWire_ROM_CODE_SIZE;i++) {
Sensor[nofFound].Rom[i] = rom[i];
}
nofFound++;
}
} while(found && nofFound<McuDS18B20_CONFIG_NUMBER_OF_SENSORS);
if (nofFound==0) {
McuShell_SendStr((unsigned char*)"No device found!\r\n", io->stdErr);
}
return ERR_OK;
}
return res;
#else
(void)cmd;
(void)handled;
(void)io;
return ERR_OK;
#endif
}
/*
** ===================================================================
** Method : StartConversion (component DS18B20)
**
** Description :
** Starts the conversion of temperature in the sensor.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_StartConversion(uint8_t sensor_index)
{
#if McuDS18B20_CONFIG_READ_AUTO
uint8_t res;
#endif
if(Device.Busy) {
return ERR_BUSY;
}
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#endif
Device.Busy = TRUE;
McuOneWire_SendReset();
#if McuDS18B20_CONFIG_MULTIPLE_BUS_DEVICES
McuOneWire_SendByte(RC_MATCH_ROM);
McuOneWire_SendBytes(Sensor[sensor_index].Rom, DS18B20_ROM_CODE_SIZE);
McuOneWire_SendByte(FC_CONVERT_T);
#else /* only single device on the bus, can skip ROM code */
McuOneWire_SendByte(RC_SKIP_ROM);
McuOneWire_SendByte(FC_CONVERT_T);
#endif
Device.Busy = FALSE;
#if McuDS18B20_CONFIG_READ_AUTO
McuWait_WaitOSms(ConvTime[Sensor[sensor_index].resolution]);
res = McuDS18B20_ReadTemperature(sensor_index);
if (res!=ERR_OK) {
return res;
}
#endif
return ERR_OK;
}
/*
** ===================================================================
** Method : SetResolution (component DS18B20)
**
** Description :
** Sets the resolution
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Index of the sensor to
** set the resolution.
** config_bits - Two bits resolution config
** value:
** [0b00] - 9 bits.
** [0b01] - 10 bits.
** [0b10] - 11 bits.
** [0b11] - 12 bits.
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_SetResolution(uint8_t sensor_index, DS18B20_ResolutionBits resolution)
{
uint8_t config;
if(Device.Busy) {
return ERR_BUSY;
}
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#else
(void)sensor_index; /* not used */
#endif
Sensor[sensor_index].resolution = resolution;
config = (((uint8_t)(resolution<<DS18B20_CONFIG_SHIFT_R0))|DS18B20_CONFIG_ONE_MASK); /* build proper configuration register mask */
Device.Busy = TRUE;
McuOneWire_SendReset();
#if McuDS18B20_CONFIG_MULTIPLE_BUS_DEVICES
Device.WorkSensor = sensor_index;
McuOneWire_SendByte(RC_MATCH_ROM);
McuOneWire_SendBytes(Sensor[sensor_index].Rom, DS18B20_ROM_CODE_SIZE);
McuOneWire_SendByte(FC_WRITE_SCRATCHPAD);
McuOneWire_SendByte(0x01);
McuOneWire_SendByte(0x10);
McuOneWire_SendByte(config);
#else /* only single device on the bus, can skip ROM code */
McuOneWire_SendByte(RC_SKIP_ROM);
McuOneWire_SendByte(FC_WRITE_SCRATCHPAD);
McuOneWire_SendByte(0x01);
McuOneWire_SendByte(0x10);
McuOneWire_SendByte(config);
#endif
Device.Busy = FALSE;
return ERR_OK;
}
/*
** ===================================================================
** Method : ReadTemperature (component DS18B20)
**
** Description :
** Read the temperature value from the sensor and stores it in
** memory
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_ReadTemperature(uint8_t sensor_index)
{
uint8_t data[DS18B20_NOF_SCRATCHPAD_BYTES]; /* scratchpad data */
uint8_t res;
res = McuDS18B20_ReadScratchpad(sensor_index, &data[0]);
if (res!=ERR_OK) {
return res;
}
/* temperature is in data[0] (LSB) and data[1] (MSB) */
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
Sensor[sensor_index].Temperature = (data[1]<<8)+data[0];
#else
Sensor[0].Temperature = (data[1]<<8)+data[0];
#endif
return ERR_OK;
}
/*
** ===================================================================
** Method : ReadResolution (component DS18B20)
**
** Description :
** Read the sensor resolution sensor and stores it in memory
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_ReadResolution(uint8_t sensor_index)
{
uint8_t data[DS18B20_NOF_SCRATCHPAD_BYTES]; /* scratchpad data */
uint8_t res;
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#endif
res = McuDS18B20_ReadScratchpad(sensor_index, &data[0]);
if (res!=ERR_OK) {
return res;
}
/* configuration is in data[4] */
Sensor[sensor_index].resolution = ((data[4])>>DS18B20_CONFIG_SHIFT_R0)&0x3; /* only two bits */
return ERR_OK;
}
/*
** ===================================================================
** Method : GetTemperature (component DS18B20)
**
** Description :
** Gets the temperature from memory.
** Parameters :
** NAME - DESCRIPTION
** * sensor_index - Index of the sensor to
** get the temperature value.
** Returns :
** --- -
** ===================================================================
*/
uint8_t McuDS18B20_GetTemperatureRaw(uint16_t sensor_index, uint32_t *raw)
{
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#else
(void)sensor_index; /* not used */
#endif
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
*raw = Sensor[sensor_index].Temperature;
#else
*raw = Sensor[0].Temperature;
#endif
return ERR_OK;
}
/*
** ===================================================================
** Method : GetTemperatureFloat (component DS18B20)
**
** Description :
** Returns the temperature from memory in floating point format.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** * temperature - Pointer to where to store
** the value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuDS18B20_GetTemperatureFloat(uint8_t sensor_index, float *temperature)
{
int16_t raw, intPart, fracPart;
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#else
(void)sensor_index; /* not used */
#endif
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
raw = Sensor[sensor_index].Temperature;
#else
raw = Sensor[0].Temperature;
#endif
intPart = raw>>4; /* integral part */
fracPart = raw&0xf; /* fractional part */
*temperature = ((float)intPart) + (((float)fracPart)*0.0625);
return ERR_OK;
}
/*
** ===================================================================
** Method : isBusy (component DS18B20)
**
** Description :
** Returns TRUE if there are a operation in progress.
** Parameters : None
** Returns :
** --- - Returns TRUE if the device is busy, and
** FALSE if its ready to operate.
** ===================================================================
*/
bool McuDS18B20_isBusy(void)
{
return Device.Busy;
}
/*
** ===================================================================
** Method : GetRomCode (component DS18B20)
**
** Description :
** Gets the rom code from the memory.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** * romCodePtr - Pointer to a pointer for the
** return value
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_GetRomCode(uint8_t sensor_index, uint8_t **romCodePtr)
{
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#else
(void)sensor_index; /* not used */
#endif
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
*romCodePtr = &Sensor[sensor_index].Rom[0];
#else
*romCodePtr = &Sensor[0].Rom[0];
#endif
return ERR_OK; /* ok */
}
/*
** ===================================================================
** Method : ReadRom (component DS18B20)
**
** Description :
** Starts to read the rom code and saves it in memory.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_ReadRom(uint8_t sensor_index)
{
uint8_t res;
if(Device.Busy) {
return ERR_BUSY;
}
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if(sensor_index>=McuDS18B20_CONFIG_NUMBER_OF_SENSORS) {
return ERR_RANGE; /* error */
}
#else
(void)sensor_index; /* not used */
#endif
Device.Busy = TRUE;
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
Device.WorkSensor = sensor_index;
#endif
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
res = McuOneWire_ReadRomCode(Sensor[sensor_index].Rom);
#else
res = McuOneWire_ReadRomCode(Sensor[0].Rom); /* 8 bytes */
#endif
Device.Busy = FALSE;
/* index 0 : family code
index 1-6: 48bit serial number
index 7 : CRC
*/
if (res!=ERR_OK) {
return res; /* error */
}
#if McuDS18B20_CONFIG_NUMBER_OF_SENSORS>1
if (Sensor[sensor_index].Rom[0]!=DS18B20_FAMILY_CODE) {
#else
if (Sensor[0].Rom[0]!=DS18B20_FAMILY_CODE) {
#endif
return ERR_FAILED; /* not a DS18B20? */
}
return ERR_OK; /* ok */
}
/*
** ===================================================================
** Method : Deinit (component DS18B20)
**
** Description :
** Driver deinitialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuDS18B20_Deinit(void)
{
/* nothing special needed here */
}
/*
** ===================================================================
** Method : Init (component DS18B20)
**
** Description :
** Initializes the device.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuDS18B20_Init(void)
{
#if McuDS18B20_CONFIG_MULTIPLE_BUS_DEVICES
int i;
for(i=0;i<McuDS18B20_CONFIG_NUMBER_OF_SENSORS;i++) {
Sensor[i].resolution = DS18B20_RESOLUTION_BITS_12;
}
memcpy(Sensor[0].Rom, "\x28\x00\x00\x00\x00\x00\x00\x00", 8);
#else
memset(&Sensor[0], 0, sizeof(Sensor[0])); /* initialize all fields with zero */
Sensor[0].resolution = DS18B20_RESOLUTION_BITS_12; /* default resolution */
#endif
Device.Value = 8500000; /* dummy value or 85<38>C */
}
/*
** ===================================================================
** Method : SearchAndAssignROMCodes (component DS18B20)
**
** Description :
** Scans the devices on the bus and assigns the ROM codes to
** the list of available sensors
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuDS18B20_SearchAndAssignROMCodes(void)
{
uint8_t rom[McuOneWire_ROM_CODE_SIZE];
bool found;
int i, nofFound = 0;
McuOneWire_ResetSearch(); /* reset search fields */
McuOneWire_TargetSearch(DS18B20_FAMILY_CODE); /* only search for DS18B20 */
do {
found = McuOneWire_Search(&rom[0], TRUE);
if (found) {
/* store ROM code in device list */
for(i=0;i<McuOneWire_ROM_CODE_SIZE;i++) {
Sensor[nofFound].Rom[i] = rom[i];
}
nofFound++;
}
} while(found && nofFound<McuDS18B20_CONFIG_NUMBER_OF_SENSORS);
if (nofFound==0) {
return ERR_FAILED; /* nothing found */
}
return ERR_OK;
}
/* END McuDS18B20. */
/*!
** @}
*/

View File

@@ -0,0 +1,325 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuDS18B20.h
** CDE edition : Community
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : DS18B20
** Version : Component 01.020, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
This is a component for the Maxim DS18B20 1-Wire temperature sensor.
** Settings :
** Component Name : McuDS18B20
** Temperature Reading : Auto
** Connection mode : One slave
** One Wire : McuOneWire
** SDK : McuLib
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** ReadRom - uint8_t McuDS18B20_ReadRom(uint8_t sensor_index);
** GetRomCode - uint8_t McuDS18B20_GetRomCode(uint8_t sensor_index, uint8_t **romCodePtr);
** isBusy - bool McuDS18B20_isBusy(void);
** StartConversion - uint8_t McuDS18B20_StartConversion(uint8_t sensor_index);
** ReadTemperature - uint8_t McuDS18B20_ReadTemperature(uint8_t sensor_index);
** GetTemperatureRaw - uint8_t McuDS18B20_GetTemperatureRaw(uint16_t sensor_index, uint32_t *raw);
** GetTemperatureFloat - uint8_t McuDS18B20_GetTemperatureFloat(uint8_t sensor_index, float...
** ReadResolution - uint8_t McuDS18B20_ReadResolution(uint8_t sensor_index);
** SetResolution - uint8_t McuDS18B20_SetResolution(uint8_t sensor_index, DS18B20_ResolutionBits...
** SearchAndAssignROMCodes - uint8_t McuDS18B20_SearchAndAssignROMCodes(void);
** ParseCommand - uint8_t McuDS18B20_ParseCommand(const unsigned char* cmd, bool *handled,...
** Init - void McuDS18B20_Init(void);
** Deinit - void McuDS18B20_Deinit(void);
**
** * Copyright (c) Original implementation: Omar Isa<73> Pinales Ayala, 2014, all rights reserved.
** * Updated and maintained by Erich Styger, 2014-2020
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuDS18B20.h
** @version 01.00
** @brief
**
This is a component for the Maxim DS18B20 1-Wire temperature sensor.
*/
/*!
** @addtogroup McuDS18B20_module McuDS18B20 module documentation
** @{
*/
#ifndef __McuDS18B20_H
#define __McuDS18B20_H
/* MODULE McuDS18B20. */
#include "McuLib.h" /* SDK and API used */
#include "McuDS18B20config.h" /* configuration */
#include "McuShell.h" /* Shell */
#ifdef __cplusplus
extern "C" {
#endif
/* sensor resolution */
typedef enum {
DS18B20_RESOLUTION_BITS_9 = 0b00, /* conversion time: 93.75 ms */
DS18B20_RESOLUTION_BITS_10 = 0b01, /* conversion time: 187.5 ms */
DS18B20_RESOLUTION_BITS_11 = 0b10, /* conversion time: 375 ms */
DS18B20_RESOLUTION_BITS_12 = 0b11 /* conversion time: 750 ms */
} DS18B20_ResolutionBits;
#define DS18B20_FAMILY_CODE 0x28 /* 8-bit family code for DS128B20 */
#define DS18B20_ROM_CODE_SIZE 8 /* 8 byte ROM code (family ID, 6 bytes for ID plus 1 byte CRC */
#define McuDS18B20_PARSE_COMMAND_ENABLED McuDS18B20_CONFIG_PARSE_COMMAND_ENABLED
/*!< set to 1 if method ParseCommand() is present, 0 otherwise */
uint8_t McuDS18B20_StartConversion(uint8_t sensor_index);
/*
** ===================================================================
** Method : StartConversion (component DS18B20)
**
** Description :
** Starts the conversion of temperature in the sensor.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_SetResolution(uint8_t sensor_index, DS18B20_ResolutionBits resolution);
/*
** ===================================================================
** Method : SetResolution (component DS18B20)
**
** Description :
** Sets the resolution
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Index of the sensor to
** set the resolution.
** config_bits - Two bits resolution config
** value:
** [0b00] - 9 bits.
** [0b01] - 10 bits.
** [0b10] - 11 bits.
** [0b11] - 12 bits.
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_ReadTemperature(uint8_t sensor_index);
/*
** ===================================================================
** Method : ReadTemperature (component DS18B20)
**
** Description :
** Read the temperature value from the sensor and stores it in
** memory
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_GetTemperatureRaw(uint16_t sensor_index, uint32_t *raw);
/*
** ===================================================================
** Method : GetTemperature (component DS18B20)
**
** Description :
** Gets the temperature from memory.
** Parameters :
** NAME - DESCRIPTION
** * sensor_index - Index of the sensor to
** get the temperature value.
** Returns :
** --- -
** ===================================================================
*/
bool McuDS18B20_isBusy(void);
/*
** ===================================================================
** Method : isBusy (component DS18B20)
**
** Description :
** Returns TRUE if there are a operation in progress.
** Parameters : None
** Returns :
** --- - Returns TRUE if the device is busy, and
** FALSE if its ready to operate.
** ===================================================================
*/
uint8_t McuDS18B20_GetRomCode(uint8_t sensor_index, uint8_t **romCodePtr);
/*
** ===================================================================
** Method : GetRomCode (component DS18B20)
**
** Description :
** Gets the rom code from the memory.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** * romCodePtr - Pointer to a pointer for the
** return value
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_ReadRom(uint8_t sensor_index);
/*
** ===================================================================
** Method : ReadRom (component DS18B20)
**
** Description :
** Starts to read the rom code and saves it in memory.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
void McuDS18B20_Init(void);
/*
** ===================================================================
** Method : Init (component DS18B20)
**
** Description :
** Initializes the device.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuDS18B20_GetTemperatureFloat(uint8_t sensor_index, float *temperature);
/*
** ===================================================================
** Method : GetTemperatureFloat (component DS18B20)
**
** Description :
** Returns the temperature from memory in floating point format.
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** * temperature - Pointer to where to store
** the value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuDS18B20_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component DS18B20)
**
** Description :
** Shell Command Line parser. Method is only available if Shell
** is enabled in the component properties.
** Parameters :
** NAME - DESCRIPTION
** cmd - command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
void McuDS18B20_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component DS18B20)
**
** Description :
** Driver deinitialization routine
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuDS18B20_ReadResolution(uint8_t sensor_index);
/*
** ===================================================================
** Method : ReadResolution (component DS18B20)
**
** Description :
** Read the sensor resolution sensor and stores it in memory
** Parameters :
** NAME - DESCRIPTION
** sensor_index - Sensor index, use zero
** if only using one sensor
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuDS18B20_SearchAndAssignROMCodes(void);
/*
** ===================================================================
** Method : SearchAndAssignROMCodes (component DS18B20)
**
** Description :
** Scans the devices on the bus and assigns the ROM codes to
** the list of available sensors
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuDS18B20. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuDS18B20_H */
/*!
** @}
*/

View File

@@ -0,0 +1,134 @@
/*
* McuDebounce.c
*
* Copyright (c) 2019, 2020, Erich Styger
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuDebounce.h"
#include <stdint.h>
#if McuLib_CONFIG_SDK_USE_FREERTOS
void McuDbnc_Process(McuDbnc_Desc_t *data) {
uint32_t buttons;
for(;;) {
switch(data->state) {
case MCUDBMC_STATE_IDLE: /* not doing anything */
return;
case MCUDBMC_STATE_START: /* entering state machine. This might be done from an interrupt, so keep it simple */
if (data->scanValue==0) { /* not assigned yet */
data->scanValue = data->getButtons();
}
data->countTimeMs = 0; /* initialize */
data->lastEventTimeMs = 0; /* initialize */
data->state = MCUDBMC_STATE_PRESS;
return; /* wait the timer period time for next iteration. Caller should enable timer to get to the next state */
case MCUDBMC_STATE_PRESS:
data->onDebounceEvent(MCUDBNC_EVENT_PRESSED, data->scanValue); /* we have a key press: call event handler */
data->state = MCUDBMC_STATE_DEBOUNCE; /* advance to next state */
return; /* wait the timer period time for next iteration */
case MCUDBMC_STATE_DEBOUNCE: /* debouncing */
data->countTimeMs += data->timerPeriodMs;
if (data->countTimeMs<data->debounceTimeMs) {
return; /* continue waiting */
}
data->state = MCUDBMC_STATE_PRESSED;
break; /* go to next state */
case MCUDBMC_STATE_PRESSED: /* button has been pressed, wait for release */
data->countTimeMs += data->timerPeriodMs;
buttons = data->getButtons();
if (buttons==0) { /* all buttons are released */
data->state = MCUDBMC_STATE_RELEASED; /* advance to next state */
break; /* advance to the next state */
} else if (buttons==data->scanValue) { /* still pressing the same keys */
if (data->countTimeMs>=data->longKeyTimeMs) { /* long key press detected */
data->onDebounceEvent(MCUDBNC_EVENT_LONG_PRESSED, data->scanValue);
data->lastEventTimeMs = data->countTimeMs;
data->state = MCUDBMC_STATE_LONG_PRESSED; /* advance to next state */
return; /* wait the timer period time for next iteration */
}
if (data->countTimeMs-data->lastEventTimeMs > data->repeatTimeMs) {
data->onDebounceEvent(MCUDBNC_EVENT_PRESSED_REPEAT, data->scanValue);
data->lastEventTimeMs = data->countTimeMs;
}
return; /* wait the timer period time for next iteration */
} else { /* we got another key set pressed */
uint32_t changed;
changed = buttons&(~data->scanValue); /* newly pressed buttons */
if (changed!=0) {
data->onDebounceEvent(MCUDBNC_EVENT_PRESSED, changed); /* generate press event for the new keys pressed */
data->lastEventTimeMs = data->countTimeMs;
}
changed = (data->scanValue)&(~buttons); /* newly released buttons */
if (changed!=0) {
data->onDebounceEvent(MCUDBNC_EVENT_RELEASED, changed); /* generate release event for the old keys released */
data->lastEventTimeMs = data->countTimeMs;
}
data->scanValue = buttons; /* store new set of buttons */
return; /* wait the timer period time for next iteration */
}
break; /* go to next state */
case MCUDBMC_STATE_LONG_PRESSED: /* we are in the long press range */
data->countTimeMs += data->timerPeriodMs;
buttons = data->getButtons();
if (buttons==0) { /* all buttons are released */
data->state = MCUDBMC_STATE_RELEASED; /* advance to next state */
break; /* advance to the next state */
} else if (buttons==data->scanValue) { /* still pressing the same keys */
if (data->countTimeMs-data->lastEventTimeMs > data->repeatTimeMs) {
data->onDebounceEvent(MCUDBNC_EVENT_LONG_PRESSED_REPEAT, data->scanValue);
data->lastEventTimeMs = data->countTimeMs;
}
return; /* wait the timer period time for next iteration */
} else { /* we got another key set pressed */
uint32_t changed;
changed = buttons&(~data->scanValue); /* newly pressed buttons */
if (changed!=0) {
data->onDebounceEvent(MCUDBNC_EVENT_PRESSED, changed); /* generate press event for the new keys pressed */
data->lastEventTimeMs = data->countTimeMs;
}
changed = (data->scanValue)&(~buttons); /* newly released buttons */
if (changed!=0) {
data->onDebounceEvent(MCUDBNC_EVENT_LONG_RELEASED, changed); /* generate release event for the old keys released */
data->lastEventTimeMs = data->countTimeMs;
}
data->scanValue = buttons; /* store new set of buttons */
return; /* wait the timer period time for next iteration */
}
break; /* go to next state */
case MCUDBMC_STATE_RELEASED:
if (data->countTimeMs>=data->longKeyTimeMs) {
data->onDebounceEvent(MCUDBNC_EVENT_LONG_RELEASED, data->scanValue); /* throw long event */
} else {
data->onDebounceEvent(MCUDBNC_EVENT_RELEASED, data->scanValue); /* throw short event */
}
data->lastEventTimeMs = data->countTimeMs;
data->state = MCUDBMC_STATE_END;
break;
case MCUDBMC_STATE_END: /* finish up */
data->onDebounceEvent(MCUDBNC_EVENT_END, data->scanValue); /* callback at the end of debouncing. */
data->scanValue = 0; /* reset */
data->countTimeMs = 0; /* reset */
data->state = MCUDBMC_STATE_IDLE; /* go back to idle */
return; /* get out of state machine */
default: /* should not happen */
break;
} /* switch */
} /* for */
}
void McuDbnc_Deinit(void) {}
void McuDbnc_Init(void) {}
#endif /* #if McuLib_CONFIG_SDK_USE_FREERTOS */

View File

@@ -0,0 +1,68 @@
/*
* McuDebounce.h
*
* Copyright (c) 2019, 2020, Erich Styger
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MCUDEBOUNCE_H_
#define MCUDEBOUNCE_H_
#include "McuDebounceconfig.h"
#include <stdint.h>
#include "McuRTOS.h"
#ifdef __cplusplus
extern "C" {
#endif
#if McuLib_CONFIG_SDK_USE_FREERTOS
typedef enum {
MCUDBMC_STATE_IDLE = 0, /*!< initial state, not doing anything */
MCUDBMC_STATE_START, /*!< starting debouncing, entered after a button press */
MCUDBMC_STATE_PRESS, /*!< state after start to send a press notification */
MCUDBMC_STATE_DEBOUNCE, /*!< debounce after press */
MCUDBMC_STATE_PRESSED, /*!< while pressing */
MCUDBMC_STATE_LONG_PRESSED, /*!< enters this state after pressing for the long press time */
MCUDBMC_STATE_RELEASED, /*!< buttons have been released */
MCUDBMC_STATE_END, /*!< final state used for cleanup */
} McuDbnc_State_e;
typedef enum {
MCUDBNC_EVENT_PRESSED, /*!< Event for key(s) pressed */
MCUDBNC_EVENT_PRESSED_REPEAT, /*!< Event for key(s) while pressed */
MCUDBNC_EVENT_LONG_PRESSED, /*!< Event for key(s) pressed for a long time */
MCUDBNC_EVENT_LONG_PRESSED_REPEAT, /*!< Event for key(s) pressed for a long time and repeated */
MCUDBNC_EVENT_RELEASED, /*!< Event for key(s) released */
MCUDBNC_EVENT_LONG_RELEASED, /*!< Event for key(s) released after pressed a long time */
MCUDBNC_EVENT_END /*!< Debouncing end event. This one is called when the FSM finishes. */
} McuDbnc_EventKinds;
typedef struct {
McuDbnc_State_e state; /* data */
/* uint32_t flags; */
uint32_t timerPeriodMs; /* config: period of timer in ms */
TimerHandle_t timer; /* config: RTOS timer handle */
uint32_t scanValue; /* data: value of buttons at debounce start */
uint32_t countTimeMs; /* data: counting time in ms from the beginning */
uint32_t lastEventTimeMs; /* data: time of last event, used for repeated messages */
uint32_t debounceTimeMs; /* config: debounce time in ms */
uint32_t repeatTimeMs; /* config: wait time for a button repeat message */
uint32_t longKeyTimeMs; /* config: wait time for a long key press */
uint32_t (*getButtons)(void); /* config: get the pressed buttons */
void (*onDebounceEvent)(McuDbnc_EventKinds event, uint32_t buttons); /* config: event handler called */
} McuDbnc_Desc_t;
void McuDbnc_Process(McuDbnc_Desc_t *data);
void McuDbnc_Deinit(void);
void McuDbnc_Init(void);
#endif /* #if McuLib_CONFIG_SDK_USE_FREERTOS */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MCUDEBOUNCE_H_ */

View File

@@ -0,0 +1,876 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuEE24.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : 24AA_EEPROM
** Version : Component 01.042, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2021-04-18, 20:37, # CodeGen: 733
** Abstract :
** Driver for Microchip 24_AA/LC EEPROMs
** Settings :
** Component name : McuEE24
** SDK : McuLib
** Device Type : 8
** Initial I2C Device Address Bits : 0x0
** Block buffer size : 32
** Acknowledge Polling : Enabled
** Page Write Time (ms) : 5
** Wait : McuWait
** ACK Polling Time (us) : 100
** Connection :
** I2C : McuGenericI2C
** Write Protection Pin : Enabled
** WP : SDK_BitIO
** Timeout : Enabled
** Timeout : McuTimeout
** Timeout Byte (ms) : 10
** Timeout Block (ms) : 60
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** ReadByte - uint8_t McuEE24_ReadByte(McuEE24_Address addr, uint8_t *data);
** WriteByte - uint8_t McuEE24_WriteByte(McuEE24_Address addr, uint8_t data);
** ReadBlock - uint8_t McuEE24_ReadBlock(McuEE24_Address addr, uint8_t *data, uint16_t...
** WriteBlock - uint8_t McuEE24_WriteBlock(McuEE24_Address addr, uint8_t *data, uint16_t...
** WriteProtect - void McuEE24_WriteProtect(void);
** WriteUnprotect - void McuEE24_WriteUnprotect(void);
** SelectDevice - uint8_t McuEE24_SelectDevice(uint8_t addrI2C);
** GetSelectedDevice - uint8_t McuEE24_GetSelectedDevice(void);
** Test - uint8_t McuEE24_Test(void);
** ParseCommand - uint8_t McuEE24_ParseCommand(const unsigned char *cmd, bool *handled, const...
** Deinit - void McuEE24_Deinit(void);
** Init - void McuEE24_Init(void);
**
** * Copyright (c) 2013-2021, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuEE24.h
** @version 01.00
** @brief
** Driver for Microchip 24_AA/LC EEPROMs
*/
/*!
** @addtogroup McuEE24_module McuEE24 module documentation
** @{
*/
/* MODULE McuEE24. */
#include "McuEE24.h"
#if McuEE24_CONFIG_HAS_WP_PIN
#include "WPpin1.h"
#endif
#include "McuWait.h"
#if McuEE24_CONFIG_USE_SHELL
#include "McuShell.h"
#endif
#if McuEE24_CONFIG_USE_UTILITY
#include "McuUtility.h"
#endif
#include "McuGenericI2C.h"
#if McuEE24_CONFIG_USE_TIMEOUT
#include "McuTimeout.h"
#endif
#if McuEE24_CONFIG_USE_TIMEOUT
#define McuEE24_TIMEOUT_BYTE_TICKS (McuEE24_CONFIG_TIMEOUT_BYTE_MS/(McuTimeout_TICK_PERIOD_MS))
#define McuEE24_TIMEOUT_BLOCK_TICKS (McuEE24_CONFIG_TIMEOUT_BLOCK_MS/(McuTimeout_TICK_PERIOD_MS))
#endif
static uint8_t McuEE24_I2CAddress = (McuEE24_CONFIG_DEVICE_I2C_ADDRESS_BITS&McuEE24_MAX_I2C_ADDR_MASK); /* current I2C address used */
/* macros for the control byte: */
#define McuEE24_CTRL_NBL (0x0A<<3) /* control byte high nibble. Typically this is 1010 (shifted by one to the right) */
#if (McuEE24_CONFIG_DEVICE_ID==8) || (McuEE24_CONFIG_DEVICE_ID==16)
#define McuEE24_CTRL_ADDR 0 /* no additional address bits */
/* define control byte as 1010|Bx|B1|B0 */
#define McuEE24_BANK_0 (0<<2) /* B0 bit (0) inside the CTRL_BYTE: 1010|B0|A1|A0 */
#define McuEE24_BANK_1 (1<<2) /* B0 bit (1) inside the CTRL_BYTE: 1010|B0|A1|A0 */
#define McuEE24_CTRL_BYTE (McuEE24_CTRL_NBL|McuEE24_CTRL_ADDR) /* 1010|B0|A1|A0 */
#define McuEE24_DEVICE_ADDR(addr) \
( McuEE24_CTRL_BYTE|((addr>>8)&0x07) )
#if 0 /* old style */
(((addr)&0x400)? \
(McuEE24_CTRL_BYTE|McuEE24_BANK_1) \
: (McuEE24_CTRL_BYTE|McuEE24_BANK_0) ) /* 7bit address of device used to select device */
#endif
#elif (McuEE24_CONFIG_DEVICE_ID==32) || (McuEE24_CONFIG_DEVICE_ID==256) || (McuEE24_CONFIG_DEVICE_ID==512)
#define McuEE24_CTRL_ADDR McuEE24_I2CAddress /* address inside control byte */
/* define control byte as 1010|A2|A1|A0 */
#define McuEE24_CTRL_BYTE (McuEE24_CTRL_NBL|McuEE24_CTRL_ADDR) /* 1010|A2|A1|A0 */
#define McuEE24_DEVICE_ADDR(addr) McuEE24_CTRL_BYTE /* 7bit address of device used to select device */
#elif McuEE24_CONFIG_DEVICE_ID==1025
#define McuEE24_CTRL_ADDR McuEE24_I2CAddress /* address inside control byte */
/* define control byte as 1010|Bx|A1|A0 */
#define McuEE24_BANK_0 (0<<2) /* B0 bit (0) inside the CTRL_BYTE: 1010|B0|A1|A0 */
#define McuEE24_BANK_1 (1<<2) /* B0 bit (1) inside the CTRL_BYTE: 1010|B0|A1|A0 */
#define McuEE24_CTRL_BYTE (McuEE24_CTRL_NBL|McuEE24_CTRL_ADDR) /* 1010|B0|A1|A0 */
#define McuEE24_DEVICE_ADDR(addr) \
(((addr)&0x10000)? \
(McuEE24_CTRL_BYTE|McuEE24_BANK_1) \
: (McuEE24_CTRL_BYTE|McuEE24_BANK_0) ) /* 7bit address of device used to select device */
#endif
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
unsigned char buf[32];
McuShell_SendStatusStr((unsigned char*)"McuEE24", (unsigned char*)"\r\n", io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), (uint8_t)McuEE24_DEVICE_ADDR(0));
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" (for memory @0x00)\r\n");
McuShell_SendStatusStr((unsigned char*)" I2C Addr", buf, io->stdOut);
McuUtility_Num16uToStr(buf, sizeof(buf), (uint16_t)McuEE24_CONFIG_DEVICE_ID);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" Type", buf, io->stdOut);
return ERR_OK;
}
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"McuEE24", (unsigned char*)"Group of McuEE24 commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" read 0x<addr>", (unsigned char*)"Read a byte from an address\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" write 0x<addr> 0x<value>", (unsigned char*)"Write a byte to an address\r\n", io->stdOut);
return ERR_OK;
}
/*
** ===================================================================
** Method : WriteByte (component 24AA_EEPROM)
**
** Description :
** Writes a single byte to specified address
** Parameters :
** NAME - DESCRIPTION
** addr - The address inside the EEPROM
** data - The data value to write
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_WriteByte(McuEE24_Address addr, uint8_t data)
{
uint8_t res, block[3];
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_DO_ACKNOWLEDGE_POLLING && McuEE24_TIMEOUT_BYTE_TICKS>0
McuTimeout_CounterHandle timeout;
bool isTimeout;
#endif
#endif
res = McuGenericI2C_SelectSlave(McuEE24_DEVICE_ADDR(addr));
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
#if (McuEE24_CONFIG_DEVICE_ID==8) || (McuEE24_CONFIG_DEVICE_ID==16)
block[0] = (uint8_t)(addr&0xff); /* low byte of address */
block[1] = data; /* switch to read mode */
res = McuGenericI2C_WriteBlock(block, 2, McuGenericI2C_SEND_STOP); /* send address and data */
#else
block[0] = (uint8_t)(addr>>8); /* high byte of address */
block[1] = (uint8_t)(addr&0xff); /* low byte of address */
block[2] = data; /* switch to read mode */
res = McuGenericI2C_WriteBlock(block, sizeof(block), McuGenericI2C_SEND_STOP); /* send address and data */
#endif
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
#if McuEE24_DO_ACKNOWLEDGE_POLLING
/* do acknowledge polling */
block[0] = 0xff; /* dummy value */
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_TIMEOUT_BYTE_TICKS>0
timeout = McuTimeout_GetCounter(McuEE24_TIMEOUT_BYTE_TICKS); /* set up timeout counter */
if (timeout==McuTimeout_OUT_OF_HANDLE) {
(void)McuGenericI2C_UnselectSlave();
return ERR_FAILED;
}
#endif
#endif
do {
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_TIMEOUT_BYTE_TICKS>0
isTimeout = McuTimeout_CounterExpired(timeout);
if (isTimeout) {
break; /* break while() */
}
#endif
#endif
McuWait_WaitOSms(McuEE24_CONFIG_PAGE_WRITE_TIME_MS);
res = McuGenericI2C_ProbeACK(block, 1, McuGenericI2C_SEND_STOP, McuEE24_CONFIG_ACK_POLLING_TIME_US); /* send address and data */
} while(res!=ERR_OK); /* wait until we get an ACK */
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_TIMEOUT_BYTE_TICKS>0
McuTimeout_LeaveCounter(timeout);
if (isTimeout) {
res = ERR_FAILED;
}
#endif
#endif
#endif /* McuEE24_CONFIG_DO_ACKNOWLEDGE_POLLING */
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
return McuGenericI2C_UnselectSlave();
}
/*
** ===================================================================
** Method : ReadByte (component 24AA_EEPROM)
**
** Description :
** Reads a single byte from the given memory address
** Parameters :
** NAME - DESCRIPTION
** addr - The address where to read from memory.
** * data - Pointer to a location where to store the
** data
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_ReadByte(McuEE24_Address addr, uint8_t *data)
{
uint8_t res;
#if (McuEE24_CONFIG_DEVICE_ID==8) || (McuEE24_CONFIG_DEVICE_ID==16)
uint8_t addr8;
addr8 = (uint8_t)(addr&0xff); /* low address byte */
#else
uint8_t addr16[2]; /* big endian address on I2C bus needs to be 16bit */
addr16[0] = (uint8_t)(addr>>8); /* 16 bit address must be in big endian format */
addr16[1] = (uint8_t)(addr&0xff);
#endif
res = McuGenericI2C_SelectSlave(McuEE24_DEVICE_ADDR(addr));
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
#if (McuEE24_CONFIG_DEVICE_ID==8) || (McuEE24_CONFIG_DEVICE_ID==16)
res = McuGenericI2C_WriteBlock(&addr8, 1, McuGenericI2C_DO_NOT_SEND_STOP); /* send 8bit address */
#else /* use 16bit address */
res = McuGenericI2C_WriteBlock(addr16, 2, McuGenericI2C_DO_NOT_SEND_STOP); /* send 16bit address */
#endif
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
res = McuGenericI2C_ReadBlock(data, 1, McuGenericI2C_SEND_STOP); /* read data byte from bus */
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
return McuGenericI2C_UnselectSlave();
}
/*
** ===================================================================
** Method : ReadBlock (component 24AA_EEPROM)
**
** Description :
** Read a block of memory.
** Parameters :
** NAME - DESCRIPTION
** addr - Address where to read the memory
** * data - Pointer to a buffer where to store the
** data
** dataSize - Size of buffer the data pointer
** is pointing to
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_ReadBlock(McuEE24_Address addr, uint8_t *data, uint16_t dataSize)
{
uint8_t res;
#if (McuEE24_CONFIG_DEVICE_ID==8) || (McuEE24_CONFIG_DEVICE_ID==16)
uint8_t addr8;
addr8 = (uint8_t)(addr&0xff);
#else
uint8_t addr16[2]; /* big endian address on I2C bus needs to be 16bit */
addr16[0] = (uint8_t)(addr>>8); /* 16 bit address must be in big endian format */
addr16[1] = (uint8_t)(addr&0xff);
#endif
res = McuGenericI2C_SelectSlave(McuEE24_DEVICE_ADDR(addr));
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
#if (McuEE24_CONFIG_DEVICE_ID==8) || (McuEE24_CONFIG_DEVICE_ID==16)
res = McuGenericI2C_WriteBlock(&addr8, 1, McuGenericI2C_DO_NOT_SEND_STOP); /* send 8bit address */
#else
res = McuGenericI2C_WriteBlock(addr16, 2, McuGenericI2C_DO_NOT_SEND_STOP); /* send 16bit address */
#endif
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
res = McuGenericI2C_ReadBlock(data, dataSize, McuGenericI2C_SEND_STOP);
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
return McuGenericI2C_UnselectSlave();
}
/*
** ===================================================================
** Method : McuEE24_WriteBlockPage (component 24AA_EEPROM)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
#ifdef __HIWARE__
#pragma MESSAGE DISABLE C1855 /* recursive function call */
#endif
uint8_t McuEE24_WriteBlockPage(McuEE24_Address addr, uint8_t *data, uint16_t dataSize)
{
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_DO_ACKNOWLEDGE_POLLING && McuEE24_TIMEOUT_BLOCK_TICKS>0
McuTimeout_CounterHandle timeout;
bool isTimeout;
#endif
#endif
uint8_t res, i, *p, block[McuEE24_CONFIG_BLOCK_BUF_SIZE+2]; /* additional 2 bytes for the address */
uint16_t eepromPage = (uint16_t)(addr/McuEE24_PAGE_SIZE);
uint8_t offset = (uint8_t)(addr%McuEE24_PAGE_SIZE);
if (dataSize==0 || dataSize>McuEE24_CONFIG_BLOCK_BUF_SIZE) {
return ERR_OVERFLOW; /* you may increase the buffer size in the properties? */
}
if (dataSize>McuEE24_PAGE_SIZE) {
uint16_t size;
size = (uint16_t)(McuEE24_PAGE_SIZE-offset);
if (size!=0) {
res = McuEE24_WriteBlock(addr, data, size); /* first page write */
if (res != ERR_OK) {
return res;
}
data += size; /* increment data pointer */
addr += size; /* increment address */
dataSize -= size; /* reduce size */
}
/* write multiple block of PAGE_SIZE */
while (dataSize>McuEE24_PAGE_SIZE) {
res = McuEE24_WriteBlock(addr, data, McuEE24_PAGE_SIZE);
if (res != ERR_OK) {
return res;
}
data += McuEE24_PAGE_SIZE; /* increment data pointer */
addr += McuEE24_PAGE_SIZE; /* increment address */
dataSize -= McuEE24_PAGE_SIZE; /* reduce size */
}
/* write remainder (if any) */
if (dataSize>0) {
return McuEE24_WriteBlock(addr, data, dataSize);
}
return ERR_OK;
}
if (offset+dataSize <= McuEE24_PAGE_SIZE) { /* no page boundary crossing */
res = McuGenericI2C_SelectSlave(McuEE24_DEVICE_ADDR(addr));
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
#if (McuEE24_CONFIG_DEVICE_ID==8) || (McuEE24_CONFIG_DEVICE_ID==16)
/* 8 bit address byte, high byte of address have been place in SelectSlave(addr) */
block[0] = (uint8_t)(addr&0xff); /* low byte of address */
p = &block[1]; i = (uint8_t)dataSize;
#else /* 16 bit address byte */
block[0] = (uint8_t)(addr>>8); /* high byte of address */
block[1] = (uint8_t)(addr&0xff); /* low byte of address */
p = &block[2]; i = (uint8_t)dataSize;
#endif
/* copy block */
while(i>0) {
*p++ = *data++;
i--;
}
res = McuGenericI2C_WriteBlock(block,
dataSize+((McuEE24_CONFIG_DEVICE_ID==8)||(McuEE24_CONFIG_DEVICE_ID==16)? 1:2), McuGenericI2C_SEND_STOP); /* send address and data */
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
#if McuEE24_DO_ACKNOWLEDGE_POLLING
/* do acknowledge polling */
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_TIMEOUT_BLOCK_TICKS>0
timeout = McuTimeout_GetCounter(McuEE24_TIMEOUT_BLOCK_TICKS); /* set up timeout counter */
if (timeout==McuTimeout_OUT_OF_HANDLE) {
(void)McuGenericI2C_UnselectSlave();
return ERR_OVERFLOW;
}
#endif
#endif
block[0] = 0xff; /* dummy value */
do {
McuWait_WaitOSms(McuEE24_CONFIG_PAGE_WRITE_TIME_MS);
res = McuGenericI2C_ProbeACK(block, 1, McuGenericI2C_SEND_STOP, McuEE24_CONFIG_ACK_POLLING_TIME_US); /* send address and data */
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_TIMEOUT_BLOCK_TICKS>0
isTimeout = McuTimeout_CounterExpired(timeout);
if (isTimeout) {
res = ERR_FAULT;
break;
}
#endif
#endif
} while(res!=ERR_OK); /* wait until we get an ACK */
#if McuEE24_CONFIG_USE_TIMEOUT
#if McuEE24_TIMEOUT_BLOCK_TICKS>0
McuTimeout_LeaveCounter(timeout);
if (isTimeout) {
res = ERR_FAILED;
}
#endif
#endif
if (res != ERR_OK) {
(void)McuGenericI2C_UnselectSlave();
return res;
}
#endif /* McuEE24_CONFIg_DO_ACKNOWLEDGE_POLLING */
return McuGenericI2C_UnselectSlave();
} else { /* crossing page boundaries: make two page writes */
res = McuEE24_WriteBlock(addr, data, (uint16_t)(McuEE24_PAGE_SIZE-offset)); /* first page write */
if (res != ERR_OK) {
return res;
}
res = McuEE24_WriteBlock((McuEE24_Address)((eepromPage+1)*McuEE24_PAGE_SIZE),
data+(McuEE24_PAGE_SIZE-offset),
(uint16_t)(dataSize-(McuEE24_PAGE_SIZE-offset))); /* first page write */
if (res != ERR_OK) {
return res;
}
}
return res;
}
#ifdef __HIWARE__
#pragma MESSAGE DEFAULT C1855 /* recursive function call */
#endif
/*
** ===================================================================
** Method : WriteBlock (component 24AA_EEPROM)
**
** Description :
** Writes a block of data to the EEPROM
** Parameters :
** NAME - DESCRIPTION
** addr - Address of memory
** * data - Pointer to the data
** dataSize - Size of data
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** ERR_OVERFLOW - data block passed has either
** size of zero or exceeds internal buffer
** size
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_WriteBlock(McuEE24_Address addr, uint8_t *data, uint16_t dataSize)
{
int32_t size;
if (dataSize<=McuEE24_CONFIG_BLOCK_BUF_SIZE) { /* fits into internal buffer */
return McuEE24_WriteBlockPage(addr, data, dataSize);
}
size = dataSize;
while(size>=McuEE24_CONFIG_BLOCK_BUF_SIZE) { /* write in chunks McuEE24_CONFIG_BLOCK_BUF_SIZE */
if (McuEE24_WriteBlock(addr, data, McuEE24_CONFIG_BLOCK_BUF_SIZE)!=ERR_OK) {
return ERR_FAILED;
}
addr += McuEE24_CONFIG_BLOCK_BUF_SIZE;
data += McuEE24_CONFIG_BLOCK_BUF_SIZE;
size -= McuEE24_CONFIG_BLOCK_BUF_SIZE;
}
if (size>0) { /* write remainder which is < EE241_BLOCK_BUF_SIZE */
if (McuEE24_WriteBlockPage(addr, data, size)!=ERR_OK) {
return ERR_FAILED;
}
}
return ERR_OK;
}
/*
** ===================================================================
** Method : Test (component 24AA_EEPROM)
**
** Description :
** Test routine to test the driver. Note that this routine
** writes to the EEPROM!
** Parameters : None
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** ERR_FAULT - Test failed
** ===================================================================
*/
#include <string.h> /* for strcmp() */
static void Err(void) {
static uint8_t errCnt = 0;
errCnt++;
}
uint8_t McuEE24_Test(void)
{
uint8_t res, val, data[16];
res = McuEE24_WriteByte(0x0000, 0);
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_WriteByte(0x0001, 1);
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_WriteByte(0x0002, 2);
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_WriteByte(0x0003, 3);
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_WriteByte(0x0004, 4);
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_WriteByte(0x0010, 5);
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_ReadByte(0x0000, &val);
if (res != ERR_OK) {
Err();
return res;
}
if (val != 0) {
Err();
return ERR_FAULT;
}
res = McuEE24_ReadByte(0x0001, &val);
if (res != ERR_OK) {
Err();
return res;
}
if (val != 1) {
Err();
return ERR_FAULT;
}
res = McuEE24_ReadByte(0x0002, &val);
if (res != ERR_OK) {
Err();
return res;
}
if (val != 2) {
Err();
return ERR_FAULT;
}
res = McuEE24_ReadByte(0x0003, &val);
if (res != ERR_OK) {
Err();
return res;
}
if (val != 3) {
Err();
return ERR_FAULT;
}
res = McuEE24_ReadByte(0x0004, &val);
if (res != ERR_OK) {
Err();
return res;
}
if (val != 4) {
Err();
return ERR_FAULT;
}
res = McuEE24_ReadByte(0x0010, &val);
if (res != ERR_OK) {
Err();
return res;
}
if (val != 5) {
Err();
return ERR_FAULT;
}
res = McuEE24_WriteBlock(0x10, (uint8_t*)"Hello", sizeof("Hello"));
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_ReadBlock(0x10, data, sizeof(data));
if (res != ERR_OK) {
Err();
return res;
}
if (strcmp((char*)"Hello", (char*)data) != 0) {
Err();
return ERR_FAULT;
}
/* testing crossing page boundary */
res = McuEE24_WriteBlock(McuEE24_PAGE_SIZE-5, (uint8_t*)"Hello World!", sizeof("Hello World!"));
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_ReadBlock(McuEE24_PAGE_SIZE-5, data, sizeof(data));
if (res != ERR_OK) {
Err();
return res;
}
if (strcmp((char*)"Hello World!", (char*)data) != 0) return ERR_FAULT;
#if McuEE24_CONFIG_DEVICE_ID==1025
/* testing writing to second bank */
res = McuEE24_WriteBlock(0x10005, (uint8_t*)"Hello bank 1!", sizeof("Hello bank 1!"));
if (res != ERR_OK) {
Err();
return res;
}
res = McuEE24_ReadBlock(0x10005, data,(uint8_t*) sizeof(data));
if (res != ERR_OK) {
Err();
return res;
}
if (strcmp((char*)"Hello bank 1!", (char*)data) != 0) {
Err();
return ERR_FAULT;
}
#endif
return ERR_OK;
}
/*
** ===================================================================
** Method : WriteProtect (component 24AA_EEPROM)
**
** Description :
** Prevents writing to the memory. Read operations are not
** affected.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEE24_WriteProtect(void)
{
#if McuEE24_CONFIG_HAS_WP_PIN
WPpin1_SetVal(); /* Tie pin to Vcc/High level to protect the memory */
#endif
}
/*
** ===================================================================
** Method : WriteUnprotect (component 24AA_EEPROM)
**
** Description :
** Allows writing to the memory
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEE24_WriteUnprotect(void)
{
#if McuEE24_CONFIG_HAS_WP_PIN
WPpin1_ClrVal(); /* Tie pin to Vss/Low level to allow writing to the memory */
#endif
}
/*
** ===================================================================
** Method : SelectDevice (component 24AA_EEPROM)
**
** Description :
** Configures the I2C address to be used for the memory. With
** this multiple devices attached to the bus can be addressed.
** Parameters :
** NAME - DESCRIPTION
** addrI2C - I2C Address of the memory device,
** formed by the address pins.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_VALUE - address exceeds address pins of
** device type used
** ===================================================================
*/
uint8_t McuEE24_SelectDevice(uint8_t addrI2C)
{
if (addrI2C>McuEE24_MAX_I2C_ADDR_MASK) {
return ERR_VALUE; /* Device address too large for device address pins available. */
}
McuEE24_I2CAddress = addrI2C;
return ERR_OK;
}
/*
** ===================================================================
** Method : GetSelectedDevice (component 24AA_EEPROM)
**
** Description :
** Returns the currently used I2C address (e.g. set with
** SelectDevice()).
** Parameters : None
** Returns :
** --- - I2C device address
** ===================================================================
*/
uint8_t McuEE24_GetSelectedDevice(void)
{
return McuEE24_I2CAddress;
}
/*
** ===================================================================
** Method : ParseCommand (component 24AA_EEPROM)
**
** Description :
** Shell Command Line parser. This method is enabled/disabled
** depending on if you have the Shell enabled/disabled in the
** properties.
** Parameters :
** NAME - DESCRIPTION
** * cmd - Pointer to command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** * io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuEE24_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io)
{
const unsigned char *p;
uint16_t addr16;
uint8_t val8, buf[8];
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, "McuEE24 help")==0) {
*handled = TRUE;
return PrintHelp(io);
} else if ((McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0) || (McuUtility_strcmp((char*)cmd, "McuEE24 status")==0)) {
*handled = TRUE;
return PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, (char*)"McuEE24 read ", sizeof("McuEE24 read ")-1)==0) {
p = cmd+sizeof("McuEE24 read ")-1;
if (McuUtility_ScanHex16uNumber(&p, &addr16)==ERR_OK) {
if (McuEE24_ReadByte(addr16, &val8)==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), val8);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStr(buf, io->stdOut);
} else {
McuShell_SendStr((unsigned char*)"**** read failed!\r\n", io->stdErr);
}
} else {
McuShell_SendStr((unsigned char*)"**** wrong address\r\n", io->stdErr);
}
*handled = TRUE;
} else if (McuUtility_strncmp((char*)cmd, (char*)"McuEE24 write ", sizeof("McuEE24 write ")-1)==0) {
p = cmd+sizeof("McuEE24 write ")-1;
if (McuUtility_ScanHex16uNumber(&p, &addr16)==ERR_OK) {
if (McuUtility_ScanHex8uNumber(&p, &val8)==ERR_OK) {
if (McuEE24_WriteByte(addr16, val8)!=ERR_OK) {
McuShell_SendStr((unsigned char*)"**** write failed!\r\n", io->stdErr);
}
} else {
McuShell_SendStr((unsigned char*)"**** wrong value\r\n", io->stdErr);
}
} else {
McuShell_SendStr((unsigned char*)"**** wrong address\r\n", io->stdErr);
}
*handled = TRUE;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : Deinit (component 24AA_EEPROM)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEE24_Deinit(void)
{
/* nothing needed */
}
/*
** ===================================================================
** Method : Init (component 24AA_EEPROM)
**
** Description :
** Driver initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEE24_Init(void)
{
/* nothing needed */
}
/* END McuEE24. */
/*!
** @}
*/

View File

@@ -0,0 +1,357 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuEE24.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : 24AA_EEPROM
** Version : Component 01.042, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2021-04-18, 20:37, # CodeGen: 733
** Abstract :
** Driver for Microchip 24_AA/LC EEPROMs
** Settings :
** Component name : McuEE24
** SDK : McuLib
** Device Type : 8
** Initial I2C Device Address Bits : 0x0
** Block buffer size : 32
** Acknowledge Polling : Enabled
** Page Write Time (ms) : 5
** Wait : McuWait
** ACK Polling Time (us) : 100
** Connection :
** I2C : McuGenericI2C
** Write Protection Pin : Enabled
** WP : SDK_BitIO
** Timeout : Enabled
** Timeout : McuTimeout
** Timeout Byte (ms) : 10
** Timeout Block (ms) : 60
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** ReadByte - uint8_t McuEE24_ReadByte(McuEE24_Address addr, uint8_t *data);
** WriteByte - uint8_t McuEE24_WriteByte(McuEE24_Address addr, uint8_t data);
** ReadBlock - uint8_t McuEE24_ReadBlock(McuEE24_Address addr, uint8_t *data, uint16_t...
** WriteBlock - uint8_t McuEE24_WriteBlock(McuEE24_Address addr, uint8_t *data, uint16_t...
** WriteProtect - void McuEE24_WriteProtect(void);
** WriteUnprotect - void McuEE24_WriteUnprotect(void);
** SelectDevice - uint8_t McuEE24_SelectDevice(uint8_t addrI2C);
** GetSelectedDevice - uint8_t McuEE24_GetSelectedDevice(void);
** Test - uint8_t McuEE24_Test(void);
** ParseCommand - uint8_t McuEE24_ParseCommand(const unsigned char *cmd, bool *handled, const...
** Deinit - void McuEE24_Deinit(void);
** Init - void McuEE24_Init(void);
**
** * Copyright (c) 2013-2021, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuEE24.h
** @version 01.00
** @brief
** Driver for Microchip 24_AA/LC EEPROMs
*/
/*!
** @addtogroup McuEE24_module McuEE24 module documentation
** @{
*/
#ifndef __McuEE24_H
#define __McuEE24_H
/* MODULE McuEE24. */
#include "McuLib.h" /* SDK and API used */
#include "McuEE24config.h" /* configuration */
#if McuEE24_CONFIG_USE_SHELL
#include "McuShell.h"
#endif
#if McuEE24_CONFIG_DEVICE_ID==8
#define McuEE24_MAX_I2C_ADDR_MASK 0 /* A2|A1|A0 are not used */
#define McuEE24_MAX_ADDRESS 0x03FF /* 8 kBit is 1KByte */
#define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */
#define McuEE24_PAGE_SIZE 16 /* maximum page size (for page/block operation) */
#elif McuEE24_CONFIG_DEVICE_ID==16
#define McuEE24_MAX_I2C_ADDR_MASK 0 /* A2|A1|A0 are not used */
#define McuEE24_MAX_ADDRESS 0x07FF /* 16 kBit is 2KByte */
#define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */
#define McuEE24_PAGE_SIZE 16 /* maximum page size (for page/block operation) */
#elif McuEE24_CONFIG_DEVICE_ID==32
#define McuEE24_MAX_I2C_ADDR_MASK 7 /* A2|A1|A0 form the I2C device address => address cannot be more than 7 (8 devices) */
#define McuEE24_MAX_ADDRESS 0x0FFF /* 32 kBit are 4KByte */
#define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */
#define McuEE24_PAGE_SIZE 8 /* maximum page size (for page/block operation) */
#elif McuEE24_CONFIG_DEVICE_ID==256
#define McuEE24_MAX_I2C_ADDR_MASK 7 /* A2|A1|A0 form the I2C device address => address cannot be more than 7 (8 devices) */
#define McuEE24_MAX_ADDRESS 0x7FFF /* 256 kBit are 32KByte */
#define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */
#define McuEE24_PAGE_SIZE 64 /* maximum page size (for page/block operation) */
#elif McuEE24_CONFIG_DEVICE_ID==512
#define McuEE24_MAX_I2C_ADDR_MASK 7 /* A2|A1|A0 form the I2C device address => address cannot be more than 7 (8 devices) */
#define McuEE24_MAX_ADDRESS 0xFFFF /* 512 kBit are 64KByte */
#define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */
#define McuEE24_PAGE_SIZE 128 /* maximum page size (for page/block operation) */
#elif McuEE24_CONFIG_DEVICE_ID==1025
#define McuEE24_MAX_I2C_ADDR_MASK 3 /* A1|A0 form the I2C device address => address cannot be more than 3 (4 devices) */
#define McuEE24_MAX_ADDRESS 0x1FFFF /* 1024 kBit are 128KByte */
#define McuEE24_ADDRT uint32_t /* a longword/32bit is needed to hold the address */
#define McuEE24_PAGE_SIZE 128 /* maximum page size (for page/block operation) */
#else
#error "unknown device?"
#endif
#ifndef __BWUserType_McuEE24_Address
#define __BWUserType_McuEE24_Address
typedef McuEE24_ADDRT McuEE24_Address; /* A type large enought to hold the address, depending on the EEPROM used. */
#endif
#define McuEE24_PARSE_COMMAND_ENABLED 1 /* set to 1 if method ParseCommand() is present, 0 otherwise */
uint8_t McuEE24_WriteByte(McuEE24_Address addr, uint8_t data);
/*
** ===================================================================
** Method : WriteByte (component 24AA_EEPROM)
**
** Description :
** Writes a single byte to specified address
** Parameters :
** NAME - DESCRIPTION
** addr - The address inside the EEPROM
** data - The data value to write
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_ReadByte(McuEE24_Address addr, uint8_t *data);
/*
** ===================================================================
** Method : ReadByte (component 24AA_EEPROM)
**
** Description :
** Reads a single byte from the given memory address
** Parameters :
** NAME - DESCRIPTION
** addr - The address where to read from memory.
** * data - Pointer to a location where to store the
** data
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_ReadBlock(McuEE24_Address addr, uint8_t *data, uint16_t dataSize);
/*
** ===================================================================
** Method : ReadBlock (component 24AA_EEPROM)
**
** Description :
** Read a block of memory.
** Parameters :
** NAME - DESCRIPTION
** addr - Address where to read the memory
** * data - Pointer to a buffer where to store the
** data
** dataSize - Size of buffer the data pointer
** is pointing to
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_WriteBlock(McuEE24_Address addr, uint8_t *data, uint16_t dataSize);
/*
** ===================================================================
** Method : WriteBlock (component 24AA_EEPROM)
**
** Description :
** Writes a block of data to the EEPROM
** Parameters :
** NAME - DESCRIPTION
** addr - Address of memory
** * data - Pointer to the data
** dataSize - Size of data
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** ERR_OVERFLOW - data block passed has either
** size of zero or exceeds internal buffer
** size
** otherwise it can return an error code of
** the underlying communication protocol.
** ===================================================================
*/
uint8_t McuEE24_Test(void);
/*
** ===================================================================
** Method : Test (component 24AA_EEPROM)
**
** Description :
** Test routine to test the driver. Note that this routine
** writes to the EEPROM!
** Parameters : None
** Returns :
** --- - Error code, possible values
** ERR_OK - OK
** ERR_FAULT - Test failed
** ===================================================================
*/
void McuEE24_WriteProtect(void);
/*
** ===================================================================
** Method : WriteProtect (component 24AA_EEPROM)
**
** Description :
** Prevents writing to the memory. Read operations are not
** affected.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEE24_WriteUnprotect(void);
/*
** ===================================================================
** Method : WriteUnprotect (component 24AA_EEPROM)
**
** Description :
** Allows writing to the memory
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuEE24_SelectDevice(uint8_t addrI2C);
/*
** ===================================================================
** Method : SelectDevice (component 24AA_EEPROM)
**
** Description :
** Configures the I2C address to be used for the memory. With
** this multiple devices attached to the bus can be addressed.
** Parameters :
** NAME - DESCRIPTION
** addrI2C - I2C Address of the memory device,
** formed by the address pins.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_VALUE - address exceeds address pins of
** device type used
** ===================================================================
*/
uint8_t McuEE24_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component 24AA_EEPROM)
**
** Description :
** Shell Command Line parser. This method is enabled/disabled
** depending on if you have the Shell enabled/disabled in the
** properties.
** Parameters :
** NAME - DESCRIPTION
** * cmd - Pointer to command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** * io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuEE24_GetSelectedDevice(void);
/*
** ===================================================================
** Method : GetSelectedDevice (component 24AA_EEPROM)
**
** Description :
** Returns the currently used I2C address (e.g. set with
** SelectDevice()).
** Parameters : None
** Returns :
** --- - I2C device address
** ===================================================================
*/
uint8_t McuEE24_WriteBlockPage(McuEE24_Address addr, uint8_t *data, uint16_t dataSize);
/*
** ===================================================================
** Method : McuEE24_WriteBlockPage (component 24AA_EEPROM)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void McuEE24_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component 24AA_EEPROM)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEE24_Init(void);
/*
** ===================================================================
** Method : Init (component 24AA_EEPROM)
**
** Description :
** Driver initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/* END McuEE24. */
#endif
/* ifndef __McuEE24_H */
/*!
** @}
*/

View File

@@ -0,0 +1,578 @@
/*
* Copyright (c) 2019, Erich Styger
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuESP32config.h"
#if McuESP32_CONFIG_SHELL_UART!=McuShellUart_CONFIG_UART_NONE
#include "McuESP32.h"
#include "McuGPIO.h"
#include "McuRTOS.h"
#include "McuUtility.h"
#include "McuWait.h"
#include "McuLog.h"
#include "McuShellUart.h"
#if McuESP32_CONFIG_USE_USB_CDC
#include "virtual_com.h"
#endif
#if McuESP32_CONFIG_USE_CTRL_PINS
static McuGPIO_Handle_t McuESP32_RF_EN_Pin; /* pin pulled LOW to reset the module */
static McuGPIO_Handle_t McuESP32_RF_IO0_Pin; /* pin pulled LOW to enable programming mode */
#endif
static QueueHandle_t uartRxQueue; /* Rx from ESP32 module */
#define McuESP32_UART_RX_QUEUE_LENGTH (4096)
static QueueHandle_t uartTxQueue; /* Tx to ESP32 module */
#define McuESP32_UART_TX_QUEUE_LENGTH (4096)
#if McuESP32_CONFIG_USE_USB_CDC
typedef enum McuESP32_USB_PrgMode_e {
McuESP32_USB_PRG_MODE_AUTO,
McuESP32_USB_PRG_MODE_ON,
McuESP32_USB_PRG_MODE_OFF,
} McuESP32_USB_PrgMode_e;
static McuESP32_USB_PrgMode_e McuESP32_UsbPrgMode = McuESP32_USB_PRG_MODE_AUTO;
static bool McuESP32_IsProgramming = false; /* if we are currently programming the ESP32 */
static bool McuESP32_ScheduleReset = true; /* do an initial reset at restart time */
#endif
static bool McuESP32_CopyUartToShell = true; /* if we copy the ESP32 UART to the Shell */
/* Below is the I/O handler for the console: data from the ESP is sent to that stdout (e.g. shell console).
* Optionally with McuESP32_CONFIG_USE_USB_CDC enabled all CDC data is sent to the ESP32 as well.
*/
static McuShell_ConstStdIOType *McuESP32_RxFromESPStdIO = NULL; /* can be overwritten with McuESP32_SetRxFromESPStdio(); */
void McuESP32_SetRxFromESPStdio(McuShell_ConstStdIOTypePtr stdio) {
McuESP32_RxFromESPStdIO = stdio;
}
McuShell_ConstStdIOTypePtr McuESP32_GetRxFromESPStdio(void) {
return McuESP32_RxFromESPStdIO;
}
#if McuESP32_CONFIG_USE_CTRL_PINS
static void AssertReset(void) {
McuGPIO_SetAsOutput(McuESP32_RF_EN_Pin, false); /* output, LOW */
}
#endif
#if McuESP32_CONFIG_USE_CTRL_PINS
static void DeassertReset(void) {
McuGPIO_SetAsInput(McuESP32_RF_EN_Pin);
}
#endif
#if McuESP32_CONFIG_USE_CTRL_PINS
static void DoReset(void) {
AssertReset();
vTaskDelay(pdMS_TO_TICKS(1));
DeassertReset();
}
#endif
#if McuESP32_CONFIG_USE_CTRL_PINS
static void AssertBootloaderMode(void) {
McuGPIO_SetAsOutput(McuESP32_RF_IO0_Pin, false); /* output, LOW */
}
#endif
#if McuESP32_CONFIG_USE_CTRL_PINS
static void DeassertBootloaderMode(void) {
McuGPIO_SetAsInput(McuESP32_RF_IO0_Pin);
}
#endif
#if McuESP32_CONFIG_USE_USB_CDC
/* idf.py flash sequence:
*
* 00> State: 3, DtrRts: 3
* 00> State: 2, DtrRts: 1
* 00> State: 3, DtrRts: 3
* 00> State: 1, DtrRts: 2
* 00> State: 0, DtrRts: 0
* 00> State: 2, DtrRts: 1
* 00> State: 3, DtrRts: 3
* 00> State: 1, DtrRts: 2
* 00> State: 0, DtrRts: 0
*
* reset at the end:
* 00> State: 2, DtrRts: 1
* 00> State: 0, DtrRts: 0
*/
void McuESP32_UartState_Callback(uint8_t state) { /* callback for DTR and RTS lines */
static uint8_t prevState = -1;
static uint8_t prevPrevState = -1;
uint8_t DtrRts;
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_trace("state: %d, prev: %d, prevprev: %d", state, prevState, prevPrevState);
#endif
if (state != prevState) {
if (McuESP32_UsbPrgMode==McuESP32_USB_PRG_MODE_AUTO || McuESP32_UsbPrgMode==McuESP32_USB_PRG_MODE_ON) {
/*
* DTR RTS EN GPIO0
* 1 1 1 1
* 0 0 1 1
* 1 0 0 0
* 0 1 1 0
*/
DtrRts = 0;
if ((state&1)==1) { /* DTR */
DtrRts |= 2; /* DTR set */
}
if ((state&2)==2) { /* DTR */
DtrRts |= 1; /* RTS set */
}
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_trace("State: %d, DtrRts: %d", state, DtrRts);
#endif
switch(DtrRts) {
default:
case 0:
DeassertReset();
McuWait_Waitus(100); /* block for a short time (in the ISR!!!) ==> should have a 100 uF added to the reset line */
DeassertBootloaderMode();
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_trace("Release both: %d", DtrRts);
#endif
break;
case 1:
AssertBootloaderMode();
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_trace("assert BL: %d", DtrRts);
#endif
break;
case 2:
if (McuGPIO_IsLow(McuESP32_RF_EN_Pin)) {
if (McuGPIO_IsLow(McuESP32_RF_IO0_Pin)) {
McuESP32_IsProgramming = true; /* the DeassertReset() below will enter bootloader mode */
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_trace("Enter Bootloader Mode");
#endif
} else {
McuESP32_IsProgramming = false; /* the DeassertReset() below will do a reset without bootloader */
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_trace("Reset");
#endif
}
}
DeassertReset();
McuWait_Waitus(100); /* block for a short time (in the ISR!!!) ==> should have a 100 uF added to the reset line */
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_trace("release reset: %d", DtrRts);
#endif
break;
case 3:
AssertReset();
//McuLog_trace("assert reset: %d", DtrRts);
break;
} /* switch */
if (state==0 && prevState==2 && prevPrevState==0) {
// reset sequence with idf.py and Arduino IDE:
// State: 0 DtrRts: 0 Release both: 0
// State: 2 DtrRts: 1 assert BL: 1
// State: 0 DtrRts: 0 Release both: 0
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_info("Request Reset");
#endif
McuESP32_ScheduleReset = true; /* cannot do reset sequence here, as called from an interrupt, so we cannot block */
McuESP32_IsProgramming = false;
}
}
prevPrevState = prevState;
prevState = state;
} /* if state!=prevState */
}
#endif
/*********************************************************************************************************/
/* Stdio Handler for sending text to the ESP32 */
static void QueueTxChar(unsigned char ch) {
(void)xQueueSendToBack(uartTxQueue, &ch, 0); /* put it back in to the Tx queue */
}
static void Dummy_ReadChar(uint8_t *c) {
*c = '\0'; /* nothing received */
}
static bool Dummy_CharPresent(void) {
return false;
}
/* for sending data to the ESP32 (tx only) */
static const McuShell_ConstStdIOType McuESP32_Tx_stdio = {
.stdIn = (McuShell_StdIO_In_FctType)Dummy_ReadChar,
.stdOut = (McuShell_StdIO_OutErr_FctType)QueueTxChar,
.stdErr = (McuShell_StdIO_OutErr_FctType)QueueTxChar,
.keyPressed = Dummy_CharPresent, /* if input is not empty */
#if McuShell_CONFIG_ECHO_ENABLED
.echoEnabled = false,
#endif
};
McuShell_ConstStdIOTypePtr McuESP32_GetTxToESPStdio(void) {
return &McuESP32_Tx_stdio;
}
/*********************************************************************************************************/
void McuESP32_CONFIG_UART_IRQ_HANDLER(void) {
uint8_t data;
uint32_t flags=0;
BaseType_t xHigherPriorityTaskWoken;
flags = McuESP32_CONFIG_UART_GET_FLAGS(McuESP32_CONFIG_UART_DEVICE);
/* If new data arrived. */
if (flags&McuESP32_CONFIG_UART_HW_RX_READY_FLAGS) {
data = McuESP32_CONFIG_UART_READ_BYTE(McuESP32_CONFIG_UART_DEVICE);
(void)xQueueSendFromISR(uartRxQueue, &data, &xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken != pdFALSE) {
__DSB();
vPortYieldFromISR();
}
}
__DSB();
}
static uint8_t McuESP32_PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"esp32", (unsigned char*)"Group of ESP32 WiFi module commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Shows ESP32 help or status\r\n", io->stdOut);
#if McuESP32_CONFIG_USE_CTRL_PINS
McuShell_SendHelpStr((unsigned char*)" reset", (unsigned char*)"Perform reset sequence\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" assert|deassart reset", (unsigned char*)"Assert or deassert reset pin\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" assert|deassart bl", (unsigned char*)"Assert or deassert bootloader pin\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" prg start|stop", (unsigned char*)"Start and stop programming sequence\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" uarttoshell on|off", (unsigned char*)"Copy UART Rx to Shell\r\n", io->stdOut);
#if McuESP32_CONFIG_USE_USB_CDC
McuShell_SendHelpStr((unsigned char*)" usbprg auto|on|off", (unsigned char*)"Use USB CDC to UART for programming\r\n", io->stdOut);
#endif
#endif
McuShell_SendHelpStr((unsigned char*)" send <cmd>", (unsigned char*)"Send a command or string to the ESP32 (non-blocking), <cmd> can be double quoted\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" sendwait <ms> <cmd>", (unsigned char*)"Send a command or string to the ESP32 and wait ms time for the response, cmd can be double quoted\r\n", io->stdOut);
return ERR_OK;
}
static uint8_t McuESP32_PrintStatus(const McuShell_StdIOType *io) {
#if McuESP32_CONFIG_USE_CTRL_PINS || McuESP32_CONFIG_USE_USB_CDC
uint8_t buf[64];
#endif
McuShell_SendStatusStr((unsigned char*)"esp32", (unsigned char*)"ESP32 status\r\n", io->stdOut);
#if McuESP32_CONFIG_USE_CTRL_PINS
McuGPIO_GetPinStatusString(McuESP32_RF_EN_Pin, buf, sizeof(buf));
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" EN", buf, io->stdOut);
McuGPIO_GetPinStatusString(McuESP32_RF_IO0_Pin, buf, sizeof(buf));
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" IO0", buf, io->stdOut);
#endif
#if McuESP32_CONFIG_USE_USB_CDC
if (McuESP32_UsbPrgMode==McuESP32_USB_PRG_MODE_ON) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"on");
if (McuESP32_CopyUartToShell) {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", nothing will be copied to shell.\r\n");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
}
} else if (McuESP32_UsbPrgMode==McuESP32_USB_PRG_MODE_AUTO) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"auto\r\n");
} else if (McuESP32_UsbPrgMode==McuESP32_USB_PRG_MODE_OFF) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"off\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" usbprg", buf, io->stdOut);
McuShell_SendStatusStr((unsigned char*)" programming", McuESP32_IsProgramming?(unsigned char*)"yes\r\n":(unsigned char*)"no\r\n", io->stdOut);
#endif
McuShell_SendStatusStr((unsigned char*)" uarttoshell", McuESP32_CopyUartToShell?(unsigned char*)"on\r\n":(unsigned char*)"off\r\n", io->stdOut);
return ERR_OK;
}
uint8_t McuESP32_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
unsigned char cmd_buffer[McuShell_CONFIG_DEFAULT_SHELL_BUFFER_SIZE];
const unsigned char *p;
if (McuUtility_strcmp((char*)cmd, (char*)McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, (char*)"esp32 help")==0) {
*handled = true;
return McuESP32_PrintHelp(io);
} else if (McuUtility_strcmp((char*)cmd, (char*)McuShell_CMD_STATUS)==0 || McuUtility_strcmp((char*)cmd, (char*)"esp32 status")==0) {
*handled = true;
return McuESP32_PrintStatus(io);
#if McuESP32_CONFIG_USE_CTRL_PINS
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 reset")==0) {
*handled = true;
DoReset();
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 prg start")==0) {
/* pulling prg pin low, followed by a reset */
*handled = true;
AssertBootloaderMode(); /* pull prg pin low: during reset, device will enter serial programming mode */
vTaskDelay(pdMS_TO_TICKS(1));
DoReset();
vTaskDelay(pdMS_TO_TICKS(1));
DeassertBootloaderMode();
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 prg stop")==0) {
/* release prg pin, followed by a reset */
*handled = true;
DeassertBootloaderMode(); /* return prg pin to high (normal) again */
vTaskDelay(pdMS_TO_TICKS(1));
DoReset();
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 assert bl")==0) {
*handled = true;
AssertBootloaderMode();
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 deassert bl")==0) {
*handled = true;
DeassertBootloaderMode();
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 assert reset")==0) {
*handled = true;
AssertReset();
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 deassert reset")==0) {
*handled = true;
DeassertReset();
return ERR_OK;
#endif
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 uarttoshell on")==0) {
*handled = true;
McuESP32_CopyUartToShell = true;
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 uarttoshell off")==0) {
*handled = true;
McuESP32_CopyUartToShell = false;
return ERR_OK;
#if McuESP32_CONFIG_USE_USB_CDC
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 usbprg auto")==0) {
*handled = true;
McuESP32_UsbPrgMode = McuESP32_USB_PRG_MODE_AUTO;
McuESP32_IsProgramming = false;
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 usbprg on")==0) {
*handled = true;
McuESP32_UsbPrgMode = McuESP32_USB_PRG_MODE_ON;
McuESP32_IsProgramming = true;
return ERR_OK;
} else if (McuUtility_strcmp((char*)cmd, (char*)"esp32 usbprg off")==0) {
*handled = true;
McuESP32_UsbPrgMode = McuESP32_USB_PRG_MODE_OFF;
McuESP32_IsProgramming = false;
return ERR_OK;
#endif
} else if (McuUtility_strncmp((char*)cmd, (char*)"esp32 send ", sizeof("esp32 send ")-1)==0) {
*handled = true;
p = cmd+sizeof("esp32 send ")-1;
if (*p=='"') { /* double-quoted command: it can contain multiple commands */
if (McuUtility_ScanDoubleQuotedString(&p, cmd_buffer, sizeof(cmd_buffer))!=ERR_OK) {
return ERR_FAILED;
}
p = cmd_buffer;
}
McuShell_SendStr(p, McuESP32_GetTxToESPStdio()->stdOut);
McuShell_SendStr((unsigned char*)"\r\n", McuESP32_GetTxToESPStdio()->stdOut);
return ERR_OK;
} else if (McuUtility_strncmp((char*)cmd, (char*)"esp32 sendwait ", sizeof("esp32 sendwait ")-1)==0) {
/* this sends a command, but captures output with a timeout so it can show it on the io used for the command, e.g. on RTT */
uint32_t ms;
*handled = true;
p = cmd+sizeof("esp32 sendwait ")-1;
if (McuUtility_ScanDecimal32uNumber(&p, &ms)!=ERR_OK) {
return ERR_FAILED;
}
while(*p==' ') {
p++; /* skip spaces */
}
if (*p=='"') { /* double-quoted command: it can contain multiple commands */
if (McuUtility_ScanDoubleQuotedString(&p, cmd_buffer, sizeof(cmd_buffer))!=ERR_OK) {
return ERR_FAILED;
}
p = cmd_buffer;
}
/* send command string: temporarily change where the response from the ESP32 goes to */
McuShell_ConstStdIOType *prevIO;
prevIO = McuESP32_GetRxFromESPStdio(); /* get current I/O */
McuESP32_SetRxFromESPStdio(io); /* set current shell I/O as output channel for what's coming from the ESP */
McuShell_SendStr(p, McuESP32_GetTxToESPStdio()->stdOut);
McuShell_SendStr((unsigned char*)"\r\n", McuESP32_GetTxToESPStdio()->stdOut);
vTaskDelay(pdMS_TO_TICKS(ms)); /* wait for the ESP to send the response */
McuESP32_SetRxFromESPStdio(prevIO); /* restore previous io */
return ERR_OK;
}
return ERR_OK;
}
static void UartRxTask(void *pv) { /* task handling characters sent by the ESP32 module and coming from the UART of the ESP32 */
unsigned char ch;
BaseType_t res;
McuShell_ConstStdIOType *io;
(void)pv; /* not used */
for(;;) {
res = xQueueReceive(uartRxQueue, &ch, portMAX_DELAY);
if (res==pdPASS) {
#if McuESP32_CONFIG_USE_USB_CDC
if (USB_CdcIsConnected()) { /* send directly to programmer attached on the USB or to the IDF monitor */
USB_CdcStdio.stdOut(ch); /* forward to USB CDC and the programmer on the host */
}
#endif
if ( McuESP32_CopyUartToShell
#if McuESP32_CONFIG_USE_USB_CDC
&& !McuESP32_IsProgramming
#endif
)
{ /* only write to shell if not in programming mode. Programming mode might crash RTT */
io = McuESP32_GetRxFromESPStdio();
if (io!=NULL) {
McuShell_SendCh(ch, io->stdOut); /* forward character */
}
}
} else {
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_fatal("ESP32 UartRxTask queue failed");
#endif
}
}
}
static void UartTxTask(void *pv) { /* task handling sending data to the ESP32 module */
unsigned char ch;
BaseType_t res;
bool workToDo;
(void)pv; /* not used */
for(;;) {
#if McuESP32_CONFIG_USE_USB_CDC
if (McuESP32_ScheduleReset) {
McuESP32_ScheduleReset = false;
#if McuESP32_CONFIG_VERBOSE_CONTROL_SIGNALS
McuLog_info("Performing reset");
#endif
DoReset();
}
#endif
workToDo = false;
do {
res = xQueueReceive(uartTxQueue, &ch, 0); /* poll queue */
if (res==pdPASS) { /* write data to ESP over UART */
workToDo = true;
McuESP32_CONFIG_UART_WRITE_BLOCKING(McuESP32_CONFIG_UART_DEVICE, &ch, 1); /* send to ESP */
}
} while (res==pdPASS);
#if McuESP32_CONFIG_USE_USB_CDC
while (USB_CdcStdio.keyPressed()) { /* check USB CDC data stream */
workToDo = true;
USB_CdcStdio.stdIn(&ch); /* read byte */
McuESP32_CONFIG_UART_WRITE_BLOCKING(McuESP32_CONFIG_UART_DEVICE, &ch, 1); /* send to ESP */
/* check if we can copy the USB CDC data to shell console too */
if (McuESP32_CopyUartToShell && !McuESP32_IsProgramming) {
McuShell_ConstStdIOTypePtr io = McuESP32_GetRxFromESPStdio();
if (io!=NULL) {
McuShell_SendCh(ch, io->stdOut); /* write to console */
}
}
}
#endif
if (!workToDo) { /* only delay if we are not busy */
vTaskDelay(pdMS_TO_TICKS(5));
}
}
}
static void InitUart(void) {
McuESP32_CONFIG_UART_CONFIG_STRUCT config;
McuESP32_CONFIG_UART_SET_UART_CLOCK();
McuESP32_CONFIG_UART_GET_DEFAULT_CONFIG(&config);
config.baudRate_Bps = McuESP32_CONFIG_UART_BAUDRATE;
config.enableRx = true;
config.enableTx = true;
/* Initialize the USART with configuration. */
McuESP32_CONFIG_UART_INIT(McuESP32_CONFIG_UART_DEVICE, &config, CLOCK_GetFreq(McuESP32_CONFIG_UART_GET_CLOCK_FREQ_SELECT));
McuESP32_CONFIG_UART_ENABLE_INTERRUPTS(McuESP32_CONFIG_UART_DEVICE, McuESP32_CONFIG_UART_ENABLE_INTERRUPT_FLAGS);
EnableIRQ(McuESP32_CONFIG_UART_IRQ_NUMBER);
NVIC_SetPriority(McuESP32_CONFIG_UART_IRQ_NUMBER, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
McuShellUart_MuxUartPins(McuESP32_CONFIG_SHELL_UART); /* mux the UART pins */
uartRxQueue = xQueueCreate(McuESP32_UART_RX_QUEUE_LENGTH, sizeof(uint8_t));
if (uartRxQueue==NULL) {
McuLog_fatal("not able to create Rx queue");
for(;;){} /* out of memory? */
}
vQueueAddToRegistry(uartRxQueue, "ESP32UartRxQueue");
uartTxQueue = xQueueCreate(McuESP32_UART_TX_QUEUE_LENGTH, sizeof(uint8_t));
if (uartTxQueue==NULL) {
McuLog_fatal("not able to create Tx queue");
for(;;){} /* out of memory? */
}
vQueueAddToRegistry(uartTxQueue, "ESP32UartTxQueue");
}
static void InitPins(void) {
#if McuESP32_CONFIG_USE_CTRL_PINS
McuGPIO_Config_t gpioConfig;
McuGPIO_GetDefaultConfig(&gpioConfig);
gpioConfig.isInput = true;
gpioConfig.hw.gpio = McuESP32_CONFIG_EN_GPIO;
gpioConfig.hw.port = McuESP32_CONFIG_EN_PORT;
gpioConfig.hw.pin = McuESP32_CONFIG_EN_PIN;
McuESP32_RF_EN_Pin = McuGPIO_InitGPIO(&gpioConfig);
gpioConfig.hw.gpio = McuESP32_CONFIG_RST_GPIO;
gpioConfig.hw.port = McuESP32_CONFIG_RST_PORT;
gpioConfig.hw.pin = McuESP32_CONFIG_RST_PIN;
McuESP32_RF_IO0_Pin = McuGPIO_InitGPIO(&gpioConfig);
#endif
}
void McuESP32_Deinit(void) {
#if McuESP32_CONFIG_USE_CTRL_PINS
McuESP32_RF_EN_Pin = McuGPIO_DeinitGPIO(McuESP32_RF_EN_Pin);
McuESP32_RF_IO0_Pin = McuGPIO_DeinitGPIO(McuESP32_RF_IO0_Pin);
#endif
vQueueDelete(uartRxQueue);
uartRxQueue = NULL;
}
void McuESP32_Init(void) {
InitPins();
InitUart();
if (xTaskCreate(
UartRxTask, /* pointer to the task */
"ESP32UartRx", /* task name for kernel awareness debugging */
500/sizeof(StackType_t), /* task stack size */
(void*)NULL, /* optional task startup argument */
tskIDLE_PRIORITY+4, /* initial priority */
(TaskHandle_t*)NULL /* optional task handle to create */
) != pdPASS)
{
McuLog_fatal("failed creating ESP32 Rx Task");
for(;;){} /* error! probably out of memory */
}
if (xTaskCreate(
UartTxTask, /* pointer to the task */
"ESP32UartTx", /* task name for kernel awareness debugging */
500/sizeof(StackType_t), /* task stack size */
(void*)NULL, /* optional task startup argument */
tskIDLE_PRIORITY+4, /* initial priority */
(TaskHandle_t*)NULL /* optional task handle to create */
) != pdPASS)
{
McuLog_fatal("failed creating ESP32 Tx Task");
for(;;){} /* error! probably out of memory */
}
}
#endif /* #if McuESP32_CONFIG_SHELL_UART */

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 2021, Erich Styger
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef McuESP32_H_
#define McuESP32_H_
#include <stdint.h>
#include "McuESP32config.h"
#ifdef __cplusplus
extern "C" {
#endif
/* used to deal with USB CDC flow control pins */
void McuESP32_UartState_Callback(uint8_t state);
#include "McuShell.h"
/*!
* \brief Shell parser routine.
* \param cmd Pointer to command line string.
* \param handled Pointer to status if command has been handled. Set to TRUE if command was understood.
* \param io Pointer to stdio handle
* \return Error code, ERR_OK if everything was ok.
*/
uint8_t McuESP32_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*!
* \brief Set a standard I/O receiving from ESP
* \param stdio Standard I/O to be used
*/
void McuESP32_SetRxFromESPStdio(McuShell_ConstStdIOTypePtr stdio);
/*!
* \brief Return the current receiving from ESP standard I/O
* \return I/O handler
*/
McuShell_ConstStdIOTypePtr McuESP32_GetRxFromESPStdio(void);
/*!
* \brief Returns the standard I/O handler for sending data (only sending) to the ESP32
* \return standard I/O handler
*/
McuShell_ConstStdIOTypePtr McuESP32_GetTxToESPStdio(void);
/*!
* \brief Module de-initialization
*/
void McuESP32_Deinit(void);
/*!
* \brief Module initialization
*/
void McuESP32_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* McuESP32_H_ */

View File

@@ -0,0 +1,263 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuEvents.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SimpleEvents
** Version : Component 01.059, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
** Settings :
** Component name : McuEvents
** SDK : McuLib
** Critical Section : McuCriticalSection
** Initialize on Init : yes
** Event Name List : (string list)
** Contents :
** SetEvent - void McuEvents_SetEvent(uint8_t event);
** ClearEvent - void McuEvents_ClearEvent(uint8_t event);
** EventsPending - bool McuEvents_EventsPending(void);
** GetEvent - bool McuEvents_GetEvent(uint8_t event);
** GetClearEvent - bool McuEvents_GetClearEvent(uint8_t event);
** HandleEvent - void McuEvents_HandleEvent(void);
**
** * Copyright (c) 2011-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuEvents.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuEvents_module McuEvents module documentation
** @{
*/
/* MODULE McuEvents. */
#include "McuEvents.h"
#include "McuCriticalSection.h"
static uint8_t McuEvents_Events[((McuEvents_CONFIG_NOF_EVENTS-1)/8)+1]; /*!< Bit set of events */
/*
** ===================================================================
** Method : SetEvent (component SimpleEvents)
**
** Description :
** Sets an event (number) be processed by the next HandleEvent()
** call
** Parameters :
** NAME - DESCRIPTION
** event - The event (number) to be set so it
** will be called by the HandleEvent() routine
** later on. Note that there cannot be
** multiple instances of an event, and the
** lower the event number, the higher the
** priority.
** Returns : Nothing
** ===================================================================
*/
void McuEvents_SetEvent(uint8_t event)
{
McuCriticalSection_CriticalVariable();
/* event is in the range of 0..255: find bit position in array */
McuCriticalSection_EnterCritical();
McuEvents_Events[event/8] |= 0x80>>(event%8);
McuCriticalSection_ExitCritical();
}
/*
** ===================================================================
** Method : ClearEvent (component SimpleEvents)
**
** Description :
** Clears one event (number). If the event is not set, then the
** function has no effect.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to be cleared.
** Returns : Nothing
** ===================================================================
*/
void McuEvents_ClearEvent(uint8_t event)
{
McuCriticalSection_CriticalVariable();
/* event is in the range of 0..255: find bit position in array */
McuCriticalSection_EnterCritical();
McuEvents_Events[event/8] &= ~(0x80>>(event%8));
McuCriticalSection_ExitCritical();
}
/*
** ===================================================================
** Method : GetEvent (component SimpleEvents)
**
** Description :
** Allows to check if an event is set or not.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to check. If the
** event is set, the function returns TRUE.
** Returns :
** --- - none
** ===================================================================
*/
bool McuEvents_GetEvent(uint8_t event)
{
/* event is in the range of 0..255: find bit position in array */
return (bool)((McuEvents_Events[event/8]&(0x80>>(event%8)))!=0);
}
/*
** ===================================================================
** Method : GetClearEvent (component SimpleEvents)
**
** Description :
** Allows to check if an event is set or not. If set, it will
** be automatically cleared.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to check. If the
** event is set, the function returns TRUE.
** Returns :
** --- - none
** ===================================================================
*/
bool McuEvents_GetClearEvent(uint8_t event)
{
bool isSet = FALSE;
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
if (McuEvents_GetEvent(event)) { /* event present */
McuEvents_Events[event/8] &= ~(0x80>>(event%8)); /* clear event */
isSet = TRUE;
}
McuCriticalSection_ExitCritical();
return isSet;
}
/*
** ===================================================================
** Method : EventsPending (component SimpleEvents)
**
** Description :
** Returns true if any events are pending, false otherwise
** Parameters : None
** Returns :
** --- - True in case any events are pending, false
** otherwise.
** ===================================================================
*/
bool McuEvents_EventsPending(void)
{
#if McuEvents_CONFIG_NOF_EVENTS<=8
return (bool)(McuEvents_Events[0]!=0);
#elif McuEvents_CONFIG_NOF_EVENTS<=16
return (bool)(McuEvents_Events[0]!=0 || McuEvents_Events[1]!=0);
#elif McuEvents_CONFIG_NOF_EVENTS<=24
return (McuEvents_Events[0]!=0 || McuEvents_Events[1]!=0 || McuEvents_Events[2]!=0);
#elif McuEvents_CONFIG_NOF_EVENTS<=32
return (bool)(McuEvents_Events[0]!=0 || McuEvents_Events[1]!=0 || McuEvents_Events[2]!=0 || McuEvents_Events[3]!=0);
#else /* iterate through the array */
char i; /* local counter */
for(i=0; i<(McuEvents_CONFIG_NOF_EVENTS/8)+1; i++) {
if (McuEvents_Events[i] != 0) { /* there are events pending */
return TRUE;
}
}
return FALSE;
#endif
}
/*
** ===================================================================
** Method : HandleEvent (component SimpleEvents)
**
** Description :
** Event handler, to be called periodically.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEvents_HandleEvent(void)
{
/* Handle the one with the highest priority. */
uint8_t event;
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
for (event=0; event<McuEvents_CONFIG_NOF_EVENTS; event++) { /* does a test on every event */
if (McuEvents_GetEvent(event)) { /* event present */
McuEvents_Events[event/8] &= ~(0x80>>(event%8)); /* clear event */
break; /* get out of loop */
}
}
McuCriticalSection_ExitCritical();
#if McuEvents_CONFIG_USE_EVENT_HANDLER
/*lint -save -e522 function lacks side effect */
if (event != McuEvents_CONFIG_NOF_EVENTS) {
McuEvents_CONFIG_EVENT_HANDLER_NAME(event);
}
/*lint -restore */
#endif
}
/*
** ===================================================================
** Method : McuEvents_Init (component SimpleEvents)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void McuEvents_Init(void)
{
#if McuEvents_CONFIG_NOF_EVENTS<=8
McuEvents_Events[0] = 0; /* initialize data structure */
#else
uint8_t i;
for(i=0;i<sizeof(McuEvents_Events); i++) {
McuEvents_Events[i] = 0; /* initialize data structure */
}
#endif
}
/* END McuEvents. */
/*!
** @}
*/

View File

@@ -0,0 +1,196 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuEvents.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SimpleEvents
** Version : Component 01.059, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
** Settings :
** Component name : McuEvents
** SDK : McuLib
** Critical Section : McuCriticalSection
** Initialize on Init : yes
** Event Name List : (string list)
** Contents :
** SetEvent - void McuEvents_SetEvent(uint8_t event);
** ClearEvent - void McuEvents_ClearEvent(uint8_t event);
** EventsPending - bool McuEvents_EventsPending(void);
** GetEvent - bool McuEvents_GetEvent(uint8_t event);
** GetClearEvent - bool McuEvents_GetClearEvent(uint8_t event);
** HandleEvent - void McuEvents_HandleEvent(void);
**
** * Copyright (c) 2011-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuEvents.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuEvents_module McuEvents module documentation
** @{
*/
#ifndef __McuEvents_H
#define __McuEvents_H
/* MODULE McuEvents. */
#include "McuLib.h" /* SDK and API used */
#include "McuEventsconfig.h" /* configuration */
/* Event prototype */
void McuEvents_CONFIG_EVENT_HANDLER_NAME(uint8_t event);
#ifdef __cplusplus
extern "C" {
#endif
void McuEvents_SetEvent(uint8_t event);
/*
** ===================================================================
** Method : SetEvent (component SimpleEvents)
**
** Description :
** Sets an event (number) be processed by the next HandleEvent()
** call
** Parameters :
** NAME - DESCRIPTION
** event - The event (number) to be set so it
** will be called by the HandleEvent() routine
** later on. Note that there cannot be
** multiple instances of an event, and the
** lower the event number, the higher the
** priority.
** Returns : Nothing
** ===================================================================
*/
void McuEvents_HandleEvent(void);
/*
** ===================================================================
** Method : HandleEvent (component SimpleEvents)
**
** Description :
** Event handler, to be called periodically.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEvents_Init(void);
/*
** ===================================================================
** Method : McuEvents_Init (component SimpleEvents)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
bool McuEvents_GetEvent(uint8_t event);
/*
** ===================================================================
** Method : GetEvent (component SimpleEvents)
**
** Description :
** Allows to check if an event is set or not.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to check. If the
** event is set, the function returns TRUE.
** Returns :
** --- - none
** ===================================================================
*/
void McuEvents_ClearEvent(uint8_t event);
/*
** ===================================================================
** Method : ClearEvent (component SimpleEvents)
**
** Description :
** Clears one event (number). If the event is not set, then the
** function has no effect.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to be cleared.
** Returns : Nothing
** ===================================================================
*/
bool McuEvents_EventsPending(void);
/*
** ===================================================================
** Method : EventsPending (component SimpleEvents)
**
** Description :
** Returns true if any events are pending, false otherwise
** Parameters : None
** Returns :
** --- - True in case any events are pending, false
** otherwise.
** ===================================================================
*/
bool McuEvents_GetClearEvent(uint8_t event);
/*
** ===================================================================
** Method : GetClearEvent (component SimpleEvents)
**
** Description :
** Allows to check if an event is set or not. If set, it will
** be automatically cleared.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to check. If the
** event is set, the function returns TRUE.
** Returns :
** --- - none
** ===================================================================
*/
/* END McuEvents. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuEvents_H */
/*!
** @}
*/

View File

@@ -0,0 +1,856 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuExtRTC.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : RTC_Maxim
** Version : Component 01.026, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2022-07-05, 20:46, # CodeGen: 776
** Abstract :
** Driver for external I2C based realtime clocks (RTC)
** Settings :
** Component name : McuExtRTC
** Device : DS3232
** I2C : McuGenericI2C
** Utility : McuUtility
** SDK : McuLib
** Shell : Enabled
** Shell : McuShell
** Contents :
** GetRTCTimeDate - uint8_t McuExtRTC_GetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date);
** SetRTCTimeDate - uint8_t McuExtRTC_SetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date);
** GetRTCTime - uint8_t McuExtRTC_GetRTCTime(McuExtRTC_TTIME *time);
** SetRTCTime - uint8_t McuExtRTC_SetRTCTime(McuExtRTC_TTIME *time);
** GetRTCDate - uint8_t McuExtRTC_GetRTCDate(McuExtRTC_TDATE *date);
** SetRTCDate - uint8_t McuExtRTC_SetRTCDate(McuExtRTC_TDATE *date);
** GetTime - uint8_t McuExtRTC_GetTime(TIMEREC *time);
** SetTime - uint8_t McuExtRTC_SetTime(uint8_t Hour, uint8_t Min, uint8_t Sec, uint8_t...
** GetDate - uint8_t McuExtRTC_GetDate(DATEREC *date);
** SetDate - uint8_t McuExtRTC_SetDate(uint16_t Year, uint8_t Month, uint8_t Day);
** GetTemperature - uint8_t McuExtRTC_GetTemperature(float *temperature);
** Read - uint8_t McuExtRTC_Read(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** Write - uint8_t McuExtRTC_Write(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** ReadByte - uint8_t McuExtRTC_ReadByte(uint8_t addr, uint8_t *buf);
** WriteByte - uint8_t McuExtRTC_WriteByte(uint8_t addr, uint8_t buf);
** ReadBlock - uint8_t McuExtRTC_ReadBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** WriteBlock - uint8_t McuExtRTC_WriteBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** ParseCommand - uint8_t McuExtRTC_ParseCommand(const unsigned char *cmd, bool *handled, const...
** Init - void McuExtRTC_Init(void);
** Deinit - void McuExtRTC_Deinit(void);
**
** * Copyright (c) 2014-2022, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuExtRTC.h
** @version 01.00
** @brief
** Driver for external I2C based realtime clocks (RTC)
*/
/*!
** @addtogroup McuExtRTC_module McuExtRTC module documentation
** @{
*/
/* MODULE McuExtRTC. */
#include "McuExtRTC.h"
static uint8_t AddHWRTCDate(uint8_t *buf, size_t bufSize) {
McuExtRTC_TDATE tdate;
const char *const weekDays[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
if (McuExtRTC_GetRTCDate(&tdate)!=ERR_OK) {
return ERR_FAILED;
}
if (tdate.dayOfWeek<=6) {
McuUtility_strcat(buf, bufSize, (unsigned char*)weekDays[tdate.dayOfWeek]);
}
McuUtility_chcat(buf, bufSize, ' ');
McuUtility_strcatNum16uFormatted(buf, bufSize, tdate.day, '0', 2);
McuUtility_chcat(buf, bufSize, '.');
McuUtility_strcatNum16uFormatted(buf, bufSize, tdate.month, '0', 2);
McuUtility_chcat(buf, bufSize, '.');
McuUtility_strcatNum16u(buf, bufSize, (uint16_t)tdate.year+2000);
return ERR_OK;
}
static uint8_t AddHWRTCTime(uint8_t *buf, size_t bufSize) {
McuExtRTC_TTIME ttime;
if (McuExtRTC_GetRTCTime(&ttime)!=ERR_OK) {
return ERR_FAILED;
}
McuUtility_strcatNum16sFormatted(buf, bufSize, ttime.hour, '0', 2);
McuUtility_chcat(buf, bufSize, ':');
McuUtility_strcatNum16sFormatted(buf, bufSize, ttime.min, '0', 2);
McuUtility_chcat(buf, bufSize, ':');
McuUtility_strcatNum16sFormatted(buf, bufSize, ttime.sec, '0', 2);
if (ttime.mode==McuExtRTC_TTIME_MODE_24H) {
McuUtility_strcat(buf, bufSize, (unsigned char*)" (24h)");
} else {
if (ttime.am_pm==McuExtRTC_TTIME_AMPM_AM) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"am");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"pm");
}
}
return ERR_OK;
}
static uint8_t DateCmd(const unsigned char *cmd, McuShell_ConstStdIOType *io) {
/* precondition: cmd points to "McuExtRTC date" */
uint8_t day, month;
uint16_t year;
const unsigned char *p;
uint8_t res = ERR_OK;
p = cmd + sizeof("McuExtRTC date")-1;
if (*p==' ') { /* ok, have an argument */
if (McuUtility_ScanDate(&p, &day, &month, &year) == ERR_OK) { /* ok, format fine */
/* update real time clock */
res = McuExtRTC_SetDate(year, month, day);
if (res!=ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failure setting RTC\r\n", io->stdErr);
res = ERR_FAILED;
} else {
/* note: spending some time here, as the RTC is busy writing data, we will read data back below */
McuShell_SendStr((unsigned char*)"Reading date from RTC: ", io->stdOut);
}
} else {
McuShell_SendStr((unsigned char*)"*** Error while reading command! ***", io->stdErr);
McuShell_SendStr((void *)cmd, io->stdErr);
McuShell_SendStr((unsigned char*)"\r\n", io->stdErr);
res = ERR_FAILED;
}
} /* has an argument */
/* print now current date */
if (res==ERR_OK) {
unsigned char buf[sizeof("Wednesday dd:mm:yyyy\\r\\n")];
buf[0]='\0';
if (AddHWRTCDate(buf, sizeof(buf))!=ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failed to get RTC date\r\n", io->stdErr);
res = ERR_FAILED;
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStr(buf, io->stdOut);
}
}
return res;
}
static uint8_t TimeCmd(const unsigned char *cmd, McuShell_ConstStdIOType *io) {
uint8_t hour, minute, second, hSecond;
const unsigned char *p;
uint8_t res = ERR_OK;
p = cmd + sizeof("McuExtRTC time")-1;
if (*p==' ') { /* has an argument */
if (McuUtility_ScanTime(&p, &hour, &minute, &second, &hSecond)==ERR_OK) { /* format fine */
/* set RTC time */
res = McuExtRTC_SetTime(hour, minute, second, hSecond);
if (res != ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failure setting RTC time\r\n", io->stdErr);
res = ERR_FAILED;
} else {
/* note: spending some time here, as the RTC is busy writing data, we will read data back below */
McuShell_SendStr((unsigned char*)"Reading time from RTC: ", io->stdOut);
}
} else {
McuShell_SendStr((unsigned char*)"*** Error while reading command: ", io->stdErr);
McuShell_SendStr(cmd, io->stdErr);
McuShell_SendStr((unsigned char*)"\r\n", io->stdErr);
res = ERR_FAILED;
}
}
/* print now current time */
if (res==ERR_OK) {
unsigned char buf[sizeof("hh:mm:ss.hh (24h)\\r\\n")];
buf[0] = '\0';
if (AddHWRTCTime(buf, sizeof(buf))!=ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failed to get RTC time\r\n", io->stdErr);
res = ERR_FAILED;
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStr(buf, io->stdOut);
}
}
return res;
}
static uint8_t PrintStatus(McuShell_ConstStdIOType *io) {
uint8_t buf[32];
McuShell_SendStatusStr((unsigned char*)"McuExtRTC", (const unsigned char*)"Hardware external time and date\r\n", io->stdOut);
buf[0] = '\0';
if (AddHWRTCDate(buf, sizeof(buf))!=ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failed to get RTC date!\r\n", io->stdErr);
return ERR_FAILED;
}
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" date", buf, io->stdOut);
buf[0] = '\0';
if (AddHWRTCTime(buf, sizeof(buf))!=ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failed to get RTC time!\r\n", io->stdErr);
return ERR_FAILED;
}
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" time", buf, io->stdOut);
McuUtility_Num16uToStr(buf, sizeof(buf), McuExtRTC_CONFIG_DEVICE);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", I2C Addr 0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuExtRTC_CONFIG_DEVICE_ADDRESS);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" device", buf, io->stdOut);
#if McuExtRTC_MEM_SIZE==0 /* no RAM on device */
/* there is no RAM for this device */
#else
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuExtRTC_MEM_RAM_START_ADDR);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"..0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuExtRTC_MEM_RAM_END_ADDR);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" RAM", buf, io->stdOut);
#endif
#if McuExtRTC_CONFIG_DEVICE==3231 || McuExtRTC_CONFIG_DEVICE==3232
float temperature;
if (McuExtRTC_GetTemperature(&temperature)==ERR_OK) {
buf[0] = '\0';
McuUtility_strcatNumFloat(buf, sizeof(buf), temperature, 2);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" degree C\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Temperature", buf, io->stdOut);
#endif
return ERR_OK;
}
/*
** ===================================================================
** Method : Read (component RTC_Maxim)
**
** Description :
** Read from the device
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address
** * buf - Pointer to read buffer
** bufSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_Read(uint8_t addr, uint8_t *buf, uint8_t bufSize)
{
return McuGenericI2C_ReadAddress(McuExtRTC_CONFIG_DEVICE_ADDRESS, &addr, 1, buf, bufSize);
}
/*
** ===================================================================
** Method : Write (component RTC_Maxim)
**
** Description :
** Write from the device
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address
** * buf - Pointer to read buffer
** bufSize -
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_Write(uint8_t addr, uint8_t *buf, uint8_t bufSize)
{
return McuGenericI2C_WriteAddress(McuExtRTC_CONFIG_DEVICE_ADDRESS, &addr, 1, buf, bufSize);
}
/*
** ===================================================================
** Method : ReadByte (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM start address
** * buf - Pointer to read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_ReadByte(uint8_t addr, uint8_t *buf)
{
#if McuExtRTC_MEM_SIZE==0 /* no RAM on device */
(void)addr; /* unused */
(void)buf; /* unused */
return ERR_FAILED; /* there is no RAM for this device */
#else
if (addr>McuExtRTC_MAX_ADDRESS) {
return ERR_RANGE; /* memory address out of range */
}
addr += McuExtRTC_MEM_RAM_START_ADDR;
return McuGenericI2C_ReadAddress(McuExtRTC_CONFIG_DEVICE_ADDRESS, &addr, 1, buf, 1);
#endif
}
/*
** ===================================================================
** Method : WriteByte (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM memory start address
** buf - value to write
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_WriteByte(uint8_t addr, uint8_t buf)
{
#if McuExtRTC_MEM_SIZE==0 /* no RAM on device */
(void)addr; /* unused */
(void)buf; /* unused */
return ERR_FAILED; /* there is no RAM for this device */
#else
if (addr>McuExtRTC_MAX_ADDRESS) {
return ERR_RANGE; /* memory address out of range */
}
addr += McuExtRTC_MEM_RAM_START_ADDR;
return McuGenericI2C_WriteAddress(McuExtRTC_CONFIG_DEVICE_ADDRESS, &addr, 1, &buf, 1);
#endif
}
/*
** ===================================================================
** Method : ReadBlock (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM start address
** * buf - Pointer to read buffer
** bufSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_ReadBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize)
{
#if McuExtRTC_MEM_SIZE==0 /* no RAM on device */
(void)addr; /* unused */
(void)buf; /* unused */
(void)bufSize; /* unused */
return ERR_FAILED; /* there is no RAM for this device */
#else
if (addr>McuExtRTC_MAX_ADDRESS || (addr+bufSize)>McuExtRTC_MEM_SIZE) {
return ERR_RANGE; /* memory address out of range */
}
addr += McuExtRTC_MEM_RAM_START_ADDR;
return McuGenericI2C_ReadAddress(McuExtRTC_CONFIG_DEVICE_ADDRESS, &addr, 1, buf, bufSize);
#endif
}
/*
** ===================================================================
** Method : WriteBlock (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM memory start address
** * buf - Pointer to read buffer
** bufSize -
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_WriteBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize)
{
#if McuExtRTC_MEM_SIZE==0 /* no RAM on device */
(void)addr; /* unused */
(void)buf; /* unused */
(void)bufSize; /* unused */
return ERR_FAILED; /* there is no RAM for this device */
#else
if (addr>McuExtRTC_MAX_ADDRESS || (addr+bufSize)>McuExtRTC_MEM_SIZE) {
return ERR_RANGE; /* memory address out of range */
}
addr += McuExtRTC_MEM_RAM_START_ADDR;
return McuGenericI2C_WriteAddress(McuExtRTC_CONFIG_DEVICE_ADDRESS, &addr, 1, buf, bufSize);
#endif
}
/*
** ===================================================================
** Method : GetRTCTimeDate (component RTC_Maxim)
**
** Description :
** Returns the time and date from the device.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time
** * date - Pointer to date
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date)
{
uint8_t buf[McuExtRTC_MEM_TIME_DATE_STRUCT_SIZE];
if (McuExtRTC_Read(McuExtRTC_MEM_TIME_DATE_STRUCT_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
time->sec = (uint8_t)(((buf[0]&0x70)>>4)*10 + (buf[0]&0x0F));
time->min = (uint8_t)((buf[1]>>4)*10 + (buf[1]&0x0F));
if (buf[2]&0x40) {
time->hour =(uint8_t)(buf[2]&0x1F);
time->mode = McuExtRTC_TTIME_MODE_12H;
time->am_pm =(uint8_t)((buf[2]&0x20)>>5);
} else {
time->hour = (uint8_t)(buf[2]&0x3F);
time->mode = McuExtRTC_TTIME_MODE_24H;
}
time->hour = (uint8_t)((time->hour>>4)*10 + (buf[2]&0x0F));
date->dayOfWeek =(uint8_t)(buf[3]-1);
date->day = (uint8_t)((buf[4]>>4)*10 + (buf[4]&0x0F));
date->month = (uint8_t)((buf[5]>>4)*10 + (buf[5]&0x0F));
date->year = (uint8_t)((buf[6]>>4)*10 + (buf[6]&0x0F));
return ERR_OK;
}
/*
** ===================================================================
** Method : SetRTCTimeDate (component RTC_Maxim)
**
** Description :
** Sets the date and time.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time to be set
** * date - Pointer to date to be set
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date)
{
uint8_t buf[McuExtRTC_MEM_TIME_DATE_STRUCT_SIZE];
if ( ((time->mode==McuExtRTC_TTIME_MODE_12H)&&((time->hour>12)||(time->hour==0)))
|| ((time->mode==McuExtRTC_TTIME_MODE_24H)&&(time->hour>23))
|| (time->min>59)||(time->sec>59)
|| (date->year>99)||(date->month>12)||(date->month==0)
|| (date->day>31)||(date->day==0)
|| (date->dayOfWeek>6))
{
return ERR_RANGE;
}
buf[0] = (uint8_t)(((time->sec/10)<<4) | (time->sec%10));
buf[1] = (uint8_t)(((time->min/10)<<4) | (time->min%10));
buf[2] = (uint8_t)(((time->hour/10)<<4) | (time->hour%10));
if (time->mode==McuExtRTC_TTIME_MODE_12H) {
buf[2] |= (time->am_pm)?0x60:0x40;
}
buf[3] = (uint8_t)(date->dayOfWeek+1);
buf[4] = (uint8_t)(((date->day/10)<<4) | (date->day%10));
buf[5] = (uint8_t)(((date->month/10)<<4) | (date->month%10));
buf[6] = (uint8_t)(((date->year/10)<<4) | (date->year%10));
if (McuExtRTC_Write(McuExtRTC_MEM_TIME_DATE_STRUCT_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : SetRTCTime (component RTC_Maxim)
**
** Description :
** Sets the time using the RTC low level information.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time to be set
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetRTCTime(McuExtRTC_TTIME *time)
{
uint8_t buf[McuExtRTC_MEM_TIME_STRUCT_SIZE];
if ( ((time->mode==McuExtRTC_TTIME_MODE_12H)&&((time->hour>12)||(time->hour==0)))
|| ((time->mode==McuExtRTC_TTIME_MODE_24H)&&(time->hour>23))
|| (time->min>59) || (time->sec>59)
)
{
return ERR_RANGE;
}
buf[0] = (uint8_t)(((time->sec/10)<<4) | (time->sec%10));
buf[1] = (uint8_t)(((time->min/10)<<4) | (time->min%10));
buf[2] = (uint8_t)(((time->hour/10)<<4) | (time->hour%10));
if (time->mode==McuExtRTC_TTIME_MODE_12H) {
buf[2] |= (time->am_pm)?0x60:0x40;
}
if (McuExtRTC_Write(McuExtRTC_MEM_TIME_STRUCT_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : GetRTCTime (component RTC_Maxim)
**
** Description :
** Returns the time using the RTC low level information.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetRTCTime(McuExtRTC_TTIME *time)
{
uint8_t buf[McuExtRTC_MEM_TIME_STRUCT_SIZE];
if (McuExtRTC_Read(McuExtRTC_MEM_TIME_STRUCT_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
time->sec = (uint8_t)(((buf[0]&0x70)>>4)*10 + (buf[0]&0x0F));
time->min = (uint8_t)((buf[1]>>4)*10 + (buf[1]&0x0F));
if (buf[2]&0x40) {
time->hour =(uint8_t)(buf[2]&0x1F);
time->mode = McuExtRTC_TTIME_MODE_12H;
time->am_pm = (uint8_t)((buf[2]&0x20)>>5);
} else {
time->hour = (uint8_t)(buf[2]&0x3F);
time->mode = McuExtRTC_TTIME_MODE_24H;
}
time->hour = (uint8_t)((time->hour>>4)*10 + (buf[2]&0x0F));
return ERR_OK;
}
/*
** ===================================================================
** Method : GetRTCDate (component RTC_Maxim)
**
** Description :
** Returns the date from the device using the RTC low level
** information.
** Parameters :
** NAME - DESCRIPTION
** * date - Pointer to date
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetRTCDate(McuExtRTC_TDATE *date)
{
uint8_t buf[McuExtRTC_MEM_DATE_STRUCT_SIZE];
if (McuExtRTC_Read(McuExtRTC_MEM_DATE_STRUCT_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
date->dayOfWeek =(uint8_t)(buf[0]-1);
date->day = (uint8_t)((buf[1]>>4)*10 + (buf[1]&0x0F));
date->month = (uint8_t)((buf[2]>>4)*10 + (buf[2]&0x0F));
date->year = (uint8_t)((buf[3]>>4)*10 + (buf[3]&0x0F));
return ERR_OK;
}
/*
** ===================================================================
** Method : SetRTCDate (component RTC_Maxim)
**
** Description :
** Sets the date using the RTC low level information.
** Parameters :
** NAME - DESCRIPTION
** * date - Pointer to date to be set
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetRTCDate(McuExtRTC_TDATE *date)
{
uint8_t buf[McuExtRTC_MEM_DATE_STRUCT_SIZE];
if ( (date->year>99)
|| (date->month>12)||(date->month==0)
|| (date->day>31)||(date->day==0)
|| (date->dayOfWeek>6)
)
{
return ERR_RANGE;
}
buf[0] = (uint8_t)(date->dayOfWeek + 1);
buf[1] = (uint8_t)(((date->day/10)<<4) | (date->day%10));
buf[2] = (uint8_t)(((date->month/10)<<4) | (date->month%10));
buf[3] = (uint8_t)(((date->year/10)<<4) | (date->year%10));
if (McuExtRTC_Write(McuExtRTC_MEM_DATE_STRUCT_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : Init (component RTC_Maxim)
**
** Description :
** Initializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuExtRTC_Init(void)
{
/* nothing to do */
}
/*
** ===================================================================
** Method : Deinit (component RTC_Maxim)
**
** Description :
** Deinitializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuExtRTC_Deinit(void)
{
/* nothing to do */
}
/*
** ===================================================================
** Method : ParseCommand (component RTC_Maxim)
**
** Description :
** Shell Command Line parser
** Parameters :
** NAME - DESCRIPTION
** * cmd - Pointer to command line
** * handled - Pointer to variable which tells if
** the command has been handled or not
** * io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io)
{
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, "McuExtRTC help")==0) {
McuShell_SendHelpStr((unsigned char*)"McuExtRTC", (const unsigned char*)"Group of McuExtRTC commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (const unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" time [hh:mm:ss[,z]]", (const unsigned char*)"Set the current time. Prints the current time if no argument\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" date [dd.mm.yyyy]", (const unsigned char*)"Set the current date. Prints the current date if no argument\r\n", io->stdOut);
*handled = TRUE;
return ERR_OK;
} else if ((McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0) || (McuUtility_strcmp((char*)cmd, "McuExtRTC status")==0)) {
*handled = TRUE;
return PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, "McuExtRTC date", sizeof("McuExtRTC date")-1)==0) {
*handled = TRUE;
return DateCmd(cmd, io);
} else if (McuUtility_strncmp((char*)cmd, "McuExtRTC time", sizeof("McuExtRTC time")-1)==0) {
*handled = TRUE;
return TimeCmd(cmd, io);
}
return ERR_OK;
}
/*
** ===================================================================
** Method : GetTime (component RTC_Maxim)
**
** Description :
** Returns the time.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetTime(TIMEREC *time)
{
McuExtRTC_TTIME ttime;
if (McuExtRTC_GetRTCTime(&ttime)!=ERR_OK) {
return ERR_FAILED;
}
time->Hour = ttime.hour;
time->Min = ttime.min;
time->Sec = ttime.sec;
time->Sec100 = 0;
return ERR_OK;
}
/*
** ===================================================================
** Method : SetTime (component RTC_Maxim)
**
** Description :
** Sets the time.
** Parameters :
** NAME - DESCRIPTION
** Hour - Hours (0 - 23)
** Min - Minutes (0 - 59)
** Sec - Seconds (0 - 59)
** Sec100 - Hundredths of seconds (0 - 99)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetTime(uint8_t Hour, uint8_t Min, uint8_t Sec, uint8_t Sec100)
{
McuExtRTC_TTIME ttime;
ttime.hour = Hour;
ttime.min = Min;
ttime.sec = Sec;
(void)Sec100; /* ignored, as cannot be stored on device */
ttime.mode = McuExtRTC_TTIME_MODE_24H;
ttime.am_pm = McuExtRTC_TTIME_AMPM_AM;
return McuExtRTC_SetRTCTime(&ttime);
}
/*
** ===================================================================
** Method : GetDate (component RTC_Maxim)
**
** Description :
** Returns the time and date from the device.
** Parameters :
** NAME - DESCRIPTION
** * date - Pointer to date
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetDate(DATEREC *date)
{
McuExtRTC_TDATE tdate;
if (McuExtRTC_GetRTCDate(&tdate)!=ERR_OK) {
return ERR_FAILED;
}
date->Year = (uint16_t)(tdate.year+2000);
date->Month = tdate.month;
date->Day = tdate.day;
return ERR_OK;
}
/*
** ===================================================================
** Method : SetDate (component RTC_Maxim)
**
** Description :
** Sets the date.
** Parameters :
** NAME - DESCRIPTION
** Year - Year in 2000 format
** Month - Month number (1..12)
** Day - Day number (1..31)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetDate(uint16_t Year, uint8_t Month, uint8_t Day)
{
McuExtRTC_TDATE tdate;
tdate.year = (uint8_t)(Year-2000);
tdate.month = Month;
tdate.day = Day;
tdate.dayOfWeek = McuUtility_WeekDay(Year, Month, Day);
return McuExtRTC_SetRTCDate(&tdate);
}
/*
** ===================================================================
** Method : GetTemperature (component RTC_Maxim)
**
** Description :
** Returns the temperature from the device internal temperature
** sensor. Only available on DS3231 and DS3232.
** Parameters :
** NAME - DESCRIPTION
** * temperature - Pointer to store the
** temperature
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetTemperature(float *temperature)
{
#if McuExtRTC_CONFIG_DEVICE==3231 || McuExtRTC_CONFIG_DEVICE==3232
int8_t high;
uint8_t low, res;
res = McuExtRTC_Read(McuExtRTC_MEM_MSB_TEMP_ADDR, (uint8_t*)&high, 1);
if (res!=ERR_OK) {
return res;
}
res = McuExtRTC_Read(McuExtRTC_MEM_LSB_TEMP_ADDR, &low, 1);
if (res!=ERR_OK) {
return res;
}
/* high values is two's complement of integer part of temperature, the upper two bits of LSB are the number of 0.25 degrees.
For example 0b00011000 0b01xxxxxx gives 24.25 degree. */
*temperature = (float)high + (((low&0xC0)>>6)*0.25f);
return ERR_OK;
#else /* not supported */
*temperature = 0.0f;
return ERR_FAILED;
#endif
}
/* END McuExtRTC. */
/*!
** @}
*/

View File

@@ -0,0 +1,529 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuExtRTC.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : RTC_Maxim
** Version : Component 01.026, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2022-07-05, 20:46, # CodeGen: 776
** Abstract :
** Driver for external I2C based realtime clocks (RTC)
** Settings :
** Component name : McuExtRTC
** Device : DS3232
** I2C : McuGenericI2C
** Utility : McuUtility
** SDK : McuLib
** Shell : Enabled
** Shell : McuShell
** Contents :
** GetRTCTimeDate - uint8_t McuExtRTC_GetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date);
** SetRTCTimeDate - uint8_t McuExtRTC_SetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date);
** GetRTCTime - uint8_t McuExtRTC_GetRTCTime(McuExtRTC_TTIME *time);
** SetRTCTime - uint8_t McuExtRTC_SetRTCTime(McuExtRTC_TTIME *time);
** GetRTCDate - uint8_t McuExtRTC_GetRTCDate(McuExtRTC_TDATE *date);
** SetRTCDate - uint8_t McuExtRTC_SetRTCDate(McuExtRTC_TDATE *date);
** GetTime - uint8_t McuExtRTC_GetTime(TIMEREC *time);
** SetTime - uint8_t McuExtRTC_SetTime(uint8_t Hour, uint8_t Min, uint8_t Sec, uint8_t...
** GetDate - uint8_t McuExtRTC_GetDate(DATEREC *date);
** SetDate - uint8_t McuExtRTC_SetDate(uint16_t Year, uint8_t Month, uint8_t Day);
** GetTemperature - uint8_t McuExtRTC_GetTemperature(float *temperature);
** Read - uint8_t McuExtRTC_Read(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** Write - uint8_t McuExtRTC_Write(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** ReadByte - uint8_t McuExtRTC_ReadByte(uint8_t addr, uint8_t *buf);
** WriteByte - uint8_t McuExtRTC_WriteByte(uint8_t addr, uint8_t buf);
** ReadBlock - uint8_t McuExtRTC_ReadBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** WriteBlock - uint8_t McuExtRTC_WriteBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize);
** ParseCommand - uint8_t McuExtRTC_ParseCommand(const unsigned char *cmd, bool *handled, const...
** Init - void McuExtRTC_Init(void);
** Deinit - void McuExtRTC_Deinit(void);
**
** * Copyright (c) 2014-2022, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuExtRTC.h
** @version 01.00
** @brief
** Driver for external I2C based realtime clocks (RTC)
*/
/*!
** @addtogroup McuExtRTC_module McuExtRTC module documentation
** @{
*/
#ifndef __McuExtRTC_H
#define __McuExtRTC_H
/* MODULE McuExtRTC. */
#include "McuLib.h" /* SDK and API used */
#include "McuExtRTCconfig.h" /* configuration */
/* Include inherited beans */
#include "McuGenericI2C.h"
#include "McuUtility.h"
#include "McuLib.h"
#include "McuShell.h"
#ifndef __BWUserType_McuExtRTC_TTIME
#define __BWUserType_McuExtRTC_TTIME
typedef struct { /* Time in binary format */
uint8_t hour; /* hours */
uint8_t min; /* minutes */
uint8_t sec; /* seconds */
bool mode; /* clock mode, 0 for 12-hour mode, otherwise 0-24 hour mode */
uint8_t am_pm; /* 0: AM, otherwise PM */
} McuExtRTC_TTIME;
#endif
#ifndef __BWUserType_McuExtRTC_TDATE
#define __BWUserType_McuExtRTC_TDATE
typedef struct { /* Date in binary format */
uint8_t year; /* year */
uint8_t month; /* month */
uint8_t day; /* day */
uint8_t dayOfWeek; /* Day of week, where 0 is the first day. In the range of 0..6 */
} McuExtRTC_TDATE;
#endif
#ifndef __BWUserType_TIMEREC
#define __BWUserType_TIMEREC
typedef struct { /* It contains actual number of hours, minutes, seconds and hundreth of seconds. */
uint8_t Hour; /* hours (0 - 23) */
uint8_t Min; /* minutes (0 - 59) */
uint8_t Sec; /* seconds (0 - 59) */
uint8_t Sec100; /* hundredth of seconds (0 - 99) */
} TIMEREC;
#endif
#ifndef __BWUserType_DATEREC
#define __BWUserType_DATEREC
typedef struct { /* It contains actual year, month, and day description. */
uint16_t Year; /* years (1998 - 2099) */
uint8_t Month; /* months (1 - 12) */
uint8_t Day; /* days (1 - 31) */
} DATEREC;
#endif
#define McuExtRTC_PARSE_COMMAND_ENABLED 1 /* set to 1 if method ParseCommand() is present, 0 otherwise */
/* device memory addresses */
#if McuExtRTC_CONFIG_DEVICE==3231 || McuExtRTC_CONFIG_DEVICE==3232
#define McuExtRTC_MEM_SECONDS_ADDR 0x00 /* Seconds */
#define McuExtRTC_MEM_MINUTES_ADDR 0x01 /* Minutes */
#define McuExtRTC_MEM_HOURS_ADDR 0x02 /* Hours */
#define McuExtRTC_MEM_DAY_ADDR 0x03 /* Day */
#define McuExtRTC_MEM_DATE_ADDR 0x04 /* Date */
#define McuExtRTC_MEM_MONTH_ADDR 0x05 /* Month */
#define McuExtRTC_MEM_YEAR_ADDR 0x06 /* Year */
#define McuExtRTC_MEM_CTRL_ADDR 0x0E /* Control */
#define McuExtRTC_MEM_CTRL_STATUS_ADDR 0x0F /* Control/Status */
#define McuExtRTC_MEM_AGING_OFFSET_ADDR 0x10 /* Aging offset */
#define McuExtRTC_MEM_MSB_TEMP_ADDR 0x11 /* MSB of Temp */
#define McuExtRTC_MEM_LSB_TEMP_ADDR 0x12 /* LSB of Temp */
/* Address 0x13 is reserved */
#if McuExtRTC_CONFIG_DEVICE==3232 /* 3231 has no RAM */
#define McuExtRTC_MEM_RAM_START_ADDR 0x14 /* device memory start address of non-volatile RAM */
#define McuExtRTC_MEM_RAM_END_ADDR 0xFF /* device memory end address of non-volatile RAM */
#endif
#elif McuExtRTC_CONFIG_DEVICE==1307
#define McuExtRTC_MEM_SECONDS_ADDR 0x00 /* Seconds */
#define McuExtRTC_MEM_MINUTES_ADDR 0x01 /* Minutes */
#define McuExtRTC_MEM_HOURS_ADDR 0x02 /* Hours */
#define McuExtRTC_MEM_DAY_ADDR 0x03 /* Day */
#define McuExtRTC_MEM_DATE_ADDR 0x04 /* Date */
#define McuExtRTC_MEM_MONTH_ADDR 0x05 /* Month */
#define McuExtRTC_MEM_YEAR_ADDR 0x06 /* Year */
#define McuExtRTC_MEM_CTRL_ADDR 0x07 /* Control */
#define McuExtRTC_MEM_RAM_START_ADDR 0x08 /* device memory start address of non-volatile RAM */
#define McuExtRTC_MEM_RAM_END_ADDR 0x3F /* device memory end address of non-volatile RAM */
#elif McuExtRTC_CONFIG_DEVICE==1342
#define McuExtRTC_MEM_SECONDS_ADDR 0x00 /* Seconds */
#define McuExtRTC_MEM_MINUTES_ADDR 0x01 /* Minutes */
#define McuExtRTC_MEM_HOURS_ADDR 0x02 /* Hours */
#define McuExtRTC_MEM_DAY_ADDR 0x03 /* Day */
#define McuExtRTC_MEM_DATE_ADDR 0x04 /* Date */
#define McuExtRTC_MEM_MONTH_ADDR 0x05 /* Month */
#define McuExtRTC_MEM_YEAR_ADDR 0x06 /* Year */
#define McuExtRTC_MEM_CTRL_ADDR 0x0E /* Control */
#else
#error "unknown device?"
#endif
#if McuExtRTC_CONFIG_DEVICE==1342
#define McuExtRTC_MEM_SIZE (0) /* no memory for DS1342 */
#elif McuExtRTC_CONFIG_DEVICE==3231
#define McuExtRTC_MEM_SIZE (0) /* no memory for DS3231*/
#else
#define McuExtRTC_MEM_SIZE (McuExtRTC_MEM_RAM_END_ADDR-McuExtRTC_MEM_RAM_START_ADDR+1) /* device memory start address of non-volatile RAM, in bytes */
#define McuExtRTC_MAX_ADDRESS (McuExtRTC_MEM_SIZE-1) /* maximum RAM address of device */
#endif
#define McuExtRTC_MEM_TIME_STRUCT_ADDR McuExtRTC_MEM_SECONDS_ADDR /* device memory start address for time */
#define McuExtRTC_MEM_TIME_STRUCT_SIZE 0x03 /* device memory size for time */
#define McuExtRTC_MEM_DATE_STRUCT_ADDR McuExtRTC_MEM_DAY_ADDR /* device memory start address for date */
#define McuExtRTC_MEM_DATE_STRUCT_SIZE 0x04 /* device memory size for date */
#define McuExtRTC_MEM_TIME_DATE_STRUCT_ADDR (McuExtRTC_MEM_TIME_STRUCT_ADDR) /* device memory start address for time and date */
#define McuExtRTC_MEM_TIME_DATE_STRUCT_SIZE (McuExtRTC_MEM_TIME_STRUCT_SIZE+McuExtRTC_MEM_DATE_STRUCT_SIZE) /* device memory size for time and date */
#define McuExtRTC_TTIME_AMPM_AM 0 /* AM */
#define McuExtRTC_TTIME_AMPM_PM 1 /* PM */
#define McuExtRTC_TTIME_MODE_12H 0 /* 12 hour clock mode */
#define McuExtRTC_TTIME_MODE_24H 1 /* 14 hour clock mode */
uint8_t McuExtRTC_GetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date);
/*
** ===================================================================
** Method : GetRTCTimeDate (component RTC_Maxim)
**
** Description :
** Returns the time and date from the device.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time
** * date - Pointer to date
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetRTCTimeDate(McuExtRTC_TTIME *time, McuExtRTC_TDATE *date);
/*
** ===================================================================
** Method : SetRTCTimeDate (component RTC_Maxim)
**
** Description :
** Sets the date and time.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time to be set
** * date - Pointer to date to be set
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetRTCTime(McuExtRTC_TTIME *time);
/*
** ===================================================================
** Method : SetRTCTime (component RTC_Maxim)
**
** Description :
** Sets the time using the RTC low level information.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time to be set
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetRTCTime(McuExtRTC_TTIME *time);
/*
** ===================================================================
** Method : GetRTCTime (component RTC_Maxim)
**
** Description :
** Returns the time using the RTC low level information.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetRTCDate(McuExtRTC_TDATE *date);
/*
** ===================================================================
** Method : GetRTCDate (component RTC_Maxim)
**
** Description :
** Returns the date from the device using the RTC low level
** information.
** Parameters :
** NAME - DESCRIPTION
** * date - Pointer to date
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetRTCDate(McuExtRTC_TDATE *date);
/*
** ===================================================================
** Method : SetRTCDate (component RTC_Maxim)
**
** Description :
** Sets the date using the RTC low level information.
** Parameters :
** NAME - DESCRIPTION
** * date - Pointer to date to be set
** Returns :
** --- - Error code
** ===================================================================
*/
void McuExtRTC_Init(void);
/*
** ===================================================================
** Method : Init (component RTC_Maxim)
**
** Description :
** Initializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuExtRTC_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component RTC_Maxim)
**
** Description :
** Deinitializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuExtRTC_Read(uint8_t addr, uint8_t *buf, uint8_t bufSize);
/*
** ===================================================================
** Method : Read (component RTC_Maxim)
**
** Description :
** Read from the device
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address
** * buf - Pointer to read buffer
** bufSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_Write(uint8_t addr, uint8_t *buf, uint8_t bufSize);
/*
** ===================================================================
** Method : Write (component RTC_Maxim)
**
** Description :
** Write from the device
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address
** * buf - Pointer to read buffer
** bufSize -
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component RTC_Maxim)
**
** Description :
** Shell Command Line parser
** Parameters :
** NAME - DESCRIPTION
** * cmd - Pointer to command line
** * handled - Pointer to variable which tells if
** the command has been handled or not
** * io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_ReadByte(uint8_t addr, uint8_t *buf);
/*
** ===================================================================
** Method : ReadByte (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM start address
** * buf - Pointer to read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_WriteByte(uint8_t addr, uint8_t buf);
/*
** ===================================================================
** Method : WriteByte (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM memory start address
** buf - value to write
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_ReadBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize);
/*
** ===================================================================
** Method : ReadBlock (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM start address
** * buf - Pointer to read buffer
** bufSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_WriteBlock(uint8_t addr, uint8_t *buf, uint8_t bufSize);
/*
** ===================================================================
** Method : WriteBlock (component RTC_Maxim)
**
** Description :
** Read from the device RAM
** Parameters :
** NAME - DESCRIPTION
** addr - device memory address, with zero as the
** RAM memory start address
** * buf - Pointer to read buffer
** bufSize -
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetTime(TIMEREC *time);
/*
** ===================================================================
** Method : GetTime (component RTC_Maxim)
**
** Description :
** Returns the time.
** Parameters :
** NAME - DESCRIPTION
** * time - Pointer to time
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetTime(uint8_t Hour, uint8_t Min, uint8_t Sec, uint8_t Sec100);
/*
** ===================================================================
** Method : SetTime (component RTC_Maxim)
**
** Description :
** Sets the time.
** Parameters :
** NAME - DESCRIPTION
** Hour - Hours (0 - 23)
** Min - Minutes (0 - 59)
** Sec - Seconds (0 - 59)
** Sec100 - Hundredths of seconds (0 - 99)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetDate(DATEREC *date);
/*
** ===================================================================
** Method : GetDate (component RTC_Maxim)
**
** Description :
** Returns the time and date from the device.
** Parameters :
** NAME - DESCRIPTION
** * date - Pointer to date
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_SetDate(uint16_t Year, uint8_t Month, uint8_t Day);
/*
** ===================================================================
** Method : SetDate (component RTC_Maxim)
**
** Description :
** Sets the date.
** Parameters :
** NAME - DESCRIPTION
** Year - Year in 2000 format
** Month - Month number (1..12)
** Day - Day number (1..31)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuExtRTC_GetTemperature(float *temperature);
/*
** ===================================================================
** Method : GetTemperature (component RTC_Maxim)
**
** Description :
** Returns the temperature from the device internal temperature
** sensor. Only available on DS3231 and DS3232.
** Parameters :
** NAME - DESCRIPTION
** * temperature - Pointer to store the
** temperature
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuExtRTC. */
#endif
/* ifndef __McuExtRTC_H */
/*!
** @}
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,707 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuFXOS8700.h
** CDE edition : Standard
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : FXOS8700CQ
** Version : Component 01.036, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2021-12-26, 15:48, # CodeGen: 768
** Abstract :
** Implements a Driver for the MMA8451 accelerometer from Freescale.
** Settings :
** Component Name : McuFXOS8700
** Slave Address : 1E
** I2C Bus : McuGenericI2C
** Constant Offsets : Enabled
** X offset : 0
** Y offset : 0
** Z offset : 0
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** Enable - uint8_t McuFXOS8700_Enable(void);
** Disable - uint8_t McuFXOS8700_Disable(void);
** MagEnable - uint8_t McuFXOS8700_MagEnable(void);
** MagDisable - uint8_t McuFXOS8700_MagDisable(void);
** isEnabled - uint8_t McuFXOS8700_isEnabled(bool *isEnabled);
** SwReset - uint8_t McuFXOS8700_SwReset(void);
** ReadReg8 - uint8_t McuFXOS8700_ReadReg8(uint8_t addr, uint8_t *val);
** WriteReg8 - uint8_t McuFXOS8700_WriteReg8(uint8_t addr, uint8_t val);
** GetX - int16_t McuFXOS8700_GetX(void);
** GetY - int16_t McuFXOS8700_GetY(void);
** GetZ - int16_t McuFXOS8700_GetZ(void);
** GetRaw8XYZ - uint8_t McuFXOS8700_GetRaw8XYZ(void* *xyz);
** CalibrateX1g - void McuFXOS8700_CalibrateX1g(void);
** CalibrateY1g - void McuFXOS8700_CalibrateY1g(void);
** CalibrateZ1g - void McuFXOS8700_CalibrateZ1g(void);
** GetXmg - int16_t McuFXOS8700_GetXmg(void);
** GetYmg - int16_t McuFXOS8700_GetYmg(void);
** GetZmg - int16_t McuFXOS8700_GetZmg(void);
** MeasureGetRawX - uint16_t McuFXOS8700_MeasureGetRawX(void);
** MeasureGetRawY - uint16_t McuFXOS8700_MeasureGetRawY(void);
** MeasureGetRawZ - uint16_t McuFXOS8700_MeasureGetRawZ(void);
** GetXOffset - int16_t McuFXOS8700_GetXOffset(void);
** GetYOffset - int16_t McuFXOS8700_GetYOffset(void);
** GetZOffset - int16_t McuFXOS8700_GetZOffset(void);
** GetX1gValue - int16_t McuFXOS8700_GetX1gValue(void);
** GetY1gValue - int16_t McuFXOS8700_GetY1gValue(void);
** GetZ1gValue - int16_t McuFXOS8700_GetZ1gValue(void);
** SetFastMode - uint8_t McuFXOS8700_SetFastMode(bool on);
** WhoAmI - uint8_t McuFXOS8700_WhoAmI(uint8_t *value);
** GetTemperature - uint8_t McuFXOS8700_GetTemperature(int8_t *temperature);
** GetMagX - uint8_t McuFXOS8700_GetMagX(int16_t *value);
** GetMagY - uint8_t McuFXOS8700_GetMagY(int16_t *value);
** GetMagZ - uint8_t McuFXOS8700_GetMagZ(int16_t *value);
** ParseCommand - uint8_t McuFXOS8700_ParseCommand(const unsigned char *cmd, bool *handled,...
** MagneticSensorReset - uint8_t McuFXOS8700_MagneticSensorReset(void);
** Init - uint8_t McuFXOS8700_Init(void);
** Deinit - uint8_t McuFXOS8700_Deinit(void);
**
** * Copyright (c) 2013-2021, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuFXOS8700.h
** @version 01.00
** @brief
** Implements a Driver for the MMA8451 accelerometer from Freescale.
*/
/*!
** @addtogroup McuFXOS8700_module McuFXOS8700 module documentation
** @{
*/
#ifndef __McuFXOS8700_H
#define __McuFXOS8700_H
/* MODULE McuFXOS8700. */
#include "McuLib.h" /* SDK and API used */
#include "McuFXOS8700config.h" /* configuration */
/* Include inherited components */
#include "McuGenericI2C.h"
#include "McuWait.h"
#include "McuLib.h"
#include "McuShell.h"
#include "McuUtility.h"
#ifdef __cplusplus
extern "C" {
#endif
#define McuFXOS8700_PARSE_COMMAND_ENABLED McuFXOS8700_CONFIG_PARSE_COMMAND_ENABLED /* set to 1 if method ParseCommand() is present, 0 otherwise */
/* 3-axis accelerometer control register addresses */
#define McuFXOS8700_CTRL_REG_1 0x2A
/* 3-axis accelerometer control register bit masks */
#define McuFXOS8700_ACTIVE_BIT_MASK 0x01
#define McuFXOS8700_F_READ_BIT_MASK 0x02
#define McuFXOS8700_CTRL_REG_2 0x2B
#define McuFXOS8700_CTRL_REG_2_MASK_RST (1<<4) /* software reset */
/* External 3-axis accelerometer data register addresses */
#define McuFXOS8700_OUT_X_MSB 0x01
#define McuFXOS8700_OUT_X_LSB 0x02
#define McuFXOS8700_OUT_Y_MSB 0x03
#define McuFXOS8700_OUT_Y_LSB 0x04
#define McuFXOS8700_OUT_Z_MSB 0x05
#define McuFXOS8700_OUT_Z_LSB 0x06
#define McuFXOS8700_WHO_AM_I 0x0D /* Who am I register, should return 0xC4 for preproduction devices and 0xC7 for production devices */
#define McuFXOS8700_WHO_AM_I_VAL 0xC7 /* production device value */
#define McuFXOS8700_XYZ_DATA_CFG 0x0E /* XYZ Data Configuration Register */
/* magnetometer control register */
#define McuFXOS8700_M_CTRL_REG_1 0x5B
#define McuFXOS8700_M_CTRL_REG_2 0x5C
#define McuFXOS8700_M_CTRL_REG_3 0x5D
/* Magnetometer data register addresses */
#define McuFXOS8700_M_OUT_X_MSB 0x33
#define McuFXOS8700_M_OUT_X_LSB 0x34
#define McuFXOS8700_M_OUT_Y_MSB 0x35
#define McuFXOS8700_M_OUT_Y_LSB 0x36
#define McuFXOS8700_M_OUT_Z_MSB 0x37
#define McuFXOS8700_M_OUT_Z_LSB 0x38
/* die temperature (needs to add an offset as not factory trimmed) */
#define McuFXOS8700_DIE_TEMP 0x51 /* die temperature register, signed 8bit in C */
#define McuFXOS8700_DIE_TEMP_OFFSET McuFXOS8700_CONFIG_TEMP_OFFSET /* offset to temperature reading as value on device is not calibrated */
#define McuFXOS8700_I2C_ADDR McuFXOS8700_CONFIG_I2C_DEVICE_ADDRESS /* I2C slave device address as set in the properties */
uint8_t McuFXOS8700_GetRaw8XYZ(uint8_t *xyz);
/*
** ===================================================================
** Method : GetRaw8XYZ (component FXOS8700CQ)
**
** Description :
** Returns in an array the x, y and z accelerometer as 8bit
** values.
** Parameters :
** NAME - DESCRIPTION
** * xyz - Pointer to an array of three unsigned 8bit
** values which are used to return the
** accelerometer values.
** Returns :
** --- - Error code, ERR_OK for no error.
** ===================================================================
*/
uint8_t McuFXOS8700_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component FXOS8700CQ)
**
** Description :
** Counterpart to Init() method.
** Parameters : None
** Returns :
** --- - Error code, ERR_OK if everything is ok.
** ===================================================================
*/
uint8_t McuFXOS8700_Init(void);
/*
** ===================================================================
** Method : Init (component FXOS8700CQ)
**
** Description :
** Initializes the device driver
** Parameters : None
** Returns :
** --- - Error code, ERR_OK if everything is ok.
** ===================================================================
*/
void McuFXOS8700_CalibrateX1g(void);
/*
** ===================================================================
** Method : CalibrateX1g (component FXOS8700CQ)
**
** Description :
** Performs a calibration of the sensor. It is assumed that the
** Y and Z sensors have 0 g, and the X sensor has 1 g.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuFXOS8700_CalibrateY1g(void);
/*
** ===================================================================
** Method : CalibrateY1g (component FXOS8700CQ)
**
** Description :
** Performs a calibration of the sensor. It is assumed that the
** X and Z sensors have 0 g, and the Y sensor has 1 g.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuFXOS8700_CalibrateZ1g(void);
/*
** ===================================================================
** Method : CalibrateZ1g (component FXOS8700CQ)
**
** Description :
** Performs a calibration of the sensor. It is assumed that the
** X and Y sensors have 0 g, and the Z sensor has 1 g.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
int16_t McuFXOS8700_GetXmg(void);
/*
** ===================================================================
** Method : GetXmg (component FXOS8700CQ)
**
** Description :
** Returns the X value in mg
** Parameters : None
** Returns :
** --- - The g value in 1/1000g units
** ===================================================================
*/
int16_t McuFXOS8700_GetYmg(void);
/*
** ===================================================================
** Method : GetYmg (component FXOS8700CQ)
**
** Description :
** Returns the Y value in mg
** Parameters : None
** Returns :
** --- - The g value in 1/1000g units
** ===================================================================
*/
int16_t McuFXOS8700_GetZmg(void);
/*
** ===================================================================
** Method : GetZmg (component FXOS8700CQ)
**
** Description :
** Returns the Z value in mg
** Parameters : None
** Returns :
** --- - The g value in 1/1000g units
** ===================================================================
*/
uint16_t McuFXOS8700_MeasureGetRawX(void);
/*
** ===================================================================
** Method : MeasureGetRawX (component FXOS8700CQ)
**
** Description :
** Performs a measurement on X channel and returns the raw
** value.
** Parameters : None
** Returns :
** --- - X sensor value
** ===================================================================
*/
uint16_t McuFXOS8700_MeasureGetRawY(void);
/*
** ===================================================================
** Method : MeasureGetRawY (component FXOS8700CQ)
**
** Description :
** Performs a measurement on Y channel and returns the raw
** value.
** Parameters : None
** Returns :
** --- - Y sensor value
** ===================================================================
*/
uint16_t McuFXOS8700_MeasureGetRawZ(void);
/*
** ===================================================================
** Method : MeasureGetRawZ (component FXOS8700CQ)
**
** Description :
** Performs a measurement on Z channel and returns the raw
** value.
** Parameters : None
** Returns :
** --- - Z sensor value
** ===================================================================
*/
int16_t McuFXOS8700_GetXOffset(void);
/*
** ===================================================================
** Method : GetXOffset (component FXOS8700CQ)
**
** Description :
** Returns the offset applied to the X value.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
int16_t McuFXOS8700_GetYOffset(void);
/*
** ===================================================================
** Method : GetYOffset (component FXOS8700CQ)
**
** Description :
** Returns the offset applied to the Y value.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
int16_t McuFXOS8700_GetZOffset(void);
/*
** ===================================================================
** Method : GetZOffset (component FXOS8700CQ)
**
** Description :
** Returns the offset applied to the Z value.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
int16_t McuFXOS8700_GetX1gValue(void);
/*
** ===================================================================
** Method : GetX1gValue (component FXOS8700CQ)
**
** Description :
** Returns the value for 1g for channel X.
** Parameters : None
** Returns :
** --- - 1g value for X
** ===================================================================
*/
int16_t McuFXOS8700_GetY1gValue(void);
/*
** ===================================================================
** Method : GetY1gValue (component FXOS8700CQ)
**
** Description :
** Returns the value for 1g for channel Y.
** Parameters : None
** Returns :
** --- - 1g value for Y
** ===================================================================
*/
int16_t McuFXOS8700_GetZ1gValue(void);
/*
** ===================================================================
** Method : GetZ1gValue (component FXOS8700CQ)
**
** Description :
** Returns the value for 1g for channel Z.
** Parameters : None
** Returns :
** --- - 1g value for Z
** ===================================================================
*/
int16_t McuFXOS8700_GetX(void);
/*
** ===================================================================
** Method : GetX (component FXOS8700CQ)
**
** Description :
** Retrieves the value for the X axis. The value is adjusted
** with the zero calibration value (0 for 0 g, negative for
** negative acceleration and positive for positive acceleration).
** Parameters : None
** Returns :
** --- - Measured X value
** ===================================================================
*/
int16_t McuFXOS8700_GetY(void);
/*
** ===================================================================
** Method : GetY (component FXOS8700CQ)
**
** Description :
** Retrieves the value for the Y axis. The value is adjusted
** with the zero calibration value (0 for 0 g, negative for
** negative acceleration and positive for positive acceleration).
** Parameters : None
** Returns :
** --- - Measured Y value
** ===================================================================
*/
int16_t McuFXOS8700_GetZ(void);
/*
** ===================================================================
** Method : GetZ (component FXOS8700CQ)
**
** Description :
** Retrieves the value for the Z axis. The value is adjusted
** with the zero calibration value (0 for 0 g, negative for
** negative acceleration and positive for positive acceleration).
** Parameters : None
** Returns :
** --- - Measured Z value
** ===================================================================
*/
uint8_t McuFXOS8700_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component FXOS8700CQ)
**
** Description :
** Shell Command Line parser. This method is enabled/disabled
** depending on if you have the Shell enabled/disabled in the
** properties.
** Parameters :
** NAME - DESCRIPTION
** * cmd - Pointer to command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** * io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_SetFastMode(bool on);
/*
** ===================================================================
** Method : SetFastMode (component FXOS8700CQ)
**
** Description :
** Turns the F_READ (Fast Read Mode) on or off
** Parameters :
** NAME - DESCRIPTION
** on - if to turn the F_READ mode on or off
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_Enable(void);
/*
** ===================================================================
** Method : Enable (component FXOS8700CQ)
**
** Description :
** Enables the device with setting the ACTIVE bit in the CTRL
** register 1
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_Disable(void);
/*
** ===================================================================
** Method : Disable (component FXOS8700CQ)
**
** Description :
** Disables the device with clearing the ACTIVE bit in the CTRL
** register 1
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_isEnabled(bool *isEnabled);
/*
** ===================================================================
** Method : isEnabled (component FXOS8700CQ)
**
** Description :
** Returns the status of the the ACTIVE bit in the CTRL
** register 1
** Parameters :
** NAME - DESCRIPTION
** * isEnabled - Pointer to where to store the
** result, TRUE if ACTIVE bit is set, FALSE
** otherwise
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuFXOS8700_WhoAmI(uint8_t *value);
/*
** ===================================================================
** Method : WhoAmI (component FXOS8700CQ)
**
** Description :
** Returns the value of the WHO_AM_I (0x0D) register
** Parameters :
** NAME - DESCRIPTION
** * value - Pointer to value to store
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_GetTemperature(int8_t *temperature);
/*
** ===================================================================
** Method : GetTemperature (component FXOS8700CQ)
**
** Description :
** Returns the temperature of the die as signed 8bit values in
** degree Celsius
** Parameters :
** NAME - DESCRIPTION
** * temperature - Pointer to variable where
** to store the temperature
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_GetMagX(int16_t *value);
/*
** ===================================================================
** Method : GetMagX (component FXOS8700CQ)
**
** Description :
** Returns the X magnetometer value.
** Parameters :
** NAME - DESCRIPTION
** * value - Pointer to where to store the value.
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_GetMagY(int16_t *value);
/*
** ===================================================================
** Method : GetMagY (component FXOS8700CQ)
**
** Description :
** Returns the Y magnetometer value.
** Parameters :
** NAME - DESCRIPTION
** * value - Pointer to where to store the value.
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_GetMagZ(int16_t *value);
/*
** ===================================================================
** Method : GetMagZ (component FXOS8700CQ)
**
** Description :
** Returns the Z magnetometer value.
** Parameters :
** NAME - DESCRIPTION
** * value - Pointer to where to store the value.
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_MagneticSensorReset(void);
/*
** ===================================================================
** Method : MagneticSensorReset (component FXOS8700CQ)
**
** Description :
** Initiates a magnetic sensor reset cycle that will restore
** correct operation after exposure to an excessive magnetic
** field which exceeds the Full Scale Range but is less than
** the Maximum Applied Magnetic Field.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_ReadReg8(uint8_t addr, uint8_t *val);
/*
** ===================================================================
** Method : ReadReg8 (component FXOS8700CQ)
**
** Description :
** Reads an 8bit device register
** Parameters :
** NAME - DESCRIPTION
** addr - device memory map address
** * val - Pointer to value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_WriteReg8(uint8_t addr, uint8_t val);
/*
** ===================================================================
** Method : WriteReg8 (component FXOS8700CQ)
**
** Description :
** Write an 8bit device register
** Parameters :
** NAME - DESCRIPTION
** addr - device memory map address
** val - value to write
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_SwReset(void);
/*
** ===================================================================
** Method : SwReset (component FXOS8700CQ)
**
** Description :
** Perform a software reset using the rst bit in the CTRL
** register 2
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_MagEnable(void);
/*
** ===================================================================
** Method : MagEnable (component FXOS8700CQ)
**
** Description :
** Enables the magnetometer
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuFXOS8700_MagDisable(void);
/*
** ===================================================================
** Method : MagDisable (component FXOS8700CQ)
**
** Description :
** Disables the magnetometer
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuFXOS8700. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuFXOS8700_H */
/*!
** @}
*/

View File

@@ -0,0 +1,609 @@
/*
* Copyright (c) 2021, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuFlash.h"
#if McuFlash_CONFIG_IS_ENABLED
#include "McuLib.h"
#if McuLib_CONFIG_CPU_IS_LPC || McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_RPxxxx /* currently limited support, only for these CPUs */
#include "McuLog.h"
#include "McuUtility.h"
#include "McuCriticalSection.h"
#if McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iap.h"
#elif McuLib_CONFIG_CPU_IS_KINETIS
#include "fsl_flash.h"
#include "fsl_smc.h"
#include "McuWait.h"
#elif McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_RP2040
#include "hardware/flash.h"
#include "hardware/sync.h"
#endif
typedef struct {
uint32_t addr;
size_t size;
} McuFlash_Memory;
static McuFlash_Memory McuFlash_RegisteredMemory; /* used in shell status, for information only */
#if McuLib_CONFIG_CPU_IS_LPC && (McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC845 || McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC804)
/* nothing needed */
#elif McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K22FN \
|| McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K22FX \
|| McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN \
|| McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC55S16
static flash_config_t s_flashDriver;
#elif McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_RP2040
/* nothing needed */
#else
#error "device not yet supported"
#endif
void McuFlash_RegisterMemory(const void *addr, size_t nofBytes) {
McuFlash_RegisteredMemory.addr = (uint32_t)addr;
McuFlash_RegisteredMemory.size = nofBytes;
}
bool McuFlash_IsAccessible(const void *addr, size_t nofBytes) {
#if McuLib_CONFIG_CPU_IS_LPC55xx
/* see https://community.nxp.com/t5/LPC-Microcontrollers-Knowledge/LPC55xx-Erased-Memory-State-0-or-1/ta-p/1135084 and
* https://www.nxp.com/docs/en/application-note/AN12949.pdf
* Accessing erased (and not written yet) memory causes a hard-fault.
*/
status_t status;
status = FLASH_VerifyErase(&s_flashDriver, (uint32_t)addr, nofBytes);
#if McuFlash_CONFIG_LOGGING_TRACE
McuLog_trace("IsAccessible: 0x%x, size %u, %s", (uint32_t)addr, nofBytes, status==kStatus_Success?"no":"yes");
#endif
if (status==kStatus_Success) {
return false; /* if it is an erased FLASH: accessing it will cause a hard fault! */
}
return true;
#else
return true;
#endif
}
bool McuFlash_IsErased(const void *addr, size_t nofBytes) {
#if McuLib_CONFIG_CPU_IS_LPC55xx
/* see https://community.nxp.com/t5/LPC-Microcontrollers-Knowledge/LPC55xx-Erased-Memory-State-0-or-1/ta-p/1135084 and
* https://www.nxp.com/docs/en/application-note/AN12949.pdf
* Accessing erased (and not written yet) memory causes a hard-fault.
*/
status_t status;
status = FLASH_VerifyErase(&s_flashDriver, (uint32_t)addr, nofBytes);
#if McuFlash_CONFIG_LOGGING_TRACE
McuLog_trace("IsErased: 0x%x, size %u, %s", (uint32_t)addr, nofBytes, status==kStatus_Success?"yes":"no");
#endif
return status==kStatus_Success; /* true if it is an erased FLASH: accessing it will cause a hard fault! */
#else
uint8_t *ptr = (uint8_t*)addr;
while (nofBytes>0) {
if (*ptr!=0xFF) {
return false; /* byte not erased */
}
ptr++;
nofBytes--;
}
return true;
#endif
}
uint8_t McuFlash_Read(const void *addr, void *data, size_t dataSize) {
#if McuFlash_CONFIG_LOGGING_TRACE
McuLog_trace("Read: 0x%x, size %u", (uint32_t)addr, dataSize);
#endif
if (!McuFlash_IsAccessible(addr, dataSize)) {
memset(data, 0xff, dataSize);
return ERR_FAULT;
}
#if McuLib_CONFIG_CPU_IS_LPC55xx
status_t status;
status = FLASH_Read(&s_flashDriver, (uint32_t)addr, data, (uint32_t)dataSize);
if(status != kStatus_Success){
return ERR_FAULT;
}
return ERR_OK;
#else
memcpy(data, addr, dataSize);
return ERR_OK;
#endif
}
static uint8_t McuFlash_ProgramPage(void *addr, const void *data, size_t dataSize) {
#if McuFlash_CONFIG_LOGGING_TRACE
McuLog_trace("ProgramPage: 0x%x, size %u", (uint32_t)addr, dataSize);
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
status_t status;
uint8_t res = ERR_OK;
if (McuFlash_Erase(addr, dataSize)!=ERR_OK) {
return ERR_FAILED;
}
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN || McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K22FN
/* need to switch to normal RUN mode for flash programming,
* with Fcore=60MHz Fbus=Fflash=20MHz
* see https://community.nxp.com/thread/377633
*/
status = SMC_SetPowerModeRun(SMC);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
McuWait_Waitms(1); /* give time to switch clock, otherwise flash programming might fail below */
#endif
/* program */
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN
uint32_t primask = DisableGlobalIRQ(); /* workaround: need to disable interrupts? */
#endif
for(;;) { /* breaks, switch back to HSRUN if things fail */
status = FLASH_Program(&s_flashDriver, (uint32_t)addr, (uint8_t*)data, dataSize);
if (status!=kStatus_FTFx_Success) {
res = ERR_FAILED;
break;
}
break;
} /* for */
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN
EnableGlobalIRQ(primask); /* workaround: need to disable interrupts? */
#endif
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN || McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K22FN
status = SMC_SetPowerModeHsrun(SMC);
if (status!=kStatus_Success) {
res = ERR_FAILED;
}
#endif
return res;
#elif McuLib_CONFIG_CPU_IS_LPC55xx
status_t status;
uint32_t failedAddress, failedData;
if (((uint32_t)addr%s_flashDriver.PFlashPageSize) != 0) {
McuLog_fatal("addr %08x must be aligned to flash page size %08x", (uint32_t)addr, s_flashDriver.PFlashPageSize);
return ERR_FAILED;
}
if (dataSize!=s_flashDriver.PFlashPageSize) { /* must match flash page size! */
McuLog_fatal("data size %08x must match flash page size %08x", dataSize, s_flashDriver.PFlashPageSize);
return ERR_FAILED;
}
/* erase first */
status = FLASH_Erase(&s_flashDriver, (uint32_t)addr, dataSize, kFLASH_ApiEraseKey);
if (status!=kStatus_Success ) {
McuLog_fatal("erasing failed with error code %d", status);
return ERR_FAILED;
}
/* check if it is erased */
status = FLASH_VerifyErase(&s_flashDriver, (uint32_t)addr, dataSize);
if (status!=kStatus_Success) {
McuLog_fatal("erase check failed");
return ERR_FAILED;
}
/* here the flash is erased, ready for getting programmed */
status = FLASH_Program(&s_flashDriver, (uint32_t)addr, (uint8_t*)data, dataSize);
if (status!=kStatus_Success) {
McuLog_fatal("failed programming flash, error %d", status);
return ERR_FAILED;
}
status = FLASH_VerifyProgram(&s_flashDriver, (uint32_t)addr, dataSize, (const uint8_t *)data, &failedAddress, &failedData);
if (status!=kStatus_Success) {
McuLog_fatal("failed verify at address %08x, data %08x", failedAddress, failedData);
return ERR_FAILED;
}
return ERR_OK;
#elif McuLib_CONFIG_CPU_IS_LPC && (McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC845 || McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC804)
uint32_t startSector = (uint32_t)addr/McuFlash_CONFIG_FLASH_BLOCK_SIZE; /* sector is 1k in size */
uint32_t endSector = ((uint32_t)addr+(McuFlash_CONFIG_FLASH_BLOCK_SIZE-1))/McuFlash_CONFIG_FLASH_BLOCK_SIZE;
uint8_t result = ERR_FAILED; /* default */
status_t res;
if (McuFlash_Erase(addr, dataSize)!=ERR_OK) {
return ERR_FAILED;
}
res = IAP_PrepareSectorForWrite(startSector, endSector); /* sector size is 1k */
if (res!=kStatus_IAP_Success) {
result = ERR_FAILED;
} else {
/* destination address should be on a 64byte boundary.
* Source address should be word (4byte) boundary
* data size (number of bytes) shall be 64, 128, 256, 512, 1024 bytes */
res = IAP_CopyRamToFlash((uint32_t)addr, (uint32_t*)data, dataSize, SystemCoreClock);
if (res!=kStatus_IAP_Success) {
result = ERR_FAILED;
} else {
res = IAP_Compare((uint32_t)addr, (uint32_t*)data, dataSize);
if (res!=kStatus_IAP_Success) {
result = ERR_FAILED;
} else {
result = ERR_OK;
}
}
}
return result;
#elif McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_RP2040
uint32_t base, size;
base = (uint32_t)addr-XIP_BASE;
if ((base%FLASH_PAGE_SIZE)!=0) {
return ERR_FAILED; /* address must be page size aligned! */
}
size = dataSize;
if ((size%FLASH_PAGE_SIZE)!=0) {
return ERR_FAILED; /* size must multiple of a page! */
}
/* first, erase the flash */
if (McuFlash_Erase(addr, dataSize)!=ERR_OK) {
return ERR_FAILED;
}
/* need to turn off interrupts. But: only for this core. If other core is running, problems might occur! */
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
flash_range_program(base, (const uint8_t *)data, size);
McuCriticalSection_ExitCritical();
return ERR_OK;
#else
#error "target not supported yet!"
return ERR_FAILED;
#endif /* McuLib_CONFIG_CPU_IS_KINETIS or McuLib_CONFIG_CPU_IS_LPC */
}
uint8_t McuFlash_Program(void *addr, const void *data, size_t dataSize) {
#if McuFlash_CONFIG_LOGGING_TRACE
McuLog_trace("Program: 0x%x, size %u", (uint32_t)addr, dataSize);
#endif
#if McuLib_CONFIG_CPU_IS_LPC55xx
if (((uint32_t)addr%McuFlash_CONFIG_FLASH_BLOCK_SIZE) != 0 || (dataSize!=McuFlash_CONFIG_FLASH_BLOCK_SIZE)) {
/* address and size not aligned to page boundaries: make backup into buffer */
uint8_t buffer[McuFlash_CONFIG_FLASH_BLOCK_SIZE];
uint8_t res;
size_t offset, remaining, size;
uint32_t pageAddr; /* address of page */
pageAddr = ((uint32_t)addr/McuFlash_CONFIG_FLASH_BLOCK_SIZE)*McuFlash_CONFIG_FLASH_BLOCK_SIZE;
offset = (uint32_t)addr%McuFlash_CONFIG_FLASH_BLOCK_SIZE; /* offset inside page */
remaining = dataSize;
while (remaining>0) {
res = McuFlash_Read((void*)pageAddr, buffer, sizeof(buffer)); /* read current flash content */
if (res!=ERR_OK) {
McuLog_fatal("failed reading from Flash at 0x%x", pageAddr);
return ERR_FAILED;
}
if (offset+remaining>McuFlash_CONFIG_FLASH_BLOCK_SIZE) {
size = McuFlash_CONFIG_FLASH_BLOCK_SIZE-offset; /* how much we can copy in this step */
} else {
size = remaining;
}
memcpy(buffer+offset, data, size); /* merge original page with new data */
/* program new data/page */
res = McuFlash_ProgramPage((void*)pageAddr, buffer, sizeof(buffer));
if (res!=ERR_OK) {
McuLog_fatal("failed making backup from Flash at 0x%x", pageAddr);
return ERR_FAILED;
}
pageAddr += McuFlash_CONFIG_FLASH_BLOCK_SIZE;
offset = 0;
data += size;
remaining -= size;
} /* while */
return res;
} else { /* a full page to program */
return McuFlash_ProgramPage(addr, data, dataSize);
}
#else
return McuFlash_ProgramPage(addr, data, dataSize);
#endif
}
#if McuLib_CONFIG_CPU_IS_LPC55xx
uint8_t McuFlash_InitErase(void *addr, size_t nofBytes) {
/* LPC55Sxx specific: erases the memory, makes it inaccessible */
status_t status;
#if McuFlash_CONFIG_LOGGING_TRACE
McuLog_trace("InitErase: 0x%x, size %u", (uint32_t)addr, nofBytes);
#endif
if ((nofBytes%McuFlash_CONFIG_FLASH_BLOCK_SIZE)!=0) { /* check if size is multiple of page size */
McuLog_fatal("wrong erase data size %d, expected multiple %d", nofBytes, McuFlash_CONFIG_FLASH_BLOCK_SIZE);
return ERR_FAILED;
}
for(int i=0; i<nofBytes/McuFlash_CONFIG_FLASH_BLOCK_SIZE; i++) { /* erase and program each page */
/* erase each page */
status = FLASH_Erase(&s_flashDriver, (uint32_t)addr+i*McuFlash_CONFIG_FLASH_BLOCK_SIZE, McuFlash_CONFIG_FLASH_BLOCK_SIZE, kFLASH_ApiEraseKey);
if (status!=kStatus_Success ) {
McuLog_fatal("erasing failed with error code %d", status);
return ERR_FAILED;
}
}
return ERR_OK;
}
#endif
uint8_t McuFlash_Erase(void *addr, size_t nofBytes) {
#if McuFlash_CONFIG_LOGGING_TRACE
McuLog_trace("Erase: 0x%x, size %u", (uint32_t)addr, nofBytes);
#endif
#if McuLib_CONFIG_CPU_IS_LPC && (McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC845 || McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC804)
/* determine sector numbers based on block/sector size */
uint32_t startSector = (uint32_t)addr/McuFlash_CONFIG_FLASH_BLOCK_SIZE;
uint32_t endSector = (((uint32_t)addr+(McuFlash_CONFIG_FLASH_BLOCK_SIZE-1))/McuFlash_CONFIG_FLASH_BLOCK_SIZE);
status_t res;
if (McuFlash_IsErased(addr, nofBytes)) { /* already eased? */
return ERR_OK; /* yes, nothing to do */
}
res = IAP_BlankCheckSector(startSector, endSector);
if (res==kStatus_IAP_Success) { /* already erased */
return ERR_OK;
}
/* erase sector */
res = IAP_PrepareSectorForWrite(startSector, endSector);
if (res!=kStatus_IAP_Success) {
return ERR_FAILED;
}
res = IAP_EraseSector(startSector, endSector, SystemCoreClock);
if (res!=kStatus_IAP_Success) {
return ERR_FAILED;
}
res = IAP_BlankCheckSector(startSector, endSector);
if (res!=kStatus_IAP_Success) {
return ERR_FAILED;
}
return ERR_OK;
#elif McuLib_CONFIG_CPU_IS_KINETIS
uint32_t pflashSectorSize = 0;
status_t status;
uint8_t res = ERR_OK;
if (McuFlash_IsErased(addr, nofBytes)) { /* already eased? */
return ERR_OK; /* yes, nothing to do */
}
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN || McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K22FN
/* need to switch to normal RUN mode for flash programming,
* with Fcore=60MHz Fbus=Fflash=20MHz
* see https://community.nxp.com/thread/377633
*/
status = SMC_SetPowerModeRun(SMC);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
McuWait_Waitms(1); /* give time to switch clock, otherwise flash programming might fail below */
#endif
/* erase */
status = FLASH_GetProperty(&s_flashDriver, kFLASH_PropertyPflash0SectorSize, &pflashSectorSize);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
if (pflashSectorSize!=McuFlash_CONFIG_FLASH_BLOCK_SIZE) {
return ERR_FAILED;
}
for(;;) { /* breaks, switch back to HSRUN on Kinetis if things fail */
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN
uint32_t primask = DisableGlobalIRQ(); /* workaround: need to disable interrupts? */
#endif
status = FLASH_Erase(&s_flashDriver, (uint32_t)addr, nofBytes, kFTFx_ApiEraseKey);
if (status!=kStatus_FTFx_Success) {
res = ERR_FAILED;
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN
EnableGlobalIRQ(primask); /* workaround: need to disable interrupts? */
#endif
break; /* error, leave for(;;) loop */
}
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN
EnableGlobalIRQ(primask); /* workaround: need to disable interrupts? */
#endif
/* Verify sector if it's been erased. */
status = FLASH_VerifyErase(&s_flashDriver, (uint32_t)addr, nofBytes, kFTFx_MarginValueUser);
if (status!=kStatus_FTFx_Success) {
res = ERR_FAILED;
break;
}
break; /* leave loop */
} /* for */
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K02FN || McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_K22FN
status = SMC_SetPowerModeHsrun(SMC);
if (status!=kStatus_Success) {
res = ERR_FAILED;
}
#endif
return res;
#elif McuLib_CONFIG_CPU_IS_LPC55xx
static const uint8_t zeroBuffer[McuFlash_CONFIG_FLASH_BLOCK_SIZE]; /* initialized with zeros, buffer in FLASH to save RAM */
uint8_t res;
if ((nofBytes%McuFlash_CONFIG_FLASH_BLOCK_SIZE)!=0) { /* check if size is multiple of page size */
McuLog_fatal("wrong erase data size %d, expected multiple of %d", nofBytes, McuFlash_CONFIG_FLASH_BLOCK_SIZE);
return ERR_FAILED;
}
for(int i=0; i<nofBytes/McuFlash_CONFIG_FLASH_BLOCK_SIZE; i++) { /* erase and program each page */
res = McuFlash_Program(addr+i*McuFlash_CONFIG_FLASH_BLOCK_SIZE, zeroBuffer, sizeof(zeroBuffer));
if (res!=ERR_OK) {
return res;
}
}
return res;
#elif McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_RP2040
uint32_t base, size;
base = (uint32_t)addr-XIP_BASE; /* flash erase operation is without the XIP_BASE offset */
if ((base%FLASH_SECTOR_SIZE)!=0) {
return ERR_FAILED; /* address must be sector aligned! */
}
size = nofBytes;
if ((size%FLASH_SECTOR_SIZE)!=0) {
return ERR_FAILED; /* size must multiple of a sector! */
}
/* need to turn off interrupts. But: only for this core. If other core is running, problems might occur! */
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
flash_range_erase(base, size);
McuCriticalSection_ExitCritical();
return ERR_OK;
#else
#error "target not supported yet!"
#endif
}
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
uint8_t buf[48];
McuShell_SendStatusStr((unsigned char*)"McuFlash", (unsigned char*)"McuFlash status\r\n", io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"size 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), McuFlash_CONFIG_FLASH_BLOCK_SIZE);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" block", buf, io->stdOut);
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_RP2040
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"page 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), FLASH_PAGE_SIZE);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", sector 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), FLASH_SECTOR_SIZE);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", block 0x");
McuUtility_strcatNum32Hex(buf, sizeof(buf), FLASH_BLOCK_SIZE);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" Flash", buf, io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum32Hex(buf, sizeof(buf), PICO_FLASH_SIZE_BYTES);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", ");
McuUtility_strcatNum32u(buf, sizeof(buf), PICO_FLASH_SIZE_BYTES/(1024*1024));
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" MBytes\r\n");
McuShell_SendStatusStr((unsigned char*)" Size", buf, io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"base 0x");
McuUtility_strcatNum32Hex(buf, sizeof(buf), XIP_BASE);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" XIP", buf, io->stdOut);
#endif
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"addr 0x");
McuUtility_strcatNum32Hex(buf, sizeof(buf), McuFlash_RegisteredMemory.addr);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", size 0x");
McuUtility_strcatNum32Hex(buf, sizeof(buf), McuFlash_RegisteredMemory.size);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" registered", buf, io->stdOut);
return ERR_OK;
}
static uint8_t ReadData(void *hndl, uint32_t addr, uint8_t *buf, size_t bufSize) {
(void)hndl; /* not used */
if (!McuFlash_IsAccessible((void*)addr, bufSize)) {
memset(buf, 0xff, bufSize);
return ERR_FAILED;
}
memcpy(buf, (void*)addr, bufSize);
return ERR_OK;
}
uint8_t McuFlash_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
const unsigned char *p;
uint32_t addr32;
int32_t size;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, "McuFlash help")==0) {
McuShell_SendHelpStr((unsigned char*)"McuFlash", (const unsigned char*)"Group of flash ini commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" dump <start> <size>", (unsigned char*)"Dump memory data\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" erase <addr> <size>", (unsigned char*)"Erase memory at address\r\n", io->stdOut);
#if McuLib_CONFIG_CPU_IS_LPC55xx
McuShell_SendHelpStr((unsigned char*)" init <addr> <size>", (unsigned char*)"Initialize memory (erase only, no programming!)\r\n", io->stdOut);
#endif
*handled = TRUE;
return ERR_OK;
} else if ((McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0) || (McuUtility_strcmp((char*)cmd, "McuFlash status")==0)) {
*handled = TRUE;
return PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, "McuFlash dump ", sizeof("McuFlash dump ")-1)==0) {
*handled = TRUE;
p = cmd+sizeof("McuFlash dump ")-1;
if (McuUtility_xatoi(&p, (int32_t*)&addr32)==ERR_OK) {
if (McuUtility_xatoi(&p, &size)==ERR_OK && size>0) {
if (McuFlash_IsAccessible((void*)addr32, size)) {
(void)McuShell_PrintMemory(NULL, addr32, addr32+size-1, 4, 16, ReadData, io);
} else {
McuShell_SendStr((unsigned char*)"*** memory not accessible\r\n", io->stdErr);
return ERR_FAILED;
}
} else {
McuShell_SendStr((unsigned char*)"*** wrong end address\r\n", io->stdErr);
return ERR_FAILED;
}
} else {
McuShell_SendStr((unsigned char*)"*** wrong start address\r\n", io->stdErr);
return ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, "McuFlash erase ", sizeof("McuFlash erase ")-1)==0) {
*handled = TRUE;
p = cmd+sizeof("McuFlash erase ")-1;
if (McuUtility_xatoi(&p, (int32_t*)&addr32)==ERR_OK) {
if ((addr32%McuFlash_CONFIG_FLASH_BLOCK_SIZE)!=0) {
McuShell_SendStr((unsigned char*)"*** address is not flash block aligned\r\n", io->stdErr);
return ERR_FAILED;
}
if (McuUtility_xatoi(&p, &size)==ERR_OK) {
return McuFlash_Erase((void*)addr32, size);
} else {
McuShell_SendStr((unsigned char*)"*** failed scanning size\r\n", io->stdErr);
return ERR_FAILED;
}
}
#if McuLib_CONFIG_CPU_IS_LPC55xx
} else if (McuUtility_strncmp((char*)cmd, "McuFlash init ", sizeof("McuFlash init ")-1)==0) {
*handled = TRUE;
p = cmd+sizeof("McuFlash init ")-1;
if (McuUtility_xatoi(&p, (int32_t*)&addr32)==ERR_OK) {
if ((addr32%McuFlash_CONFIG_FLASH_BLOCK_SIZE)!=0) {
McuShell_SendStr((unsigned char*)"*** address is not flash block aligned\r\n", io->stdErr);
return ERR_FAILED;
}
if (McuUtility_xatoi(&p, &size)==ERR_OK) {
return McuFlash_InitErase((void*)addr32, size);
} else {
McuShell_SendStr((unsigned char*)"*** failed scanning size\r\n", io->stdErr);
return ERR_FAILED;
}
}
#endif
}
return ERR_OK;
}
void McuFlash_Deinit(void) {
}
void McuFlash_Init(void) {
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC55xx
status_t result; /* Return code from each flash driver function */
memset(&s_flashDriver, 0, sizeof(flash_config_t));
/* Setup flash driver structure for device and initialize variables. */
result = FLASH_Init(&s_flashDriver);
#if McuLib_CONFIG_CPU_IS_KINETIS
if (result!=kStatus_FTFx_Success) {
McuLog_fatal("McuFlash_Init() failed!");
for(;;) { /* error */ }
}
#elif McuLib_CONFIG_CPU_IS_LPC55xx
if (result!=kStatus_Success) {
McuLog_fatal("McuFlash_Init() failed!");
for(;;) { /* error */ }
}
#endif
#endif
}
#endif
#endif /* McuFlash_CONFIG_IS_ENABLED */

View File

@@ -0,0 +1,101 @@
/*
* Copyright (c) 2021, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MININI_MCUFLASH_H_
#define MININI_MCUFLASH_H_
#include "McuFlashconfig.h"
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Decides if memory is accessible. On some architectures it needs to be prepared first.
* \param addr Memory area to check
* \param nofBytes Number of bytes to check
* \return true if memory can be accessed, false otherwise
*/
bool McuFlash_IsAccessible(const void *addr, size_t nofBytes);
/*!
* \brief Decides if memory is erased or not.
* \param addr Memory area to check
* \param nofBytes Number of bytes to check
* \return true if memory is erased, false otherwise
*/
bool McuFlash_IsErased(const void *addr, size_t nofBytes);
/*!
* \brief Erases a memory area
* \param addr Memory area to erase
* \param nofBytes Number of bytes to erase
* \return Error code, ERR_OK if everything is fine
*/
uint8_t McuFlash_Erase(void *addr, size_t nofBytes);
/*!
* \brief For LPC55Sxx only: initializes memory with an erase, making it inaccessible
* \param addr Start address of memory, must be 0x200 aligned
* \param nofBytes Number of bytes, must be multiple if 0x200
* \return Error code, ERR_OK if everything is fine
*/
uint8_t McuFlash_InitErase(void *addr, size_t nofBytes);
/*!
* \brief Program the flash memory with data
* \param addr Address where to store the data
* \param data Pointer to the data
* \param dataSize Number of data bytes
* \return Error code, ERR_OK if everything is fine
*/
uint8_t McuFlash_Program(void *addr, const void *data, size_t dataSize);
/*!
* \brief Read the flash memory
* \param addr Address where to store the data
* \param data Pointer where to store the data
* \param dataSize Number of data bytes
* \return Error code, ERR_OK if everything is fine
*/
uint8_t McuFlash_Read(const void *addr, void *data, size_t dataSize);
/*!
* \brief Register a memory area. This is for information only, to print the information with the Shell status command.
* \param addr Start address of memory area
* \param nofBytes Number of bytes
*/
void McuFlash_RegisterMemory(const void *addr, size_t nofBytes);
#include "McuShell.h"
/*!
* \brief Shell command line parser
* \param cmd Pointer to the command string
* \param handled If command has been recognized and handled
* \param io I/O hander used for output
* \return Error code, ERR_OK if everything is fine
*/
uint8_t McuFlash_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*!
* \brief Module de-initialization
*/
void McuFlash_Deinit(void);
/*!
* \brief Module initialization
*/
void McuFlash_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MININI_MCUFLASH_H_ */

View File

@@ -0,0 +1,434 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuFontDisplay.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : FontDisplay
** Version : Component 01.201, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2023-12-20, 18:09, # CodeGen: 825
** Abstract :
** Driver to write fonts using GFont component
** Settings :
** Bean name : McuFontDisplay
** System :
** InhGDisplay : McuGDisplaySSD1306
** Contents :
** GetFontHeight - void McuFontDisplay_GetFontHeight(McuFontDisplay_Font *font,...
** GetStringHeight - McuFontDisplay_PixelDim McuFontDisplay_GetStringHeight(uint8_t *str,...
** GetCharWidth - void McuFontDisplay_GetCharWidth(uint8_t ch, McuFontDisplay_PixelDim...
** GetStringWidth - McuFontDisplay_PixelDim McuFontDisplay_GetStringWidth(uint8_t *str,...
** WriteString - void McuFontDisplay_WriteString(uint8_t *str, McuFontDisplay_PixelColor...
** WriteStringWidth - void McuFontDisplay_WriteStringWidth(uint8_t *str, McuFontDisplay_PixelColor...
** WriteChar - void McuFontDisplay_WriteChar(uint8_t ch, McuFontDisplay_PixelColor color,...
** Deinit - void McuFontDisplay_Deinit(void);
** Init - void McuFontDisplay_Init(void);
**
** * Copyright (c) 2011-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuFontDisplay.h
** @version 01.00
** @brief
** Driver to write fonts using GFont component
*/
/*!
** @addtogroup McuFontDisplay_module McuFontDisplay module documentation
** @{
*/
/* MODULE McuFontDisplay. */
#include "McuFontDisplay.h"
#include <stddef.h> /* for NULL */
/*
** ===================================================================
** Method : WriteChar (component FontDisplay)
**
** Description :
** Function to write a character at the start point. Set the
** start point with the function setCursor.
** Parameters :
** NAME - DESCRIPTION
** ch - the character to print
** color - Foreground color to be used (for the
** character pixels)
** * xCursor - Pointer to x position of character
** (upper left corner). On return this will
** contain the next x position.
** * yCursor - Pointer to y position of character
** (upper left corner). On return this will
** contain the next y position.
** * font - Pointer to font information
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_WriteChar(uint8_t ch, McuFontDisplay_PixelColor color, McuFontDisplay_PixelDim *xCursor, McuFontDisplay_PixelDim *yCursor, McuFontDisplay_Font *font)
{
PGFONT_CharInfo charStruct; /* font information */
uint8_t *data; /* actual character of string text[] */
uint8_t w; /* counter variable row bits of character */
uint8_t h; /* counter variable column bits of character */
McuFontDisplay_PixelDim currY;
McuFontDisplay_PixelDim currX;
signed char b; /* bit position in byte stream */
if (ch=='\t') { /* tabulator */
ch = ' '; /* use a space instead */
}
charStruct = font->GetFontChar((uint8_t)ch);
if (ch=='\n') { /* move to a new line */
*yCursor += font->boundingBoxHeight; /* set next cursor position */
return;
}
if (ch=='\r') { /* move to beginning of line */
return; /* do nothing. Only the caller may know what the beginning of line is */
}
data = (uint8_t*)charStruct->CharBMP; /* get the pointer */
if (data != NULL) { /* printable character. Only if we have a character info. This is not the case e.g. for \n */
currY = (McuFontDisplay_PixelDim)(*yCursor
+ font->boundingBoxHeight /* height of box. This includes the space between lines plus the space under the base line */
- font->lineSpaceBoxHeight /* space between two lines */
- font->underlineBoxHeight /* space below the base line */
- charStruct->offsetY
- charStruct->height);
currX = (McuFontDisplay_PixelDim)(*xCursor + charStruct->offsetX);
h = 0;
for(;;) { /* breaks, process line by line */
w = 0; /* width position */
b = 7; /* bit position, MSB first */
for(;;) { /* breaks, prints one pixel line */
if ((((*data)&(1<<b))>>b)==1) { /* note that we do not change the background pixels */
McuGDisplaySSD1306_PutPixel((McuFontDisplay_PixelDim)(currX+w), currY, color);
}
w++; /* width counter */
b--; /* next pixel */
if((b==-1)||(w==charStruct->width)) { /* last bit of byte reached or last bit of the width reached */
if(w==charStruct->width) { /* last bit of the row from the current character */
break; /* out of while loop */
} else {
b = 7;
data++; /* next byte */
}
}
} /* for */
data++; /* next byte */
h++; /* height counter increment */
currY++; /* one row up */
if(h==(charStruct->height)){ /* finished character */
break;
} /* next row of character */
} /* for */
*xCursor += charStruct->dwidth; /* set next cursor position */
} /* if printable character */
}
/*
** ===================================================================
** Method : WriteString (component FontDisplay)
**
** Description :
** Function to write a string or character at the startpoint.
** Set the startpoint with the function setCursor.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the character string
** color - Foreground color to be used (for the
** character pixels)
** * xCursor - Pointer to x position of first
** character (upper left corner). On return
** this will contain the next y position.
** * yCursor - Pointer to y position of character
** (upper left corner). On return this will
** contain the next y position.
** * font - Pointer to font information
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_WriteString(uint8_t *str, McuFontDisplay_PixelColor color, McuFontDisplay_PixelDim *xCursor, McuFontDisplay_PixelDim *yCursor, McuFontDisplay_Font *font)
{
McuFontDisplay_PixelDim x = *xCursor;
while(*str!='\0') {
if (*str=='\r') {
*xCursor = x;
} else if (*str=='\n') {
*xCursor = x;
*yCursor += font->boundingBoxHeight;
} else {
McuFontDisplay_WriteChar(*str, color, xCursor, yCursor, font);
}
str++;
}
}
/*
** ===================================================================
** Method : WriteStringWidth (component FontDisplay)
**
** Description :
** Function to write a string or character at the startpoint.
** Set the startpoint with the function setCursor. If the
** string reaches the given width, the text gets wrapped to a
** new line.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the character string
** color - Foreground color to be used (for the
** character pixels)
** * xCursor - Pointer to x position of first
** character (upper left corner). On return
** this will contain the next y position.
** * yCursor - Pointer to y position of character
** (upper left corner). On return this will
** contain the next y position.
** * font - Pointer to font information
** width - Maximum of width of the text box. If
** text reaches the end of the box, the text
** gets wrapped to a new line.
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_WriteStringWidth(uint8_t *str, McuFontDisplay_PixelColor color, McuFontDisplay_PixelDim *xCursor, McuFontDisplay_PixelDim *yCursor, McuFontDisplay_Font *font, McuFontDisplay_PixelDim width)
{
McuFontDisplay_PixelDim x = *xCursor;
while(*str!='\0') {
if (*str=='\r') {
*xCursor = x;
} else if (*str=='\n') {
*xCursor = x;
*yCursor += font->boundingBoxHeight;
} else {
if ((McuFontDisplay_PixelDim)((*xCursor - x) + ((PGFONT_CharInfo)(font->GetFontChar((uint8_t)*str)))->dwidth) >= width)
{ /* check if we would reach the end of the box: wrap to a new line */
*xCursor = x;
*yCursor += font->boundingBoxHeight;
}
McuFontDisplay_WriteChar(*str, color, xCursor, yCursor, font);
}
str++;
}
}
/*
** ===================================================================
** Method : GetCharWidth (component FontDisplay)
**
** Description :
** returns the width (in pixels) of a font character.
** Parameters :
** NAME - DESCRIPTION
** ch - character for which to calculate the width
** * charWidth - Pointer to width of the
** character in pixels (this is only for the
** character, without the space after the
** character)
** * totalWidth - Pointer to the total width
** of the character, including to the space
** after the character.
** * font - Pointer to font information
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_GetCharWidth(uint8_t ch, McuFontDisplay_PixelDim *charWidth, McuFontDisplay_PixelDim *totalWidth, McuFontDisplay_Font *font)
{
PGFONT_CharInfo charStruct;
charStruct = font->GetFontChar((uint8_t)ch);
if (charStruct != NULL) {
*charWidth = (McuFontDisplay_PixelDim)(charStruct->width+charStruct->offsetX);
*totalWidth = (McuFontDisplay_PixelDim)charStruct->dwidth;
} else {
*charWidth = 0;
*totalWidth = 0;
}
}
/*
** ===================================================================
** Method : GetStringWidth (component FontDisplay)
**
** Description :
** returns the width (in pixels) of a font string. For multiple
** line strings (separated by \
** ) or for strings with \r it returns the longest string
** length.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the string.
** * font - Pointer to font information
** * lastCharSpace - Pointer to the width
** of the last character space, useful if you
** combine multiple strings. The pointer may
** be NULL.
** Returns :
** --- - Error code
** ===================================================================
*/
McuFontDisplay_PixelDim McuFontDisplay_GetStringWidth(uint8_t *str, McuFontDisplay_Font *font, McuFontDisplay_PixelDim *lastCharSpace)
{
unsigned char *p; /* pointer to the actual character */
McuFontDisplay_PixelDim currWidth; /* current width of string */
McuFontDisplay_PixelDim maxWidth; /* maximum width of string */
McuFontDisplay_PixelDim maxWidthSpace; /* last space of maximum string */
McuFontDisplay_PixelDim charSpace; /* last character space */
McuFontDisplay_PixelDim charWidth, totalWidth; /* character and total width of character */
currWidth = maxWidth = 0;
charWidth = totalWidth = 0;
charSpace = maxWidthSpace = 0;
p = str;
for (;;) { /* breaks */
if (*p=='\n' || *p=='\r' || *p=='\0') { /* multi-line string */
currWidth -= charSpace; /* subtract last space */
if (currWidth > maxWidth) { /* remember maximum line */
maxWidth = currWidth;
maxWidthSpace = charSpace;
}
currWidth = charSpace = 0;
if (*p == '\0') {
break;
}
} else {
McuFontDisplay_GetCharWidth(*p, &charWidth, &totalWidth, font);
currWidth += totalWidth;
charSpace = (McuFontDisplay_PixelDim)(totalWidth-charWidth); /* calculate space of last/current character */
}
p++; /* next character */
} /* for */
if (lastCharSpace != NULL) {
*lastCharSpace = maxWidthSpace;
}
return maxWidth; /* return width */
}
/*
** ===================================================================
** Method : GetFontHeight (component FontDisplay)
**
** Description :
** returns the height (in pixels) of a font.
** Parameters :
** NAME - DESCRIPTION
** * font - Pointer to font information
** * charHeight - Pointer to height of the
** character in pixels.
** * totalHeight - Pointer to the total
** height of the character, including to the
** space below the character.
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_GetFontHeight(McuFontDisplay_Font *font, McuFontDisplay_PixelDim *charHeight, McuFontDisplay_PixelDim *totalHeight)
{
*charHeight = (McuFontDisplay_PixelDim)(font->boundingBoxHeight-font->lineSpaceBoxHeight);
*totalHeight = font->boundingBoxHeight;
}
/*
** ===================================================================
** Method : GetStringHeight (component FontDisplay)
**
** Description :
** returns the height (in pixels) of a font string. For
** multiple line strings (separated by newline) or for strings
** with \r it returns the longest list.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the string.
** * font - Pointer to font information
** * lastLineSpace - Pointer to the height
** of the last line space, useful if you
** combine multiple strings. The pointer may
** be NULL.
** Returns :
** --- - Error code
** ===================================================================
*/
McuFontDisplay_PixelDim McuFontDisplay_GetStringHeight(uint8_t *str, McuFontDisplay_Font *font, McuFontDisplay_PixelDim *lastLineSpace)
{
uint16_t nofLines;
McuFontDisplay_PixelDim charHeight, totalHeight;
if (*str == '\0') {
if (lastLineSpace != NULL) {
*lastLineSpace = 0;
}
return 0;
}
nofLines = 1;
while (*str != '\0') { /* breaks */
if (*str=='\n') { /* multi-line string */
nofLines++;
}
str++; /* next character */
}
McuFontDisplay_GetFontHeight(font, &charHeight, &totalHeight);
if (lastLineSpace != NULL) {
*lastLineSpace = (McuFontDisplay_PixelDim)(totalHeight-charHeight);
}
return (McuFontDisplay_PixelDim)((nofLines-1)*totalHeight + charHeight); /* return height */
}
/*
** ===================================================================
** Method : Deinit (component FontDisplay)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_Deinit(void)
{
/* nothing needed */
}
/*
** ===================================================================
** Method : Init (component FontDisplay)
**
** Description :
** Driver initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_Init(void)
{
/* nothing needed */
}
/* END McuFontDisplay. */
/*!
** @}
*/

View File

@@ -0,0 +1,281 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuFontDisplay.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : FontDisplay
** Version : Component 01.201, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2023-12-20, 18:09, # CodeGen: 825
** Abstract :
** Driver to write fonts using GFont component
** Settings :
** Bean name : McuFontDisplay
** System :
** InhGDisplay : McuGDisplaySSD1306
** Contents :
** GetFontHeight - void McuFontDisplay_GetFontHeight(McuFontDisplay_Font *font,...
** GetStringHeight - McuFontDisplay_PixelDim McuFontDisplay_GetStringHeight(uint8_t *str,...
** GetCharWidth - void McuFontDisplay_GetCharWidth(uint8_t ch, McuFontDisplay_PixelDim...
** GetStringWidth - McuFontDisplay_PixelDim McuFontDisplay_GetStringWidth(uint8_t *str,...
** WriteString - void McuFontDisplay_WriteString(uint8_t *str, McuFontDisplay_PixelColor...
** WriteStringWidth - void McuFontDisplay_WriteStringWidth(uint8_t *str, McuFontDisplay_PixelColor...
** WriteChar - void McuFontDisplay_WriteChar(uint8_t ch, McuFontDisplay_PixelColor color,...
** Deinit - void McuFontDisplay_Deinit(void);
** Init - void McuFontDisplay_Init(void);
**
** * Copyright (c) 2011-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuFontDisplay.h
** @version 01.00
** @brief
** Driver to write fonts using GFont component
*/
/*!
** @addtogroup McuFontDisplay_module McuFontDisplay module documentation
** @{
*/
#ifndef __McuFontDisplay_H
#define __McuFontDisplay_H
/* MODULE McuFontDisplay. */
#include "McuLib.h" /* SDK and API used */
#include "McuFontDisplayconfig.h" /* configuration */
#include "McuGDisplaySSD1306.h" /* Graphic display interface */
#include "McuGFont.h" /* Font interface */
#ifdef __cplusplus
extern "C" {
#endif
typedef McuGDisplaySSD1306_PixelDim McuFontDisplay_PixelDim; /* Type which can hold a integral type for the x/y pixel dimension. This is depending on the display used. */
typedef McuGDisplaySSD1306_PixelColor McuFontDisplay_PixelColor; /* Type defining the color type (depends on display used). */
typedef GFONT_Callbacks McuFontDisplay_Font; /* Pointer to GFONT_Callbacks */
void McuFontDisplay_WriteString(uint8_t *str, McuFontDisplay_PixelColor color, McuFontDisplay_PixelDim *xCursor, McuFontDisplay_PixelDim *yCursor, McuFontDisplay_Font *font);
/*
** ===================================================================
** Method : WriteString (component FontDisplay)
**
** Description :
** Function to write a string or character at the startpoint.
** Set the startpoint with the function setCursor.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the character string
** color - Foreground color to be used (for the
** character pixels)
** * xCursor - Pointer to x position of first
** character (upper left corner). On return
** this will contain the next y position.
** * yCursor - Pointer to y position of character
** (upper left corner). On return this will
** contain the next y position.
** * font - Pointer to font information
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_WriteChar(uint8_t ch, McuFontDisplay_PixelColor color, McuFontDisplay_PixelDim *xCursor, McuFontDisplay_PixelDim *yCursor, McuFontDisplay_Font *font);
/*
** ===================================================================
** Method : WriteChar (component FontDisplay)
**
** Description :
** Function to write a character at the start point. Set the
** start point with the function setCursor.
** Parameters :
** NAME - DESCRIPTION
** ch - the character to print
** color - Foreground color to be used (for the
** character pixels)
** * xCursor - Pointer to x position of character
** (upper left corner). On return this will
** contain the next x position.
** * yCursor - Pointer to y position of character
** (upper left corner). On return this will
** contain the next y position.
** * font - Pointer to font information
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_GetCharWidth(uint8_t ch, McuFontDisplay_PixelDim *charWidth, McuFontDisplay_PixelDim *totalWidth, McuFontDisplay_Font *font);
/*
** ===================================================================
** Method : GetCharWidth (component FontDisplay)
**
** Description :
** returns the width (in pixels) of a font character.
** Parameters :
** NAME - DESCRIPTION
** ch - character for which to calculate the width
** * charWidth - Pointer to width of the
** character in pixels (this is only for the
** character, without the space after the
** character)
** * totalWidth - Pointer to the total width
** of the character, including to the space
** after the character.
** * font - Pointer to font information
** Returns : Nothing
** ===================================================================
*/
McuFontDisplay_PixelDim McuFontDisplay_GetStringWidth(uint8_t *str, McuFontDisplay_Font *font, McuFontDisplay_PixelDim *lastCharSpace);
/*
** ===================================================================
** Method : GetStringWidth (component FontDisplay)
**
** Description :
** returns the width (in pixels) of a font string. For multiple
** line strings (separated by \
** ) or for strings with \r it returns the longest string
** length.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the string.
** * font - Pointer to font information
** * lastCharSpace - Pointer to the width
** of the last character space, useful if you
** combine multiple strings. The pointer may
** be NULL.
** Returns :
** --- - Error code
** ===================================================================
*/
void McuFontDisplay_GetFontHeight(McuFontDisplay_Font *font, McuFontDisplay_PixelDim *charHeight, McuFontDisplay_PixelDim *totalHeight);
/*
** ===================================================================
** Method : GetFontHeight (component FontDisplay)
**
** Description :
** returns the height (in pixels) of a font.
** Parameters :
** NAME - DESCRIPTION
** * font - Pointer to font information
** * charHeight - Pointer to height of the
** character in pixels.
** * totalHeight - Pointer to the total
** height of the character, including to the
** space below the character.
** Returns : Nothing
** ===================================================================
*/
McuFontDisplay_PixelDim McuFontDisplay_GetStringHeight(uint8_t *str, McuFontDisplay_Font *font, McuFontDisplay_PixelDim *lastLineSpace);
/*
** ===================================================================
** Method : GetStringHeight (component FontDisplay)
**
** Description :
** returns the height (in pixels) of a font string. For
** multiple line strings (separated by newline) or for strings
** with \r it returns the longest list.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the string.
** * font - Pointer to font information
** * lastLineSpace - Pointer to the height
** of the last line space, useful if you
** combine multiple strings. The pointer may
** be NULL.
** Returns :
** --- - Error code
** ===================================================================
*/
void McuFontDisplay_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component FontDisplay)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_Init(void);
/*
** ===================================================================
** Method : Init (component FontDisplay)
**
** Description :
** Driver initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuFontDisplay_WriteStringWidth(uint8_t *str, McuFontDisplay_PixelColor color, McuFontDisplay_PixelDim *xCursor, McuFontDisplay_PixelDim *yCursor, McuFontDisplay_Font *font, McuFontDisplay_PixelDim width);
/*
** ===================================================================
** Method : WriteStringWidth (component FontDisplay)
**
** Description :
** Function to write a string or character at the startpoint.
** Set the startpoint with the function setCursor. If the
** string reaches the given width, the text gets wrapped to a
** new line.
** Parameters :
** NAME - DESCRIPTION
** * str - Pointer to the character string
** color - Foreground color to be used (for the
** character pixels)
** * xCursor - Pointer to x position of first
** character (upper left corner). On return
** this will contain the next y position.
** * yCursor - Pointer to y position of character
** (upper left corner). On return this will
** contain the next y position.
** * font - Pointer to font information
** width - Maximum of width of the text box. If
** text reaches the end of the box, the text
** gets wrapped to a new line.
** Returns : Nothing
** ===================================================================
*/
/* END McuFontDisplay. */
#ifdef __cplusplus
}
#endif
#endif
/* ifndef __McuFontDisplay_H */
/*!
** @}
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,700 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuGDisplaySSD1306.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : GDisplay
** Version : Component 01.211, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-09, 10:10, # CodeGen: 829
** Abstract :
** Graphical display driver for LCD or other displays
** Settings :
** Component name : McuGDisplaySSD1306
** SDK : McuLib
** Inverted Pixels : no
** Memory Buffer : Enabled
** Orientation : Landscape
** Clear screen on Init : no
** Hardware :
** Display : McuSSD1306
** Watchdog : Disabled
** RTOS : Disabled
** Contents :
** PutPixel - void McuGDisplaySSD1306_PutPixel(McuGDisplaySSD1306_PixelDim x,...
** SetPixel - void McuGDisplaySSD1306_SetPixel(McuGDisplaySSD1306_PixelDim x,...
** ClrPixel - void McuGDisplaySSD1306_ClrPixel(McuGDisplaySSD1306_PixelDim x,...
** Clear - void McuGDisplaySSD1306_Clear(void);
** DrawBox - void McuGDisplaySSD1306_DrawBox(McuGDisplaySSD1306_PixelDim x,...
** DrawFilledBox - void McuGDisplaySSD1306_DrawFilledBox(McuGDisplaySSD1306_PixelDim x,...
** DrawHLine - void McuGDisplaySSD1306_DrawHLine(McuGDisplaySSD1306_PixelDim x,...
** DrawVLine - void McuGDisplaySSD1306_DrawVLine(McuGDisplaySSD1306_PixelDim x,...
** DrawLine - void McuGDisplaySSD1306_DrawLine(McuGDisplaySSD1306_PixelDim xstart,...
** DrawCircle - void McuGDisplaySSD1306_DrawCircle(McuGDisplaySSD1306_PixelDim x0,...
** DrawFilledCircle - void McuGDisplaySSD1306_DrawFilledCircle(McuGDisplaySSD1306_PixelDim x0,...
** DrawBarChart - void McuGDisplaySSD1306_DrawBarChart(McuGDisplaySSD1306_PixelDim x,...
** DrawMonoBitmap - void McuGDisplaySSD1306_DrawMonoBitmap(int16_t x, int16_t y, PIMAGE image,...
** DrawMonoBitmapMask - void McuGDisplaySSD1306_DrawMonoBitmapMask(McuGDisplaySSD1306_PixelDim x,...
** DrawColorBitmap - void McuGDisplaySSD1306_DrawColorBitmap(McuGDisplaySSD1306_PixelDim x,...
** Draw65kBitmap - void McuGDisplaySSD1306_Draw65kBitmap(McuGDisplaySSD1306_PixelDim x1,...
** Draw256BitmapLow - void McuGDisplaySSD1306_Draw256BitmapLow(McuGDisplaySSD1306_PixelDim x1,...
** Draw256BitmapHigh - void McuGDisplaySSD1306_Draw256BitmapHigh(McuGDisplaySSD1306_PixelDim x1,...
** UpdateFull - void McuGDisplaySSD1306_UpdateFull(void);
** UpdateRegion - void McuGDisplaySSD1306_UpdateRegion(McuGDisplaySSD1306_PixelDim x,...
** GetDisplayOrientation - McuGDisplaySSD1306_DisplayOrientation M...
** SetDisplayOrientation - void McuGDisplaySSD1306_SetDisplayOrien...
** GetWidth - McuGDisplaySSD1306_PixelDim McuGDisplaySSD1306_GetWidth(void);
** GetHeight - McuGDisplaySSD1306_PixelDim McuGDisplaySSD1306_GetHeight(void);
** GetLongerSide - McuGDisplaySSD1306_PixelDim McuGDisplaySSD1306_GetLongerSide(void);
** GetShorterSide - McuGDisplaySSD1306_PixelDim McuGDisplaySSD1306_GetShorterSide(void);
** GetDisplay - void McuGDisplaySSD1306_GetDisplay(void);
** GiveDisplay - void McuGDisplaySSD1306_GiveDisplay(void);
** Deinit - void McuGDisplaySSD1306_Deinit(void);
** Init - void McuGDisplaySSD1306_Init(void);
**
** * Copyright (c) 2013-2023, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuGDisplaySSD1306.h
** @version 01.00
** @brief
** Graphical display driver for LCD or other displays
*/
/*!
** @addtogroup McuGDisplaySSD1306_module McuGDisplaySSD1306 module documentation
** @{
*/
#ifndef __McuGDisplaySSD1306_H
#define __McuGDisplaySSD1306_H
/* MODULE McuGDisplaySSD1306. */
#include "McuLib.h" /* SDK and API used */
#include "McuGDisplaySSD1306config.h" /* configuration */
#include McuGDisplaySSD1306_CONFIG_DISPLAY_HEADER_FILE
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _TIMAGE_IS_DEFINED
#define _TIMAGE_IS_DEFINED
/* this type is declared in PE_Types.h for non-LDD processors, need to declare it locally otherwise */
typedef struct { /* Image */
uint16_t width; /* Image width */
uint16_t height; /* Image height */
const uint8_t *pixmap; /* Image pixel bitmap */
uint16_t size; /* Image size */
const char *name; /* Image name */
} TIMAGE;
typedef TIMAGE* PIMAGE ; /* Pointer to image */
#endif /* _TIMAGE_IS_DEFINED */
#include "McuSSD1306.h"
#define McuGDisplaySSD1306_RGB565(R,G,B) ((McuGDisplaySSD1306_PixelColor)((((R)&0x1f)<<11)+(((G)&0x3f)<<5)+((B)&0x1f))) /* convert RGB into 565 color format */
#define McuGDisplaySSD1306_COLOR_PIXEL_SET McuSSD1306_COLOR_PIXEL_SET /* value for a pixel set */
#define McuGDisplaySSD1306_COLOR_PIXEL_CLR McuSSD1306_COLOR_PIXEL_CLR /* value for a pixel cleared */
#if McuGDisplaySSD1306_CONFIG_INVERTED_PIXEL_COLOR
#define McuGDisplaySSD1306_COLOR_BLACK McuSSD1306_COLOR_WHITE /* white color */
#define McuGDisplaySSD1306_COLOR_WHITE McuSSD1306_COLOR_BLACK /* black color */
#define McuGDisplaySSD1306_COLOR_RED (~McuSSD1306_COLOR_RED) /* red color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_RED (~McuSSD1306_COLOR_BRIGHT_RED) /* bright red color */
#define McuGDisplaySSD1306_COLOR_DARK_RED (~McuSSD1306_COLOR_DARK_RED) /* dark red color */
#define McuGDisplaySSD1306_COLOR_GREEN (~McuSSD1306_COLOR_GREEN) /* green color */
#define McuGDisplaySSD1306_COLOR_DARK_GREEN (~McuSSD1306_COLOR_DARK_GREEN) /* dark green color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_GREEN (~McuSSD1306_COLOR_BRIGHT_GREEN) /* bright green color */
#define McuGDisplaySSD1306_COLOR_BLUE (~McuSSD1306_COLOR_BLUE) /* blue color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_BLUE (~McuSSD1306_COLOR_BRIGHT_BLUE) /* bright blue color */
#define McuGDisplaySSD1306_COLOR_DARK_BLUE (~McuSSD1306_COLOR_DARK_BLUE) /* dark blue color */
#define McuGDisplaySSD1306_COLOR_YELLOW (~McuSSD1306_COLOR_YELLOW) /* yellow color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_YELLOW (~McuSSD1306_COLOR_BRIGHT_YELLOW)/* bright yellow color */
#define McuGDisplaySSD1306_COLOR_ORANGE (~McuSSD1306_COLOR_ORANGE) /* orange color */
#define McuGDisplaySSD1306_COLOR_GREY (~McuSSD1306_COLOR_GREY) /* grey color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_GREY (~McuSSD1306_COLOR_BRIGHT_GREY) /* bright grey color */
#else
#define McuGDisplaySSD1306_COLOR_BLACK McuSSD1306_COLOR_BLACK /* black color */
#define McuGDisplaySSD1306_COLOR_WHITE McuSSD1306_COLOR_WHITE /* white color */
#define McuGDisplaySSD1306_COLOR_RED McuSSD1306_COLOR_RED /* red color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_RED McuSSD1306_COLOR_BRIGHT_RED /* bright red color */
#define McuGDisplaySSD1306_COLOR_DARK_RED McuSSD1306_COLOR_DARK_RED /* dark red color */
#define McuGDisplaySSD1306_COLOR_GREEN McuSSD1306_COLOR_GREEN /* green color */
#define McuGDisplaySSD1306_COLOR_DARK_GREEN McuSSD1306_COLOR_DARK_GREEN /* dark green color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_GREEN McuSSD1306_COLOR_BRIGHT_GREEN /* bright green color */
#define McuGDisplaySSD1306_COLOR_BLUE McuSSD1306_COLOR_BLUE /* blue color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_BLUE McuSSD1306_COLOR_BRIGHT_BLUE /* bright blue color */
#define McuGDisplaySSD1306_COLOR_DARK_BLUE McuSSD1306_COLOR_DARK_BLUE /* dark blue color */
#define McuGDisplaySSD1306_COLOR_YELLOW McuSSD1306_COLOR_YELLOW /* yellow color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_YELLOW McuSSD1306_COLOR_BRIGHT_YELLOW /* bright yellow color */
#define McuGDisplaySSD1306_COLOR_ORANGE McuSSD1306_COLOR_ORANGE /* orange color */
#define McuGDisplaySSD1306_COLOR_GREY McuSSD1306_COLOR_GREY /* grey color */
#define McuGDisplaySSD1306_COLOR_BRIGHT_GREY McuSSD1306_COLOR_BRIGHT_GREY /* bright grey color */
#endif
typedef McuSSD1306_PixelDim McuGDisplaySSD1306_PixelDim; /* Display specific type for a pixel coordinate. */
typedef McuSSD1306_PixelColor McuGDisplaySSD1306_PixelColor; /* Display specific color type. */
typedef McuSSD1306_PixelCount McuGDisplaySSD1306_PixelCount; /* Type able to hold the number of pixels for the display. */
/* wrappers for the low level display orientation enumeration and type */
typedef McuSSD1306_DisplayOrientation McuGDisplaySSD1306_DisplayOrientation;
#define McuGDisplaySSD1306_ORIENTATION_PORTRAIT McuSSD1306_ORIENTATION_PORTRAIT
#define McuGDisplaySSD1306_ORIENTATION_PORTRAIT180 McuSSD1306_ORIENTATION_PORTRAIT180
#define McuGDisplaySSD1306_ORIENTATION_LANDSCAPE McuSSD1306_ORIENTATION_LANDSCAPE
#define McuGDisplaySSD1306_ORIENTATION_LANDSCAPE180 McuSSD1306_ORIENTATION_LANDSCAPE180
/* using Memory Buffer */
/* Landscape */
#define McuGDisplaySSD1306_BUF_BYTE(x,y) /* how to access a byte in the display buf[][] */ \
/* one bit per pixel */\
McuSSD1306_DisplayBuf[(y)/8][x]
#if McuGDisplaySSD1306_CONFIG_NOF_BITS_PER_PIXEL==1
#define McuGDisplaySSD1306_BUF_BYTE_PIXEL_BIT_NO(x,y) /* pixel bit number inside display buffer byte (0 is LSB, 7 MSB) */ \
((uint8_t)((y)%8))
#endif
#if McuGDisplaySSD1306_CONFIG_NOF_BITS_PER_PIXEL==1
#define McuGDisplaySSD1306_BUF_BYTE_PIXEL_MASK(x,y) /* pixel mask for an individual bit inside a display buffer byte */ \
(1<<McuGDisplaySSD1306_BUF_BYTE_PIXEL_BIT_NO(x,y))
#define McuGDisplaySSD1306_BUF_BYTE_GET_PIXEL(x,y) /* extract a pixel */ \
((McuGDisplaySSD1306_BUF_BYTE(x,y)&McuGDisplaySSD1306_BUF_BYTE_PIXEL_MASK(x,y))>>McuGDisplaySSD1306_BUF_BYTE_PIXEL_BIT_NO(x,y))
#elif McuGDisplaySSD1306_CONFIG_NOF_BITS_PER_PIXEL==8
#define McuGDisplaySSD1306_BUF_BYTE_PIXEL_MASK(x,y) /* pixel mask for an individual bit inside a display buffer byte */ \
0xff
#define McuGDisplaySSD1306_BUF_BYTE_GET_PIXEL(x,y) /* extract a pixel */ \
McuGDisplaySSD1306_BUF_BYTE(x,y)
#elif McuGDisplaySSD1306_CONFIG_NOF_BITS_PER_PIXEL==16
/* no byte access used */
#elif McuGDisplaySSD1306_CONFIG_NOF_BITS_PER_PIXEL==24
/* Neopixels, no byte access used */
#else
#error "not supported"
#endif
void McuGDisplaySSD1306_Clear(void);
/*
** ===================================================================
** Method : Clear (component GDisplay)
**
** Description :
** Clears the display buffer.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_SetPixel(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y);
/*
** ===================================================================
** Method : SetPixel (component GDisplay)
**
** Description :
** Sets a pixel in the display buffer
** Parameters :
** NAME - DESCRIPTION
** x - Pixel x position
** y - Pixel y position
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_ClrPixel(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y);
/*
** ===================================================================
** Method : ClrPixel (component GDisplay)
**
** Description :
** Clears a single pixel in the display.
** Parameters :
** NAME - DESCRIPTION
** x - Pixel x position.
** y - Pixel y position.
** Returns : Nothing
** ===================================================================
*/
#define McuGDisplaySSD1306_UpdateFull() McuSSD1306_UpdateFull()
/*
** ===================================================================
** Method : UpdateFull (component GDisplay)
**
** Description :
** Updates the image on the display. This is needed in case the
** display requires a periodic refresh. For display using
** windowing, this function may be implemented as dummy stub,
** as the display content already is written.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawFilledBox(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, McuGDisplaySSD1306_PixelDim width, McuGDisplaySSD1306_PixelDim height, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : DrawFilledBox (component GDisplay)
**
** Description :
** Draws a rectangle box (filled)
** Parameters :
** NAME - DESCRIPTION
** x - x left upper coordinate
** y - y left upper coordinate
** width - Width in pixels
** height - Height in pixels
** color - color to be used to fill the box.
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_PutPixel(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : PutPixel (component GDisplay)
**
** Description :
**
** Parameters :
** NAME - DESCRIPTION
** x - x coordinate
** y - y coordinate
** color - color to be used for the pixel
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawBox(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, McuGDisplaySSD1306_PixelDim width, McuGDisplaySSD1306_PixelDim height, McuGDisplaySSD1306_PixelDim lineWidth, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : DrawBox (component GDisplay)
**
** Description :
** Draws a rectangle line box
** Parameters :
** NAME - DESCRIPTION
** x - x left upper coordinate
** y - y left upper coordinate
** width - width in pixels
** height - height in pixels
** lineWidth - width of the line
** color - color for the box
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawMonoBitmap(int16_t x, int16_t y, PIMAGE image, McuGDisplaySSD1306_PixelColor pixelColor, McuGDisplaySSD1306_PixelColor backgroundColor);
/*
** ===================================================================
** Method : DrawMonoBitmap (component GDisplay)
**
** Description :
** Draws a B/W bitmap.
** Parameters :
** NAME - DESCRIPTION
** x - x position of left upper corner
** y - y position of left upper corner
** image - Pointer to image structure and
** information.
** pixelColor - Color to be used for pixels
** (pixel set)
** backgroundColor - Color to be used
** for background (pixel not set)
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawHLine(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, McuGDisplaySSD1306_PixelDim length, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : DrawHLine (component GDisplay)
**
** Description :
** Draws a horizontal line
** Parameters :
** NAME - DESCRIPTION
** x - x left upper coordinate
** y - y left upper coordinate
** length - Length of line in pixels
** color - color to be used to fill the box.
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawVLine(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, McuGDisplaySSD1306_PixelDim length, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : DrawVLine (component GDisplay)
**
** Description :
** Draws a vertical line
** Parameters :
** NAME - DESCRIPTION
** x - x left upper coordinate
** y - y left upper coordinate
** length - Length of line in pixels
** color - color to be used to fill the box.
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawBarChart(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, McuGDisplaySSD1306_PixelDim width, McuGDisplaySSD1306_PixelDim height, uint8_t *data, uint8_t nofData, McuGDisplaySSD1306_PixelColor barColor, uint8_t borderWidth, McuGDisplaySSD1306_PixelColor borderColor, uint8_t borderSpace);
/*
** ===================================================================
** Method : DrawBarChart (component GDisplay)
**
** Description :
** Draws a series of bars for a chart
** Parameters :
** NAME - DESCRIPTION
** x - upper left corner x coordinate
** y - upper left corner y coordinate
** width - Chart box width
** height - Chart box height
** * data - Pointer to data (series of % values
** from 0...100%)
** nofData - number of data bytes
** barColor - Color to be used for the bars.
** borderWidth - width of a border to be
** draw. Pass zero if there shall be no border.
** borderColor - Color to be used for the
** border (if borderWidth is not zero)
** borderSpace - Space to be used in pixels
** between border and bars.
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawColorBitmap(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, PIMAGE image);
/*
** ===================================================================
** Method : DrawColorBitmap (component GDisplay)
**
** Description :
** Draws a color bitmap. Pixel data is in 3-3-2 RGB format.
** Parameters :
** NAME - DESCRIPTION
** x - x position of left upper corner
** y - y position of left upper corner
** image - Pointer to image structure and
** information.
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawLine(McuGDisplaySSD1306_PixelDim xstart, McuGDisplaySSD1306_PixelDim ystart, McuGDisplaySSD1306_PixelDim xend, McuGDisplaySSD1306_PixelDim yend, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : DrawLine (component GDisplay)
**
** Description :
** Draws a line using the Bresenham method
** Parameters :
** NAME - DESCRIPTION
** xstart - x start coordinate
** ystart - y start coordinate
** xend - x end coordinate
** yend - y end coordinate
** color - color to be used for the line
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawCircle(McuGDisplaySSD1306_PixelDim x0, McuGDisplaySSD1306_PixelDim y0, McuGDisplaySSD1306_PixelDim radius, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : DrawCircle (component GDisplay)
**
** Description :
** Draws a circle using the Bresenham method
** Parameters :
** NAME - DESCRIPTION
** x0 - x start coordinate
** y0 - y start coordinate
** radius - Radius of the circle
** color - color to be used for the line
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_Draw65kBitmap(McuGDisplaySSD1306_PixelDim x1, McuGDisplaySSD1306_PixelDim y1, McuGDisplaySSD1306_PixelDim x2, McuGDisplaySSD1306_PixelDim y2, uint16_t *bmp, bool compressed);
/*
** ===================================================================
** Method : Draw65kBitmap (component GDisplay)
**
** Description :
** Draws a 65k color bitmap (compressed or uncompressed)
** Parameters :
** NAME - DESCRIPTION
** x1 - left upper starting corner
** y1 - left upper starting corner
** x2 - right lower corner
** y2 - right lower corner
** * bmp - Pointer to bitmap
** compressed -
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_Draw256BitmapLow(McuGDisplaySSD1306_PixelDim x1, McuGDisplaySSD1306_PixelDim y1, McuGDisplaySSD1306_PixelDim x2, McuGDisplaySSD1306_PixelDim y2, uint8_t *bmp, bool compressed);
/*
** ===================================================================
** Method : Draw256BitmapLow (component GDisplay)
**
** Description :
** Draws a 256 color bitmap (compressed or uncompressed)
** Parameters :
** NAME - DESCRIPTION
** x1 - left upper starting corner
** y1 - left upper starting corner
** x2 - right lower corner
** y2 - right lower corner
** * bmp - Pointer to bitmap
** compressed -
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_Draw256BitmapHigh(McuGDisplaySSD1306_PixelDim x1, McuGDisplaySSD1306_PixelDim y1, McuGDisplaySSD1306_PixelDim x2, McuGDisplaySSD1306_PixelDim y2, uint8_t *bmp, McuGDisplaySSD1306_PixelColor *ColorTable, bool compressed);
/*
** ===================================================================
** Method : Draw256BitmapHigh (component GDisplay)
**
** Description :
** Draws a 256 color bitmap (compressed or uncompressed) with a
** color table.
** Parameters :
** NAME - DESCRIPTION
** x1 - left upper starting corner
** y1 - left upper starting corner
** x2 - right lower corner
** y2 - right lower corner
** * bmp - Pointer to bitmap
** * ColorTable - Pointer to array of colors
** (color table)
** compressed -
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_UpdateRegion(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, McuGDisplaySSD1306_PixelDim w, McuGDisplaySSD1306_PixelDim h);
/*
** ===================================================================
** Method : UpdateRegion (component GDisplay)
**
** Description :
** Update a region of the display.
** Parameters :
** NAME - DESCRIPTION
** x - x coordinate
** y - y coordinate
** w - Width of the update region
** h - height of the update region
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawFilledCircle(McuGDisplaySSD1306_PixelDim x0, McuGDisplaySSD1306_PixelDim y0, McuGDisplaySSD1306_PixelDim radius, McuGDisplaySSD1306_PixelColor color);
/*
** ===================================================================
** Method : DrawFilledCircle (component GDisplay)
**
** Description :
** Draws a circle using the Bresenham method
** Parameters :
** NAME - DESCRIPTION
** x0 - x start coordinate
** y0 - y start coordinate
** radius - Radius of the circle
** color - fill color to be used
** Returns : Nothing
** ===================================================================
*/
#define McuGDisplaySSD1306_GetDisplayOrientation McuSSD1306_GetDisplayOrientation
/*
** ===================================================================
** Method : GetDisplayOrientation (component GDisplay)
**
** Description :
** Returns the current display orientation
** Parameters : None
** Returns :
** --- - current display orientation
** ===================================================================
*/
#define McuGDisplaySSD1306_SetDisplayOrientation McuSSD1306_SetDisplayOrientation
/*
** ===================================================================
** Method : SetDisplayOrientation (component GDisplay)
**
** Description :
** Sets the display orientation. If you enable this method,
** then the orientation of the display can be changed at
** runtime. However, this requires additional resources.
** Parameters :
** NAME - DESCRIPTION
** newOrientation - new orientation to
** be used
** Returns : Nothing
** ===================================================================
*/
#define McuGDisplaySSD1306_GetWidth McuSSD1306_GetWidth
/*
** ===================================================================
** Method : GetWidth (component GDisplay)
**
** Description :
** Returns the width of the display in pixels (in x direction)
** Parameters : None
** Returns :
** --- - pixel count
** ===================================================================
*/
#define McuGDisplaySSD1306_GetHeight McuSSD1306_GetHeight
/*
** ===================================================================
** Method : GetHeight (component GDisplay)
**
** Description :
** Returns the height of the display in pixels (in y direction)
** Parameters : None
** Returns :
** --- - pixel count
** ===================================================================
*/
#define McuGDisplaySSD1306_GetLongerSide McuSSD1306_GetLongerSide
/*
** ===================================================================
** Method : GetLongerSide (component GDisplay)
**
** Description :
** Returns the size of the longer side of the display
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
#define McuGDisplaySSD1306_GetShorterSide McuSSD1306_GetShorterSide
/*
** ===================================================================
** Method : GetShorterSide (component GDisplay)
**
** Description :
** Returns the size of the shorter side of the display
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
void McuGDisplaySSD1306_GetDisplay(void);
/*
** ===================================================================
** Method : GetDisplay (component GDisplay)
**
** Description :
** Method used to reserve the display (for mutual exclusive
** access)
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_GiveDisplay(void);
/*
** ===================================================================
** Method : GiveDisplay (component GDisplay)
**
** Description :
** Returns the display after having it reserved with
** GetDisplay()
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_Init(void);
/*
** ===================================================================
** Method : Init (component GDisplay)
**
** Description :
** Driver initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component GDisplay)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGDisplaySSD1306_DrawMonoBitmapMask(McuGDisplaySSD1306_PixelDim x, McuGDisplaySSD1306_PixelDim y, PIMAGE image, McuGDisplaySSD1306_PixelColor pixelColor);
/*
** ===================================================================
** Method : DrawMonoBitmapMask (component GDisplay)
**
** Description :
** Draws a B/W bitmap, but only the pixels which are set
** Parameters :
** NAME - DESCRIPTION
** x - x position of left upper corner
** y - y position of left upper corner
** image - Pointer to image structure and
** information.
** pixelColor - Color to be used for pixels
** (pixel set)
** Returns : Nothing
** ===================================================================
*/
/* END McuGDisplaySSD1306. */
#ifdef __cplusplus
}
#endif
#endif
/* ifndef __McuGDisplaySSD1306_H */
/*!
** @}
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,218 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuGFont.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : GFont
** Version : Component 01.131, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-13, 18:42, # CodeGen: 675
** Abstract :
** Driver for graphical fonts
** Settings :
** Component name : McuGFont
** SDK : McuLib
** Overwrite Bounding Box Height : Disabled
** Name : Helv
** Size : 8
** Style : normal
** Contents :
** GetFontChar - PGFONT_CharInfo McuGFont_GetFontChar(uint8_t ch);
** GetBoxHeight - uint8_t McuGFont_GetBoxHeight(void);
** GetFont - PGFONT_Callbacks McuGFont_GetFont(void);
** GetUnderlineBoxHeight - uint8_t McuGFont_GetUnderlineBoxHeight(void);
** GetLineSpaceHeight - uint8_t McuGFont_GetLineSpaceHeight(void);
** Deinit - void McuGFont_Deinit(void);
** Init - void McuGFont_Init(void);
**
** * Copyright (c) 2011-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuGFont.h
** @version 01.00
** @brief
** Driver for graphical fonts
*/
/*!
** @addtogroup McuGFont_module McuGFont module documentation
** @{
*/
#ifndef __McuGFont_H
#define __McuGFont_H
/* MODULE McuGFont. */
#include "McuLib.h" /* SDK and API used */
#include "McuGFontconfig.h" /* configuration */
/* Include inherited components */
#include "McuLib.h"
#ifndef __BWUserType_PConstByte
#define __BWUserType_PConstByte
typedef const uint8_t *PConstByte; /* Pointer to a constant byte. */
#endif
#ifndef __BWUserType_GFONT_CharInfo
#define __BWUserType_GFONT_CharInfo
typedef struct { /* A descriptor describing the font. */
int8_t dwidth; /* position of next char. relative to the current */
uint8_t width; /* width of character in pixels */
uint8_t height; /* height of character in pixels */
int8_t offsetX; /* horizontal offset to left edge of bounding box */
int8_t offsetY; /* vertical offset to bottom edge of bounding box */
PConstByte CharBMP; /* pointer to character bitmap defined above */
} GFONT_CharInfo;
#endif
#ifndef __BWUserType_PGFONT_CharInfo
#define __BWUserType_PGFONT_CharInfo
typedef GFONT_CharInfo* PGFONT_CharInfo ; /* A pointer to GFONT_CharInfo */
#endif
#ifndef __BWUserType_CallbackGetFontChar
#define __BWUserType_CallbackGetFontChar
typedef PGFONT_CharInfo (*CallbackGetFontChar)(uint8_t ch); /* Callback used to get the font information for a single character. */
#endif
#ifndef __BWUserType_GFONT_Callbacks
#define __BWUserType_GFONT_Callbacks
typedef struct { /* Structure with font relevant callbacks. */
CallbackGetFontChar GetFontChar; /* Callback for retrieving a font character. */
uint8_t boundingBoxHeight; /* Height of the bounding box. This includes the height of the underline box height. */
uint8_t underlineBoxHeight; /* Height of the underline box height. */
uint8_t lineSpaceBoxHeight; /* Height of the space between lines */
} GFONT_Callbacks;
#endif
#ifndef __BWUserType_PGFONT_Callbacks
#define __BWUserType_PGFONT_Callbacks
typedef GFONT_Callbacks* PGFONT_Callbacks ; /* Pointer to struct for font callbacks. */
#endif
PGFONT_CharInfo McuGFont_GetFontChar(uint8_t ch);
/*
** ===================================================================
** Method : GetFontChar (component GFont)
**
** Description :
** Returns for a given character the corresponding font bitmap.
** Parameters :
** NAME - DESCRIPTION
** ch - The character for that a bitmap is required.
** Returns :
** --- - Character font bitmap
** ===================================================================
*/
uint8_t McuGFont_GetBoxHeight(void);
/*
** ===================================================================
** Method : GetBoxHeight (component GFont)
**
** Description :
** Function to get the height of the bounding box.
** Parameters : None
** Returns :
** --- - Height of bounding box
** ===================================================================
*/
PGFONT_Callbacks McuGFont_GetFont(void);
/*
** ===================================================================
** Method : GetFont (component GFont)
**
** Description :
** Returns callbacks for fonts to be used by the font driver.
** Parameters : None
** Returns :
** --- - Font callbacks.
** ===================================================================
*/
#define McuGFont_GetLineSpaceHeight() \
2
/*
** ===================================================================
** Method : GetLineSpaceHeight (component GFont)
**
** Description :
** Returns the size of the line space height
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
#define McuGFont_GetUnderlineBoxHeight() \
2
/*
** ===================================================================
** Method : GetUnderlineBoxHeight (component GFont)
**
** Description :
** Returns the size of the underline box height
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
void McuGFont_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component GFont)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGFont_Init(void);
/*
** ===================================================================
** Method : Init (component GFont)
**
** Description :
** Driver initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/* END McuGFont. */
#endif
/* ifndef __McuGFont_H */
/*!
** @}
*/

View File

@@ -0,0 +1,783 @@
/*
* Copyright (c) 2019-2021, Erich Styger
*
* Driver for GPIO pins
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuLibconfig.h"
#include "McuGPIO.h"
#include "McuUtility.h"
#include "McuLog.h"
#include <stddef.h>
#include <string.h> /* for memset */
#include <assert.h>
#if MCUGPIO_CONFIG_USE_FREERTOS_HEAP
#include "McuRTOS.h"
#else
#include <stdlib.h> /* for malloc()/free() */
#endif
#if McuLib_CONFIG_NXP_SDK_USED
#include "fsl_gpio.h"
#elif McuLib_CONFIG_CPU_IS_STM32
/* nothing special needed */
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
#include "fsl_port.h"
#elif McuLib_CONFIG_CPU_IS_LPC
#include "fsl_iocon.h"
#elif McuLib_CONFIG_CPU_IS_IMXRT
#include "fsl_iomuxc.h"
#elif McuLib_CONFIG_CPU_IS_STM32
#include "stm32f3xx_hal.h"
#elif McuLib_CONFIG_CPU_IS_ESP32
#include "driver/gpio.h"
#elif McuLib_CONFIG_CPU_IS_RPxxxx
#include "hardware/gpio.h"
#elif McuLib_CONFIG_CPU_IS_MCX
#include "fsl_port.h"
#endif
#if McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0 /* LPC845 specific defines, not available in SDK */
#define McuGPIO_IOCON_PIO_CLKDIV0 0x00u /*!<@brief IOCONCLKDIV0 */
#define McuGPIO_IOCON_PIO_HYS_EN 0x20u /*!<@brief Enable hysteresis */
#define McuGPIO_IOCON_PIO_INV_DI 0x00u /*!<@brief Input not invert */
#define McuGPIO_IOCON_PIO_MODE_PULL_INACTIVE (0x0u<<3) /* Inactive (no pull-down/pull-up resistor enabled) */
#define McuGPIO_IOCON_PIO_MODE_PULL_DOWN (0x1u<<3) /* Pull-down enabled */
#define McuGPIO_IOCON_PIO_MODE_PULL_UP (0x2u<<3) /* Pull-up enabled */
#define McuGPIO_IOCON_PIO_MODE_PULL_REPEATER (0x3u<<3) /* Repeater mode */
#define McuGPIO_IOCON_PIO_OD_DI 0x00u /*!<@brief Disables Open-drain function */
#define McuGPIO_IOCON_PIO_SMODE_BYPASS 0x00u /*!<@brief Bypass input filter */
#define McuGPIO_IOCON_PIO_DEFAULTS \
/* Enable hysteresis */ \
McuGPIO_IOCON_PIO_HYS_EN | \
/* Input not invert */ \
McuGPIO_IOCON_PIO_INV_DI | \
/* Disables Open-drain function */ \
McuGPIO_IOCON_PIO_OD_DI | \
/* Bypass input filter */ \
McuGPIO_IOCON_PIO_SMODE_BYPASS | \
/* IOCONCLKDIV0 */ \
McuGPIO_IOCON_PIO_CLKDIV0
#endif
/* default configuration, used for initializing the config */
static const McuGPIO_Config_t defaultConfig =
{
.isInput = true,
.isHighOnInit = false,
.hw = {
#if McuLib_CONFIG_NXP_SDK_USED && !McuLib_CONFIG_IS_KINETIS_KE
.gpio = NULL,
#elif McuLib_CONFIG_CPU_IS_STM32
.gpio = NULL,
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
.name = "",
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
.port = 0,
#if McuLib_CONFIG_IS_KINETIS_KE
.portType = 0,
.portNum = 0,
#endif
#elif McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0
.port = 0,
.iocon = -1,
#elif McuLib_CONFIG_CPU_IS_LPC
.port = 0,
#elif McuLib_CONFIG_CPU_IS_MCX
.port = NULL, /* e.g. PORT0 */
#endif
#if McuLib_CONFIG_CPU_IS_ESP32
.pin = GPIO_NUM_NC,
#else
.pin = 0,
#endif
.pull = McuGPIO_PULL_DISABLE,
}
};
typedef struct McuGPIO_t {
#if McuLib_CONFIG_CPU_IS_ESP32
bool isHigh; /* status of output pin, because we cannot toggle pin and we cannot read pin status if it is output pin */
#endif
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
struct gpiod_line *line; /* will be requested with gpiod_chip_get_line() */
bool isHigh; /* status of output pin, because we cannot toggle pin and we cannot read pin status if it is output pin */
#endif
bool isInput;
McuGPIO_HwPin_t hw;
} McuGPIO_t;
void McuGPIO_GetDefaultConfig(McuGPIO_Config_t *config) {
assert(config!=NULL);
memcpy(config, &defaultConfig, sizeof(*config));
}
static void McuGPIO_ConfigurePin(McuGPIO_t *pin, bool isInput, bool isHighOnInit) {
#if McuLib_CONFIG_NXP_SDK_USED
gpio_pin_config_t pin_config; /* config for the SDK */
memset(&pin_config, 0, sizeof(pin_config)); /* init all fields */
if (isInput) {
#if McuLib_CONFIG_CPU_IS_IMXRT
pin_config.direction = kGPIO_DigitalInput;
#else
pin_config.pinDirection = kGPIO_DigitalInput;
#endif
} else {
#if McuLib_CONFIG_CPU_IS_IMXRT
pin_config.direction = kGPIO_DigitalOutput;
#else
pin_config.pinDirection = kGPIO_DigitalOutput;
#endif
}
#if McuLib_CONFIG_CPU_IS_IMXRT
pin_config.interruptMode = kGPIO_NoIntmode; /* no interrupts */
#endif
pin_config.outputLogic = isHighOnInit;
#if McuLib_CONFIG_IS_KINETIS_KE
GPIO_PinInit(pin->hw.portNum, pin->hw.pin, &pin_config);
#elif McuLib_CONFIG_CPU_IS_KINETIS
GPIO_PinInit(pin->hw.gpio, pin->hw.pin, &pin_config);
#elif McuLib_CONFIG_CPU_IS_LPC
GPIO_PinInit(pin->hw.gpio, pin->hw.port, pin->hw.pin, &pin_config);
#elif McuLib_CONFIG_CPU_IS_IMXRT
GPIO_PinInit(pin->hw.gpio, pin->hw.pin, &pin_config);
#elif McuLib_CONFIG_CPU_IS_MCX
GPIO_PinInit(pin->hw.gpio, pin->hw.pin, &pin_config);
#endif
#elif McuLib_CONFIG_CPU_IS_STM32
GPIO_InitTypeDef config;
/* setup initialization structure */
config.Alternate = 0; /* init */
if (isInput) {
config.Mode = GPIO_MODE_INPUT; /* configure as input pin */
} else {
config.Mode = GPIO_MODE_OUTPUT_PP; /* configure as push/pull output pin */
}
switch(pin->hw.pull) {
case McuGPIO_PULL_DISABLE: config.Pull = GPIO_NOPULL; break;
case McuGPIO_PULL_UP: config.Pull = GPIO_PULLUP; break;
case McuGPIO_PULL_DOWN: config.Pull = GPIO_PULLDOWN; break;
}
config.Speed = GPIO_SPEED_FREQ_LOW;
config.Pin = pin->hw.pin;
HAL_GPIO_Init(pin->hw.gpio, &config);
/* write default output level */
if (!isInput) {
HAL_GPIO_WritePin(pin->hw.gpio, pin->hw.pin, isHighOnInit?GPIO_PIN_SET:GPIO_PIN_RESET);
}
#elif McuLib_CONFIG_CPU_IS_ESP32
if (gpio_reset_pin(pin->hw.pin)!=ESP_OK) {
McuLog_fatal("failed resetting pin");
}
if (isInput) {
gpio_set_direction(pin->hw.pin, GPIO_MODE_INPUT);
} else {
gpio_set_direction(pin->hw.pin, GPIO_MODE_OUTPUT);
}
switch(pin->hw.pull) {
case McuGPIO_PULL_DISABLE: gpio_set_pull_mode(pin->hw.pin, GPIO_FLOATING); break;
case McuGPIO_PULL_UP: gpio_set_pull_mode(pin->hw.pin, GPIO_PULLUP_ONLY); break;
case McuGPIO_PULL_DOWN: gpio_set_pull_mode(pin->hw.pin, GPIO_PULLDOWN_ONLY); break;
}
if (!isInput) {
gpio_set_level(pin->hw.pin, isHighOnInit?1:0);
pin->isHigh = isHighOnInit;
}
#elif McuLib_CONFIG_CPU_IS_RPxxxx
if (!isInput) { /* set output level first */
gpio_put(pin->hw.pin, isHighOnInit); /* set initial logic level */
}
if (isInput) {
gpio_set_dir(pin->hw.pin, GPIO_IN);
} else {
gpio_set_dir(pin->hw.pin, GPIO_OUT);
}
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
pin->line = gpiod_chip_get_line(pin->hw.chip, pin->hw.pin);
if (isInput) {
gpiod_line_request_input(pin->line, pin->hw.name);
} else {
gpiod_line_request_output(pin->line, pin->hw.name, isHighOnInit);
}
if (!isInput) {
gpiod_line_set_value(pin->line, isHighOnInit?1:0);
pin->isHigh = isHighOnInit;
}
#endif
}
void McuGPIO_SetAsInput(McuGPIO_Handle_t gpio) {
McuGPIO_t *pin = (McuGPIO_t*)gpio;
assert(gpio!=NULL);
McuGPIO_ConfigurePin(pin, true, false /* don't care */);
pin->isInput = true;
}
void McuGPIO_SetAsOutput(McuGPIO_Handle_t gpio, bool setHigh) {
McuGPIO_t *pin = (McuGPIO_t*)gpio;
assert(gpio!=NULL);
McuGPIO_ConfigurePin(pin, false, setHigh);
pin->isInput = false;
}
bool McuGPIO_IsInput(McuGPIO_Handle_t gpio) {
McuGPIO_t *pin = (McuGPIO_t*)gpio;
return pin->isInput;
}
bool McuGPIO_IsOutput(McuGPIO_Handle_t gpio) {
McuGPIO_t *pin = (McuGPIO_t*)gpio;
return !pin->isInput;
}
#if McuLib_CONFIG_CPU_IS_IMXRT
void McuGPIO_SetMux(McuGPIO_HwPin_t *hw, uint32_t muxRegister, uint32_t muxMode, uint32_t inputRegister, uint32_t inputDaisy, uint32_t configRegister) {
hw->mux.muxRegister = muxRegister;
hw->mux.muxMode = muxMode;
hw->mux.inputRegister = inputRegister;
hw->mux.inputDaisy = inputDaisy;
hw->mux.configRegister = configRegister;
}
#endif
McuGPIO_Handle_t McuGPIO_InitGPIO(McuGPIO_Config_t *config) {
McuGPIO_t *handle;
assert(config!=NULL);
/* allocate memory for handle */
#if MCUGPIO_CONFIG_USE_FREERTOS_HEAP
handle = (McuGPIO_t*)pvPortMalloc(sizeof(McuGPIO_t)); /* get a new device descriptor */
#else
handle = (McuGPIO_t*)malloc(sizeof(McuGPIO_t)); /* get a new device descriptor */
#endif
assert(handle!=NULL);
if (handle!=NULL) { /* if malloc failed, will return NULL pointer */
memset(handle, 0, sizeof(McuGPIO_t)); /* init all fields */
handle->isInput = config->isInput;
memcpy(&handle->hw, &config->hw, sizeof(handle->hw)); /* copy hardware information */
}
#if McuLib_CONFIG_CPU_IS_RPxxxx
gpio_init(config->hw.pin);
#endif
McuGPIO_ConfigurePin(handle, config->isInput, config->isHighOnInit);
McuGPIO_SetPullResistor((McuGPIO_Handle_t)handle, config->hw.pull); /* GPIO muxing might be done with setting the pull registers, e.g. for LPC845 */
/* do the pin muxing */
#if McuLib_CONFIG_IS_KINETIS_KE
/* no pin muxing needed */
#elif McuLib_CONFIG_CPU_IS_KINETIS
PORT_SetPinMux(config->hw.port, config->hw.pin, kPORT_MuxAsGpio);
#elif McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0 /* e.g. LPC845 */
/* nothing needed here, because IOCON_PinMuxSet() is already called with the McuGPIO_SetPullResistor() above. */
#elif McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==33 /* LPC55S69 for LPC55S16 */
#define _IOCON_PIO_DIGITAL_EN 0x0100u /*!<@brief Enables digital function */
#define _IOCON_PIO_FUNC0 0x00u /*!<@brief Selects pin function 0 */
#define _IOCON_PIO_INV_DI 0x00u /*!<@brief Input function is not inverted */
#define _IOCON_PIO_MODE_PULLUP 0x20u /*!<@brief Selects pull-up function */
#define _IOCON_PIO_OPENDRAIN_DI 0x00u /*!<@brief Open drain is disabled */
#define _IOCON_PIO_SLEW_STANDARD 0x00u /*!<@brief Standard mode, output slew rate control is enabled */
static const uint32_t port_pin_config = (
_IOCON_PIO_FUNC0 |
/* Selects pull-up function */
_IOCON_PIO_MODE_PULLUP |
/* Standard mode, output slew rate control is enabled */
_IOCON_PIO_SLEW_STANDARD |
/* Input function is not inverted */
_IOCON_PIO_INV_DI |
/* Enables digital function */
_IOCON_PIO_DIGITAL_EN |
/* Open drain is disabled */
_IOCON_PIO_OPENDRAIN_DI);
IOCON_PinMuxSet(IOCON, config->hw.port, config->hw.pin, port_pin_config);
#elif McuLib_CONFIG_CPU_IS_IMXRT
IOMUXC_SetPinMux( handle->hw.mux.muxRegister,
handle->hw.mux.muxMode,
handle->hw.mux.inputRegister,
handle->hw.mux.inputDaisy,
handle->hw.mux.configRegister,
0U);
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_IMXRT1064
/* GPIO1 and GPIO6 share same IO MUX function, configured in GPR26 */
if (handle->hw.gpio==GPIO1) {
IOMUXC_GPR->GPR26 &= ~(1<<handle->hw.pin); /* 0: GPIO1, 1: GPIO6 */
} else if (handle->hw.gpio==GPIO6) {
IOMUXC_GPR->GPR26 |= (1<<handle->hw.pin); /* 0: GPIO1, 1: GPIO6 */
/* GPIO2 and GPIO7 share same IO MUX function, configured in GPR27 */
} else if (handle->hw.gpio==GPIO2) {
IOMUXC_GPR->GPR27 &= (1<<handle->hw.pin); /* 0: GPIO2, 1: GPIO7 */
} else if (handle->hw.gpio==GPIO7) {
IOMUXC_GPR->GPR27 |= (1<<handle->hw.pin); /* 0: GPIO2, 1: GPIO7 */
/* GPIO3 and GPIO8 share same IO MUX function, configured in GPR28 */
} else if (handle->hw.gpio==GPIO3) {
IOMUXC_GPR->GPR28 &= (1<<handle->hw.pin); /* 0: GPIO3, 1: GPIO8 */
} else if (handle->hw.gpio==GPIO8) {
IOMUXC_GPR->GPR28 |= (1<<handle->hw.pin); /* 0: GPIO3, 1: GPIO8 */
/* GPIO4 and GPIO9 share same IO MUX function, configured in GPR29 */
} else if (handle->hw.gpio==GPIO4) {
IOMUXC_GPR->GPR29 &= (1<<handle->hw.pin); /* 0: GPIO4, 1: GPIO9 */
} else if (handle->hw.gpio==GPIO9) {
IOMUXC_GPR->GPR29 |= (1<<handle->hw.pin); /* 0: GPIO4, 1: GPIO9 */
}
#endif /* McuLib_CONFIG_CPU_VARIANT_NXP_IMXRT1064 */
#elif McuLib_CONFIG_CPU_IS_STM32
/* no muxing */
#elif McuLib_CONFIG_CPU_IS_ESP32
/* no muxing needed */
#elif McuLib_CONFIG_CPU_IS_RPxxxx
/* no muxing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
/* no muxing needed */
#endif
return (McuGPIO_Handle_t)handle;
}
McuGPIO_Handle_t McuGPIO_DeinitGPIO(McuGPIO_Handle_t gpio) {
assert(gpio!=NULL);
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
McuGPIO_t *pin = (McuGPIO_t*)gpio;
gpiod_line_release(pin->line);
#elif McuLib_CONFIG_CPU_IS_RPxxxx
McuGPIO_t *pin = (McuGPIO_t*)gpio;
gpio_deinit(pin->hw.pin);
#endif
#if MCUGPIO_CONFIG_USE_FREERTOS_HEAP
vPortFree(gpio);
#else
free(gpio);
#endif
return NULL;
}
void McuGPIO_SetLow(McuGPIO_Handle_t gpio) {
assert(gpio!=NULL);
McuGPIO_t *pin = (McuGPIO_t*)gpio;
#if McuLib_CONFIG_CPU_IS_KINETIS
#if McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(pin->hw.gpio, (1<<pin->hw.pin));
#elif McuLib_CONFIG_IS_KINETIS_KE
GPIO_PortClear(pin->hw.portNum, (1<<pin->hw.pin));
#else
GPIO_PortClear(pin->hw.gpio, (1<<pin->hw.pin));
#endif
#elif McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(pin->hw.gpio, pin->hw.port, (1<<pin->hw.pin));
#elif McuLib_CONFIG_CPU_IS_IMXRT
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 0U);
#elif McuLib_CONFIG_CPU_IS_STM32
HAL_GPIO_WritePin(pin->hw.gpio, pin->hw.pin, GPIO_PIN_RESET);
#elif McuLib_CONFIG_CPU_IS_ESP32
gpio_set_level(pin->hw.pin, 0); /* low */
pin->isHigh = false;
#elif McuLib_CONFIG_CPU_IS_RPxxxx
gpio_put(pin->hw.pin, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
gpiod_line_set_value(pin->line, 0);
pin->isHigh = false;
#elif McuLib_CONFIG_CPU_IS_MCX
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 0);
#endif
}
void McuGPIO_SetHigh(McuGPIO_Handle_t gpio) {
assert(gpio!=NULL);
McuGPIO_t *pin = (McuGPIO_t*)gpio;
#if McuLib_CONFIG_CPU_IS_KINETIS
#if McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(pin->hw.gpio, (1<<pin->hw.pin));
#elif McuLib_CONFIG_IS_KINETIS_KE
GPIO_PortSet(pin->hw.portNum, (1<<pin->hw.pin));
#else
GPIO_PortSet(pin->hw.gpio, (1<<pin->hw.pin));
#endif
#elif McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(pin->hw.gpio, pin->hw.port, (1<<pin->hw.pin));
#elif McuLib_CONFIG_CPU_IS_IMXRT
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 1U);
#elif McuLib_CONFIG_CPU_IS_STM32
HAL_GPIO_WritePin(pin->hw.gpio, pin->hw.pin, GPIO_PIN_SET);
#elif McuLib_CONFIG_CPU_IS_ESP32
gpio_set_level(pin->hw.pin, 1); /* high */
pin->isHigh = true;
#elif McuLib_CONFIG_CPU_IS_RPxxxx
gpio_put(pin->hw.pin, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
gpiod_line_set_value(pin->line, 1);
pin->isHigh = true;
#elif McuLib_CONFIG_CPU_IS_MCX
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 1);
#endif
}
void McuGPIO_Toggle(McuGPIO_Handle_t gpio) {
assert(gpio!=NULL);
McuGPIO_t *pin = (McuGPIO_t*)gpio;
#if McuLib_CONFIG_CPU_IS_KINETIS
#if McuLib_CONFIG_SDK_VERSION < 250
GPIO_TogglePinsOutput(pin->hw.gpio, (1<<pin->hw.pin));
#elif McuLib_CONFIG_IS_KINETIS_KE
GPIO_PortToggle(pin->hw.portNum, (1<<pin->hw.pin));
#else
GPIO_PortToggle(pin->hw.gpio, (1<<pin->hw.pin));
#endif
#elif McuLib_CONFIG_CPU_IS_LPC
GPIO_PortToggle(pin->hw.gpio, pin->hw.port, (1<<pin->hw.pin));
#elif McuLib_CONFIG_CPU_IS_IMXRT
GPIO_PortToggle(pin->hw.gpio, (1<<pin->hw.pin));
#elif McuLib_CONFIG_CPU_IS_STM32
HAL_GPIO_TogglePin(pin->hw.gpio, pin->hw.pin);
#elif McuLib_CONFIG_CPU_IS_ESP32
if (pin->isHigh) {
gpio_set_level(pin->hw.pin, 0);
pin->isHigh = false;
} else {
gpio_set_level(pin->hw.pin, 1);
pin->isHigh = true;
}
#elif McuLib_CONFIG_CPU_IS_RPxxxx
gpio_xor_mask(1<<pin->hw.pin);
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
if (pin->isHigh) {
gpiod_line_set_value(pin->line, 0);
pin->isHigh = false;
} else {
gpiod_line_set_value(pin->line, 1);
pin->isHigh = true;
}
#elif McuLib_CONFIG_CPU_IS_MCX
GPIO_PortToggle(pin->hw.gpio, 1<<pin->hw.pin);
#endif
}
void McuGPIO_SetValue(McuGPIO_Handle_t gpio, bool val) {
assert(gpio!=NULL);
McuGPIO_t *pin = (McuGPIO_t*)gpio;
if (val) { /* set to HIGH */
#if McuLib_CONFIG_CPU_IS_KINETIS
#if McuLib_CONFIG_SDK_VERSION < 250
GPIO_SetPinsOutput(pin->hw.gpio, (1<<pin->hw.pin));
#elif McuLib_CONFIG_IS_KINETIS_KE
GPIO_PortSet(pin->hw.portNum, (1<<pin->hw.pin));
#else
GPIO_PortSet(pin->hw.gpio, (1<<pin->hw.pin));
#endif
#elif McuLib_CONFIG_CPU_IS_LPC
GPIO_PortSet(pin->hw.gpio, pin->hw.port, (1<<pin->hw.pin));
#elif McuLib_CONFIG_CPU_IS_IMXRT
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 1U);
#elif McuLib_CONFIG_CPU_IS_STM32
HAL_GPIO_WritePin(pin->hw.gpio, pin->hw.pin, GPIO_PIN_RESET);
#elif McuLib_CONFIG_CPU_IS_ESP32
gpio_set_level(pin->hw.pin, 1); /* high */
pin->isHigh = true;
#elif McuLib_CONFIG_CPU_IS_RPxxxx
gpio_put(pin->hw.pin, 1);
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
gpiod_line_set_value(pin->line, 0);
pin->isHigh = false;
#elif McuLib_CONFIG_CPU_IS_MCX
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 1);
#endif
} else { /* set to LOW */
#if McuLib_CONFIG_CPU_IS_KINETIS
#if McuLib_CONFIG_SDK_VERSION < 250
GPIO_ClearPinsOutput(pin->hw.gpio, (1<<pin->hw.pin));
#elif McuLib_CONFIG_IS_KINETIS_KE
GPIO_PortClear(pin->hw.portNum, (1<<pin->hw.pin));
#else
GPIO_PortClear(pin->hw.gpio, (1<<pin->hw.pin));
#endif
#elif McuLib_CONFIG_CPU_IS_LPC
GPIO_PortClear(pin->hw.gpio, pin->hw.port, (1<<pin->hw.pin));
#elif McuLib_CONFIG_CPU_IS_IMXRT
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 1U);
#elif McuLib_CONFIG_CPU_IS_STM32
HAL_GPIO_WritePin(pin->hw.gpio, pin->hw.pin, GPIO_PIN_SET);
#elif McuLib_CONFIG_CPU_IS_ESP32
gpio_set_level(pin->hw.pin, 0); /* low */
pin->isHigh = false;
#elif McuLib_CONFIG_CPU_IS_RPxxxx
gpio_put(pin->hw.pin, 0);
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
gpiod_line_set_value(pin->line, 1);
pin->isHigh = true;
#elif McuLib_CONFIG_CPU_IS_MCX
GPIO_PinWrite(pin->hw.gpio, pin->hw.pin, 0);
#endif
}
}
bool McuGPIO_GetValue(McuGPIO_Handle_t gpio) {
return McuGPIO_IsHigh(gpio);
}
bool McuGPIO_IsHigh(McuGPIO_Handle_t gpio) {
assert(gpio!=NULL);
McuGPIO_t *pin = (McuGPIO_t*)gpio;
#if McuLib_CONFIG_CPU_IS_KINETIS
#if McuLib_CONFIG_SDK_VERSION < 250
return GPIO_ReadPinInput(pin->hw.gpio, pin->hw.pin)!=0;
#elif McuLib_CONFIG_IS_KINETIS_KE
return GPIO_PinRead(pin->hw.portNum, pin->hw.pin)!=0;
#else
return GPIO_PinRead(pin->hw.gpio, pin->hw.pin)!=0;
#endif
#elif McuLib_CONFIG_CPU_IS_LPC
return GPIO_PinRead(pin->hw.gpio, pin->hw.port, pin->hw.pin)!=0;
#elif McuLib_CONFIG_CPU_IS_IMXRT
return GPIO_PinRead(pin->hw.gpio, pin->hw.pin)!=0;
#elif McuLib_CONFIG_CPU_IS_STM32
return HAL_GPIO_ReadPin(pin->hw.gpio, pin->hw.pin);
#elif McuLib_CONFIG_CPU_IS_ESP32
if (pin->isInput) {
return gpio_get_level(pin->hw.pin);
} else { /* on ESP32, if pin is configured as output, gpio_get_level() always returns 0 */
return pin->isHigh;
}
#elif McuLib_CONFIG_CPU_IS_RPxxxx
return gpio_get(pin->hw.pin)!=0;
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
return gpiod_line_get_value(pin->line)!=0;
#elif McuLib_CONFIG_CPU_IS_MCX
return GPIO_PinRead(pin->hw.gpio, pin->hw.pin);
#endif
return false;
}
bool McuGPIO_IsLow(McuGPIO_Handle_t gpio) {
return !McuGPIO_IsHigh(gpio);
}
void McuGPIO_GetPinStatusString(McuGPIO_Handle_t gpio, unsigned char *buf, size_t bufSize) {
McuGPIO_t *pin = (McuGPIO_t*)gpio;
*buf = '\0';
if (McuGPIO_IsOutput(gpio)) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"Out:");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"Inp:");
}
if (McuGPIO_IsHigh(gpio)) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"H");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"L");
}
#if (McuLib_CONFIG_NXP_SDK_USED || McuLib_CONFIG_CPU_IS_STM32) && !McuLib_CONFIG_IS_KINETIS_KE
McuUtility_strcat(buf, bufSize, (unsigned char*)" gpio:0x");
McuUtility_strcatNum32Hex(buf, bufSize, (uint32_t)pin->hw.gpio); /* write address */
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
McuUtility_strcat(buf, bufSize, (unsigned char*)" port:0x");
McuUtility_strcatNum32Hex(buf, bufSize, (uint32_t)pin->hw.port); /* write address */
#elif McuLib_CONFIG_CPU_IS_LPC /* all LPC, including M33 and M0+ */
McuUtility_strcat(buf, bufSize, (unsigned char*)" port:");
McuUtility_strcatNum32u(buf, bufSize, (uint32_t)pin->hw.port); /* write port number */
#endif
McuUtility_strcat(buf, bufSize, (unsigned char*)" pin:");
McuUtility_strcatNum32u(buf, bufSize, (uint32_t)pin->hw.pin); /* write pin number */
#if McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0
McuUtility_strcat(buf, bufSize, (unsigned char*)" iocon:");
McuUtility_strcatNum32u(buf, bufSize, (uint32_t)pin->hw.iocon); /* write IOCON number */
#endif
McuUtility_strcat(buf, bufSize, (unsigned char*)" pull:");
switch(pin->hw.pull) {
case McuGPIO_PULL_DISABLE:
McuUtility_strcat(buf, bufSize, (unsigned char*)"dis");
break;
case McuGPIO_PULL_UP:
McuUtility_strcat(buf, bufSize, (unsigned char*)"up ");
break;
case McuGPIO_PULL_DOWN:
McuUtility_strcat(buf, bufSize, (unsigned char*)"dwn");
break;
default:
McuUtility_strcat(buf, bufSize, (unsigned char*)"???");
break;
}
}
void McuGPIO_SetPullResistor(McuGPIO_Handle_t gpio, McuGPIO_PullType pull) {
McuGPIO_t *pin = (McuGPIO_t*)gpio;
pin->hw.pull = pull;
#if McuLib_CONFIG_IS_KINETIS_KE
/* only pull-up */
if (pull == McuGPIO_PULL_DISABLE) {
PORT_SetPinPullUpEnable(pin->hw.port, pin->hw.portType, pin->hw.pin, false);
} else if (pull == McuGPIO_PULL_UP) {
PORT_SetPinPullUpEnable(pin->hw.port, pin->hw.portType, pin->hw.pin, true);
}
#elif McuLib_CONFIG_CPU_IS_KINETIS
/* mask out bits for Pull-Select, Pull-Enable and Interrupt status flags, then OR-ing the new flags */
if (pull == McuGPIO_PULL_DISABLE) {
pin->hw.port->PCR[pin->hw.pin] = ((pin->hw.port->PCR[pin->hw.pin] &
/* Mask bits to zero which are setting */
(~(PORT_PCR_PS_MASK | PORT_PCR_PE_MASK | PORT_PCR_ISF_MASK)))
| PORT_PCR_PE(0)); /* disable pull resistor */
} else if (pull == McuGPIO_PULL_UP) {
pin->hw.port->PCR[pin->hw.pin] = ((pin->hw.port->PCR[pin->hw.pin] &
/* Mask bits to zero which are setting */
(~(PORT_PCR_PS_MASK | PORT_PCR_PE_MASK | PORT_PCR_ISF_MASK)))
/* | PORT_PCR_PFE(1) */ /* enable passive filter */
| PORT_PCR_PS(1) /* pull select 1: pull-up */
| PORT_PCR_PE(1)); /* enable pull resistor */
} else if (pull == McuGPIO_PULL_DOWN) {
pin->hw.port->PCR[pin->hw.pin] = ((pin->hw.port->PCR[pin->hw.pin] &
/* Mask bits to zero which are setting */
(~(PORT_PCR_PS_MASK | PORT_PCR_PE_MASK | PORT_PCR_ISF_MASK)))
| PORT_PCR_PS(0) /* pull select 0: pull-down */
| PORT_PCR_PE(1)); /* enable pull resistor */
}
#elif McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0 /* e.g. LPC845 */
uint32_t IOCON_config;
if (pull == McuGPIO_PULL_DISABLE) {
IOCON_config = ( McuGPIO_IOCON_PIO_MODE_PULL_INACTIVE | McuGPIO_IOCON_PIO_DEFAULTS);
} else if (pull == McuGPIO_PULL_UP) {
IOCON_config = ( McuGPIO_IOCON_PIO_MODE_PULL_UP | McuGPIO_IOCON_PIO_DEFAULTS);
} else if (pull == McuGPIO_PULL_DOWN) {
IOCON_config = ( McuGPIO_IOCON_PIO_MODE_PULL_DOWN | McuGPIO_IOCON_PIO_DEFAULTS);
} else {
IOCON_config = ( McuGPIO_IOCON_PIO_MODE_PULL_INACTIVE | McuGPIO_IOCON_PIO_DEFAULTS);
}
IOCON_PinMuxSet(IOCON, pin->hw.iocon, IOCON_config);
#elif McuLib_CONFIG_CPU_IS_LPC
uint32_t config;
/*! IOCON_PIO_MODE:
* MODE - Selects function mode (on-chip pull-up/pull-down resistor control).
* 0b00..Inactive. Inactive (no pull-down/pull-up resistor enabled).
* 0b01..Pull-down. Pull-down resistor enabled.
* 0b10..Pull-up. Pull-up resistor enabled.
* 0b11..Repeater. Repeater mode.
*/
if (pull == McuGPIO_PULL_DISABLE) {
config = IOCON_PIO_MODE(0b00); /* inactive */
} else if (pull == McuGPIO_PULL_UP) {
config = IOCON_PIO_MODE(0b10); /* pull-up */
} else if (pull == McuGPIO_PULL_DOWN) {
config = IOCON_PIO_MODE(0b01); /* pull-down */
} else { /* default */
config = IOCON_PIO_MODE(0b00); /* inactive */
}
IOCON->PIO[pin->hw.port][pin->hw.pin] = ((IOCON->PIO[pin->hw.port][pin->hw.pin] &
(~(IOCON_PIO_MODE_MASK))) /* Mask bits to zero which are setting */
| config); /* Select function mode (on-chip pull-up/pull-down resistor control) */
#elif McuLib_CONFIG_CPU_IS_IMXRT
if (pin->hw.mux.configRegister!=0) {
uint32_t configValue; /* configuration of IOMUXC SW_PAD_CTL (hw.mux.configRegister) */
configValue = *((volatile uint32_t *)pin->hw.mux.configRegister); /* read current config */
#if 0
configValue = (0<<16) /* Hysteresis enable field: 0: hysteresis disabled */
| (0b00<<14) /* pull-up/down: 00: 100k Ohm pull-down, 01: 47k pull-up, 10: 100k pull-up, 11: 22k pull-up */
| (0<<13) /* pull/keep select: 0: keeper, 1: pull */
| (0<<12) /* pull/keep enable: 0: disabled, 1: enabled */
| (0<<11) /* open drain: 0: disabled, 1: enabled */
| (0b00<<6) /* speed: 00: 50 MHz, 01: 100 MHz, 10: 100 MHz, 11: 200 MHz */
| (0b000<<3) /* drive strength: 000: disabled */
| (0<<0) /* slew rage: 0: slow slew rate, 1: fast slew rate */
;
#endif
/* masking out the bits we are going to set: */
configValue &= ~((0b11<<14) /* pull-up/down */
| (1<<13) /* pull/keep select: */
| (1<<12)); /* pull/keep enable */
if (pull == McuGPIO_PULL_DISABLE) {
configValue |= (0b00<<14) /* pull-up/down: 00: 100k Ohm pull-down, 01: 47k pull-up, 10: 100k pull-up, 11: 22k pull-up */
| (0<<13) /* pull/keep select: 0: keeper, 1: pull */
| (0<<12); /* pull/keep enable: 0: disabled, 1: enabled */
} else if (pull == McuGPIO_PULL_UP) { /* 100k pull-up */
configValue |= (0b10<<14) /* pull-up/down: 00: 100k Ohm pull-down, 01: 47k pull-up, 10: 100k pull-up, 11: 22k pull-up */
| (1<<13) /* pull/keep select: 0: keeper, 1: pull */
| (1<<12); /* pull/keep enable: 0: disabled, 1: enabled */
} else if (pull == McuGPIO_PULL_DOWN) { /* 100k pull-down */
configValue |= (0b00<<14) /* pull-up/down: 00: 100k Ohm pull-down, 01: 47k pull-up, 10: 100k pull-up, 11: 22k pull-up */
| (1<<13) /* pull/keep select: 0: keeper, 1: pull */
| (1<<12); /* pull/keep enable: 0: disabled, 1: enabled */
}
IOMUXC_SetPinConfig(pin->hw.mux.muxRegister,
pin->hw.mux.muxMode,
pin->hw.mux.inputRegister,
pin->hw.mux.inputDaisy,
pin->hw.mux.configRegister,
configValue);
}
#elif McuLib_CONFIG_CPU_IS_STM32
McuGPIO_ConfigurePin(pin, false /* don't care as only for output */, &pin->hw);
#elif McuLib_CONFIG_CPU_IS_ESP32
if (pull == McuGPIO_PULL_DISABLE) {
gpio_set_pull_mode(pin->hw.pin, GPIO_FLOATING);
} else if (pull == McuGPIO_PULL_UP) {
gpio_set_pull_mode(pin->hw.pin, GPIO_PULLUP_ONLY);
} else if (pull == McuGPIO_PULL_DOWN) {
gpio_set_pull_mode(pin->hw.pin, GPIO_PULLDOWN_ONLY);
}
#elif McuLib_CONFIG_CPU_IS_RPxxxx
if (pull == McuGPIO_PULL_DISABLE) {
gpio_disable_pulls(pin->hw.pin);
} else if (pull == McuGPIO_PULL_UP) {
gpio_pull_up(pin->hw.pin);
} else if (pull == McuGPIO_PULL_DOWN) {
gpio_pull_down(pin->hw.pin);
}
#elif McuLib_CONFIG_CPU_IS_MCX
port_pin_config_t config = {
.pullSelect=kPORT_PullDisable,
/* Low internal pull resistor value is selected. */
.pullValueSelect = kPORT_LowPullResistor,
/* Fast slew rate is configured */
.slewRate=kPORT_FastSlewRate,
/* Passive input filter is disabled */
.passiveFilterEnable=kPORT_PassiveFilterDisable,
/* Open drain output is disabled */
.openDrainEnable=kPORT_OpenDrainDisable,
/* Low drive strength is configured */
.driveStrength=kPORT_LowDriveStrength,
/* Pin is configured as PIO0_10 */
.mux=kPORT_MuxAlt0,
/* Digital input enabled */
.inputBuffer=kPORT_InputBufferEnable,
/* Digital input is not inverted */
.invertInput=kPORT_InputNormal,
/* Pin Control Register fields [15:0] are not locked */
.lockRegister=kPORT_UnlockRegister
};
if (pull == McuGPIO_PULL_DISABLE) {
config.pullSelect = kPORT_PullDisable; /* inactive */
} else if (pull == McuGPIO_PULL_UP) {
config.pullSelect = kPORT_PullUp; /* pull-up */
} else if (pull == McuGPIO_PULL_DOWN) {
config.pullSelect = kPORT_PullDown; /* pull-down */
} else { /* default */
config.pullSelect = kPORT_PullDisable; /* inactive */
}
PORT_SetPinConfig(pin->hw.port, pin->hw.pin, (const port_pin_config_t*)&config);
#endif
}
void McuGPIO_Init(void) {
/* nothing to do */
}
void McuGPIO_Deinit(void) {
/* nothing to do */
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright (c) 2019-2021, Erich Styger
* All rights reserved.
*
* Driver for GPIO pins
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef McuGPIO_H_
#define McuGPIO_H_
#include <stdint.h>
#include <stddef.h>
#include "McuLib.h"
#if McuLib_CONFIG_NXP_SDK_USED
#include "fsl_gpio.h"
#if McuLib_CONFIG_IS_KINETIS_KE
#include "fsl_port.h"
#elif McuLib_CONFIG_CPU_IS_IMXRT
#include "fsl_iomuxc.h"
#endif
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
#include <gpiod.h>
#elif McuLib_CONFIG_CPU_IS_STM32
#include "stm32f3xx_hal.h"
#elif McuLib_CONFIG_CPU_IS_ESP32
#include "driver/gpio.h"
#elif McuLib_CONFIG_CPU_IS_RPxxxx
#include "hardware/gpio.h"
#endif
#include "McuLibconfig.h"
#include "McuGPIOconfig.h"
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum McuGPIO_PullType {
McuGPIO_PULL_DISABLE,
McuGPIO_PULL_UP,
McuGPIO_PULL_DOWN,
} McuGPIO_PullType;
typedef struct McuGPIO_Dummy_s { int dummy; } McuGPIO_Dummy_s; /*!< using a pointer to a struct instead a pointer to void for handle, used for handle type 'safety' only */
typedef McuGPIO_Dummy_s *McuGPIO_Handle_t; /*!< GPIO handle type */
typedef struct McuGPIO_HwPin_t {
#if McuLib_CONFIG_NXP_SDK_USED && !McuLib_CONFIG_IS_KINETIS_KE
GPIO_Type *gpio; /* pointer to GPIO */
#elif McuLib_CONFIG_CPU_IS_STM32
GPIO_TypeDef *gpio;
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
struct gpiod_chip *chip; /* must be retrieved once, e.g.e with gpiod_chip_open_by_name("gpiochip0") */
const char *name; /* assigned name for the pin */
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
PORT_Type *port; /* pointer to port, e.g. PORTA, for KE this is PORT */
#if McuLib_CONFIG_IS_KINETIS_KE
port_type_t portType; /* e.g. kPORT_PTH */
gpio_port_num_t portNum; /* e.g. kGPIO_PORTH */
#endif
#elif McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CORTEX_M==0
uint32_t port; /* port number */
uint8_t iocon; /* I/O Connection index used for muxing, e.g. IOCON_INDEX_PIO0_0 */
#elif McuLib_CONFIG_CPU_IS_LPC
uint32_t port; /* port number */
#elif McuLib_CONFIG_CPU_IS_MCX
PORT_Type *port; /* e.g. PORT0 */
#elif McuLib_CONFIG_CPU_IS_IMXRT
/* Information needed for IOMUXC_SetPinMux(), provided e.g. with IOMUXC_GPIO_AD_B0_09_GPIO1_IO09.
* Set it e.g. with
* McuGPIO_SetMux(&config.hw, IOMUXC_GPIO_AD_B0_09_GPIO1_IO09);
*/
struct {
uint32_t muxRegister; /* pin mux register */
uint32_t muxMode; /* pin mux mode */
uint32_t inputRegister; /* select input register */
uint32_t inputDaisy; /* the input daisy */
uint32_t configRegister; /* the configuration register */
} mux;
#endif
#if McuLib_CONFIG_CPU_IS_ESP32
gpio_num_t pin; /* pin number, e.g. GPIO_NUM_10 */
#else
uint32_t pin; /* pin number */
#endif
McuGPIO_PullType pull; /* pull resistor configuration */
} McuGPIO_HwPin_t;
typedef struct McuGPIO_Config_t {
bool isInput;
bool isHighOnInit;
McuGPIO_HwPin_t hw;
} McuGPIO_Config_t;
#if McuLib_CONFIG_CPU_IS_IMXRT
/*!
* \brief Used to set the Muxing configuration.
* Usage: McuGPIO_SetMux(&config.hw, IOMUXC_GPIO_AD_B0_09_GPIO1_IO09);
* @param hw Pointer to hardware struct
* @param muxRegister The muxing register
* @param muxMode The muxing mode
* @param inputRegister The input register, 0 for not used
* @param inputDaisy The input daisy value
* @param configRegister The configuration register
*/
void McuGPIO_SetMux(McuGPIO_HwPin_t *hw, uint32_t muxRegister, uint32_t muxMode, uint32_t inputRegister, uint32_t inputDaisy, uint32_t configRegister);
#endif
void McuGPIO_GetDefaultConfig(McuGPIO_Config_t *config);
McuGPIO_Handle_t McuGPIO_InitGPIO(McuGPIO_Config_t *config);
McuGPIO_Handle_t McuGPIO_DeinitGPIO(McuGPIO_Handle_t gpio);
void McuGPIO_SetAsInput(McuGPIO_Handle_t gpio);
void McuGPIO_SetAsOutput(McuGPIO_Handle_t gpio, bool setHigh);
bool McuGPIO_IsInput(McuGPIO_Handle_t gpio);
bool McuGPIO_IsOutput(McuGPIO_Handle_t gpio);
void McuGPIO_SetLow(McuGPIO_Handle_t gpio);
void McuGPIO_SetHigh(McuGPIO_Handle_t gpio);
void McuGPIO_Toggle(McuGPIO_Handle_t gpio);
bool McuGPIO_IsLow(McuGPIO_Handle_t gpio);
bool McuGPIO_IsHigh(McuGPIO_Handle_t gpio);
void McuGPIO_SetValue(McuGPIO_Handle_t gpio, bool val);
bool McuGPIO_GetValue(McuGPIO_Handle_t gpio);
void McuGPIO_GetPinStatusString(McuGPIO_Handle_t gpio, unsigned char *buf, size_t bufSize);
void McuGPIO_SetPullResistor(McuGPIO_Handle_t gpio, McuGPIO_PullType pull);
/* driver initialization */
void McuGPIO_Init(void);
/* driver de-initialization */
void McuGPIO_Deinit(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* McuGPIO_H_ */

View File

@@ -0,0 +1,807 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuGenericI2C.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : GenericI2C
** Version : Component 01.052, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-08-05, 17:56, # CodeGen: 845
** Abstract :
** This component implements a generic I2C driver wrapper to work both with LDD and non-LDD I2C components.
** Settings :
** Component name : McuGenericI2C
** Wait : McuWait
** Support STOP_NOSTART : no
** Write Buffer Size : 32
** non-LDD I2C : Enabled
** I2C : McuGenericSWI2C
** LDD I2C : Disabled
** RTOS : Enabled
** RTOS : McuRTOS
** Semaphore : no
** Init() on startup : yes
** Contents :
** SelectSlave - uint8_t McuGenericI2C_SelectSlave(uint8_t i2cAddr);
** UnselectSlave - uint8_t McuGenericI2C_UnselectSlave(void);
** RequestBus - void McuGenericI2C_RequestBus(void);
** ReleaseBus - void McuGenericI2C_ReleaseBus(void);
** WriteBlock - uint8_t McuGenericI2C_WriteBlock(void* data, uint16_t dataSize,...
** ReadBlock - uint8_t McuGenericI2C_ReadBlock(void* data, uint16_t dataSize,...
** ReadBlockGeneric - uint8_t McuGenericI2C_ReadBlockGeneric(void* data, uint16_t dataSize,...
** ReadAddressWait - uint8_t McuGenericI2C_ReadAddressWait(uint8_t i2cAddr, uint8_t *memAddr,...
** ReadAddress - uint8_t McuGenericI2C_ReadAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t...
** WriteAddress - uint8_t McuGenericI2C_WriteAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t...
** ReadByte - uint8_t McuGenericI2C_ReadByte(uint8_t i2cAddr, uint8_t *data);
** WriteByte - uint8_t McuGenericI2C_WriteByte(uint8_t i2cAddr, uint8_t data);
** ReadByteAddress8 - uint8_t McuGenericI2C_ReadByteAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** WriteByteAddress8 - uint8_t McuGenericI2C_WriteByteAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** ReadWordAddress8 - uint8_t McuGenericI2C_ReadWordAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** WriteWordAddress8 - uint8_t McuGenericI2C_WriteWordAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** ProbeACK - uint8_t McuGenericI2C_ProbeACK(void* data, uint16_t dataSize,...
** GetSemaphore - void* McuGenericI2C_GetSemaphore(void);
** ScanDevice - uint8_t McuGenericI2C_ScanDevice(uint8_t i2cAddr);
** Deinit - void McuGenericI2C_Deinit(void);
** Init - void McuGenericI2C_Init(void);
**
** * Copyright (c) 2013-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuGenericI2C.h
** @version 01.00
** @brief
** This component implements a generic I2C driver wrapper to work both with LDD and non-LDD I2C components.
*/
/*!
** @addtogroup McuGenericI2C_module McuGenericI2C module documentation
** @{
*/
/* MODULE McuGenericI2C. */
#include "McuGenericI2C.h"
#include "McuWait.h"
#include "McuRTOS.h"
#include "McuGenericSWI2C.h"
#if McuGenericI2C_CONFIG_USE_TIMEOUT
#include "McuTimeout.h"
#endif
#ifndef NULL
#define NULL 0L
#endif /* NULL */
#if McuGenericI2C_CONFIG_USE_TIMEOUT
#define TIMEOUT_COUNTER_HANDLE McuTimeout_CounterHandle
#define TIMEOUT_GET_COUNTER McuTimeout_GetCounter
#define TIMEOUT_LEAVE_COUNTER McuTimeout_LeaveCounter
#define TIMEOUT_COUNTER_EXPIRED McuTimeout_CounterExpired
#define TIMEOUT_OUT_OF_HANDLE McuTimeout_OUT_OF_HANDLE
#define McuGenericI2C_TIMEOUT_NOF_TICKS(factor) ((McuGenericI2C_CONFIG_TIMEOUT_US*(factor))/1000/McuTimeout_TICK_PERIOD_MS)
#define McuGenericI2C_TIMEOUT_TICKS(factor) (McuGenericI2C_TIMEOUT_NOF_TICKS(factor)>0?McuGenericI2C_TIMEOUT_NOF_TICKS(factor):1) /* at least one tick */
#endif
#if McuGenericI2C_CONFIG_USE_MUTEX
static SemaphoreHandle_t McuGenericI2C_busSem = NULL; /* Semaphore to protect I2C bus access */
#endif
/*
** ===================================================================
** Method : RequestBus (component GenericI2C)
**
** Description :
** Starts a critical section for accessing the bus.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericI2C_RequestBus(void)
{
/*lint -save -e522 function lacks side effect */
#if McuGenericI2C_CONFIG_USE_ON_REQUEST_BUS_EVENT
McuGenericI2C_CONFIG_ON_REQUEST_BUS_EVENT();
#endif
/*lint -restore */
#if McuGenericI2C_CONFIG_USE_MUTEX
(void)xSemaphoreTakeRecursive(McuGenericI2C_busSem, portMAX_DELAY);
#endif
}
/*
** ===================================================================
** Method : ReleaseBus (component GenericI2C)
**
** Description :
** Finishes a critical section for accessing the bus.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericI2C_ReleaseBus(void)
{
#if McuGenericI2C_CONFIG_USE_MUTEX
(void)xSemaphoreGiveRecursive(McuGenericI2C_busSem);
#endif
/*lint -save -e522 function lacks side effect */
#if McuGenericI2C_CONFIG_USE_ON_RELEASE_BUS_EVENT
McuGenericI2C_CONFIG_ON_RELEASE_BUS_EVENT();
#endif
/*lint -restore */
}
/*
** ===================================================================
** Method : SelectSlave (component GenericI2C)
**
** Description :
** Selects the slave device on the bus. Method might use a
** semaphore to protect bus access.
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_SelectSlave(uint8_t i2cAddr)
{
McuGenericI2C_RequestBus();
if (McuGenericI2C_CONFIG_SELECT_SLAVE(i2cAddr)!=ERR_OK) {
McuGenericI2C_ReleaseBus();
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
return ERR_FAILED;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : UnselectSlave (component GenericI2C)
**
** Description :
** Unselects the device. Method will release a used a semaphore.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_UnselectSlave(void)
{
McuGenericI2C_ReleaseBus();
return ERR_OK;
}
/*
** ===================================================================
** Method : ReadBlockGeneric (component GenericI2C)
**
** Description :
** Read from the device a block with using additional control
** and flags.
** Parameters :
** NAME - DESCRIPTION
** * data - Read buffer
** dataSize - Size of read buffer
** flagsSend - flags for the send transaction
** flagsStart - Start flags
** flagsAck - Acknowledge flags
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadBlockGeneric(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags, McuGenericI2C_EnumStartFlags flagsStart, McuGenericI2C_EnumAckFlags flagsAck)
{
uint8_t res = ERR_OK;
#if McuGenericI2C_CONFIG_RECV_BLOCK_CUSTOM_AVAILABLE
for(;;) { /* breaks */
uint16_t nof;
res = McuGenericI2C_CONFIG_RECV_BLOCK_CUSTOM(data, dataSize, &nof, flagsStart, flagsAck);
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
if (flags==McuGenericI2C_SEND_STOP) {
res = McuGenericI2C_CONFIG_SEND_STOP();
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
}
break; /* break for(;;) */
} /* for(;;) */
#else
return ERR_FAILED; /* RecvBlockCustom() is not available (e.g. not available in the Hardware I2C component */
#endif
return res;
}
/*
** ===================================================================
** Method : ReadBlock (component GenericI2C)
**
** Description :
** Read from the device a block.
** Parameters :
** NAME - DESCRIPTION
** * data - Read buffer
** dataSize - Size of read buffer
** flags - flags for the transaction
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadBlock(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags)
{
uint8_t res = ERR_OK;
uint16_t nof;
for(;;) { /* breaks */
res = McuGenericI2C_CONFIG_RECV_BLOCK(data, dataSize, &nof);
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
if (flags==McuGenericI2C_SEND_STOP) {
res = McuGenericI2C_CONFIG_SEND_STOP();
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
}
break; /* break for(;;) */
} /* for(;;) */
return res;
}
/*
** ===================================================================
** Method : WriteBlock (component GenericI2C)
**
** Description :
** Write a block to the device.
** Parameters :
** NAME - DESCRIPTION
** * data - Data write buffer
** dataSize -
** flags - flags for the transaction
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteBlock(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags)
{
uint16_t nof;
uint8_t res = ERR_OK;
for(;;) { /* breaks */
#if McuGenericI2C_CONFIG_SUPPORT_STOP_NO_START
if (McuGenericI2C_STOP_NOSTART==flags) {
res = McuGenericI2C_CONFIG_SEND_BLOCK_CONTINUE(data, dataSize, &nof);
} else {
res = McuGenericI2C_CONFIG_SEND_BLOCK(data, dataSize, &nof);
}
#else
res = McuGenericI2C_CONFIG_SEND_BLOCK(data, dataSize, &nof);
#endif
if (res!=ERR_OK) {
(void)McuGenericI2C_CONFIG_SEND_STOP();
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
if (flags==McuGenericI2C_SEND_STOP || (flags==McuGenericI2C_STOP_NOSTART)) {
res = McuGenericI2C_CONFIG_SEND_STOP();
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
}
break; /* break for(;;) */
} /* for(;;) */
return res;
}
/*
** ===================================================================
** Method : ReadAddressWait (component GenericI2C)
**
** Description :
** Same as ReadAddress, but with an optional wait between the
** address and read. Read from the device. This writes
** (S+i2cAddr+0), (memAddr), (Sr+i2cAddr+1), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** * memAddr - Pointer to device memory address
** memAddrSize - number of address bytes
** waitMs - Wait time between the address part
** and reading the data part. Wait time can be
** zero.
** * data - Pointer to read buffer
** dataSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadAddressWait(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint16_t waitMs, uint8_t *data, uint16_t dataSize)
{
uint8_t res = ERR_OK;
uint16_t nof;
if (McuGenericI2C_SelectSlave(i2cAddr)!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
return ERR_FAILED;
}
for(;;) { /* breaks */
if(memAddr!=NULL) { /* only if we want to send an address */
res = McuGenericI2C_CONFIG_SEND_BLOCK((void*)memAddr, memAddrSize, &nof);
if (res!=ERR_OK) {
(void)McuGenericI2C_CONFIG_SEND_STOP();
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
}
/* optional wait time */
if (waitMs!=0) {
McuWait_WaitOSms(waitMs);
}
if (data!=NULL) {
/* receive data */
res = McuGenericI2C_CONFIG_RECV_BLOCK(data, dataSize, &nof);
if (res!=ERR_OK) {
(void)McuGenericI2C_CONFIG_SEND_STOP();
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
res = McuGenericI2C_CONFIG_SEND_STOP();
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
} /* if receive data */
break; /* break for(;;) */
} /* for(;;) */
if (McuGenericI2C_UnselectSlave()!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
return ERR_FAILED;
}
return res;
}
/*
** ===================================================================
** Method : ReadAddress (component GenericI2C)
**
** Description :
** Read from the device. This writes (S+i2cAddr+0), (memAddr),
** (Sr+i2cAddr+1), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** * memAddr - Pointer to device memory address
** memAddrSize - number of address bytes
** * data - Pointer to read buffer
** dataSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint8_t *data, uint16_t dataSize)
{
return McuGenericI2C_ReadAddressWait(i2cAddr, memAddr, memAddrSize, 0, data, dataSize);
}
/*
** ===================================================================
** Method : WriteAddress (component GenericI2C)
**
** Description :
** Write to the device: (S+i2cAddr+0), (memAddr), (data)...
** (data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** * memAddr - Pointer to device memory address
** memAddrSize - number of address bytes
** * data - Pointer to data write buffer
** dataSize - Size of data buffer in bytes
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint8_t *data, uint16_t dataSize)
{
static uint8_t writeBuf[McuGenericI2C_WRITE_BUFFER_SIZE];
uint8_t *p;
uint16_t i;
uint16_t nof;
uint8_t res = ERR_OK;
if (McuGenericI2C_SelectSlave(i2cAddr)!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
return ERR_FAILED;
}
if (memAddrSize+dataSize>McuGenericI2C_WRITE_BUFFER_SIZE) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
return ERR_FAILED;
}
i = 0; p = memAddr;
while(i<McuGenericI2C_WRITE_BUFFER_SIZE && memAddrSize>0) {
writeBuf[i++] = *p++;
memAddrSize--;
}
p = data;
while(i<McuGenericI2C_WRITE_BUFFER_SIZE && dataSize>0) {
writeBuf[i++] = *p++;
dataSize--;
}
for(;;) { /* breaks */
res = McuGenericI2C_CONFIG_SEND_BLOCK((void*)writeBuf, i, &nof);
if (res!=ERR_OK) {
(void)McuGenericI2C_CONFIG_SEND_STOP();
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
res = McuGenericI2C_CONFIG_SEND_STOP();
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
break; /* break for(;;) */
} /* for(;;) */
if (McuGenericI2C_UnselectSlave()!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
return ERR_FAILED;
}
return res;
}
/*
** ===================================================================
** Method : Init (component GenericI2C)
**
** Description :
** Initializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericI2C_Init(void)
{
#if McuGenericI2C_CONFIG_USE_MUTEX
McuGenericI2C_busSem = xSemaphoreCreateRecursiveMutex();
if (McuGenericI2C_busSem==NULL) { /* semaphore creation failed */
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
for(;;) {} /* error, not enough memory? */
}
vQueueAddToRegistry(McuGenericI2C_busSem, "McuGenericI2C_Mutex");
#endif
}
/*
** ===================================================================
** Method : Deinit (component GenericI2C)
**
** Description :
** Deinitializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericI2C_Deinit(void)
{
#if McuGenericI2C_CONFIG_USE_MUTEX
vQueueUnregisterQueue(McuGenericI2C_busSem);
vSemaphoreDelete(McuGenericI2C_busSem);
McuGenericI2C_busSem = NULL;
#endif
}
/*
** ===================================================================
** Method : GetSemaphore (component GenericI2C)
**
** Description :
** Returns the currently allocated semaphore.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
void* McuGenericI2C_GetSemaphore(void)
{
#if McuGenericI2C_CONFIG_USE_MUTEX
return McuGenericI2C_busSem;
#else
return NULL; /* RTOS and Semaphore enabled in properties */
#endif
}
/*
** ===================================================================
** Method : ReadByteAddress8 (component GenericI2C)
**
** Description :
** Read a byte from the device using an 8bit memory address.
** This writes (S+i2cAddr+0), (memAddr), (Sr+i2cAddr+1), (data)..
** .(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** memAddr - Device memory address
** * data - Pointer to read buffer (single byte)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadByteAddress8(uint8_t i2cAddr, uint8_t memAddr, uint8_t *data)
{
return McuGenericI2C_ReadAddress(i2cAddr, &memAddr, sizeof(memAddr), data, 1);
}
/*
** ===================================================================
** Method : WriteByteAddress8 (component GenericI2C)
**
** Description :
** Write a byte to the device using an 8bit memory address:
** (S+i2cAddr+0), (memAddr), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** memAddr - Device memory address
** data - Data value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteByteAddress8(uint8_t i2cAddr, uint8_t memAddr, uint8_t data)
{
return McuGenericI2C_WriteAddress(i2cAddr, &memAddr, sizeof(memAddr), &data, sizeof(data));
}
/*
** ===================================================================
** Method : ReadWordAddress8 (component GenericI2C)
**
** Description :
** Read a word from the device using an 8bit memory address.
** This writes (S+i2cAddr+0), (memAddr), (Sr+i2cAddr+1), (data)..
** .(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** memAddr - Device memory address
** * data - Pointer to read buffer (single byte)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadWordAddress8(uint8_t i2cAddr, uint8_t memAddr, uint16_t *data)
{
return McuGenericI2C_ReadAddress(i2cAddr, &memAddr, sizeof(memAddr), (uint8_t*)data, 2);
}
/*
** ===================================================================
** Method : WriteWordAddress8 (component GenericI2C)
**
** Description :
** Write a word to the device using an 8bit memory address:
** (S+i2cAddr+0), (memAddr), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** memAddr - Device memory address
** data - Data value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteWordAddress8(uint8_t i2cAddr, uint8_t memAddr, uint16_t data)
{
return McuGenericI2C_WriteAddress(i2cAddr, &memAddr, sizeof(memAddr), (uint8_t*)&data, sizeof(data));
}
/*
** ===================================================================
** Method : ScanDevice (component GenericI2C)
**
** Description :
** Checks if a device responds on the bus with an ACK.
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - 7bit I2C device address
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ScanDevice(uint8_t i2cAddr)
{
uint8_t res = ERR_OK;
uint16_t nof;
uint8_t dummy;
if (McuGenericI2C_SelectSlave(i2cAddr)!=ERR_OK) {
return ERR_FAILED;
}
for(;;) { /* breaks */
res = McuGenericI2C_CONFIG_RECV_BLOCK((void*)&dummy, 1, &nof);
if (res!=ERR_OK) {
(void)McuGenericI2C_CONFIG_SEND_STOP();
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
res = McuGenericI2C_CONFIG_SEND_STOP();
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
break; /* break for(;;) */
} /* for(;;) */
if (McuGenericI2C_UnselectSlave()!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
return ERR_FAILED;
}
return res;
}
/*
** ===================================================================
** Method : ProbeACK (component GenericI2C)
**
** Description :
** Accesses the bus to check if the device responds with an ACK
** (ACK polling).
** Parameters :
** NAME - DESCRIPTION
** * data - Data write buffer
** dataSize -
** flags - flags for the transaction
** WaitTimeUS - Waiting time in microseconds
** to wait for the ACK on the bus.
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ProbeACK(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags, uint16_t WaitTimeUS)
{
uint16_t nof;
uint8_t res = ERR_OK;
(void)WaitTimeUS; /* not used */
for(;;) { /* breaks */
res = McuGenericI2C_CONFIG_SEND_BLOCK(data, dataSize, &nof);
if (res!=ERR_OK) {
(void)McuGenericI2C_CONFIG_SEND_STOP();
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
if (flags==McuGenericI2C_SEND_STOP) {
res = McuGenericI2C_CONFIG_SEND_STOP();
if (res!=ERR_OK) {
#if McuGenericI2C_CONFIG_USE_ON_ERROR_EVENT
McuGenericI2C_CONFIG_ON_ERROR_EVENT();
#endif
break; /* break for(;;) */
}
}
break; /* break for(;;) */
} /* for(;;) */
return res;
}
/*
** ===================================================================
** Method : ReadByte (component GenericI2C)
**
** Description :
** Read a byte from the device. This writes (S+i2cAddr+0),
** (Sr+i2cAddr+1),(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** * data - Pointer to read buffer (single byte)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadByte(uint8_t i2cAddr, uint8_t *data)
{
return McuGenericI2C_ReadAddress(i2cAddr, NULL, 0, data, 1);
}
/*
** ===================================================================
** Method : WriteByte (component GenericI2C)
**
** Description :
** Write a byte to the device: (S+i2cAddr+0).(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** data - Data value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteByte(uint8_t i2cAddr, uint8_t data)
{
return McuGenericI2C_WriteAddress(i2cAddr, NULL, 0, &data, 1);
}
/* END McuGenericI2C. */
/*!
** @}
*/

View File

@@ -0,0 +1,475 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuGenericI2C.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : GenericI2C
** Version : Component 01.052, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-08-05, 17:56, # CodeGen: 845
** Abstract :
** This component implements a generic I2C driver wrapper to work both with LDD and non-LDD I2C components.
** Settings :
** Component name : McuGenericI2C
** Wait : McuWait
** Support STOP_NOSTART : no
** Write Buffer Size : 32
** non-LDD I2C : Enabled
** I2C : McuGenericSWI2C
** LDD I2C : Disabled
** RTOS : Enabled
** RTOS : McuRTOS
** Semaphore : no
** Init() on startup : yes
** Contents :
** SelectSlave - uint8_t McuGenericI2C_SelectSlave(uint8_t i2cAddr);
** UnselectSlave - uint8_t McuGenericI2C_UnselectSlave(void);
** RequestBus - void McuGenericI2C_RequestBus(void);
** ReleaseBus - void McuGenericI2C_ReleaseBus(void);
** WriteBlock - uint8_t McuGenericI2C_WriteBlock(void* data, uint16_t dataSize,...
** ReadBlock - uint8_t McuGenericI2C_ReadBlock(void* data, uint16_t dataSize,...
** ReadBlockGeneric - uint8_t McuGenericI2C_ReadBlockGeneric(void* data, uint16_t dataSize,...
** ReadAddressWait - uint8_t McuGenericI2C_ReadAddressWait(uint8_t i2cAddr, uint8_t *memAddr,...
** ReadAddress - uint8_t McuGenericI2C_ReadAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t...
** WriteAddress - uint8_t McuGenericI2C_WriteAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t...
** ReadByte - uint8_t McuGenericI2C_ReadByte(uint8_t i2cAddr, uint8_t *data);
** WriteByte - uint8_t McuGenericI2C_WriteByte(uint8_t i2cAddr, uint8_t data);
** ReadByteAddress8 - uint8_t McuGenericI2C_ReadByteAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** WriteByteAddress8 - uint8_t McuGenericI2C_WriteByteAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** ReadWordAddress8 - uint8_t McuGenericI2C_ReadWordAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** WriteWordAddress8 - uint8_t McuGenericI2C_WriteWordAddress8(uint8_t i2cAddr, uint8_t memAddr,...
** ProbeACK - uint8_t McuGenericI2C_ProbeACK(void* data, uint16_t dataSize,...
** GetSemaphore - void* McuGenericI2C_GetSemaphore(void);
** ScanDevice - uint8_t McuGenericI2C_ScanDevice(uint8_t i2cAddr);
** Deinit - void McuGenericI2C_Deinit(void);
** Init - void McuGenericI2C_Init(void);
**
** * Copyright (c) 2013-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuGenericI2C.h
** @version 01.00
** @brief
** This component implements a generic I2C driver wrapper to work both with LDD and non-LDD I2C components.
*/
/*!
** @addtogroup McuGenericI2C_module McuGenericI2C module documentation
** @{
*/
#ifndef __McuGenericI2C_H
#define __McuGenericI2C_H
/* MODULE McuGenericI2C. */
#include "McuLib.h" /* SDK and API used */
#include "McuGenericI2Cconfig.h" /* configuration */
#ifdef __cplusplus
extern "C" {
#endif
#define McuGenericI2C_WRITE_BUFFER_SIZE McuGenericI2C_CONFIG_WRITE_BUFFER_SIZE /* size of internal buffer used, set in the component properties */
typedef enum McuGenericI2C_EnumSendFlags_ {
McuGenericI2C_SEND_STOP, /* STOP is sent */
McuGenericI2C_DO_NOT_SEND_STOP, /* STOP is not sent */
McuGenericI2C_STOP_NOSTART /* send STOP without START condition */
} McuGenericI2C_EnumSendFlags;
typedef enum McuGenericI2C_EnumStartFlags_ {
McuGenericI2C_SEND_START, /* Start is sent */
McuGenericI2C_DO_NOT_SEND_START /* Start is not sent */
} McuGenericI2C_EnumStartFlags;
typedef enum McuGenericI2C_EnumAckFlags_ {
McuGenericI2C_SEND_LAST_ACK, /* Nack after last received byte is sent */
McuGenericI2C_DO_NOT_LAST_ACK /* Nack after last received byte is not sent */
} McuGenericI2C_EnumAckFlags;
void McuGenericI2C_Init(void);
/*
** ===================================================================
** Method : Init (component GenericI2C)
**
** Description :
** Initializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericI2C_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component GenericI2C)
**
** Description :
** Deinitializes the driver.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuGenericI2C_ReadAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint8_t *data, uint16_t dataSize);
/*
** ===================================================================
** Method : ReadAddress (component GenericI2C)
**
** Description :
** Read from the device. This writes (S+i2cAddr+0), (memAddr),
** (Sr+i2cAddr+1), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** * memAddr - Pointer to device memory address
** memAddrSize - number of address bytes
** * data - Pointer to read buffer
** dataSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint8_t *data, uint16_t dataSize);
/*
** ===================================================================
** Method : WriteAddress (component GenericI2C)
**
** Description :
** Write to the device: (S+i2cAddr+0), (memAddr), (data)...
** (data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** * memAddr - Pointer to device memory address
** memAddrSize - number of address bytes
** * data - Pointer to data write buffer
** dataSize - Size of data buffer in bytes
** Returns :
** --- - Error code
** ===================================================================
*/
void* McuGenericI2C_GetSemaphore(void);
/*
** ===================================================================
** Method : GetSemaphore (component GenericI2C)
**
** Description :
** Returns the currently allocated semaphore.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadBlock(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags);
/*
** ===================================================================
** Method : ReadBlock (component GenericI2C)
**
** Description :
** Read from the device a block.
** Parameters :
** NAME - DESCRIPTION
** * data - Read buffer
** dataSize - Size of read buffer
** flags - flags for the transaction
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteBlock(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags);
/*
** ===================================================================
** Method : WriteBlock (component GenericI2C)
**
** Description :
** Write a block to the device.
** Parameters :
** NAME - DESCRIPTION
** * data - Data write buffer
** dataSize -
** flags - flags for the transaction
** Returns :
** --- - Error code
** ===================================================================
*/
void McuGenericI2C_RequestBus(void);
/*
** ===================================================================
** Method : RequestBus (component GenericI2C)
**
** Description :
** Starts a critical section for accessing the bus.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericI2C_ReleaseBus(void);
/*
** ===================================================================
** Method : ReleaseBus (component GenericI2C)
**
** Description :
** Finishes a critical section for accessing the bus.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuGenericI2C_SelectSlave(uint8_t i2cAddr);
/*
** ===================================================================
** Method : SelectSlave (component GenericI2C)
**
** Description :
** Selects the slave device on the bus. Method might use a
** semaphore to protect bus access.
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_UnselectSlave(void);
/*
** ===================================================================
** Method : UnselectSlave (component GenericI2C)
**
** Description :
** Unselects the device. Method will release a used a semaphore.
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadByteAddress8(uint8_t i2cAddr, uint8_t memAddr, uint8_t *data);
/*
** ===================================================================
** Method : ReadByteAddress8 (component GenericI2C)
**
** Description :
** Read a byte from the device using an 8bit memory address.
** This writes (S+i2cAddr+0), (memAddr), (Sr+i2cAddr+1), (data)..
** .(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** memAddr - Device memory address
** * data - Pointer to read buffer (single byte)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteByteAddress8(uint8_t i2cAddr, uint8_t memAddr, uint8_t data);
/*
** ===================================================================
** Method : WriteByteAddress8 (component GenericI2C)
**
** Description :
** Write a byte to the device using an 8bit memory address:
** (S+i2cAddr+0), (memAddr), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** memAddr - Device memory address
** data - Data value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ScanDevice(uint8_t i2cAddr);
/*
** ===================================================================
** Method : ScanDevice (component GenericI2C)
**
** Description :
** Checks if a device responds on the bus with an ACK.
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - 7bit I2C device address
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ProbeACK(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags, uint16_t WaitTimeUS);
/*
** ===================================================================
** Method : ProbeACK (component GenericI2C)
**
** Description :
** Accesses the bus to check if the device responds with an ACK
** (ACK polling).
** Parameters :
** NAME - DESCRIPTION
** * data - Data write buffer
** dataSize -
** flags - flags for the transaction
** WaitTimeUS - Waiting time in microseconds
** to wait for the ACK on the bus.
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadBlockGeneric(void* data, uint16_t dataSize, McuGenericI2C_EnumSendFlags flags, McuGenericI2C_EnumStartFlags flagsStart, McuGenericI2C_EnumAckFlags flagsAck);
/*
** ===================================================================
** Method : ReadBlockGeneric (component GenericI2C)
**
** Description :
** Read from the device a block with using additional control
** and flags.
** Parameters :
** NAME - DESCRIPTION
** * data - Read buffer
** dataSize - Size of read buffer
** flagsSend - flags for the send transaction
** flagsStart - Start flags
** flagsAck - Acknowledge flags
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadWordAddress8(uint8_t i2cAddr, uint8_t memAddr, uint16_t *data);
/*
** ===================================================================
** Method : ReadWordAddress8 (component GenericI2C)
**
** Description :
** Read a word from the device using an 8bit memory address.
** This writes (S+i2cAddr+0), (memAddr), (Sr+i2cAddr+1), (data)..
** .(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** memAddr - Device memory address
** * data - Pointer to read buffer (single byte)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteWordAddress8(uint8_t i2cAddr, uint8_t memAddr, uint16_t data);
/*
** ===================================================================
** Method : WriteWordAddress8 (component GenericI2C)
**
** Description :
** Write a word to the device using an 8bit memory address:
** (S+i2cAddr+0), (memAddr), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** memAddr - Device memory address
** data - Data value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadByte(uint8_t i2cAddr, uint8_t *data);
/*
** ===================================================================
** Method : ReadByte (component GenericI2C)
**
** Description :
** Read a byte from the device. This writes (S+i2cAddr+0),
** (Sr+i2cAddr+1),(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** * data - Pointer to read buffer (single byte)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_WriteByte(uint8_t i2cAddr, uint8_t data);
/*
** ===================================================================
** Method : WriteByte (component GenericI2C)
**
** Description :
** Write a byte to the device: (S+i2cAddr+0).(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C address of device
** data - Data value
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuGenericI2C_ReadAddressWait(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint16_t waitMs, uint8_t *data, uint16_t dataSize);
/*
** ===================================================================
** Method : ReadAddressWait (component GenericI2C)
**
** Description :
** Same as ReadAddress, but with an optional wait between the
** address and read. Read from the device. This writes
** (S+i2cAddr+0), (memAddr), (Sr+i2cAddr+1), (data)...(data+P)
** Parameters :
** NAME - DESCRIPTION
** i2cAddr - I2C Address of device
** * memAddr - Pointer to device memory address
** memAddrSize - number of address bytes
** waitMs - Wait time between the address part
** and reading the data part. Wait time can be
** zero.
** * data - Pointer to read buffer
** dataSize - Size of read buffer
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuGenericI2C. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuGenericI2C_H */
/*!
** @}
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,470 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuGenericSWI2C.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : GenericSWI2C
** Version : Component 01.028, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-09, 10:10, # CodeGen: 829
** Abstract :
**
** Settings :
** Component name : McuGenericSWI2C
** Delay (ns) : 1250
** Trials : 256
** SDA : SDK_BitIO
** SCL : SDK_BitIO
** Wait : McuWait
** Yield : no
** Contents :
** ResetBus - bool McuGenericSWI2C_ResetBus(void);
** SendChar - uint8_t McuGenericSWI2C_SendChar(uint8_t Chr);
** RecvChar - uint8_t McuGenericSWI2C_RecvChar(uint8_t *Chr);
** SendBlock - uint8_t McuGenericSWI2C_SendBlock(void *Ptr, uint16_t Siz, uint16_t *Snt);
** SendBlockContinue - uint8_t McuGenericSWI2C_SendBlockContinue(void *Ptr, uint16_t Siz, uint16_t...
** RecvBlock - uint8_t McuGenericSWI2C_RecvBlock(void *Ptr, uint16_t Siz, uint16_t *Rcv);
** RecvBlockCustom - uint8_t McuGenericSWI2C_RecvBlockCustom(void *Ptr, uint16_t Siz, uint16_t...
** SendAck - void McuGenericSWI2C_SendAck(bool Ack);
** SendStop - uint8_t McuGenericSWI2C_SendStop(void);
** SelectSlave - uint8_t McuGenericSWI2C_SelectSlave(uint8_t Slv);
** GetSelected - uint8_t McuGenericSWI2C_GetSelected(uint8_t *Slv);
** Deinit - void McuGenericSWI2C_Deinit(void);
** Init - void McuGenericSWI2C_Init(void);
**
** * Copyright (c) 2014-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuGenericSWI2C.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuGenericSWI2C_module McuGenericSWI2C module documentation
** @{
*/
#ifndef __McuGenericSWI2C_H
#define __McuGenericSWI2C_H
/* MODULE McuGenericSWI2C. */
#include "McuLib.h" /* SDK and API used */
#include "McuGenericSWI2Cconfig.h" /* configuration */
#define McuGenericSWI2C_RECVBLOCKCUSTOM_AVAILABLE (1)
/*!< Define which can be used to check if the function RecvBlockCustom() is available */
typedef enum McuGenericSWI2C_EnumStartFlags_ {
McuGenericSWI2C_SEND_START, /* Start is sent */
McuGenericSWI2C_DO_NOT_SEND_START /* Start is not sent */
} McuGenericSWI2C_EnumStartFlags;
typedef enum McuGenericSWI2C_EnumAckFlags_ {
McuGenericSWI2C_SEND_LAST_ACK, /* Nack after last received byte is sent */
McuGenericSWI2C_DO_NOT_LAST_ACK /* Nack after last received byte is not sent */
} McuGenericSWI2C_EnumAckFlags;
/* defines to be used for McuGenericSWI2C_SendAck(); */
#define McuGenericSWI2C_ACK 0U
#define McuGenericSWI2C_NOACK 1U
void McuGenericSWI2C_Init(void);
/*
** ===================================================================
** Method : Init (component GenericSWI2C)
**
** Description :
** Initializes the associated peripheral(s) and the components
** internal variables.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuGenericSWI2C_SendChar(uint8_t Chr);
/*
** ===================================================================
** Method : SendChar (component GenericSWI2C)
**
** Description :
** When working as a MASTER, this method writes 7 bits of slave
** address plus R/W bit = 0 to the I2C bus and then writes one
** character (byte) to the bus. The slave address must be
** specified before by the "SelectSlave" method or in the
** component initialization section of 'Slave address init'
** property. When working as the SLAVE, this method writes one
** character (byte) to the bus. If the ERR_NOTAVAIL error code
** returned, the char is successfully sent to master but the
** master device responds by an acknowledgment instead of no
** acknowledgment at the end of transfer. 'OnError' event is
** called in this case.
** Parameters :
** NAME - DESCRIPTION
** Chr - Character to send
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_BUSY - The slave device is busy, it
** does not respond by the acknowledgment
** (MASTER mode only)
** ERR_NOTAVAIL - The master device sends
** acknowledgment instead of no acknowledgment
** after the last byte transfer (SLAVE mode
** only)
** ERR_DISABLED - Device is disabled
** ERR_BUSOFF - Clock timeout elapsed (SLAVE
** mode only)
** ===================================================================
*/
uint8_t McuGenericSWI2C_RecvChar(uint8_t *Chr);
/*
** ===================================================================
** Method : RecvChar (component GenericSWI2C)
**
** Description :
** When working as a MASTER, this method writes 7 bits of slave
** address plus R/W bit = 1 to the I2C bus and then reads one
** character (byte) from the bus. The slave address must be
** specified before by the "SelectSlave" method or in the
** component initialization section of 'Slave address init'
** property. When working as a SLAVE, this method reads one
** character (byte) from the bus.
** Parameters :
** NAME - DESCRIPTION
** * Chr - Pointer to received character
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_BUSY - The slave device is busy, it
** does not respond by the acknowledgment
** (MASTER mode only)
** ERR_DISABLED - Device is disabled
** ERR_BUSOFF - Clock timeout elapsed (SLAVE
** mode only)
** ===================================================================
*/
uint8_t McuGenericSWI2C_SendBlock(void *Ptr, uint16_t Siz, uint16_t *Snt);
/*
** ===================================================================
** Method : SendBlock (component GenericSWI2C)
**
** Description :
** When working as a MASTER, this method writes 7 bits of slave
** address plus R/W bit = 0 to the I2C bus and then writes the
** block of characters to the bus. If the component is disabled
** (by the "Disable" method or initialization), the block is
** moved to the output buffer if the 'Output buffer size'
** property is different from zero. The content of the output
** buffer is sent immediately with the stop condition at the
** end when the component is enabled by the "Enable" method.
** After the output buffer transmission, the whole output
** buffer is cleared. The slave address must be specified
** before by the "SelectSlave" method or in component
** initialization section of 'Slave address init' property.
** When working as a SLAVE, this method writes block of
** characters to the bus. If the ERR_NOTAVAIL error code is
** returned, the whole block is successfully sent to a master
** but the master device responds by an acknowledgment instead
** of no acknowledgment sent at the end of the last block byte
** transfer. 'OnError' event is called in this case.
** Parameters :
** NAME - DESCRIPTION
** * Ptr - A pointer to the block of data to send
** Siz - The size of the block
** * Snt - A pointer to the number of data that are
** sent (copied to buffer)
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_BUSY - The slave device is busy, it
** does not respond by the acknowledgment
** (MASTER mode only)
** ERR_TXFULL - Output buffer is full (MASTER
** mode only)
** ERR_NOTAVAIL - The master device sends
** acknowledgment instead of no acknowledgment
** after the last byte transfer (SLAVE mode
** only)
** ERR_DISABLED - Device is disabled
** ERR_BUSOFF - Clock timeout elapsed (SLAVE
** mode only)
** ===================================================================
*/
uint8_t McuGenericSWI2C_RecvBlock(void *Ptr, uint16_t Siz, uint16_t *Rcv);
/*
** ===================================================================
** Method : RecvBlock (component GenericSWI2C)
**
** Description :
** When working as a MASTER, this method writes 7 bits of slave
** address plus R/W bit = 1 to the I2C bus and then reads the
** block of characters from the bus. The slave address must be
** specified before by the "SelectSlave" method or in component
** initialization section of 'Slave address init' property.
** When working as a SLAVE, this method reads the block of
** characters from the bus.
** Parameters :
** NAME - DESCRIPTION
** * Ptr - A pointer to the block space for received
** data
** Siz - The size of the block
** * Rcv - A pointer to the number of actually
** received data
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_BUSY - The slave device is busy, it
** does not respond by the acknowledgment
** (MASTER mode only)
** ERR_DISABLED - Device is disabled
** ERR_BUSOFF - Clock timeout elapsed (SLAVE
** mode only)
** ===================================================================
*/
uint8_t McuGenericSWI2C_SendStop(void);
/*
** ===================================================================
** Method : SendStop (component GenericSWI2C)
**
** Description :
** When working as a MASTER, if the 'Automatic stop condition'
** property value is 'no', this method sends a valid stop
** condition to the serial data line of the I2C bus to
** terminate the communication on the bus after using send
** methods. This method is enabled only if the component is in
** MASTER mode and 'Automatic stop condition' property value is
** 'no'
** Parameters : None
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_DISABLED - Device is disabled
** ===================================================================
*/
uint8_t McuGenericSWI2C_SelectSlave(uint8_t Slv);
/*
** ===================================================================
** Method : SelectSlave (component GenericSWI2C)
**
** Description :
** When working as a MASTER, this method selects a new slave
** for communication by its slave address value. Any send or
** receive method are directed to or from the selected device,
** until a new slave device is selected by this method. If the
** selected slave uses 10-bit slave addressing, as the
** parameter 7 bits must be passed, which involves 10-bit
** addressing (11110XX), including two MSBs of slave address
** (XX). The second byte of the 10-bit slave address must be
** sent to the slave as a general character of send methods.
** This method is available only if the component is in MASTER
** mode.
** Parameters :
** NAME - DESCRIPTION
** Slv - Slave address value
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_DISABLED - Device is disabled
** ===================================================================
*/
uint8_t McuGenericSWI2C_GetSelected(uint8_t *Slv);
/*
** ===================================================================
** Method : GetSelected (component GenericSWI2C)
**
** Description :
** When working as a MASTER, this method returns the
** identification address value of the slave, which is
** currently selected for communication with the master. If the
** current slave uses 10-bit slave addressing, the method
** returns the first 7 bits only, which involves 10-bit
** addressing (11110XX), including two MSBs of the slave
** address (XX). This method is not able to return the rest
** value of 10-bit slave address. This method is available only
** if the component is in MASTER mode.
** Parameters :
** NAME - DESCRIPTION
** * Slv - A pointer to the current selected slave
** address value
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ===================================================================
*/
bool McuGenericSWI2C_ResetBus(void);
/*
** ===================================================================
** Method : ResetBus (component GenericSWI2C)
**
** Description :
** Reset bus if needed.
** Parameters : None
** Returns :
** --- - TRUE if bus is idle, FALSE if bus is
** busy/hung
** ===================================================================
*/
uint8_t McuGenericSWI2C_SendBlockContinue(void *Ptr, uint16_t Siz, uint16_t *Snt);
/*
** ===================================================================
** Method : SendBlockContinue (component GenericSWI2C)
**
** Description :
** Same is SendBlock() but does not send start condition. When
** working as a MASTER, this method writes 7 bits of slave
** address plus R/W bit = 0 to the I2C bus and then writes the
** block of characters to the bus. If the component is disabled
** (by the "Disable" method or initialization), the block is
** moved to the output buffer if the 'Output buffer size'
** property is different from zero. The content of the output
** buffer is sent immediately with the stop condition at the
** end when the component is enabled by the "Enable" method.
** After the output buffer transmission, the whole output
** buffer is cleared. The slave address must be specified
** before by the "SelectSlave" method or in component
** initialization section of 'Slave address init' property.
** When working as a SLAVE, this method writes block of
** characters to the bus. If the ERR_NOTAVAIL error code is
** returned, the whole block is successfully sent to a master
** but the master device responds by an acknowledgment instead
** of no acknowledgment sent at the end of the last block byte
** transfer. 'OnError' event is called in this case.
** Parameters :
** NAME - DESCRIPTION
** * Ptr - A pointer to the block of data to send
** Siz - The size of the block
** * Snt - A pointer to the number of data that are
** sent (copied to buffer)
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_BUSY - The slave device is busy, it
** does not respond by the acknowledgment
** (MASTER mode only)
** ERR_TXFULL - Output buffer is full (MASTER
** mode only)
** ERR_NOTAVAIL - The master device sends
** acknowledgment instead of no acknowledgment
** after the last byte transfer (SLAVE mode
** only)
** ERR_DISABLED - Device is disabled
** ERR_BUSOFF - Clock timeout elapsed (SLAVE
** mode only)
** ===================================================================
*/
uint8_t McuGenericSWI2C_RecvBlockCustom(void *Ptr, uint16_t Siz, uint16_t *Rcv, McuGenericSWI2C_EnumStartFlags flagsStart, McuGenericSWI2C_EnumAckFlags flagsAck);
/*
** ===================================================================
** Method : RecvBlockCustom (component GenericSWI2C)
**
** Description :
** Same as RecvBlock(), but with additional flags to control
** the bus transfer.
** Parameters :
** NAME - DESCRIPTION
** * Ptr - A pointer to the block space for received
** data
** Siz - The size of the block
** * Rcv - A pointer to the number of actually
** received data
** flagsStart - Flags for start condition
** flagsAck - Flags for Ack after last byte
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_BUSY - The slave device is busy, it
** does not respond by the acknowledgment
** (MASTER mode only)
** ERR_DISABLED - Device is disabled
** ERR_BUSOFF - Clock timeout elapsed (SLAVE
** mode only)
** ===================================================================
*/
void McuGenericSWI2C_SendAck(bool Ack);
/*
** ===================================================================
** Method : SendAck (component GenericSWI2C)
**
** Description :
** The method sends ACK to the bus.
** Parameters :
** NAME - DESCRIPTION
** Ack - If acknowledge is high or low
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWI2C_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component GenericSWI2C)
**
** Description :
** Driver de-initialization method.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/* END McuGenericSWI2C. */
#endif
/* ifndef __McuGenericSWI2C_H */
/*!
** @}
*/

View File

@@ -0,0 +1,363 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuGenericSWSPI.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : GenericSWSPI
** Version : Component 01.031, Driver 01.15, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-13, 18:42, # CodeGen: 675
** Abstract :
**
** Settings :
** Contents :
** RecvChar - uint8_t McuGenericSWSPI_RecvChar(uint8_t *Chr);
** SendChar - uint8_t McuGenericSWSPI_SendChar(uint8_t val);
** CharsInRxBuf - uint8_t McuGenericSWSPI_CharsInRxBuf(void);
** CharsInTxBuf - uint8_t McuGenericSWSPI_CharsInTxBuf(void);
** SetShiftClockPolarity - uint8_t McuGenericSWSPI_SetShiftClockPolarity(uint8_t Edge);
** SetIdleClockPolarity - uint8_t McuGenericSWSPI_SetIdleClockPolarity(uint8_t Level);
** Write_ReadDummy - void McuGenericSWSPI_Write_ReadDummy(uint8_t val);
** SetSlowMode - void McuGenericSWSPI_SetSlowMode(void);
** SetFastMode - void McuGenericSWSPI_SetFastMode(void);
** Deinit - void McuGenericSWSPI_Deinit(void);
** Init - void McuGenericSWSPI_Init(void);
**
** * Copyright (c) 2013-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuGenericSWSPI.h
** @version 01.15
** @brief
**
*/
/*!
** @addtogroup McuGenericSWSPI_module McuGenericSWSPI module documentation
** @{
*/
/* MODULE McuGenericSWSPI. */
#include "McuGenericSWSPI.h"
/* Include inherited components */
#include "Clock1.h"
#include "Input1.h"
#include "Output1.h"
#include "McuWait.h"
#include "McuLib.h"
/* data-clock-clock */
#define OVERRUN_ERR 0x01 /* Overrun error flag bit */
#define CHAR_IN_RX 0x08 /* Char is in RX buffer */
static uint8_t McuGenericSWSPI_FastMode; /* 0: slow, 1: fast */
#define MOSI_IDLE_POLARITY 1 /* MOSI idle polarity is high */
#define CLOCK_IDLE_POLARITY 0 /* Clock idle polarity is low */
static uint8_t CLKshift;
static uint8_t CLKsampl;
static uint8_t InputBuffer;
static uint8_t SerFlag; /* Flags for serial communication */
/* Bits: 0 - OverRun error */
/* 1 - Unused */
/* 2 - Unused */
/* 3 - Char in RX buffer */
/* 4 - Unused */
/* 5 - Unused */
/* 6 - Unused */
/* 7 - Unused */
#define McuGenericSWSPI_DELAY() \
if (McuGenericSWSPI_FastMode) { /* we can change the speed at runtime */ \
McuWait_Waitus(0); /* delay for some cycles */ \
} else { \
McuWait_Waitus(0); /* delay for some cycles */ \
}
/*
** ===================================================================
** Method : SetFastMode (component GenericSWSPI)
**
** Description :
** Sets the fast mode
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_SetFastMode(void)
{
McuGenericSWSPI_FastMode = 1;
}
/*
** ===================================================================
** Method : SetSlowMode (component GenericSWSPI)
**
** Description :
** Changes to slow mode
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_SetSlowMode(void)
{
McuGenericSWSPI_FastMode = 0;
}
/*
** ===================================================================
** Method : RecvChar (component GenericSWSPI)
**
** Description :
** If any data received, this method returns one character,
** otherwise it returns an error code (it does not wait for
** data).
** Parameters :
** NAME - DESCRIPTION
** * Chr - A pointer to the received character.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_RXEMPTY - No data in receiver
** ERR_OVERRUN - Overrun error is detected
** ===================================================================
*/
uint8_t McuGenericSWSPI_RecvChar(uint8_t *Chr)
{
if(!(SerFlag & CHAR_IN_RX)) { /* Is char. received */
return ERR_RXEMPTY;
}
*Chr = InputBuffer; /* Store the character */
if(SerFlag&OVERRUN_ERR) { /* Is "overrun" occurred? */
SerFlag &= ~(OVERRUN_ERR|CHAR_IN_RX); /* If yes, clear flags */
return ERR_OVERRUN; /* ... and return error */
} else {
SerFlag &= ~CHAR_IN_RX; /* If no, clear flag */
return ERR_OK; /* ... and return */
}
}
/*
** ===================================================================
** Method : Write_ReadDummy (component GenericSWSPI)
**
** Description :
** Writes to the bus, but does not read.
** Parameters :
** NAME - DESCRIPTION
** val - value to put on the bus
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_Write_ReadDummy(uint8_t val)
{
int i;
for(i=0; i<8; i++) {
McuGenericSWSPI_DELAY();
Output1_PutVal((bool)(val&128)); /* Set value on MOSI */
InputBuffer <<= 1;
McuGenericSWSPI_DELAY();
Clock1_PutVal(CLKsampl); /* Set CLK to sample value */
val <<= 1;
Clock1_PutVal(CLKshift); /* Set CLK to shift value */
}
Output1_PutVal((bool)MOSI_IDLE_POLARITY); /* Set value on MOSI */
}
/*
** ===================================================================
** Method : SendChar (component GenericSWSPI)
**
** Description :
** Sends one character to the channel.
** Parameters :
** NAME - DESCRIPTION
** val - Character to send.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ===================================================================
*/
uint8_t McuGenericSWSPI_SendChar(uint8_t val)
{
int i;
for(i=0; i<8; i++) {
McuGenericSWSPI_DELAY();
Output1_PutVal((bool)(val&128)); /* Set value on MOSI */
InputBuffer <<= 1;
McuGenericSWSPI_DELAY();
Clock1_PutVal(CLKsampl); /* Set CLK to sample value */
InputBuffer |= Input1_GetVal()?1:0; /* Read value from MISO */
val <<= 1;
Clock1_PutVal(CLKshift); /* Set CLK to shift value */
}
Output1_PutVal((bool)MOSI_IDLE_POLARITY); /* Set value on MOSI */
if(SerFlag&CHAR_IN_RX) { /* Is char. received? */
SerFlag |= OVERRUN_ERR; /* If yes then set "overrun" flag */
} else {
SerFlag |= CHAR_IN_RX; /* If no then set "char in Rx" flag */
}
return ERR_OK;
}
/*
** ===================================================================
** Method : CharsInRxBuf (component GenericSWSPI)
**
** Description :
** Returns number of characters in the input buffer.
** Parameters : None
** Returns :
** --- - Returns number of characters in the input
** buffer.
** ===================================================================
*/
uint8_t McuGenericSWSPI_CharsInRxBuf(void)
{
return (uint8_t)((SerFlag & CHAR_IN_RX)?(uint8_t)1:(uint8_t)0); /* Return number of chars in receive buffer */
}
/*
** ===================================================================
** Method : CharsInTxBuf (component GenericSWSPI)
**
** Description :
** Returns number of characters in the output buffer.
** Parameters : None
** Returns :
** --- - Returns number of characters in the output
** buffer.
** ===================================================================
*/
#if 0 /* implemented as macro in the header file */
uint8_t McuGenericSWSPI_CharsInTxBuf(void)
{
return 0; /* Return number of chars in transmit buffer */
}
#endif
/*
** ===================================================================
** Method : SetShiftClockPolarity (component GenericSWSPI)
**
** Description :
** Sets the shift clock polarity at runtime. Output data will
** be shifted on the selected edge polarity.
** Parameters :
** NAME - DESCRIPTION
** Edge - Edge polarity, possible values:
** 0-falling edge,
** 1-rising edge.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ===================================================================
*/
uint8_t McuGenericSWSPI_SetShiftClockPolarity(uint8_t Edge)
{
CLKshift = (uint8_t)(Edge?(uint8_t)1:(uint8_t)0); /* Set shift value */
CLKsampl = (uint8_t)(CLKshift^(uint8_t)0x01); /* Set sample value */
return ERR_OK;
}
/*
** ===================================================================
** Method : SetIdleClockPolarity (component GenericSWSPI)
**
** Description :
** Set the idle clock polarity at runtime. If communication
** does not run, the clock signal will be set to the required
** level.
** Parameters :
** NAME - DESCRIPTION
** Level - Idle clock polarity:
** 0-low
** 1-high
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ===================================================================
*/
uint8_t McuGenericSWSPI_SetIdleClockPolarity(uint8_t Level)
{
Clock1_PutVal((uint8_t)Level); /* Set CLK to (new) idle value */
return ERR_OK;
}
/*
** ===================================================================
** Method : Init (component GenericSWSPI)
**
** Description :
** Driver Initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_Init(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED != McuLib_CONFIG_SDK_PROCESSOR_EXPERT
Input1_Init();
Output1_Init();
Clock1_Init();
#endif
McuGenericSWSPI_SetSlowMode(); /* slow mode is default */
/* clock idle low, falling edge: Data - Sample - Shift */
CLKsampl = 1;
CLKshift = 0;
Clock1_PutVal((bool)CLOCK_IDLE_POLARITY); /* Set CLK to idle value */
Output1_PutVal((bool)MOSI_IDLE_POLARITY); /* Set value on MOSI */
SerFlag = 0; /* Clear flags */
}
/*
** ===================================================================
** Method : Deinit (component GenericSWSPI)
**
** Description :
** Driver Deinitialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_Deinit(void)
{
#if McuLib_CONFIG_SDK_VERSION_USED != McuLib_CONFIG_SDK_PROCESSOR_EXPERT
Input1_Deinit();
Output1_Deinit();
Clock1_Deinit();
#endif
}
/* END __McuGenericSWSPI_H */
/*!
** @}
*/

View File

@@ -0,0 +1,251 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuGenericSWSPI.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : GenericSWSPI
** Version : Component 01.031, Driver 01.15, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-13, 18:42, # CodeGen: 675
** Abstract :
**
** Settings :
** Contents :
** RecvChar - uint8_t McuGenericSWSPI_RecvChar(uint8_t *Chr);
** SendChar - uint8_t McuGenericSWSPI_SendChar(uint8_t val);
** CharsInRxBuf - uint8_t McuGenericSWSPI_CharsInRxBuf(void);
** CharsInTxBuf - uint8_t McuGenericSWSPI_CharsInTxBuf(void);
** SetShiftClockPolarity - uint8_t McuGenericSWSPI_SetShiftClockPolarity(uint8_t Edge);
** SetIdleClockPolarity - uint8_t McuGenericSWSPI_SetIdleClockPolarity(uint8_t Level);
** Write_ReadDummy - void McuGenericSWSPI_Write_ReadDummy(uint8_t val);
** SetSlowMode - void McuGenericSWSPI_SetSlowMode(void);
** SetFastMode - void McuGenericSWSPI_SetFastMode(void);
** Deinit - void McuGenericSWSPI_Deinit(void);
** Init - void McuGenericSWSPI_Init(void);
**
** * Copyright (c) 2013-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuGenericSWSPI.h
** @version 01.15
** @brief
**
*/
/*!
** @addtogroup McuGenericSWSPI_module McuGenericSWSPI module documentation
** @{
*/
#ifndef __McuGenericSWSPI_H
#define __McuGenericSWSPI_H
/* MODULE McuGenericSWSPI. */
#include "McuLib.h" /* SDK and API used */
#include "McuGenericSWSPIconfig.h" /* configuration */
#ifdef __cplusplus
extern "C" {
#endif
void McuGenericSWSPI_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component GenericSWSPI)
**
** Description :
** Driver Deinitialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_SetFastMode(void);
/*
** ===================================================================
** Method : SetFastMode (component GenericSWSPI)
**
** Description :
** Sets the fast mode
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_SetSlowMode(void);
/*
** ===================================================================
** Method : SetSlowMode (component GenericSWSPI)
**
** Description :
** Changes to slow mode
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuGenericSWSPI_Write_ReadDummy(uint8_t val);
/*
** ===================================================================
** Method : Write_ReadDummy (component GenericSWSPI)
**
** Description :
** Writes to the bus, but does not read.
** Parameters :
** NAME - DESCRIPTION
** val - value to put on the bus
** Returns : Nothing
** ===================================================================
*/
uint8_t McuGenericSWSPI_RecvChar(uint8_t *Chr);
/*
** ===================================================================
** Method : RecvChar (component GenericSWSPI)
**
** Description :
** If any data received, this method returns one character,
** otherwise it returns an error code (it does not wait for
** data).
** Parameters :
** NAME - DESCRIPTION
** * Chr - A pointer to the received character.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_RXEMPTY - No data in receiver
** ERR_OVERRUN - Overrun error is detected
** ===================================================================
*/
uint8_t McuGenericSWSPI_SendChar(uint8_t val);
/*
** ===================================================================
** Method : SendChar (component GenericSWSPI)
**
** Description :
** Sends one character to the channel.
** Parameters :
** NAME - DESCRIPTION
** val - Character to send.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ===================================================================
*/
uint8_t McuGenericSWSPI_CharsInRxBuf(void);
/*
** ===================================================================
** Method : CharsInRxBuf (component GenericSWSPI)
**
** Description :
** Returns number of characters in the input buffer.
** Parameters : None
** Returns :
** --- - Returns number of characters in the input
** buffer.
** ===================================================================
*/
#define McuGenericSWSPI_CharsInTxBuf() 0 /* we always directly send the characters without buffering */
/*
** ===================================================================
** Method : CharsInTxBuf (component GenericSWSPI)
**
** Description :
** Returns number of characters in the output buffer.
** Parameters : None
** Returns :
** --- - Returns number of characters in the output
** buffer.
** ===================================================================
*/
uint8_t McuGenericSWSPI_SetShiftClockPolarity(uint8_t Edge);
/*
** ===================================================================
** Method : SetShiftClockPolarity (component GenericSWSPI)
**
** Description :
** Sets the shift clock polarity at runtime. Output data will
** be shifted on the selected edge polarity.
** Parameters :
** NAME - DESCRIPTION
** Edge - Edge polarity, possible values:
** 0-falling edge,
** 1-rising edge.
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ===================================================================
*/
uint8_t McuGenericSWSPI_SetIdleClockPolarity(uint8_t Level);
/*
** ===================================================================
** Method : SetIdleClockPolarity (component GenericSWSPI)
**
** Description :
** Set the idle clock polarity at runtime. If communication
** does not run, the clock signal will be set to the required
** level.
** Parameters :
** NAME - DESCRIPTION
** Level - Idle clock polarity:
** 0-low
** 1-high
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ===================================================================
*/
void McuGenericSWSPI_Init(void);
/*
** ===================================================================
** Method : McuGenericSWSPI_Init (component GenericSWSPI)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
/* END McuGenericSWSPI. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* ifndef __McuGenericSWSPI_H */
/*!
** @}
*/

View File

@@ -0,0 +1,244 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuHardFault.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : HardFault
** Version : Component 01.024, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2022-07-19, 17:00, # CodeGen: 782
** Abstract :
** Component to simplify hard faults for ARM (Kinetis, S32K).
** Settings :
** Component name : McuHardFault
** Contents :
** HardFaultHandler - void McuHardFault_HardFaultHandler(void);
** Deinit - void McuHardFault_Deinit(void);
** Init - void McuHardFault_Init(void);
**
** * Copyright (c) 2014-2022, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuHardFault.h
** @version 01.00
** @brief
** Component to simplify hard faults for ARM (Kinetis, S32K).
*/
/*!
** @addtogroup McuHardFault_module McuHardFault module documentation
** @{
*/
/* MODULE McuHardFault. */
#include "McuHardFault.h"
#if McuLib_CONFIG_CPU_IS_ARM_CORTEX_M
/*
** ===================================================================
** Method : McuHardFault_HandlerC (component HardFault)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
/**
* This is called from the HardFaultHandler with a pointer the Fault stack
* as the parameter. We can then read the values from the stack and place them
* into local variables for ease of reading.
* We then read the various Fault Status and Address Registers to help decode
* cause of the fault.
* The function ends with a BKPT instruction to force control back into the debugger
*/
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
void McuHardFault_HandlerC(uint32_t *hardfault_args)
{
/*lint -save -e550 Symbol not accessed. */
static volatile unsigned long stacked_r0;
static volatile unsigned long stacked_r1;
static volatile unsigned long stacked_r2;
static volatile unsigned long stacked_r3;
static volatile unsigned long stacked_r12;
static volatile unsigned long stacked_lr;
static volatile unsigned long stacked_pc;
static volatile unsigned long stacked_psr;
static volatile unsigned long _CFSR;
static volatile unsigned long _HFSR;
static volatile unsigned long _DFSR;
static volatile unsigned long _AFSR;
static volatile unsigned long _BFAR;
static volatile unsigned long _MMAR;
stacked_r0 = ((unsigned long)hardfault_args[0]); /* http://www.asciiworld.com/-Smiley,20-.html */
stacked_r1 = ((unsigned long)hardfault_args[1]); /* oooo$$$$$$$$$$$$oooo */
stacked_r2 = ((unsigned long)hardfault_args[2]); /* oo$$$$$$$$$$$$$$$$$$$$$$$$o */
stacked_r3 = ((unsigned long)hardfault_args[3]); /* oo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o o$ $$ o$ */
stacked_r12 = ((unsigned long)hardfault_args[4]); /* o $ oo o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o $$ $$ $$o$ */
stacked_lr = ((unsigned long)hardfault_args[5]); /* oo $ $ "$ o$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$o $$$o$$o$ */
stacked_pc = ((unsigned long)hardfault_args[6]); /* "$$$$$$o$ o$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$o $$$$$$$$ */
stacked_psr = ((unsigned long)hardfault_args[7]); /* $$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$ */
/* $$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$ """$$$ */
/* Configurable Fault Status Register */ /* "$$$""""$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ "$$$ */
/* Consists of MMSR, BFSR and UFSR */ /* $$$ o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ "$$$o */
_CFSR = (*((volatile unsigned long *)(0xE000ED28))); /* o$$" $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$o */
/* $$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" "$$$$$$ooooo$$$$o */
/* Hard Fault Status Register */ /* o$$$oooo$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ o$$$$$$$$$$$$$$$$$ */
_HFSR = (*((volatile unsigned long *)(0xE000ED2C))); /* $$$$$$$$"$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$"""""""" */
/* """" $$$$ "$$$$$$$$$$$$$$$$$$$$$$$$$$$$" o$$$ */
/* Debug Fault Status Register */ /* "$$$o """$$$$$$$$$$$$$$$$$$"$$" $$$ */
_DFSR = (*((volatile unsigned long *)(0xE000ED30))); /* $$$o "$$""$$$$$$"""" o$$$ */
/* $$$$o o$$$" */
/* Auxiliary Fault Status Register */ /* "$$$$o o$$$$$$o"$$$$o o$$$$ */
_AFSR = (*((volatile unsigned long *)(0xE000ED3C))); /* "$$$$$oo ""$$$$o$$$$$o o$$$$"" */
/* ""$$$$$oooo "$$$o$$$$$$$$$""" */
/* ""$$$$$$$oo $$$$$$$$$$ */
/* Read the Fault Address Registers. */ /* """"$$$$$$$$$$$ */
/* These may not contain valid values. */ /* $$$$$$$$$$$$ */
/* Check BFARVALID/MMARVALID to see */ /* $$$$$$$$$$" */
/* if they are valid values */ /* "$$$"" */
/* MemManage Fault Address Register */
_MMAR = (*((volatile unsigned long *)(0xE000ED34)));
/* Bus Fault Address Register */
_BFAR = (*((volatile unsigned long *)(0xE000ED38)));
#if 0 /* experimental, seems not to work properly with GDB in KDS V3.2.0 */
#ifdef __GNUC__ /* might improve stack, see https://www.element14.com/community/message/199113/l/gdb-assisted-debugging-of-hard-faults#199113 */
__asm volatile (
"tst lr,#4 \n" /* check which stack pointer we are using */
"ite eq \n"
"mrseq r0, msp \n" /* use MSP */
"mrsne r0, psp \n" /* use PSP */
"mov sp, r0 \n" /* set stack pointer so GDB shows proper stack frame */
);
#endif
#endif
__asm("BKPT #0\n") ; /* cause the debugger to stop */
/*lint -restore */
}
/*
** ===================================================================
** Method : HardFaultHandler (component HardFault)
**
** Description :
** Hard Fault Handler
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
__attribute__((naked))
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_RPI_PICO
void isr_hardfault(void)
#elif McuLib_CONFIG_SDK_VERSION_USED != McuLib_CONFIG_SDK_PROCESSOR_EXPERT
void HardFault_Handler(void)
#else
void McuHardFault_HardFaultHandler(void)
#endif
{
__asm volatile (
".syntax unified \n" /* needed for the 'adds r1,#2' below */
" movs r0,#4 \n" /* load bit mask into R0 */
" mov r1, lr \n" /* load link register into R1 */
" tst r0, r1 \n" /* compare with bitmask */
" beq _MSP \n" /* if bitmask is set: stack pointer is in PSP. Otherwise in MSP */
" mrs r0, psp \n" /* otherwise: stack pointer is in PSP */
" b _GetPC \n" /* go to part which loads the PC */
"_MSP: \n" /* stack pointer is in MSP register */
" mrs r0, msp \n" /* load stack pointer into R0 */
"_GetPC: \n" /* find out where the hard fault happened */
" ldr r1,[r0,#24] \n" /* load program counter into R1. R1 contains address of the next instruction where the hard fault happened */
#if McuHardFault_CONFIG_SETTING_SEMIHOSTING
/* The following code checks if the hard fault is caused by a semihosting BKPT instruction which is "BKPT 0xAB" (opcode: 0xBEAB)
The idea is taken from the MCUXpresso IDE/SDK code, so credits and kudos to the MCUXpresso IDE team! */
" ldrh r2,[r1] \n" /* load opcode causing the fault */
" ldr r3,=0xBEAB \n" /* load constant 0xBEAB (BKPT 0xAB) into R3" */
" cmp r2,r3 \n" /* is it the BKPT 0xAB? */
" beq _SemihostReturn \n" /* if yes, return from semihosting */
" b McuHardFault_HandlerC \n" /* if no, dump the register values and halt the system */
"_SemihostReturn: \n" /* returning from semihosting fault */
" adds r1,#2 \n" /* r1 points to the semihosting BKPT instruction. Adjust the PC to skip it (2 bytes) */
" str r1,[r0,#24] \n" /* store back the adjusted PC value to the interrupt stack frame */
" movs r1,#32 \n" /* need to pass back a return value to emulate a successful semihosting operation. 32 is an arbitrary value */
" str r1,[r0,#0] \n" /* store the return value on the stack frame */
" bx lr \n" /* return from the exception handler back to the application */
#else
" b McuHardFault_HandlerC \n" /* decode more information. R0 contains pointer to stack frame */
#endif
);
}
/*
** ===================================================================
** Method : Deinit (component HardFault)
**
** Description :
** Deinitializes the driver
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuHardFault_Deinit(void)
{
#if McuHardFault_CONFIG_SETTING_DISABLE_WRITE_BUFFER
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_PROCESSOR_EXPERT
SCB_ACTLR &= ~(SCB_ACTLR_DISDEFWBUF_MASK); /* write buffer bit, see https://community.nxp.com/docs/DOC-103810 */
#elif McuLib_CONFIG_NXP_SDK_USED && McuLib_McuLib_CONFIG_CORTEX_M!=7 /* not for M7? */
SCnSCB->ACTLR &= ~SCnSCB_ACTLR_DISDEFWBUF_Msk;
#endif
#endif
}
/*
** ===================================================================
** Method : Init (component HardFault)
**
** Description :
** Initializes the driver
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuHardFault_Init(void)
{
#if McuHardFault_CONFIG_SETTING_DISABLE_WRITE_BUFFER
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_PROCESSOR_EXPERT
SCB_ACTLR |= SCB_ACTLR_DISDEFWBUF_MASK; /* write buffer bit, see https://community.nxp.com/docs/DOC-103810 */
#elif McuLib_CONFIG_NXP_SDK_USED && McuLib_McuLib_CONFIG_CORTEX_M!=7 /* not for M7? */
SCnSCB->ACTLR |= SCnSCB_ACTLR_DISDEFWBUF_Msk;
#endif
#endif
}
#endif /* McuLib_CONFIG_CPU_IS_ARM_CORTEX_M */
/* END McuHardFault. */
/*!
** @}
*/

View File

@@ -0,0 +1,123 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuHardFault.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : HardFault
** Version : Component 01.024, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2022-07-19, 17:00, # CodeGen: 782
** Abstract :
** Component to simplify hard faults for ARM (Kinetis, S32K).
** Settings :
** Component name : McuHardFault
** Contents :
** HardFaultHandler - void McuHardFault_HardFaultHandler(void);
** Deinit - void McuHardFault_Deinit(void);
** Init - void McuHardFault_Init(void);
**
** * Copyright (c) 2014-2022, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuHardFault.h
** @version 01.00
** @brief
** Component to simplify hard faults for ARM (Kinetis, S32K).
*/
/*!
** @addtogroup McuHardFault_module McuHardFault module documentation
** @{
*/
#ifndef __McuHardFault_H
#define __McuHardFault_H
/* MODULE McuHardFault. */
#include "McuLib.h" /* SDK and API used */
#include "McuHardFaultconfig.h" /* configuration */
void McuHardFault_HardFaultHandler(void);
/*
** ===================================================================
** Method : HardFaultHandler (component HardFault)
**
** Description :
** Hard Fault Handler
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#ifdef __GNUC__ /* 'used' attribute needed for GNU LTO (Link Time Optimization) */
void McuHardFault_HandlerC(uint32_t *hardfault_args) __attribute__((used));
#else
void McuHardFault_HandlerC(uint32_t *hardfault_args);
#endif
/*
** ===================================================================
** Method : McuHardFault_HandlerC (component HardFault)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void McuHardFault_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component HardFault)
**
** Description :
** Deinitializes the driver
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuHardFault_Init(void);
/*
** ===================================================================
** Method : Init (component HardFault)
**
** Description :
** Initializes the driver
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/* END McuHardFault. */
#endif
/* ifndef __McuHardFault_H */
/*!
** @}
*/

View File

@@ -0,0 +1,472 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuI2CSpy.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : I2CSpy
** Version : Component 01.017, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-13, 18:42, # CodeGen: 675
** Abstract :
** This component implements a utility to inspect devices on the I2C bus.
** Settings :
** Component name : McuI2CSpy
** I2C : McuGenericI2C
** Default Address : 0x0
** Default Address Size : 1
** Default Bytes per Line : 8
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** SetDeviceAddress - uint8_t McuI2CSpy_SetDeviceAddress(uint8_t addr);
** GetDeviceAddress - uint8_t McuI2CSpy_GetDeviceAddress(void);
** SetAddressSize - uint8_t McuI2CSpy_SetAddressSize(uint8_t size);
** SetBytesPerLine - uint8_t McuI2CSpy_SetBytesPerLine(uint8_t nofBytesPerLine);
** ReadRegData - uint8_t McuI2CSpy_ReadRegData(uint32_t addr, uint8_t *data, size_t dataSize);
** WriteRegData - uint8_t McuI2CSpy_WriteRegData(uint32_t addr, uint8_t *data, uint16_t dataSize);
** ParseCommand - uint8_t McuI2CSpy_ParseCommand(const unsigned char *cmd, bool *handled, const...
** Deinit - void McuI2CSpy_Deinit(void);
** Init - uint8_t McuI2CSpy_Init(void);
**
** * Copyright (c) 2013-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuI2CSpy.h
** @version 01.00
** @brief
** This component implements a utility to inspect devices on the I2C bus.
*/
/*!
** @addtogroup McuI2CSpy_module McuI2CSpy module documentation
** @{
*/
/* MODULE McuI2CSpy. */
#include "McuI2CSpy.h"
#define McuI2CSpy_DEFAULT_I2C_ADDR 0
#define McuI2CSpy_DEFAULT_ADDR_SIZE 1
#define McuI2CSpy_DEFAULT_BYTES_PER_LINE 8
typedef struct {
uint8_t deviceAddr; /* I2C 7bit device address */
uint8_t addrSize; /* number of address bytes, e.g. 1, 2, 3 or 4 bytes */
uint8_t bytesPerLine; /* number of bytes per line for dump */
} McuI2CSpy_TDataState;
static McuI2CSpy_TDataState McuI2CSpy_deviceData;
#define MAX_NOF_BYTES_PER_LINE 32 /* maximum number of bytes per line */
static uint8_t Read(uint32_t addr, const McuShell_StdIOType *io) {
uint8_t val;
uint8_t hexBuf[3];
if (McuI2CSpy_ReadRegData(addr, &val, 1)!=ERR_OK) {
McuShell_SendStr((unsigned char*)"\r\n*** read failed!\r\n", io->stdErr);
return ERR_FAILED;
}
McuShell_SendStr((unsigned char*)"value: 0x", io->stdOut);
hexBuf[0] = '\0';
McuUtility_strcatNum8Hex(hexBuf, sizeof(hexBuf), val);
McuShell_SendStr(hexBuf, io->stdOut);
McuShell_SendStr((unsigned char*)"\r\n", io->stdOut);
return ERR_OK;
}
static uint8_t ReadData(void *hndl, uint32_t addr, uint8_t *buf, size_t bufSize) {
(void)hndl; /* not used */
if (McuI2CSpy_ReadRegData(addr, buf, bufSize)!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
static void ScanDevices(const McuShell_StdIOType *io) {
uint8_t addr, oldAddr;
uint8_t buf[3], res;
oldAddr = McuI2CSpy_GetDeviceAddress();
for (addr=0; addr<0x7f; addr++) {
McuShell_SendStr((unsigned char*)"scan of I2C device addr 0x", io->stdOut);
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), addr);
McuShell_SendStr(buf, io->stdOut);
if (McuI2CSpy_SetDeviceAddress(addr)!=ERR_OK) {
McuShell_SendStr((unsigned char*)": failed selecting device\r\n", io->stdErr);
break; /* get out of for loop */
}
res = McuGenericI2C_ScanDevice(addr);
if (res==ERR_NOTAVAIL) {
McuShell_SendStr((unsigned char*)": no ACK\r\n", io->stdErr);
} else if (res==ERR_OK) {
McuShell_SendStr((unsigned char*)": Device responded!\r\n", io->stdErr);
} else {
McuShell_SendStr((unsigned char*)": *** failed! ***\r\n", io->stdErr);
}
} /* for */
(void)McuI2CSpy_SetDeviceAddress(oldAddr); /* restore old device address */
}
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
unsigned char buf[3];
McuShell_SendStatusStr((unsigned char*)"McuI2CSpy", (unsigned char*)"\r\n", io->stdOut);
McuShell_SendStatusStr((unsigned char*)" deviceAddr", (unsigned char*)"0x", io->stdOut);
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuI2CSpy_GetDeviceAddress());
McuShell_SendStr(buf, io->stdOut);
McuShell_SendStr((unsigned char*)"\r\n", io->stdOut);
McuShell_SendStatusStr((unsigned char*)" addrSize", (unsigned char*)"", io->stdOut);
McuShell_SendNum8u(McuI2CSpy_deviceData.addrSize, io->stdOut);
McuShell_SendStr((unsigned char*)"\r\n", io->stdOut);
McuShell_SendStatusStr((unsigned char*)" bytes/Line", (unsigned char*)"", io->stdOut);
McuShell_SendNum8u(McuI2CSpy_deviceData.bytesPerLine, io->stdOut);
McuShell_SendStr((unsigned char*)"\r\n", io->stdOut);
return ERR_OK;
}
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"McuI2CSpy", (unsigned char*)"Group of McuI2CSpy commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" bytesPerLine <number>", (unsigned char*)"Number of bytes per line for dump command (1..32)\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" scan", (unsigned char*)"Scans device addresses\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" device 0x<addr>", (unsigned char*)"Set the I2C device address\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" addrSize <size>", (unsigned char*)"Address size used for device memory map (1, 2, 3 or 4)\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" read 0x<addr>", (unsigned char*)"Read a byte from an address\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" write 0x<addr> 0x<data>", (unsigned char*)"Write a data to an address. 0x<data> can be multiple items.\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" dump 0x<start>..0x<end>", (unsigned char*)"Read data from an address range\r\n", io->stdOut);
return ERR_OK;
}
/*
** ===================================================================
** Method : ParseCommand (component I2CSpy)
**
** Description :
** Shell Command Line parser
** Parameters :
** NAME - DESCRIPTION
** * cmd - Pointer to command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io)
{
uint8_t addr8, value8;
uint32_t addr32, end32;
const unsigned char *p;
uint8_t cnt;
uint8_t buf[16];
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, "McuI2CSpy help")==0) {
*handled = TRUE;
return PrintHelp(io);
} else if ((McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0) || (McuUtility_strcmp((char*)cmd, "McuI2CSpy status")==0)) {
*handled = TRUE;
return PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, "McuI2CSpy bytesPerLine ", sizeof("McuI2CSpy bytesPerLine ")-1)==0) {
p = cmd+sizeof("McuI2CSpy bytesPerLine ")-1;
if (McuUtility_ScanDecimal8uNumber(&p, &value8)==ERR_OK && value8>=1 && value8<=MAX_NOF_BYTES_PER_LINE) {
(void)McuI2CSpy_SetBytesPerLine(value8);
} else {
McuShell_SendStr((unsigned char*)"**** wrong bytes per line, must be 1..32\r\n", io->stdErr);
}
*handled = TRUE;
} else if (McuUtility_strncmp((char*)cmd, "McuI2CSpy device ", sizeof("McuI2CSpy device ")-1)==0) {
p = cmd+sizeof("McuI2CSpy device ")-1;
if (McuUtility_ScanHex8uNumber(&p, &addr8)==ERR_OK && addr8<=0x7F) {
(void)McuI2CSpy_SetDeviceAddress(addr8);
} else {
McuShell_SendStr((unsigned char*)"**** wrong device address\r\n", io->stdErr);
}
*handled = TRUE;
} else if (McuUtility_strncmp((char*)cmd, "McuI2CSpy read ", sizeof("McuI2CSpy read ")-1)==0) {
p = cmd+sizeof("McuI2CSpy read ")-1;
if (McuUtility_ScanHex32uNumber(&p, &addr32)==ERR_OK) {
(void)Read(addr32, io);
} else {
McuShell_SendStr((unsigned char*)"**** wrong address\r\n", io->stdErr);
}
*handled = TRUE;
} else if (McuUtility_strncmp((char*)cmd, "McuI2CSpy addrSize ", sizeof("McuI2CSpy addrSize ")-1)==0) {
p = cmd+sizeof("McuI2CSpy addrSize ")-1;
if (McuUtility_ScanDecimal8uNumber(&p, &value8)==ERR_OK && value8>=1 && value8<=4) {
(void)McuI2CSpy_SetAddressSize(value8);
} else {
McuShell_SendStr((unsigned char*)"**** addrSize of range (1-4)\r\n", io->stdErr);
}
*handled = TRUE;
} else if (McuUtility_strncmp((char*)cmd, "McuI2CSpy write ", sizeof("McuI2CSpy write ")-1)==0) {
p = cmd+sizeof("McuI2CSpy write ")-1;
if (McuUtility_ScanHex32uNumber(&p, &addr32)==ERR_OK) {
for(cnt=0; cnt<sizeof(buf) && *p!='\0'; cnt++) { /* breaks */
if (McuUtility_ScanHex8uNumber(&p, &buf[cnt])!=ERR_OK) {
McuShell_SendStr((unsigned char*)"**** wrong data format\r\n", io->stdErr);
cnt = 0;
break;
}
} /* for */
if (cnt>=1) {
(void)McuI2CSpy_WriteRegData(addr32, &buf[0], cnt);
}
} /* if */
*handled = TRUE;
} else if (McuUtility_strncmp((char*)cmd, "McuI2CSpy dump ", sizeof("McuI2CSpy dump ")-1)==0) {
p = cmd+sizeof("McuI2CSpy dump ")-1;
if (McuUtility_ScanHex32uNumber(&p, &addr32)==ERR_OK) {
if (McuUtility_strncmp((char*)p, "..", sizeof("..")-1)==0) {
p = p+sizeof("..")-1;
if (McuUtility_ScanHex32uNumber(&p, &end32)==ERR_OK) {
(void)McuShell_PrintMemory(NULL, addr32, end32, McuI2CSpy_deviceData.addrSize, McuI2CSpy_deviceData.bytesPerLine, ReadData, io);
} else {
McuShell_SendStr((unsigned char*)"**** wrong end address\r\n", io->stdErr);
}
} else {
McuShell_SendStr((unsigned char*)"**** wrong format, '..' expected.\r\n", io->stdErr);
}
} else {
McuShell_SendStr((unsigned char*)"**** wrong start address\r\n", io->stdErr);
}
*handled = TRUE;
} else if (McuUtility_strcmp((char*)cmd, "McuI2CSpy scan")==0) {
ScanDevices(io);
*handled = TRUE;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : SetDeviceAddress (component I2CSpy)
**
** Description :
** Sets the I2C Device address to be used
** Parameters :
** NAME - DESCRIPTION
** addr - I2C 7bit address
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_SetDeviceAddress(uint8_t addr)
{
McuI2CSpy_deviceData.deviceAddr = addr;
return ERR_OK;
}
/*
** ===================================================================
** Method : GetDeviceAddress (component I2CSpy)
**
** Description :
** Returns the current I2C Device address used
** Parameters : None
** Returns :
** --- - 7bit Device Address
** ===================================================================
*/
uint8_t McuI2CSpy_GetDeviceAddress(void)
{
return McuI2CSpy_deviceData.deviceAddr;
}
/*
** ===================================================================
** Method : SetAddressSize (component I2CSpy)
**
** Description :
** Specifies the address size of the I2C device memory
** Parameters :
** NAME - DESCRIPTION
** size - Either 1 (8bit), 2 (16bit), 3 (24bit),
** or 4 (32bit)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_SetAddressSize(uint8_t size)
{
McuI2CSpy_deviceData.addrSize = size;
return ERR_OK;
}
/*
** ===================================================================
** Method : SetBytesPerLine (component I2CSpy)
**
** Description :
** Sets the number of bytes per line for the Dump shell command
** Parameters :
** NAME - DESCRIPTION
** nofBytesPerLine - Number of bytes
** per line
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_SetBytesPerLine(uint8_t nofBytesPerLine)
{
McuI2CSpy_deviceData.bytesPerLine = nofBytesPerLine;
return ERR_OK;
}
/*
** ===================================================================
** Method : Init (component I2CSpy)
**
** Description :
** Initialization method
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_Init(void)
{
if (McuI2CSpy_SetDeviceAddress(McuI2CSpy_DEFAULT_I2C_ADDR)!=ERR_OK) {
return ERR_FAILED;
}
if (McuI2CSpy_SetBytesPerLine(McuI2CSpy_DEFAULT_BYTES_PER_LINE)!=ERR_OK) {
return ERR_FAILED;
}
if (McuI2CSpy_SetAddressSize(McuI2CSpy_DEFAULT_ADDR_SIZE)!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : Deinit (component I2CSpy)
**
** Description :
** Deinitialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuI2CSpy_Deinit(void)
{
/* nothing to do */
}
/*
** ===================================================================
** Method : McuI2CSpy_OnRequestBus (component I2CSpy)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void McuI2CSpy_OnRequestBus(void)
{
/* Write your code here ... */
}
/*
** ===================================================================
** Method : McuI2CSpy_OnReleaseBus (component I2CSpy)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void McuI2CSpy_OnReleaseBus(void)
{
/* Write your code here ... */
}
/*
** ===================================================================
** Method : ReadRegData (component I2CSpy)
**
** Description :
** Reads data starting from a register address from the current
** device
** Parameters :
** NAME - DESCRIPTION
** addr - Device address
** * data - Pointer to data buffer where read data
** is stored
** dataSize - size of data buffer in bytes
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_ReadRegData(uint32_t addr, uint8_t *data, size_t dataSize)
{
uint8_t addrBuf[4];
addrBuf[3] = (uint8_t)(addr&0xff);
addrBuf[2] = (uint8_t)((addr&0xff00)>>8);
addrBuf[1] = (uint8_t)((addr&0xff0000)>>16);
addrBuf[0] = (uint8_t)((addr&0xff000000)>>24);
return McuGenericI2C_ReadAddress(McuI2CSpy_deviceData.deviceAddr, &addrBuf[4-McuI2CSpy_deviceData.addrSize],
McuI2CSpy_deviceData.addrSize, data, dataSize);
}
/*
** ===================================================================
** Method : WriteRegData (component I2CSpy)
**
** Description :
** Writes data starting from a register address to the current
** device
** Parameters :
** NAME - DESCRIPTION
** addr - Address in device
** * data - Pointer to data to write
** dataSize - Size of data in bytes
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_WriteRegData(uint32_t addr, uint8_t *data, uint16_t dataSize)
{
uint8_t addrBuf[4];
addrBuf[3] = (uint8_t)(addr&0xff);
addrBuf[2] = (uint8_t)((addr&0xff00)>>8);
addrBuf[1] = (uint8_t)((addr&0xff0000)>>16);
addrBuf[0] = (uint8_t)((addr&0xff000000)>>24);
return McuGenericI2C_WriteAddress(McuI2CSpy_deviceData.deviceAddr, &addrBuf[4-McuI2CSpy_deviceData.addrSize],
McuI2CSpy_deviceData.addrSize, data, dataSize);
}
/* END McuI2CSpy. */
/*!
** @}
*/

View File

@@ -0,0 +1,237 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuI2CSpy.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : I2CSpy
** Version : Component 01.017, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-13, 18:42, # CodeGen: 675
** Abstract :
** This component implements a utility to inspect devices on the I2C bus.
** Settings :
** Component name : McuI2CSpy
** I2C : McuGenericI2C
** Default Address : 0x0
** Default Address Size : 1
** Default Bytes per Line : 8
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** SetDeviceAddress - uint8_t McuI2CSpy_SetDeviceAddress(uint8_t addr);
** GetDeviceAddress - uint8_t McuI2CSpy_GetDeviceAddress(void);
** SetAddressSize - uint8_t McuI2CSpy_SetAddressSize(uint8_t size);
** SetBytesPerLine - uint8_t McuI2CSpy_SetBytesPerLine(uint8_t nofBytesPerLine);
** ReadRegData - uint8_t McuI2CSpy_ReadRegData(uint32_t addr, uint8_t *data, size_t dataSize);
** WriteRegData - uint8_t McuI2CSpy_WriteRegData(uint32_t addr, uint8_t *data, uint16_t dataSize);
** ParseCommand - uint8_t McuI2CSpy_ParseCommand(const unsigned char *cmd, bool *handled, const...
** Deinit - void McuI2CSpy_Deinit(void);
** Init - uint8_t McuI2CSpy_Init(void);
**
** * Copyright (c) 2013-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuI2CSpy.h
** @version 01.00
** @brief
** This component implements a utility to inspect devices on the I2C bus.
*/
/*!
** @addtogroup McuI2CSpy_module McuI2CSpy module documentation
** @{
*/
#ifndef __McuI2CSpy_H
#define __McuI2CSpy_H
/* MODULE McuI2CSpy. */
#include "McuLib.h" /* SDK and API used */
#include "McuI2CSpyconfig.h" /* configuration */
/* Include inherited components */
#include "McuGenericI2C.h"
#include "McuLib.h"
#include "McuShell.h"
#include "McuUtility.h"
#define McuI2CSpy_PARSE_COMMAND_ENABLED 1 /* set to 1 if method ParseCommand() is present, 0 otherwise */
uint8_t McuI2CSpy_Init(void);
/*
** ===================================================================
** Method : Init (component I2CSpy)
**
** Description :
** Initialization method
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
void McuI2CSpy_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component I2CSpy)
**
** Description :
** Deinitialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuI2CSpy_SetDeviceAddress(uint8_t addr);
/*
** ===================================================================
** Method : SetDeviceAddress (component I2CSpy)
**
** Description :
** Sets the I2C Device address to be used
** Parameters :
** NAME - DESCRIPTION
** addr - I2C 7bit address
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_SetAddressSize(uint8_t size);
/*
** ===================================================================
** Method : SetAddressSize (component I2CSpy)
**
** Description :
** Specifies the address size of the I2C device memory
** Parameters :
** NAME - DESCRIPTION
** size - Either 1 (8bit), 2 (16bit), 3 (24bit),
** or 4 (32bit)
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_SetBytesPerLine(uint8_t nofBytesPerLine);
/*
** ===================================================================
** Method : SetBytesPerLine (component I2CSpy)
**
** Description :
** Sets the number of bytes per line for the Dump shell command
** Parameters :
** NAME - DESCRIPTION
** nofBytesPerLine - Number of bytes
** per line
** Returns :
** --- - Error code
** ===================================================================
*/
void McuI2CSpy_OnRequestBus(void);
void McuI2CSpy_OnReleaseBus(void);
uint8_t McuI2CSpy_ReadRegData(uint32_t addr, uint8_t *data, size_t dataSize);
/*
** ===================================================================
** Method : ReadRegData (component I2CSpy)
**
** Description :
** Reads data starting from a register address from the current
** device
** Parameters :
** NAME - DESCRIPTION
** addr - Device address
** * data - Pointer to data buffer where read data
** is stored
** dataSize - size of data buffer in bytes
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_WriteRegData(uint32_t addr, uint8_t *data, uint16_t dataSize);
/*
** ===================================================================
** Method : WriteRegData (component I2CSpy)
**
** Description :
** Writes data starting from a register address to the current
** device
** Parameters :
** NAME - DESCRIPTION
** addr - Address in device
** * data - Pointer to data to write
** dataSize - Size of data in bytes
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component I2CSpy)
**
** Description :
** Shell Command Line parser
** Parameters :
** NAME - DESCRIPTION
** * cmd - Pointer to command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuI2CSpy_GetDeviceAddress(void);
/*
** ===================================================================
** Method : GetDeviceAddress (component I2CSpy)
**
** Description :
** Returns the current I2C Device address used
** Parameters : None
** Returns :
** --- - 7bit Device Address
** ===================================================================
*/
/* END McuI2CSpy. */
#endif
/* ifndef __McuI2CSpy_H */
/*!
** @}
*/

View File

@@ -0,0 +1,356 @@
/*
* Copyright (c) 2019-2023, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuI2cLibconfig.h"
#if McuLib_CONFIG_MCUI2CLIB_ENABLED
#include "McuLib.h"
#include "McuI2cLib.h"
#if MCUI2CLIB_CONFIG_I2C_RELEASE_BUS
#include "McuGPIO.h"
#endif
#include "McuWait.h"
#include "McuRTOS.h"
#include "McuLog.h"
#if McuLib_CONFIG_CPU_IS_KINETIS
#include "fsl_port.h"
#include "fsl_i2c.h"
#elif McuLib_CONFIG_CPU_IS_LPC
#include "pin_mux.h"
#include "fsl_iocon.h"
#include "fsl_i2c.h"
#elif McuLib_CONFIG_CPU_IS_RPxxxx
#include "hardware/i2c.h"
#elif McuLib_CONFIG_CPU_IS_ESP32
#include "driver/i2c_master.h"
#endif
#if McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC845
#include "fsl_swm.h"
#include "fsl_i2c.h"
#endif
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#endif
#if McuLib_CONFIG_SDK_VERSION_USED!=McuLib_CONFIG_SDK_LINUX
static uint8_t i2cSlaveDeviceAddr; /* used to store the current I2C device address used */
#endif
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
static int i2cBusHandle; /* file handle of I2C bus */
#endif
#if McuLib_CONFIG_CPU_IS_ESP32
static i2c_device_config_t dev_cfg = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = 0, /* dummy device number */
.scl_speed_hz = MCUI2CLIB_CONFIG_I2C_BAUDRATE,
.scl_wait_us = 0, /* use default value */
.flags.disable_ack_check = 0, /* ACK check enabled */
};
static i2c_master_dev_handle_t dev_handle = NULL;
static i2c_master_bus_handle_t bus_handle = NULL;
static void Esp32_SelectDevice(uint8_t deviceAddr) {
/* for ESP32, we re-configure the dev_handle if we switch to a new device */
esp_err_t err;
if (deviceAddr!=dev_cfg.device_address) { /* new device to be used? */
if (dev_handle!=NULL) { /* free previous device handle */
err = i2c_master_bus_rm_device(dev_handle);
if (err!=ESP_OK) {
McuLog_fatal("failed adding bus device");
}
}
dev_cfg.device_address = deviceAddr;
err = i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle);
if (err!=ESP_OK) {
McuLog_fatal("failed adding bus device");
}
}
}
#endif /* McuLib_CONFIG_CPU_IS_ESP32 */
uint8_t McuI2cLib_SendBlock(void *Ptr, uint16_t Siz, uint16_t *Snt) {
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC
status_t status;
#if McuLib_CONFIG_CPU_IS_KINETIS
I2C_MasterClearStatusFlags(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR, kI2C_ArbitrationLostFlag | kI2C_IntPendingFlag | kI2C_StartDetectFlag | kI2C_StopDetectFlag);
#elif McuLib_CONFIG_CPU_IS_LPC
I2C_MasterClearStatusFlags(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR, kI2C_MasterPendingFlag | kI2C_MasterArbitrationLostFlag | kI2C_MasterStartStopErrorFlag);
#endif
status = I2C_MasterStart(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR, i2cSlaveDeviceAddr, kI2C_Write);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
#elif McuLib_CONFIG_CPU_IS_RPxxxx
/* nothing needed */
#elif McuLib_CONFIG_CPU_IS_ESP32
/* nothing needed */
#endif
#if MCUI2CLIB_CONFIG_ADD_DELAY
McuWait_Waitus(MCUI2CLIB_CONFIG_ADD_DELAY_US);
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC
status = I2C_MasterWriteBlocking(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR, Ptr, Siz, kI2C_TransferNoStartFlag|kI2C_TransferNoStopFlag);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
#elif McuLib_CONFIG_CPU_IS_RPxxxx
int nofBytesWritten;
#if MCUI2CLIB_CONFIG_TIMEOUT_BYTE_US==0
nofBytesWritten = i2c_write_blocking(MCUI2CLIB_CONFIG_I2C_DEVICE, i2cSlaveDeviceAddr, (uint8_t*)Ptr, Siz, false);
#else
nofBytesWritten = i2c_write_timeout_us(MCUI2CLIB_CONFIG_I2C_DEVICE, i2cSlaveDeviceAddr, (uint8_t*)Ptr, Siz, false, Siz*MCUI2CLIB_CONFIG_TIMEOUT_BYTE_US);
#endif
if (nofBytesWritten!=Siz) {
*Snt = nofBytesWritten;
return ERR_FAILED;
}
#elif McuLib_CONFIG_CPU_IS_ESP32
esp_err_t ret;
ret = i2c_master_transmit(dev_handle, Ptr, Siz, pdMS_TO_TICKS(MCUI2CLIB_I2C_MASTER_TIMEOUT_MS));
if (ret!=ESP_OK) {
return ERR_FAILED;
}
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
if (write(i2cBusHandle, Ptr, Siz)<0) {
return ERR_FAILED;
}
#endif
*Snt = Siz;
return ERR_OK;
}
uint8_t McuI2cLib_RecvBlock(void *Ptr, uint16_t Siz, uint16_t *Rcv) {
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC
status_t status;
status = I2C_MasterRepeatedStart(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR, i2cSlaveDeviceAddr, kI2C_Read);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
#if MCUI2CLIB_CONFIG_ADD_DELAY
McuWait_Waitus(MCUI2CLIB_CONFIG_ADD_DELAY_US);
#endif
status = I2C_MasterReadBlocking(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR, Ptr, Siz, kI2C_TransferDefaultFlag);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
#elif McuLib_CONFIG_CPU_IS_RPxxxx
int nofBytesRead;
nofBytesRead = i2c_read_blocking(MCUI2CLIB_CONFIG_I2C_DEVICE, i2cSlaveDeviceAddr, (uint8_t*)Ptr, Siz, false);
if (nofBytesRead!=Siz) {
*Rcv = nofBytesRead;
return ERR_FAILED;
}
#elif McuLib_CONFIG_CPU_IS_ESP32
esp_err_t ret;
ret = i2c_master_receive(dev_handle, Ptr, Siz, pdMS_TO_TICKS(MCUI2CLIB_I2C_MASTER_TIMEOUT_MS));
if (ret!=ESP_OK) {
return ERR_FAILED;
}
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
if (read(i2cBusHandle, Ptr, Siz)!=Siz) {
return ERR_FAILED;
}
#endif
*Rcv = Siz;
return ERR_OK;
}
uint8_t McuI2cLib_SendStop(void) {
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC
status_t status;
status = I2C_MasterStop(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR);
if (status!=kStatus_Success) {
return ERR_FAILED;
}
return ERR_OK;
#elif McuLib_CONFIG_CPU_IS_RPxxxx
return ERR_OK; /* not required for RP2040 */
#elif McuLib_CONFIG_CPU_IS_ESP32
return ERR_OK; /* not required for ESP32 */
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
return ERR_OK; /* not required for Linux */
#else
return ERR_FAILED;
#endif
}
uint8_t McuI2cLib_SelectSlave(uint8_t Slv) {
#if McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
if (ioctl(i2cBusHandle, I2C_SLAVE, Slv)<0) { /* select the device */
return ERR_FAILED;
}
#else
i2cSlaveDeviceAddr = Slv;
#if McuLib_CONFIG_CPU_IS_ESP32
Esp32_SelectDevice(Slv);
#endif
#endif
return ERR_OK;
}
#if MCUI2CLIB_CONFIG_I2C_RELEASE_BUS
static void McuI2cLib_ReleaseBus(void) {
McuGPIO_Handle_t sdaPin, sclPin;
McuGPIO_Config_t config;
uint8_t i = 0;
McuGPIO_GetDefaultConfig(&config);
config.isInput = false;
config.isHighOnInit = true;
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC
config.hw.gpio = MCUI2CLIB_CONFIG_SDA_GPIO;
config.hw.port = MCUI2CLIB_CONFIG_SDA_GPIO_PORT;
#endif
config.hw.pin = MCUI2CLIB_CONFIG_SDA_GPIO_PIN;
sdaPin = McuGPIO_InitGPIO(&config);
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC
config.hw.gpio = MCUI2CLIB_CONFIG_SCL_GPIO;
config.hw.port = MCUI2CLIB_CONFIG_SCL_GPIO_PORT;
#endif
config.hw.pin = MCUI2CLIB_CONFIG_SCL_GPIO_PIN;
sclPin = McuGPIO_InitGPIO(&config);
/* Drive SDA low first to simulate a start */
McuGPIO_SetLow(sdaPin);
McuWait_Waitus(10);
/* Send 9 pulses on SCL and keep SDA high */
for (i = 0; i < 9; i++) {
McuGPIO_SetLow(sclPin);
McuWait_Waitus(10);
McuGPIO_SetHigh(sdaPin);
McuWait_Waitus(10);
McuGPIO_SetHigh(sclPin);
McuWait_Waitus(20);
}
/* Send stop */
McuGPIO_SetLow(sclPin);
McuWait_Waitus(10);
McuGPIO_SetLow(sdaPin);
McuWait_Waitus(10);
McuGPIO_SetLow(sclPin);
McuWait_Waitus(10);
McuGPIO_SetHigh(sdaPin);
McuWait_Waitus(10);
/* cleanup */
sdaPin = McuGPIO_DeinitGPIO(sdaPin);
sclPin = McuGPIO_DeinitGPIO(sclPin);
}
#endif /* MCUI2CLIB_CONFIG_I2C_RELEASE_BUS */
/* mux as I2C pins */
static void McuI2cLib_ConfigureI2cPins(void) {
#if McuLib_CONFIG_CPU_IS_KINETIS \
|| McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC55S16 \
|| McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC55S69 \
|| McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC845
MCUI2CLIB_CONFIG_MUX_I2C_PINS();
#elif McuLib_CONFIG_CPU_IS_RPxxxx
gpio_set_function(MCUI2CLIB_CONFIG_SDA_GPIO_PIN, GPIO_FUNC_I2C);
gpio_set_function(MCUI2CLIB_CONFIG_SCL_GPIO_PIN, GPIO_FUNC_I2C);
gpio_pull_up(MCUI2CLIB_CONFIG_SDA_GPIO_PIN);
gpio_pull_up(MCUI2CLIB_CONFIG_SCL_GPIO_PIN);
#elif McuLib_CONFIG_CPU_IS_ESP32
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
/* nothing needed */
#else
#error "unknown configuration and MCU"
#endif
}
void McuI2cLib_Deinit(void) {
/* nothing implemented */
}
#if McuLib_CONFIG_CPU_IS_ESP32
static esp_err_t esp32_master_init(void) {
esp_err_t err;
i2c_master_bus_config_t i2c_mst_config = {
.clk_source = I2C_CLK_SRC_DEFAULT,
.i2c_port = MCUI2CLIB_CONFIG_I2C_DEVICE,
.scl_io_num = MCUI2CLIB_CONFIG_SCL_GPIO_PIN,
.sda_io_num = MCUI2CLIB_CONFIG_SDA_GPIO_PIN,
.glitch_ignore_cnt = 7,
.intr_priority = 0, /* use default priority */
.trans_queue_depth = 0, /* only valid/needed in asynchronous transaction */
.flags.enable_internal_pullup = true, /* weak pull-ups anyway, use external pull-ups in addition! */
};
err = i2c_new_master_bus(&i2c_mst_config, &bus_handle);
if (err!=ESP_OK) {
McuLog_fatal("failed creating new master bus");
}
return err;
}
#endif /* McuLib_CONFIG_CPU_IS_ESP32 */
void McuI2cLib_Init(void) {
#if MCUI2CLIB_CONFIG_I2C_RELEASE_BUS
McuI2cLib_ReleaseBus();
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS \
|| McuLib_CONFIG_CPU_IS_LPC55xx && McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC55S16 \
|| McuLib_CONFIG_CPU_IS_LPC55xx && McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC55S69 \
|| McuLib_CONFIG_CPU_IS_LPC && McuLib_CONFIG_CPU_VARIANT==McuLib_CONFIG_CPU_VARIANT_NXP_LPC845
MCUI2CLIB_CONFIG_CLOCK_SELECT();
#elif McuLib_CONFIG_CPU_IS_RPxxxx
i2c_init(MCUI2CLIB_CONFIG_I2C_DEVICE, MCUI2CLIB_CONFIG_I2C_BAUDRATE);
#elif McuLib_CONFIG_CPU_IS_ESP32
if (esp32_master_init()!=ESP_OK) {
McuLog_fatal("failed initializing I2C");
}
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
i2cBusHandle = open(MCUI2CLIB_CONFIG_I2C_DEVICE, O_RDWR); /* device is something like "/dev/i2c-1" */
if(i2cBusHandle<0) { /* open bus */
McuLog_fatal("Failed to open I2C bus!\n");
}
#else
#error "unknown configuration and MCU"
#endif
McuI2cLib_ConfigureI2cPins();
#if McuLib_CONFIG_CPU_IS_KINETIS || McuLib_CONFIG_CPU_IS_LPC
i2c_master_config_t masterConfig;
uint32_t sourceClock;
/*
* masterConfig->baudRate_Bps = 100000U;
* masterConfig->enableStopHold = false;
* masterConfig->glitchFilterWidth = 0U;
* masterConfig->enableMaster = true;
*/
I2C_MasterGetDefaultConfig(&masterConfig);
masterConfig.baudRate_Bps = MCUI2CLIB_CONFIG_I2C_BAUDRATE;
sourceClock = MCUI2CLIB_CONFIG_I2C_MASTER_CLK_FREQ;
I2C_MasterInit(MCUI2CLIB_CONFIG_I2C_MASTER_BASEADDR, &masterConfig, sourceClock);
#elif McuLib_CONFIG_CPU_IS_RPxxxx
/* nothing needed */
#elif McuLib_CONFIG_CPU_IS_ESP32
/* nothing needed */
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_LINUX
/* nothing needed */
#endif
}
#endif /* McuLib_CONFIG_MCUI2CLIB_ENABLED */

View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2019-2022, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MCUI2CLIB_H_
#define MCUI2CLIB_H_
#include <stdint.h>
#include "McuI2cLibconfig.h"
typedef enum McuI2cLib_EnumStartFlags_ {
MCUI2CLIB_SEND_START, /* Start is sent */
MCUI2CLIB_DO_NOT_SEND_START /* Start is not sent */
} McuI2cLib_EnumStartFlags;
typedef enum I2CLIB_EnumAckFlags_ {
MCUI2CLIB_SEND_LAST_ACK, /* Nack after last received byte is sent */
MCUI2CLIB_DO_NOT_LAST_ACK /* Nack after last received byte is not sent */
} McuI2cLib_EnumAckFlags;
uint8_t McuI2cLib_RecvBlockCustom(void *Ptr, uint16_t Siz, uint16_t *Rcv, McuI2cLib_EnumStartFlags flagsStart, McuI2cLib_EnumAckFlags flagsAck);
uint8_t McuI2cLib_RecvBlock(void *Ptr, uint16_t Siz, uint16_t *Rcv);
uint8_t McuI2cLib_SendBlock(void *Ptr, uint16_t Siz, uint16_t *Snt);
uint8_t McuI2cLib_SendBlockContinue(void *Ptr, uint16_t Siz, uint16_t *Snt);
uint8_t McuI2cLib_SendStop(void);
uint8_t McuI2cLib_SelectSlave(uint8_t Slv);
uint8_t McuI2cLib_ReadAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint8_t *data, uint16_t dataSize);
uint8_t McuI2cLib_WriteAddress(uint8_t i2cAddr, uint8_t *memAddr, uint8_t memAddrSize, uint8_t *data, uint16_t dataSize);
void McuI2cLib_Deinit(void);
void McuI2cLib_Init(void);
#endif /* MCUI2CLIB_H_ */

View File

@@ -0,0 +1,312 @@
/**
* Copyright (c) 2023, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*
* \brief Driver for the TI INA260 current/voltage sensor.
*/
#include "McuINA260.h"
#include "McuUtility.h"
#include "McuGenericI2C.h"
#define SwapBytes(u16) ((u16<<8)|(u16>>8))
/*!
* \brief Convert the 16bit current register value to micro amps
* \param value McuINA260_ADDR_CURRENT_REGISTER register value
* \return Current in micro amp
*/
static int32_t McuINA260_ConvertCurrentRegisterToMicroAmps(int16_t value) {
/* LSB == 1.25 mA == 1250 uA */
return value*1250;
}
/*!
* \brief Convert the voltage register value into miro volts
* \param value McuINA260_ADDR_BUS_VOLTAGE_REGISTER register value
* \return Voltage in micro volt
*/
static uint32_t McuINA260_ConvertBusVoltageRegisterToMicroVoltage(uint16_t value) {
/* LSB == 1.25 mV == 1250 uV */
return (uint32_t)value*1250;
}
/*!
* \brief Convert the power register value into miro volts
* \param value McuINA260_ADDR_POWER_REGISTER register value
* \return Voltage in milli watt
*/
static uint32_t McuINA260_ConvertPowerRegisterToMilliWatt(uint16_t value) {
/* LSB == 10 mW */
return (uint32_t)value*10;
}
uint8_t McuINA260_ReadRegister(INA260_REG_e reg, uint16_t *value) {
uint8_t res;
uint16_t data;
res = McuGenericI2C_ReadWordAddress8(McuINA260_CONFIG_I2C_ADDRESS, reg, &data);
if (res!=ERR_OK) {
return res;
}
*value = SwapBytes(data);
return ERR_OK;
}
uint8_t McuINA260_WriteRegister(INA260_REG_e reg, uint16_t value) {
uint8_t res;
uint16_t data;
data = SwapBytes(value);
res = McuGenericI2C_WriteWordAddress8(McuINA260_CONFIG_I2C_ADDRESS, reg, data);
if (res!=ERR_OK) {
return res;
}
return ERR_OK;
}
uint8_t McuINA260_ReadConfigRegister(uint16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_CONFIGURATION_REGISTER, value);
}
uint8_t McuINA260_WriteConfigRegister(uint16_t value) {
return McuINA260_WriteRegister(McuINA260_ADDR_CONFIGURATION_REGISTER, value);
}
uint8_t McuINA260_WriteResetBit(void) {
return McuINA260_WriteConfigRegister(1<<15);
}
uint8_t McuINA260_ReadCurrentRegister(int16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_CURRENT_REGISTER, (uint16_t*)value);
}
uint8_t McuINA260_ReadBusVoltageRegister(uint16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_BUS_VOLTAGE_REGISTER, value);
}
uint8_t McuINA260_ReadPowerRegister(uint16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_POWER_REGISTER, value);
}
uint8_t McuINA260_ReadMaskEnableRegister(uint16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_MASK_ENABLE_REGISTER, value);
}
uint8_t McuINA260_ReadAlertLimitRegister(uint16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_ALERT_LIMIT_REGISTER, value);
}
uint8_t McuINA260_ReadManufacturereIDRegister(uint16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_MANUFACTURER_ID_REGISTER, value);
}
uint8_t McuINA260_ReadDieIDRegister(uint16_t *value) {
return McuINA260_ReadRegister(McuINA260_ADDR_DIE_ID_REGISTER, value);
}
/*!
* \brief Read the bus voltage measurement value from the device.
* \return Power value, as mV (micro-Volt).
*/
uint32_t McuINA260_ReadVoltage(void) {
uint8_t res;
uint16_t val;
res = McuINA260_ReadBusVoltageRegister(&val);
if (res==ERR_OK) {
return McuINA260_ConvertBusVoltageRegisterToMicroVoltage(val);
} else {
return 0; /* error case */
}
}
/*!
* \brief Read the power measurement value from the device.
* \return Power value, as mW (milli-Watt).
*/
uint32_t McuINA260_ReadPower(void) {
uint8_t res;
uint16_t val;
res = McuINA260_ReadPowerRegister(&val);
if (res==ERR_OK) {
return McuINA260_ConvertPowerRegisterToMilliWatt(val);
} else {
return 0; /* error case */
}
}
/*!
* \brief Read the current measurement value from the device.
* \return Current value, as uA (micro-Amps).
*/
int32_t McuINA260_ReadCurrent(void) {
uint8_t res;
int16_t val;
res = McuINA260_ReadCurrentRegister(&val);
if (res==ERR_OK) {
return McuINA260_ConvertCurrentRegisterToMicroAmps(val);
} else {
return 0; /* error case */
}
}
#if McuINA260_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
uint8_t buf[32];
uint16_t value;
int16_t i16;
McuShell_SendStatusStr((unsigned char*)"McuINA260", (unsigned char*)"INA260 sensor status\r\n", io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_CONFIG_I2C_ADDRESS);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" I2C addr", buf, io->stdOut);
if (McuINA260_ReadConfigRegister(&value)==ERR_OK) {
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_ADDR_CONFIGURATION_REGISTER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"h: 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), value);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"FAILED\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Config", buf, io->stdOut);
if (McuINA260_ReadCurrentRegister(&i16)==ERR_OK) {
int32_t uA = McuINA260_ConvertCurrentRegisterToMicroAmps(i16);
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_ADDR_CURRENT_REGISTER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"h: 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), i16);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", ");
McuUtility_strcatNum32s(buf, sizeof(buf), uA/1000);
McuUtility_chcat(buf, sizeof(buf), '.');
if (uA<0) { /* value can be negative */
uA = -uA; /* make it positive for the modulo operation below */
}
McuUtility_strcatNum32sFormatted(buf, sizeof(buf), uA%1000, '0', 3);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" mA\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"FAILED\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Current", buf, io->stdOut);
if (McuINA260_ReadBusVoltageRegister(&value)==ERR_OK) {
uint32_t uV = McuINA260_ConvertBusVoltageRegisterToMicroVoltage(value);
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_ADDR_BUS_VOLTAGE_REGISTER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"h: 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), value);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", ");
McuUtility_strcatNum32u(buf, sizeof(buf), uV/1000);
McuUtility_chcat(buf, sizeof(buf), '.');
McuUtility_strcatNum32sFormatted(buf, sizeof(buf), uV%1000, '0', 3);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" mV\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"FAILED\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Bus voltage", buf, io->stdOut);
if (McuINA260_ReadPowerRegister(&value)==ERR_OK) {
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_ADDR_POWER_REGISTER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"h: 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), value);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)", ");
McuUtility_strcatNum32u(buf, sizeof(buf), McuINA260_ConvertPowerRegisterToMilliWatt(value));
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" mW\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"FAILED\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Power", buf, io->stdOut);
if (McuINA260_ReadAlertLimitRegister(&value)==ERR_OK) {
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_ADDR_ALERT_LIMIT_REGISTER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"h: 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), value);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"FAILED\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Alert limit", buf, io->stdOut);
if (McuINA260_ReadManufacturereIDRegister(&value)==ERR_OK) {
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_ADDR_MANUFACTURER_ID_REGISTER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"h: 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), value);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"FAILED\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Manufac. ID", buf, io->stdOut);
if (McuINA260_ReadDieIDRegister(&value)==ERR_OK) {
buf[0] = '\0';
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuINA260_ADDR_DIE_ID_REGISTER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"h: 0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), value);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"FAILED\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Die ID", buf, io->stdOut);
return ERR_OK;
}
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"INA260", (unsigned char*)"Group of INA260 commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" reset", (unsigned char*)"Reset the device with the reset bit\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" config <val>", (unsigned char*)"Write a value to the configuration register\r\n", io->stdOut);
return ERR_OK;
}
uint8_t McuINA260_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io) {
uint8_t res = ERR_OK;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP) == 0
|| McuUtility_strcmp((char*)cmd, "INA260 help") == 0)
{
*handled = true;
return PrintHelp(io);
} else if ( (McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0)
|| (McuUtility_strcmp((char*)cmd, "INA260 status")==0)
)
{
*handled = true;
res = PrintStatus(io);
} else if (McuUtility_strcmp((char*)cmd, "INA260 reset")==0) {
*handled = true;
return McuINA260_WriteResetBit();
} else if (McuUtility_strncmp((char*)cmd, "INA260 config ", sizeof("INA260 config "-1))==0) {
const unsigned char *p;
int32_t val;
*handled = true;
p = cmd + sizeof("INA260 config "-1);
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0) {
return McuINA260_WriteConfigRegister(val);
}
}
return res;
}
#endif /* McuINA260_CONFIG_PARSE_COMMAND_ENABLED */
void McuINA260_Deinit(void) {
/* nothing needed */
}
void McuINA260_Init(void) {
/* nothing needed */
}

View File

@@ -0,0 +1,89 @@
/**
* Copyright (c) 2023, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*
* \brief Driver for the TI INA260 current/voltage sensor.
*/
#ifndef McuINA260_H_
#define McuINA260_H_
#include "McuINA260config.h"
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* TI INA260 device registers: */
typedef enum INA260_REG_e {
McuINA260_ADDR_CONFIGURATION_REGISTER = 0x00,
McuINA260_ADDR_CURRENT_REGISTER = 0x01,
McuINA260_ADDR_BUS_VOLTAGE_REGISTER = 0x02,
McuINA260_ADDR_POWER_REGISTER = 0x03,
McuINA260_ADDR_MASK_ENABLE_REGISTER = 0x06,
McuINA260_ADDR_ALERT_LIMIT_REGISTER = 0x07,
McuINA260_ADDR_MANUFACTURER_ID_REGISTER = 0xFE,
McuINA260_ADDR_DIE_ID_REGISTER = 0xFF,
} INA260_REG_e;
/*!
* \brief Read a device register
* \param reg Device register
* \param value Pointer where to store the register value
* \return Error code, ERR_OK if everything is ok.
*/
uint8_t McuINA260_ReadRegister(INA260_REG_e reg, uint16_t *value);
/*!
* \brief Write a device register
* \param reg Device register
* \param value Register value to write
* \return Error code, ERR_OK if everything is ok.
*/
uint8_t McuINA260_WriteRegister(INA260_REG_e reg, uint16_t value);
/*!
* \brief Read the bus voltage measurement value from the device.
* \return Power value, as mV (micro-Volt).
*/
uint32_t McuINA260_ReadVoltage(void);
/*!
* \brief Read the power measurement value from the device.
* \return Power value, as mW (milli-Watt).
*/
uint32_t McuINA260_ReadPower(void);
/*!
* \brief Read the current measurement value from the device.
* \return Current value, as uA (micro-Amps).
*/
int32_t McuINA260_ReadCurrent(void);
#if McuINA260_CONFIG_PARSE_COMMAND_ENABLED
#include "McuShell.h"
/*!
* \brief Shell command line handler
* \param cmd Pointer to the command string
* \param handled Return value to indicate if command has been recognized
* \param io I/O handler for input/output
* \return Error code, ERR_OK for no error
*/
uint8_t McuINA260_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io);
#endif
/*! \brief Module de-initialization */
void McuINA260_Deinit(void);
/*! \brief Module initialization */
void McuINA260_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* McuINA260_H_ */

View File

@@ -0,0 +1,120 @@
/*
* Copyright (c) 2024, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuLib.h"
#include "McuIO.h"
#include "McuRTOS.h"
#include "McuLog.h"
#include "McuRB.h"
#include <stdio.h>
#include <stdlib.h>
static int McuIO_Read(McuIO_Desc_t *io) {
char ch;
#if MCUIO_CONFIG_USE_FREERTOS_QUEUE
if (xQueueReceive((QueueHandle_t)io->buffer.buf, &ch, portMAX_DELAY)!= pdPASS) {
McuLog_fatal("failed receiving data");
return EOF;
}
#else
McuRB_Get((McuRB_Handle_t)io->buffer.buf, &ch);
#endif
return ch;
}
static int McuIO_Write(McuIO_Desc_t *io, char ch) {
#if MCUIO_CONFIG_USE_FREERTOS_QUEUE
if (xQueueSend((QueueHandle_t)io->buffer.buf, &ch, portMAX_DELAY)!= pdPASS) {
McuLog_fatal("failed sending");
return 0; /* failed */
}
return 1; /* success */
#else
if (McuRB_Put((McuRB_Handle_t)io->buffer.buf, &ch)!=ERR_OK) {
return 0; /* failed */
}
return 1; /* success */
#endif
}
static size_t McuIO_NofData(McuIO_Desc_t *io) {
#if MCUIO_CONFIG_USE_FREERTOS_QUEUE
return uxQueueMessagesWaiting((QueueHandle_t)io->buffer.buf);
#else
return McuRB_NofElements((McuRB_Handle_t)io->buffer.buf);
#endif
}
static size_t McuIO_NofFree(McuIO_Desc_t *io) {
#if MCUIO_CONFIG_USE_FREERTOS_QUEUE
return uxQueueSpacesAvailable((QueueHandle_t)io->buffer.buf);
#else
return McuRB_NofFreeElements((McuRB_Handle_t)io->buffer.buf);
#endif
}
static void McuIO_OutFlush(void) {
/* default dummy implemenation */
}
static void McuIO_OutWrite(char ch) {
(void)ch;
/* default dummy implemenation */
}
McuIO_Desc_t *McuIO_NewIO(size_t nofBufferElements) {
McuIO_Desc_t *io;
#if MCUIO_CONFIG_USE_FREERTOS_HEAP
io = (McuIO_Desc_t*)pvPortMalloc(sizeof(McuIO_Desc_t)); /* get a new device descriptor */
#else
io = (McuIO_Desc_t*)malloc(sizeof(McuIO_Desc_t)); /* get a new device descriptor */
#endif
if (io==NULL) {
McuLog_fatal("failed allocating memory");
return NULL;
}
#if MCUIO_CONFIG_USE_FREERTOS_QUEUE
io->buffer.buf = xQueueCreate(nofBufferElements, sizeof(uint8_t));
if (io->buffer.buf==NULL) {
McuLog_fatal("failed creating buffer");
return NULL;
}
vQueueAddToRegistry(io->buffer.buf, "ioBuf");
#else
McuRB_Config_t config;
McuRB_GetDefaultconfig(&config);
config.elementSize = sizeof(uint8_t);
config.nofElements = nofBufferElements;
io->buffer.buf = McuRB_InitRB(&config);
if (io->buffer.buf==NULL) {
McuLog_fatal("failed creating buffer");
return NULL;
}
#endif
io->buffer.read = McuIO_Read;
io->buffer.write = McuIO_Write;
io->buffer.nofData = McuIO_NofData;
io->buffer.nofFree = McuIO_NofFree;
io->out.flush = McuIO_OutFlush;
io->out.write = McuIO_OutWrite;
return io;
}
McuIO_Desc_t *McuIO_FreeIO(McuIO_Desc_t *io) {
#if MCUIO_CONFIG_USE_FREERTOS_QUEUE
vQueueDelete(io->buffer.buf);
io->buffer.buf = NULL;
#else
io->buffer.buf = McuRB_DeinitRB(io->buffer.buf);
#endif
#if MCUIO_CONFIG_USE_FREERTOS_HEAP
vPortFree(io);
#else
free(io);
#endif
return NULL;
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 2024, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
* Devines the SDEP IDs.
*/
#ifndef _MCU_IO_H__
#define _MCU_IO_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "McuIOconfig.h"
#include <stddef.h>
typedef struct McuIO_Desc_t {
struct {
void *buf; /* handle to the buffer */
int (*write)(struct McuIO_Desc_t *io, char ch); /* write a character, returns the number of bytes written */
int (*read)(struct McuIO_Desc_t *io); /* read a character and return it, or return EOF */
size_t (*nofData)(struct McuIO_Desc_t *io); /* return the number of data character in buffer */
size_t (*nofFree)(struct McuIO_Desc_t *io); /* return the number of free character in buffer */
} buffer;
struct {
void (*write)(char ch);
void (*flush)(void); /* optional flushing method, can be NULL */
} out;
} McuIO_Desc_t;
McuIO_Desc_t *McuIO_NewIO(size_t nofBufferElements);
McuIO_Desc_t *McuIO_FreeIO(McuIO_Desc_t *io);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _MCU_IO_H__ */

View File

@@ -0,0 +1,454 @@
/*
* Copyright (c) 2019, Erich Styger, Sarah Gander
* All rights reserved.
*
* Driver for GPIO pins
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuLib.h"
#if McuLib_CONFIG_CPU_IS_STM
#include "libIIC.h"
#endif
#include "McuLC709203Fconfig.h"
#include "McuLC709203F.h"
#include "McuGenericI2C.h"
#include "McuUtility.h"
#include "McuWait.h"
#define LC709203F_I2C_SLAVE_ADDR 0x0B
#define LC709203F_REG_SET_BEFORE_RSOC 0x04 /* Before RSCOC */
#define LC709203F_REG_SET_THERMB 0x06 /* Thermistor B */
#define LC709203F_REG_INIT_RSOC 0x07 /* Initial RSOC */
#define LC709203F_REG_CELL_TEMP 0x08 /* Cell temperature */
#define LC709203F_REG_VOLTAGE 0x09 /* Cell voltage */
#define LC709203F_REG_CURRENT_DIRECTION 0x0A /* Current direction */
#define LC709203F_REG_ADJ_APPLI 0x0B /* APA, Adjustment Pack Application, sets Parasitic impedance */
#define LC709203F_REG_APT 0x0C /* APT, Adjustment Pack Thermistor, adjust temperature measurement delay timing */
#define LC709203F_REG_RSOC 0x0D /* RSOC, value based 0-100 scale */
#define LC709203F_REG_ITE 0x0F /* ITE, Indicator to Empty */
#define LC709203F_REG_IC_VER 0x11 /* IC version */
#define LC709203F_REG_CHG_PARAM 0x12 /* change of parameter */
#define LC709203F_REG_RSOC_ALM 0x13 /* Alarm low RSOC */
#define LC709203F_REG_LOW_CELL_VOL_ALM 0x14 /* Alarm Low Cell Voltage */
#define lC709203F_REG_PW_MODE 0x15 /* IC Power Mode */
#define LC709203F_REG_EN_NTC 0x16 /* Status Bit, enable Thermistor mode */
#define LC709203F_REG_NUM_PARAMS 0x1A /* Number of the parameter, display batter profile code */
#define MCULC_TEMP_ZERO_CELSIUS 0x0AAC /* From the data sheet command table: 0x0AAC is 0 degree Celsius */
static uint8_t i2cReadCmdData(uint8_t i2cAddr, uint8_t cmd, uint8_t *data, size_t length) {
return McuGenericI2C_ReadAddress(i2cAddr, &cmd, sizeof(cmd), data, length);
}
static uint8_t i2cWriteCmdData(uint8_t i2cAddr, uint8_t cmd, uint8_t *data, size_t length) {
return McuGenericI2C_WriteAddress(i2cAddr, &cmd, sizeof(cmd), data, length);
}
static uint8_t calcCrc8Atm(uint8_t a, uint8_t b) {
/* the sensor uses a CRC-8-ATM,
* Polynomial: x8 + x2 + x + 1
* Corresponds to: 100000111
*/
#define POLY_8 0x8380
uint8_t i = 0;
uint16_t val = 0;
val = (uint16_t)(a^b);
val <<= 8;
for(i=0; i<8; i++) {
if (val&0x8000 ){
val ^= POLY_8;
}
val <<= 1;
}
return (uint8_t)(val >> 8);
}
static uint8_t calcCRC_WriteAccess16(uint8_t i2cSlaveAddr, uint8_t cmd, uint8_t low, uint8_t high) {
uint8_t crc;
crc = calcCrc8Atm(0x00, i2cSlaveAddr<<1); /* I2C slave address */
crc = calcCrc8Atm(crc, cmd); /* command */
crc = calcCrc8Atm(crc, low); /* data byte */
return calcCrc8Atm(crc, high); /* data byte */
}
static uint8_t calcCRC_ReadAccess16(uint8_t i2cSlaveAddr, uint8_t cmd, uint8_t low, uint8_t high) {
uint8_t crc;
crc = calcCrc8Atm(0x00, i2cSlaveAddr<<1); /* I2C slave address */
crc = calcCrc8Atm(crc, cmd); /* command */
crc = calcCrc8Atm(crc, (i2cSlaveAddr<<1)|1); /* I2C address with R bit set */
crc = calcCrc8Atm(crc, low); /* data byte */
return calcCrc8Atm(crc, high); /* data byte */
}
static uint8_t CheckCrc(uint8_t i2cSlaveAddr, uint8_t cmd, uint8_t low, uint8_t high, uint8_t crc) {
uint8_t val;
val = calcCRC_ReadAccess16(i2cSlaveAddr, cmd, low, high);
if (val != crc) {
return ERR_FAILED;
}
return ERR_OK;
}
static uint8_t CheckI2CErr(uint8_t res) {
if (res==ERR_OK) {
return ERR_OK; /* ok */
}
#if MCULC_CONFIG_BLOCK_ON_I2C_ERROR
for(;;) { /* I2C Error? wait for the watchdog to kick in... */
McuWait_WaitOSms(50);
}
#endif
return ERR_FAILED;
}
static uint8_t WriteCmdWordChecked(uint8_t i2cSlaveAddr, uint8_t cmd, uint8_t low, uint8_t high) {
uint8_t data[3];
data[0] = low;
data[1] = high;
data[2] = calcCRC_WriteAccess16(i2cSlaveAddr, cmd, data[0], data[1]);
return CheckI2CErr(i2cWriteCmdData(i2cSlaveAddr, cmd, data, sizeof(data)));
}
void McuLC_Wakeup(void) {
/* Generates wake up signal on SDA, according to the data sheet.
* This has to happen before any other I2C communication on the bus:
* Pull down SDA for 0.6us, then high again,
* wait for 400 us
* */
#if McuLib_CONFIG_CPU_IS_STM
/* set SDA pin of I2C to GPIO Output mode. */
HAL_I2C_MspDeInit(&hi2c3);
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = I2C_SDA_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
HAL_GPIO_WritePin(I2C_SDA_GPIO_Port, I2C_SDA_Pin, GPIO_PIN_RESET);
McuWait_Waitus(1); /* SDA min 0.6us low */
HAL_GPIO_WritePin(I2C_SDA_GPIO_Port, I2C_SDA_Pin, GPIO_PIN_SET);
McuWait_Waitus(400); /* wait 400us */
/* set SDA pin of I2C to GPIO Ouput mode. */
HAL_I2C_MspInit(&hi2c3);
#elif McuLib_CONFIG_SDK_VERSION_USED==McuLib_CONFIG_SDK_PROCESSOR_EXPERT
PORT_PDD_SetPinMuxControl(PORTB_BASE_PTR, 3, PORT_PDD_MUX_CONTROL_ALT1); /* MUX SDA/PTB3 as GPIO */
PORT_PDD_SetPinOpenDrain(PORTB_BASE_PTR, 3, PORT_PDD_OPEN_DRAIN_ENABLE);
GPIO_PDD_SetPortOutputDirectionMask(PTB_BASE_PTR, (1<<3)); /* SDA/PTB3 as output */
GPIO_PDD_ClearPortDataOutputMask(PTB_BASE_PTR, 1<<3); /* SDA/PB3 low */
McuWait_Waitus(1); /* SDA min 0.6us low */
GPIO_PDD_SetPortDataOutputMask(PTB_BASE_PTR, 1<<3); /* SDA/PB3 high */
McuWait_Waitus(400); /* wait 400us */
/* mux back to normal I2C mode with interrupts enabled */
PORTB_PCR3 = (uint32_t)((PORTB_PCR3 & (uint32_t)~(uint32_t)(
PORT_PCR_ISF_MASK |
PORT_PCR_MUX(0x05)
)) | (uint32_t)(
PORT_PCR_MUX(0x02)
));
PORT_PDD_SetPinOpenDrain(PORTB_BASE_PTR, 0x03u, PORT_PDD_OPEN_DRAIN_ENABLE); /* Set SDA pin as open drain */
#else
/* NYI for NXP SDK yet */
#endif
}
static uint8_t ReadCmdWordChecked(uint8_t i2cSlaveAddr, uint8_t cmd, uint16_t *val) {
uint8_t data[3];
uint8_t res;
res = CheckI2CErr(i2cReadCmdData(i2cSlaveAddr, cmd, data, sizeof(data)));
if (res!=ERR_OK) {
return res;
}
res = CheckI2CErr(CheckCrc(i2cSlaveAddr, cmd, data[0], data[1], data[2]));
if (res!=ERR_OK) {
return res;
}
*val = (data[1]<<8) | data[0];
return ERR_OK;
}
/* returns cell voltage in mV */
uint8_t McuLC_GetVoltage(uint16_t *pVoltage) {
return ReadCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_VOLTAGE, pVoltage);
}
/* returns cell temperature (10 = 1 degree C) */
uint8_t McuLC_GetTemperature(int16_t *pTemperature) {
/* cell temperature is in 0.1C units, from 0x09E4 (-20C) up to 0x0D04 (60C) */
uint8_t res;
res = ReadCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_CELL_TEMP, (uint16_t*)pTemperature);
if (res!=ERR_OK) {
return res;
}
*pTemperature -= MCULC_TEMP_ZERO_CELSIUS; /* From the data sheet command table: 0x0AAC is 0 degree Celsius */
return ERR_OK;
}
uint8_t McuLC_SetTemperature(int16_t temperature) {
/* cell temperature is in 0.1C units, from 0x09E4 (-20C) up to 0x0D04 (60C) */
temperature = ((uint16_t)temperature)+MCULC_TEMP_ZERO_CELSIUS; /* From the data sheet command table: 0x0AAC is 0 degree Celsius */
return WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_CELL_TEMP, ((uint16_t)temperature)&0xff, (((uint16_t)temperature)>>8)&0xff);
}
/* returns battery Relative State of Charge in percent */
uint8_t McuLC_GetRSOC(uint16_t *pRsoc) {
return ReadCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_RSOC, pRsoc);
}
/* Indicator to empty, returns battery charge in thousandth */
uint8_t McuLC_GetITE(uint16_t *pIte) {
return ReadCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_ITE, pIte);
}
/* Indicator to empty, returns battery charge in thousandth */
uint8_t McuLC_GetICversion(uint16_t *pVersion) {
return ReadCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_IC_VER, pVersion);
}
#if MCULC709203F_CONFIG_PARSE_COMMAND_ENABLED
static const unsigned char *McuLC_CurrentDirectionToString(McuLC_CurrentDirection dir) {
switch(dir) {
case McuLC_CURRENT_DIR_AUTO: return (const unsigned char*)"auto";
case McuLC_CURRENT_DIR_CHARGING: return (const unsigned char*)"charging";
case McuLC_CURRENT_DIR_DISCHARING: return (const unsigned char*)"discharging";
case McuLC_CURRENT_DIR_ERROR:
default: return (const unsigned char*)"ERROR";
}
}
#endif
uint8_t McuLC_GetCurrentDirection(McuLC_CurrentDirection *pDir) {
uint16_t val;
uint8_t res;
res = ReadCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_CURRENT_DIRECTION, &val);
if (res!=ERR_OK) {
return res;
}
switch(val) {
case 0: *pDir = McuLC_CURRENT_DIR_AUTO; break;
case 1: return McuLC_CURRENT_DIR_CHARGING; break;
case 0xffff: return McuLC_CURRENT_DIR_DISCHARING; break;
default: return McuLC_CURRENT_DIR_ERROR; break;
}
return ERR_OK;
}
uint8_t McuLC_SetCurrentDirection(McuLC_CurrentDirection direction) {
uint8_t low, high;
switch(direction) {
case McuLC_CURRENT_DIR_AUTO: low = 0x00; high = 0x00; break;
case McuLC_CURRENT_DIR_CHARGING: low = 0x01; high = 0x00; break;
case McuLC_CURRENT_DIR_DISCHARING: low = 0xff; high = 0xff; break;
default:
CheckI2CErr(ERR_FAILED);
return ERR_FAILED;
}
return WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_CURRENT_DIRECTION, low, high);
}
#if MCULC709203F_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintStatus(McuShell_ConstStdIOType *io) {
uint8_t buf[32], res;
McuShell_SendStatusStr((unsigned char*)"LC", (const unsigned char*)"\r\n", io->stdOut);
{
uint16_t version;
res = McuLC_GetICversion(&version); /* battery charge in thousandth */
if (res==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum16Hex(buf, sizeof(buf), version);
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" IC version", buf, io->stdOut);
}
{
uint16_t rsoc;
res = McuLC_GetRSOC(&rsoc); /* battery charge in percent */
if (res==ERR_OK) {
McuUtility_Num16uToStr(buf, sizeof(buf), rsoc);
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)"\% (0..100)\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" RSOC", buf, io->stdOut);
}
{
uint16_t ite;
res = McuLC_GetITE(&ite); /* battery charge in thousandth */
if (res==ERR_OK) {
McuUtility_Num16uToStr(buf, sizeof(buf), ite);
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)" (0..1000)\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" ITE", buf, io->stdOut);
}
{
int16_t temperature;
bool isI2Cmode;
res = McuLC_GetTemperature(&temperature); /* cell temperature in 1/10-degree C */
if (res==ERR_OK) {
McuUtility_Num16sToStr(buf, sizeof(buf), temperature/10);
McuUtility_chcat(buf, sizeof(buf), '.');
if (temperature<0) { /* make it positive */
temperature = -temperature;
}
McuUtility_strcatNum16s(buf, sizeof(buf), temperature%10);
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)" C");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR");
}
if (McuLC_GetTemperatureMeasurementMode(&isI2Cmode)==ERR_OK) {
if (isI2Cmode) {
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)" (I2C mode)");
} else {
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)" (Thermistor mode)");
}
} else {
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)" (ERROR!)");
}
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" Temperature", buf, io->stdOut);
}
{
uint16_t mVolt;
res = McuLC_GetVoltage(&mVolt); /* cell voltage in milli-volts */
if (res==ERR_OK) {
McuUtility_Num16uToStr(buf, sizeof(buf), mVolt);
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)" mV\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Voltage", buf, io->stdOut);
}
{
McuLC_CurrentDirection direction;
res = McuLC_GetCurrentDirection(&direction);
if (res==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), McuLC_CurrentDirectionToString(direction));
McuUtility_strcat(buf, sizeof(buf), (const unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" Current dir", buf, io->stdOut);
}
return ERR_OK;
}
#endif /* MCULC709203F_CONFIG_PARSE_COMMAND_ENABLED */
#if MCULC709203F_CONFIG_PARSE_COMMAND_ENABLED
uint8_t McuLC_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
uint8_t res = ERR_OK;
const uint8_t *p;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, "LC help")==0) {
McuShell_SendHelpStr((unsigned char*)"LC", (const unsigned char*)"Group of LC709203F commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (const unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" settemp <temp>", (const unsigned char*)"In I2C temperature mode, set the temperature in deci-Celsius\r\n", io->stdOut);
*handled = TRUE;
return ERR_OK;
} else if ((McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0) || (McuUtility_strcmp((char*)cmd, "LC status")==0)) {
*handled = TRUE;
return PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, (char*)"LC settemp ", sizeof("LC settemp ")-1)==0) {
int16_t val;
*handled = TRUE;
p = cmd+sizeof("LC settemp ")-1;
if (McuUtility_ScanDecimal16sNumber(&p, &val)!=ERR_OK) {
return ERR_FAILED;
}
return McuLC_SetTemperature(val);
}
return res;
}
#endif /* MCULC709203F_CONFIG_PARSE_COMMAND_ENABLED */
uint8_t McuLC_GetTemperatureMeasurementMode(bool *isI2Cmode) {
uint16_t val=0;
uint8_t res;
res = ReadCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_EN_NTC, &val);
if (res!=ERR_OK) {
return res;
}
*isI2Cmode = val==0; /* 0: i2c, 1: thermistor mode */
return ERR_OK;
}
uint8_t McuLC_SetTemperatureMeasurementMode(bool i2cMode) {
return WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_EN_NTC, i2cMode?0x00:0x01, 0x0);
}
uint8_t McuLC_SetPowerMode(bool sleepMode) {
return WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, lC709203F_REG_PW_MODE, sleepMode?0x02:0x01, 0x00);
}
uint8_t McuLC_Init(void) {
/* initializes LC709203F for Renata ICP543759PMT battery */
uint8_t res;
/* operational mode (1: operational, 2: sleep), 0x0001 = operational mode */
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, lC709203F_REG_PW_MODE, 0x01, 0x00);
if (res!=ERR_OK) { return ERR_FAILED; }
/* APA, set parasitic impedance (table 7 in data sheet): 0x000C, value for 280mA */
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_ADJ_APPLI, 0x0C, 0x00);
if (res!=ERR_OK) { return ERR_FAILED; }
/* Battery Profile (table 8 in data sheet): 0x0001 = Type 1 */
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_CHG_PARAM, 0x01, 0x00);
if (res!=ERR_OK) { return ERR_FAILED; }
/* write 0xAA55 to initialize RSOC */
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_INIT_RSOC, 0x55, 0xAA);
if (res!=ERR_OK) { return ERR_FAILED; }
/* Set battery measurement mode: 0x0001: thermistor mode. 0x0000: I2C mode */
#if MCULC709203F_CONFIG_USE_THERMISTOR
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_EN_NTC, 0x01, 0x00);
if (res!=ERR_OK) { return ERR_FAILED; }
#else
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_EN_NTC, 0x00, 0x00);
if (res!=ERR_OK) { return ERR_FAILED; }
#endif
/* set the B-constant of the thermistor to be measured */
#if MCULC709203F_CONFIG_USE_THERMISTOR
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_SET_THERMB, 0x6B, 0x0D); /* Thermistor B-Constant: 0x0D6B = B=3435 */
if (res!=ERR_OK) { return ERR_FAILED; }
#endif
/* Low voltage alarm setting: 0x0C1C = 3100mV = 3.1V, low byte first */
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_LOW_CELL_VOL_ALM, 0x1C, 0x0C);
if (res!=ERR_OK) { return ERR_FAILED; }
/* 0x0000 = alarm disable, low byte first */
res = WriteCmdWordChecked(LC709203F_I2C_SLAVE_ADDR, LC709203F_REG_RSOC_ALM, 0x00, 0x00);
if (res!=ERR_OK) { return ERR_FAILED; }
return ERR_OK;
}
void McuLC_Deinit(void) {
/* nothing to do */
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (c) 2019, Erich Styger
* All rights reserved.
*
* Interface for for the LC709203 battery gauge I2C sensor
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef SOURCES_MCULC709203F_H_
#define SOURCES_MCULC709203F_H_
#ifdef __cplusplus
extern "C" {
#endif
#if MCULC709203F_CONFIG_PARSE_COMMAND_ENABLED
#include "McuShell.h"
#endif
/*!
* \brief Returns the current battery voltage
* \param pVoltage Pointer where to store the value (in mV)
* \return Error code, ERR_OK for no error
*/
uint8_t McuLC_GetVoltage(uint16_t *pVoltage);
typedef enum {
McuLC_CURRENT_DIR_AUTO, /*!< automatic mode (default) */
McuLC_CURRENT_DIR_CHARGING, /*!< charging mode */
McuLC_CURRENT_DIR_DISCHARING, /*!< discharging mode */
McuLC_CURRENT_DIR_ERROR /*!< error case */
} McuLC_CurrentDirection;
/*!< Current direction used for McuLC_GetCurrentDirection() and McuLC_SetCurrentDirection() */
uint8_t McuLC_GetVoltage(uint16_t *pVoltage);
uint8_t McuLC_GetTemperature(int16_t *pTemperature);
uint8_t McuLC_GetRSOC(uint16_t *pRsoc);
uint8_t McuLC_GetITE(uint16_t *pIte);
uint8_t McuLC_GetICversion(uint16_t *pVersion);
uint8_t McuLC_SetTemperatureMeasurementMode(bool i2cMode);
/*!
* \brief Get the current temperature measurement mode
* \param pDir Pointer where to store the mode
* \return Error code, ERR_OK if everything is ok
*/
uint8_t McuLC_GetTemperatureMeasurementMode(bool *isI2Cmode);
/*!
* \brief Get the current direction mode
* \param pDir Pointer where to store the mode
* \return Error code, ERR_OK if everything is ok
*/
uint8_t McuLC_GetCurrentDirection(McuLC_CurrentDirection *pDir);
/*!
* \brief Set the current direction mode
* \param dir Mode to set
* \return Error code, ERR_OK if everything is ok
*/
uint8_t McuLC_SetCurrentDirection(McuLC_CurrentDirection dir);
/*!
* \brief Sets the device power mode (normal or sleep mode)
* \param sleepMode true to put device into sleep mode, false for normal operational mode
* \return Error code, ERR_OK if everything is ok
*/
uint8_t McuLC_SetPowerMode(bool sleepMode);
/*!
* \brief Wake up the device from sleep mode. Uses bit-banging. If other devices are on the bus, this method has to be called before anything else!
*/
void McuLC_Wakeup(void); /* must be done before any other I2C communication on the bus! */
#if MCULC709203F_CONFIG_PARSE_COMMAND_ENABLED
/*!
* \brief Module command line parser
* \param cmd Pointer to string to be parsed
* \param handled set to true if command was recognized
* \param io standard I/O handler
* \return Error code, ERR_OK if everything is ok
*/
uint8_t McuLC_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
#endif
/*!
* \brief Driver initialization. I2C bus must be operational for this.
* \return Error code, ERR_OK if everything is ok
*/
uint8_t McuLC_Init(void);
/*!
* \brief Driver de-initialisation
*/
void McuLC_Deinit(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* SOURCES_MCULC709203F_H_ */

View File

@@ -0,0 +1,160 @@
/*
* Copyright (c) 2019-2021, Erich Styger
* All rights reserved.
*
* Driver for LEDs
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuLibconfig.h"
#include "McuLEDconfig.h"
#include "McuLED.h"
#include "McuGPIO.h"
#if McuLib_CONFIG_NXP_SDK_USED
#include "fsl_gpio.h"
#elif McuLib_CONFIG_CPU_IS_STM32
#include "stm32f3xx_hal.h"
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
#include "fsl_port.h"
#elif McuLib_CONFIG_CPU_IS_ESP32
#include "driver/gpio.h"
#endif
#include <stddef.h>
#include <string.h> /* for memset */
#include <stdlib.h> /* for malloc() and free() */
#include <assert.h>
#if MCULED_CONFIG_USE_FREERTOS_HEAP
#include "McuRTOS.h"
#endif
/* default configuration, used for initializing the config */
static const McuLED_Config_t defaultConfig =
{
.isLowActive = false,
.isOnInit = false,
.hw = {
#if McuLib_CONFIG_NXP_SDK_USED && !McuLib_CONFIG_IS_KINETIS_KE
.gpio = NULL,
#elif McuLib_CONFIG_CPU_IS_STM32
.gpio = NULL,
#endif
#if McuLib_CONFIG_CPU_IS_KINETIS
.port = NULL,
#elif McuLib_CONFIG_CPU_IS_LPC
.port = 0,
#endif
#if McuLib_CONFIG_CPU_IS_ESP32
.pin = GPIO_NUM_NC,
#else
.pin = 0,
#endif
}
};
typedef struct {
McuGPIO_Handle_t gpio;
bool isLowActive;
} McuLED_t;
void McuLED_GetDefaultConfig(McuLED_Config_t *config) {
assert(config!=NULL);
memcpy(config, &defaultConfig, sizeof(*config));
}
McuLED_Handle_t McuLED_InitLed(McuLED_Config_t *config) {
McuGPIO_Config_t gpio_config; /* config for the SDK */
McuGPIO_Handle_t gpio;
McuLED_t *handle;
assert(config!=NULL);
McuGPIO_GetDefaultConfig(&gpio_config);
gpio_config.isInput = false; /* LED is output only */
memcpy(&gpio_config.hw, &config->hw, sizeof(gpio_config.hw)); /* copy hardware information */
if (config->isLowActive) {
gpio_config.isHighOnInit = !config->isOnInit;
} else {
gpio_config.isHighOnInit = config->isOnInit;
}
gpio = McuGPIO_InitGPIO(&gpio_config); /* create gpio handle */
#if MCULED_CONFIG_USE_FREERTOS_HEAP
handle = (McuLED_t*)pvPortMalloc(sizeof(McuLED_t)); /* get a new device descriptor */
#else
handle = (McuLED_t*)malloc(sizeof(McuLED_t)); /* get a new device descriptor */
#endif
assert(handle!=NULL);
if (handle!=NULL) { /* if malloc failed, will return NULL pointer */
memset(handle, 0, sizeof(McuLED_t)); /* init all fields */
handle->gpio = gpio;
handle->isLowActive = config->isLowActive;
}
return (McuLED_Handle_t)handle;
}
McuLED_Handle_t McuLED_DeinitLed(McuLED_Handle_t led) {
assert(led!=NULL);
McuGPIO_DeinitGPIO(((McuLED_t*)led)->gpio);
#if MCULED_CONFIG_USE_FREERTOS_HEAP
vPortFree(led);
#else
free(led);
#endif
return NULL;
}
void McuLED_On(McuLED_Handle_t led) {
assert(led!=NULL);
McuLED_t *desc = (McuLED_t*)led;
if (desc->isLowActive) {
McuGPIO_SetLow(desc->gpio);
} else {
McuGPIO_SetHigh(desc->gpio);
}
}
void McuLED_Off(McuLED_Handle_t led) {
assert(led!=NULL);
McuLED_t *desc = (McuLED_t*)led;
if (desc->isLowActive) {
McuGPIO_SetHigh(desc->gpio);
} else {
McuGPIO_SetLow(desc->gpio);
}
}
void McuLED_Toggle(McuLED_Handle_t led) {
assert(led!=NULL);
McuLED_t *desc = (McuLED_t*)led;
McuGPIO_Toggle(desc->gpio);
}
bool McuLED_Get(McuLED_Handle_t led) {
assert(led!=NULL);
McuLED_t *desc = (McuLED_t*)led;
if (desc->isLowActive) {
return !McuGPIO_IsHigh(desc->gpio);
} else {
return McuGPIO_IsHigh(desc->gpio);
}
}
void McuLED_Set(McuLED_Handle_t led, bool isOn) {
if (isOn) {
McuLED_On(led);
} else {
McuLED_Off(led);
}
}
void McuLED_Init(void) {
/* nothing to do */
}
void McuLED_Deinit(void) {
/* nothing to do */
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 2019-2021, Erich Styger
* All rights reserved.
*
* Driver for LEDs
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef McuLED_H_
#define McuLED_H_
#include <stdbool.h>
#include "McuLibconfig.h"
#include "McuLEDconfig.h"
#include "McuGPIO.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct McuLED_Dummy_s { int dummy; } McuLED_Dummy_s; /*!< using a pointer to a struct instead a pointer to void for handle, used for handle type 'safety' only */
typedef McuLED_Dummy_s *McuLED_Handle_t; /*!< LED handle type */
typedef struct {
bool isLowActive;
bool isOnInit;
McuGPIO_HwPin_t hw;
} McuLED_Config_t;
void McuLED_GetDefaultConfig(McuLED_Config_t *config);
McuLED_Handle_t McuLED_InitLed(McuLED_Config_t *config);
McuLED_Handle_t McuLED_DeinitLed(McuLED_Handle_t led);
void McuLED_On(McuLED_Handle_t led);
void McuLED_Off(McuLED_Handle_t led);
void McuLED_Toggle(McuLED_Handle_t led);
bool McuLED_Get(McuLED_Handle_t led);
void McuLED_Set(McuLED_Handle_t led, bool isOn);
/* driver initialization */
void McuLED_Init(void);
/* driver deinitialization */
void McuLED_Deinit(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* McuLED_H_ */

View File

@@ -0,0 +1,95 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuLib.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : McuLibConfig
** Version : Component 01.019, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:44, # CodeGen: 835
** Abstract :
** Configures the drivers for various SDKs and APIs used.
** Settings :
** Component name : McuLib
** SDK : Processor Expert
** Contents :
** Init - void McuLib_Init(void);
** Deinit - void McuLib_Deinit(void);
**
** * Copyright (c) 2016-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuLib.h
** @version 01.00
** @brief
** Configures the drivers for various SDKs and APIs used.
*/
/*!
** @addtogroup McuLib_module McuLib module documentation
** @{
*/
/* MODULE McuLib. */
#include "McuLib.h"
/*
** ===================================================================
** Method : Init (component McuLibConfig)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuLib_Init(void)
{
/* nothing to implement */
}
/*
** ===================================================================
** Method : Deinit (component McuLibConfig)
**
** Description :
** Driver deinitialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuLib_Deinit(void)
{
/* nothing to implement */
}
/* END McuLib. */
/*!
** @}
*/

View File

@@ -0,0 +1,195 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuLib.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : McuLibConfig
** Version : Component 01.019, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2024-07-29, 05:44, # CodeGen: 835
** Abstract :
** Configures the drivers for various SDKs and APIs used.
** Settings :
** Component name : McuLib
** SDK : Processor Expert
** Contents :
** Init - void McuLib_Init(void);
** Deinit - void McuLib_Deinit(void);
**
** * Copyright (c) 2016-2024, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuLib.h
** @version 01.00
** @brief
** Configures the drivers for various SDKs and APIs used.
*/
/*!
** @addtogroup McuLib_module McuLib module documentation
** @{
*/
#ifndef __McuLib_H
#define __McuLib_H
/* MODULE McuLib. */
#include "McuLibconfig.h" /* include configuration header file */
#ifdef __cplusplus
extern "C" {
#endif
#if McuLib_CONFIG_SDK_VERSION_USED == McuLib_CONFIG_SDK_PROCESSOR_EXPERT
#ifndef __IASMARM__ /* not including standard header files if using IAR assembler */
/* Include shared modules, which are used for whole project */
#include "PE_Types.h"
#include "PE_Error.h"
#include "PE_Const.h"
#include "IO_Map.h"
#include "Cpu.h" /* include CPU related interfaces and defines */
#endif
#else /* use non-Processor Expert SDK: generic or silicon vendor SDK */
/* defines of common types used by Processor Expert, which might not be provided by the SDK */
#if !(defined(__ICCARM__) || defined(__HIWARE__)) /* Hiware compiler (S08, S12) only supports C89 */
#include <stdint.h> /* uint8_t, int16_t, ... */
#include <stdbool.h> /* bool, true, false, ... */
#endif
/* boolean values */
#ifndef FALSE
#define FALSE 0x00u
#endif
#ifndef TRUE
#define TRUE 0x01u
#endif
/* error codes */
#define ERR_OK 0x00U /*!< OK */
#define ERR_SPEED 0x01U /*!< This device does not work in the active speed mode. */
#define ERR_RANGE 0x02U /*!< Parameter out of range. */
#define ERR_VALUE 0x03U /*!< Parameter of incorrect value. */
#define ERR_OVERFLOW 0x04U /*!< Timer overflow. */
#define ERR_MATH 0x05U /*!< Overflow during evaluation. */
#define ERR_ENABLED 0x06U /*!< Device is enabled. */
#define ERR_DISABLED 0x07U /*!< Device is disabled. */
#define ERR_BUSY 0x08U /*!< Device is busy. */
#define ERR_NOTAVAIL 0x09U /*!< Requested value or method not available. */
#define ERR_RXEMPTY 0x0AU /*!< No data in receiver. */
#define ERR_TXFULL 0x0BU /*!< Transmitter is full. */
#define ERR_BUSOFF 0x0CU /*!< Bus not available. */
#define ERR_OVERRUN 0x0DU /*!< Overrun error is detected. */
#define ERR_FRAMING 0x0EU /*!< Framing error is detected. */
#define ERR_PARITY 0x0FU /*!< Parity error is detected. */
#define ERR_NOISE 0x10U /*!< Noise error is detected. */
#define ERR_IDLE 0x11U /*!< Idle error is detected. */
#define ERR_FAULT 0x12U /*!< Fault error is detected. */
#define ERR_BREAK 0x13U /*!< Break char is received during communication. */
#define ERR_CRC 0x14U /*!< CRC error is detected. */
#define ERR_ARBITR 0x15U /*!< A node losts arbitration. This error occurs if two nodes start transmission at the same time. */
#define ERR_PROTECT 0x16U /*!< Protection error is detected. */
#define ERR_UNDERFLOW 0x17U /*!< Underflow error is detected. */
#define ERR_UNDERRUN 0x18U /*!< Underrun error is detected. */
#define ERR_COMMON 0x19U /*!< Common error of a device. */
#define ERR_LINSYNC 0x1AU /*!< LIN synchronization error is detected. */
#define ERR_FAILED 0x1BU /*!< Requested functionality or process failed. */
#define ERR_QFULL 0x1CU /*!< Queue is full. */
#define ERR_PARAM_MASK 0x80U /*!< Invalid mask. */
#define ERR_PARAM_MODE 0x81U /*!< Invalid mode. */
#define ERR_PARAM_INDEX 0x82U /*!< Invalid index. */
#define ERR_PARAM_DATA 0x83U /*!< Invalid data. */
#define ERR_PARAM_SIZE 0x84U /*!< Invalid size. */
#define ERR_PARAM_VALUE 0x85U /*!< Invalid value. */
#define ERR_PARAM_RANGE 0x86U /*!< Invalid parameter's range or parameters' combination. */
#define ERR_PARAM_LOW_VALUE 0x87U /*!< Invalid value (LOW part). */
#define ERR_PARAM_HIGH_VALUE 0x88U /*!< Invalid value (HIGH part). */
#define ERR_PARAM_ADDRESS 0x89U /*!< Invalid address. */
#define ERR_PARAM_PARITY 0x8AU /*!< Invalid parity. */
#define ERR_PARAM_WIDTH 0x8BU /*!< Invalid width. */
#define ERR_PARAM_LENGTH 0x8CU /*!< Invalid length. */
#define ERR_PARAM_ADDRESS_TYPE 0x8DU /*!< Invalid address type. */
#define ERR_PARAM_COMMAND_TYPE 0x8EU /*!< Invalid command type. */
#define ERR_PARAM_COMMAND 0x8FU /*!< Invalid command. */
#define ERR_PARAM_RECIPIENT 0x90U /*!< Invalid recipient. */
#define ERR_PARAM_BUFFER_COUNT 0x91U /*!< Invalid buffer count. */
#define ERR_PARAM_ID 0x92U /*!< Invalid ID. */
#define ERR_PARAM_GROUP 0x93U /*!< Invalid group. */
#define ERR_PARAM_CHIP_SELECT 0x94U /*!< Invalid chip select. */
#define ERR_PARAM_ATTRIBUTE_SET 0x95U /*!< Invalid set of attributes. */
#define ERR_PARAM_SAMPLE_COUNT 0x96U /*!< Invalid sample count. */
#define ERR_PARAM_CONDITION 0x97U /*!< Invalid condition. */
#define ERR_PARAM_TICKS 0x98U /*!< Invalid ticks parameter. */
/* Other basic data types */
typedef signed char int8;
typedef signed short int int16;
typedef signed long int int32;
typedef unsigned char uint8;
typedef unsigned short int uint16;
typedef unsigned long int uint32;
#endif
void McuLib_Init(void);
/*
** ===================================================================
** Method : Init (component McuLibConfig)
**
** Description :
** Driver initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuLib_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component McuLibConfig)
**
** Description :
** Driver deinitialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/* END McuLib. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuLib_H */
/*!
** @}
*/

View File

@@ -0,0 +1,583 @@
/*
* Copyright (c) 2017 rxi
*
* 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.
*/
/* Original source is from https://github.com/rxi/log.c
* McuLib integration and extensions: Copyright (c) 2020 Erich Styger
*/
#include "McuLog.h"
#if McuLog_CONFIG_IS_ENABLED
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include "McuTimeDate.h"
#include "McuUtility.h"
#include "McuXFormat.h"
#include "McuShell.h"
#if McuLog_CONFIG_USE_MUTEX
#include "McuRTOS.h"
#endif
#if McuLog_CONFIG_USE_FILE
#include "McuFatFS.h"
#endif
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER || McuLog_CONFIG_USE_RTT_CONSOLE
#include "McuRTT.h"
#endif
static struct {
McuLog_Levels_e level; /* 0 (TRACE) to 5 (FATAL) */
#if McuLog_CONFIG_USE_MUTEX
SemaphoreHandle_t McuLog_Mutex; /* built-in FreeRTOS mutex used for lock below */
#endif
#if McuLog_CONFIG_USE_MUTEX
log_LockFn lock; /* user mutex for synchronization */
void *udata; /* optional data for lock */
#endif
McuShell_ConstStdIOType *consoleIo[McuLog_CONFIG_NOF_CONSOLE_LOGGER]; /* I/O for console logging */
bool quiet; /* if console logging is silent/quiet */
#if McuLog_CONFIG_USE_COLOR
bool color; /* if using color for terminal */
#endif
#if McuLog_CONFIG_USE_FILE
McuFatFS_FIL *fp; /* file handle */
McuFatFS_FIL logFile; /* FatFS log file descriptor */
#endif
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
bool rttDataLogger;
#endif
} McuLog_ConfigData;
static const char *const level_names[] = {
"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"
};
#if McuLog_CONFIG_USE_COLOR
static const char *const level_colors[] = { /* color codes for messages */
McuShell_ANSI_COLOR_TEXT_BRIGHT_BLUE, /* trace */
McuShell_ANSI_COLOR_TEXT_BRIGHT_GREEN, /* debug */
McuShell_ANSI_COLOR_TEXT_BRIGHT_CYAN, /* info */
McuShell_ANSI_COLOR_TEXT_BRIGHT_YELLOW, /* warn */
McuShell_ANSI_COLOR_TEXT_BRIGHT_RED, /* error */
McuShell_ANSI_COLOR_TEXT_BRIGHT_MAGENTA /* fatal */
};
#endif
#if McuLog_CONFIG_USE_MUTEX
static void lock(void) {
if (McuLog_ConfigData.lock!=NULL) {
McuLog_ConfigData.lock(McuLog_ConfigData.udata, true);
}
}
#endif
#if McuLog_CONFIG_USE_MUTEX
static void unlock(void) {
if (McuLog_ConfigData.lock!=NULL) {
McuLog_ConfigData.lock(McuLog_ConfigData.udata, false);
}
}
#endif
void McuLog_set_console(McuShell_ConstStdIOType *io, uint8_t index) {
assert(index<McuLog_CONFIG_NOF_CONSOLE_LOGGER);
McuLog_ConfigData.consoleIo[index] = io;
}
#if McuLog_CONFIG_USE_MUTEX
void McuLog_set_udata(void *udata) {
McuLog_ConfigData.udata = udata;
}
#endif
#if McuLog_CONFIG_USE_MUTEX
void McuLog_set_lock(log_LockFn fn) {
McuLog_ConfigData.lock = fn;
}
#endif
#if McuLog_CONFIG_USE_FILE
void McuLog_set_fp(McuFatFS_FIL *fp) {
McuLog_ConfigData.fp = fp;
}
#endif
#if McuLog_CONFIG_USE_FILE
int McuLog_open_logfile(const unsigned char *logFileName) {
McuFatFS_FRESULT fres;
fres = f_open(&McuLog_ConfigData.logFile, (const TCHAR*)logFileName, FA_WRITE|FA_OPEN_APPEND);
if (fres != FR_OK) {
McuLog_set_fp(NULL);
return -1; /* failed */
}
McuLog_set_fp(&McuLog_ConfigData.logFile);
return 0; /* success */
}
#endif
#if McuLog_CONFIG_USE_FILE
int McuLog_close_logfile(void) {
McuFatFS_FRESULT fres;
fres = f_close(McuLog_ConfigData.fp);
McuLog_set_fp(NULL);
if (fres != FR_OK) {
return -1; /* failed */
}
return 0; /* success */
}
#endif
void McuLog_set_level(McuLog_Levels_e level) {
McuLog_ConfigData.level = level;
}
void McuLog_set_quiet(bool enable) {
McuLog_ConfigData.quiet = enable;
}
#if McuLog_CONFIG_USE_COLOR
void McuLog_set_color(bool enable) {
McuLog_ConfigData.color = enable;
}
#endif
static void OutputCharFctConsole(void *p, char ch) {
McuShell_StdIO_OutErr_FctType io = (McuShell_StdIO_OutErr_FctType)p;
#if McuLog_CONFIG_USE_RTT_CONSOLE
if (io==McuRTT_StdIOSendChar) { /* using RTT: check first if we are able to send */
unsigned int rttUpSize = SEGGER_RTT_GetUpBufferFreeSize(0);
if (rttUpSize<1) { /* there is NOT enough space available in the RTT up buffer */
return; /* do not send :-( */
}
}
#endif
io(ch);
}
#if McuLog_CONFIG_USE_FILE
static void OutputCharFctFile(void *p, char ch) {
McuFatFS_FIL *fp = (McuFatFS_FIL*)p;
f_putc(ch, fp);
}
#endif
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
void McuLog_set_rtt_logger(bool enable) {
McuLog_ConfigData.rttDataLogger = enable;
}
#endif
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
static void OutputCharRttLoggerFct(void *p, char ch) {
McuRTT_Write(McuLog_RTT_DATA_LOGGER_CHANNEL, (const char*)&ch, sizeof(char));
}
#endif
static void OutString(const unsigned char *str, void (*outchar)(void *,char), void *p) {
while(*str!='\0') {
outchar(p, *str);
str++;
}
}
static void LogHeader(DATEREC *date, TIMEREC *time, McuLog_Levels_e level, bool supportColor, const char *file, int line, void (*outchar)(void *,char), void *param) {
unsigned char buf[32];
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE || McuLog_CONFIG_LOG_TIMESTAMP_TIME
/* date/time */
buf[0] = '\0';
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE
McuTimeDate_AddDateString((unsigned char*)buf, sizeof(buf), date, (unsigned char*)McuTimeDate_CONFIG_DEFAULT_DATE_FORMAT_STR);
McuUtility_chcat(buf, sizeof(buf), ' ');
#endif
#if McuLog_CONFIG_LOG_TIMESTAMP_TIME
McuTimeDate_AddTimeString((unsigned char*)buf, sizeof(buf), time, (unsigned char*)McuTimeDate_CONFIG_DEFAULT_TIME_FORMAT_STR);
McuUtility_chcat(buf, sizeof(buf), ' ');
#endif
OutString(buf, outchar, param);
#endif
/* level */
buf[0] = '\0';
#if McuLog_CONFIG_USE_COLOR
if (supportColor && McuLog_ConfigData.color) {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)level_colors[level]);
}
#endif
McuUtility_strcatPad(buf, sizeof(buf), (unsigned char*)level_names[level], ' ', sizeof("DEBUG ")-1);
#if McuLog_CONFIG_USE_COLOR
if (supportColor && McuLog_ConfigData.color) {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)McuShell_ANSI_CONTROL_RESET);
}
#endif
OutString(buf, outchar, param);
#if McuLog_CONFIG_LOG_STRIP_FILENAME_PATH
/* file name */
const unsigned char *p;
p = (const unsigned char*)file;
if (*p=='.') { /* relative */
while(*p==' ' || *p=='.') {
p++; /* skip leading spaces or dots */
}
} else { /* scan for separator */
size_t pos;
pos = McuUtility_strlen(file)-1; /* end of the string */
while(pos>1 && !(file[pos-1]=='/' || file[pos-1]=='\\')) { /* scan back to find the last separator */
pos--;
}
if (pos==1 && !(file[pos-1]=='/' || file[pos-1]=='\\')) { /* no separator at all? */
pos = 0; /* no separator, start from the beginning */
}
p = (const unsigned char*)&file[pos];
}
OutString(p, outchar, param);
#else
OutString((unsigned char*)file, outchar, param);
#endif
/* line number */
buf[0] = '\0';
McuUtility_chcat(buf, sizeof(buf), ':');
McuUtility_strcatNum32u(buf, sizeof(buf), line);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)": ");
OutString(buf, outchar, param);
}
#if McuLog_CONFIG_USE_PRINTF_STYLE
void McuLog_ChannelLog(uint8_t channel, McuLog_Levels_e level, const char *file, int line, const char *fmt, ...) {
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE
DATEREC date;
#define DATE_PTR &date
#else
#define DATE_PTR NULL
#endif
#if McuLog_CONFIG_LOG_TIMESTAMP_TIME
TIMEREC time;
#define TIME_PTR &time
#else
#define TIME_PTR NULL
#endif
va_list list;
if (level < McuLog_ConfigData.level) {
return;
}
if (channel>=McuLog_CONFIG_NOF_CONSOLE_LOGGER) {
return; /* wrong channel number? */
}
#if McuLog_CONFIG_USE_MUTEX
lock(); /* Acquire lock */
#endif
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE || McuLog_CONFIG_LOG_TIMESTAMP_TIME
(void)McuTimeDate_GetTimeDate(TIME_PTR, DATE_PTR); /* Get current date and time */
#endif
if (!McuLog_ConfigData.quiet) {
if(McuLog_ConfigData.consoleIo[channel]!=NULL) { /* log to console */
LogHeader(DATE_PTR, TIME_PTR, level, true, file, line, OutputCharFctConsole, McuLog_ConfigData.consoleIo[channel]->stdErr);
/* open argument list */
va_start(list, fmt);
McuXFormat_xvformat(OutputCharFctConsole, McuLog_ConfigData.consoleIo[channel]->stdErr, fmt, list);
va_end(list);
OutString((unsigned char *)"\n", OutputCharFctConsole, McuLog_ConfigData.consoleIo[channel]->stdErr);
}
}
#if McuLog_CONFIG_USE_MUTEX
unlock(); /* Release lock */
#endif
}
#endif
#if McuLog_CONFIG_USE_PRINTF_STYLE
void McuLog_log(McuLog_Levels_e level, const char *file, int line, const char *fmt, ...) {
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE
DATEREC date;
#define DATE_PTR &date
#else
#define DATE_PTR NULL
#endif
#if McuLog_CONFIG_LOG_TIMESTAMP_TIME
TIMEREC time;
#define TIME_PTR &time
#else
#define TIME_PTR NULL
#endif
va_list list;
if (level < McuLog_ConfigData.level) {
return;
}
#if McuLog_CONFIG_USE_MUTEX
lock(); /* Acquire lock */
#endif
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE || McuLog_CONFIG_LOG_TIMESTAMP_TIME
(void)McuTimeDate_GetTimeDate(TIME_PTR, DATE_PTR); /* Get current date and time */
#endif
if (!McuLog_ConfigData.quiet) {
for(int i=0; i<McuLog_CONFIG_NOF_CONSOLE_LOGGER; i++) {
if(McuLog_ConfigData.consoleIo[i]!=NULL) { /* log to console */
LogHeader(DATE_PTR, TIME_PTR, level, true, file, line, OutputCharFctConsole, McuLog_ConfigData.consoleIo[i]->stdErr);
/* open argument list */
va_start(list, fmt);
McuXFormat_xvformat(OutputCharFctConsole, McuLog_ConfigData.consoleIo[i]->stdErr, fmt, list);
va_end(list);
OutString((unsigned char *)"\n", OutputCharFctConsole, McuLog_ConfigData.consoleIo[i]->stdErr);
}
} /* for */
}
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
/* log to RTT Data Logger */
if (McuLog_ConfigData.rttDataLogger) {
LogHeader(DATE_PTR, TIME_PTR, level, false, file, line, OutputCharRttLoggerFct, NULL);
/* open argument list */
va_start(list, fmt);
McuXFormat_xvformat(OutputCharRttLoggerFct, NULL, fmt, list);
va_end(list);
OutString((unsigned char *)"\n", OutputCharRttLoggerFct, NULL);
}
#endif
#if McuLog_CONFIG_USE_FILE
/* Log to file */
if (McuLog_ConfigData.fp) {
LogHeader(DATE_PTR, &time, level, false, file, line, OutputCharFctFile, McuLog_ConfigData.fp);
/* open argument list */
va_start(list, fmt);
McuXFormat_xvformat(OutputCharFctFile, McuLog_ConfigData.fp, fmt, list);
va_end(list);
OutString((unsigned char *)"\n", OutputCharFctFile, McuLog_ConfigData.fp);
f_sync(McuLog_ConfigData.fp);
}
#endif
#if McuLog_CONFIG_USE_MUTEX
unlock(); /* Release lock */
#endif
}
#endif
void McuLog_logString(McuLog_Levels_e level, const char *file, int line, const char *str) {
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE
DATEREC date;
#define DATE_PTR &date
#else
#define DATE_PTR NULL
#endif
#if McuLog_CONFIG_LOG_TIMESTAMP_TIME
TIMEREC time;
#define TIME_PTR &time
#else
#define TIME_PTR NULL
#endif
if (level < McuLog_ConfigData.level) {
return;
}
#if McuLog_CONFIG_USE_MUTEX
lock(); /* Acquire lock */
#endif
#if McuLog_CONFIG_LOG_TIMESTAMP_DATE || McuLog_CONFIG_LOG_TIMESTAMP_TIME
(void)McuTimeDate_GetTimeDate(TIME_PTR, DATE_PTR); /* Get current date and time */
#endif
if (!McuLog_ConfigData.quiet) {
for(int i=0; i<McuLog_CONFIG_NOF_CONSOLE_LOGGER; i++) {
if(McuLog_ConfigData.consoleIo[i]!=NULL) { /* log to console */
LogHeader(DATE_PTR, TIME_PTR, level, true, file, line, OutputCharFctConsole, McuLog_ConfigData.consoleIo[i]->stdErr);
OutString((unsigned char *)str, OutputCharFctConsole, McuLog_ConfigData.consoleIo[i]->stdErr);
OutString((unsigned char *)"\n", OutputCharFctConsole, McuLog_ConfigData.consoleIo[i]->stdErr);
}
} /* for */
}
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
/* log to RTT Data Logger */
if (McuLog_ConfigData.rttDataLogger) {
LogHeader(DATE_PTR, TIME_PTR, level, false, file, line, OutputCharRttLoggerFct, NULL);
OutString((unsigned char *)str, OutputCharRttLoggerFct, NULL);
OutString((unsigned char *)"\n", OutputCharRttLoggerFct, NULL);
}
#endif
#if McuLog_CONFIG_USE_FILE
/* Log to file */
if (McuLog_ConfigData.fp) {
LogHeader(DATE_PTR, &time, level, false, file, line, OutputCharFctFile, McuLog_ConfigData.fp);
OutString((unsigned char *)str, OutputCharFctFile, McuLog_ConfigData.fp);
OutString((unsigned char *)"\n", OutputCharFctFile, McuLog_ConfigData.fp);
f_sync(McuLog_ConfigData.fp);
}
#endif
#if McuLog_CONFIG_USE_MUTEX
unlock(); /* Release lock */
#endif
}
#if McuLog_CONFIG_USE_MUTEX
static void LockUnlockCallback(void *data, bool lock) {
(void)data; /* unused */
if (lock) {
(void)xSemaphoreTakeRecursive(McuLog_ConfigData.McuLog_Mutex, portMAX_DELAY);
} else {
(void)xSemaphoreGiveRecursive(McuLog_ConfigData.McuLog_Mutex);
}
}
#endif
#if McuLog_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
uint8_t buf[16];
McuShell_SendStatusStr((unsigned char*)"McuLog", (unsigned char*)"Log status\r\n", io->stdOut);
McuUtility_Num8uToStr(buf, sizeof(buf), McuLog_CONFIG_NOF_CONSOLE_LOGGER);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" channel\r\n");
McuShell_SendStatusStr((unsigned char*)" console", buf, io->stdOut);
#if McuLog_CONFIG_USE_FILE
McuShell_SendStatusStr((unsigned char*)" file", McuLog_ConfigData.fp!=NULL?(unsigned char*)"yes\r\n":(unsigned char*)"no\r\n", io->stdOut);
#endif
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
McuShell_SendStatusStr((unsigned char*)" rttlogger", McuLog_ConfigData.rttDataLogger?(unsigned char*)"on\r\n":(unsigned char*)"off\r\n", io->stdOut);
#endif
#if McuLog_CONFIG_USE_MUTEX
McuShell_SendStatusStr((unsigned char*)" lock", McuLog_ConfigData.lock!=NULL?(unsigned char*)"yes\r\n":(unsigned char*)"no\r\n", io->stdOut);
#endif
McuShell_SendStatusStr((unsigned char*)" level", (unsigned char*)level_names[McuLog_ConfigData.level], io->stdOut);
McuShell_SendStr((unsigned char*)" (", io->stdOut);
McuShell_SendNum8u(McuLog_ConfigData.level, io->stdOut);
McuShell_SendStr((unsigned char*)"), logging for this level and higher\r\n", io->stdOut);
#if McuLog_CONFIG_USE_COLOR
McuShell_SendStatusStr((unsigned char*)" color", McuLog_ConfigData.color?(unsigned char*)"on\r\n":(unsigned char*)"off\r\n", io->stdOut);
#endif
return ERR_OK;
}
#endif /* McuLog_CONFIG_PARSE_COMMAND_ENABLED */
#if McuLog_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"McuLog", (unsigned char*)"Group of McuLog commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" level <level>", (unsigned char*)"Set log level, 0 (TRACE), 1 (DEBUG), 2 (INFO), 3 (WARN), 4 (ERROR), 5 (FATAL)\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" quiet <on|off>", (unsigned char*)"Set quiet mode for console\r\n", io->stdOut);
#if McuLog_CONFIG_USE_COLOR
McuShell_SendHelpStr((unsigned char*)" color <on|off>", (unsigned char*)"Set color mode\r\n", io->stdOut);
#endif
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
McuShell_SendHelpStr((unsigned char*)" rttlogger <on|off>", (unsigned char*)"Set rtt data logger mode\r\n", io->stdOut);
#endif
return ERR_OK;
}
#endif /* McuLog_CONFIG_PARSE_COMMAND_ENABLED */
#if McuLog_CONFIG_PARSE_COMMAND_ENABLED
uint8_t McuLog_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
uint8_t res = ERR_OK;
const unsigned char *p;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP) == 0
|| McuUtility_strcmp((char*)cmd, "McuLog help") == 0)
{
*handled = TRUE;
return PrintHelp(io);
} else if ( (McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0)
|| (McuUtility_strcmp((char*)cmd, "McuLog status")==0)
)
{
*handled = TRUE;
res = PrintStatus(io);
} else if (McuUtility_strcmp((char*)cmd, "McuLog quiet on")==0) {
*handled = TRUE;
McuLog_set_quiet(true);
} else if (McuUtility_strcmp((char*)cmd, "McuLog quiet off")==0) {
*handled = TRUE;
McuLog_set_quiet(false);
#if McuLog_CONFIG_USE_COLOR
} else if (McuUtility_strcmp((char*)cmd, "McuLog color on")==0) {
*handled = TRUE;
McuLog_set_color(true);
} else if (McuUtility_strcmp((char*)cmd, "McuLog color off")==0) {
*handled = TRUE;
McuLog_set_color(false);
#endif
} else if (McuUtility_strncmp((char*)cmd, "McuLog level ", sizeof("McuLog level ")-1)==0) {
uint8_t level;
*handled = TRUE;
p = cmd+sizeof("McuLog level ")-1;
if (McuUtility_ScanDecimal8uNumber(&p, &level)==ERR_OK && level<=McuLog_FATAL) {
McuLog_set_level(level);
}
}
return res;
}
#endif /* McuLog_CONFIG_PARSE_COMMAND_ENABLED */
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
static char McuLog_RttUpBuffer[McuLog_CONFIG_RTT_DATA_LOGGER_BUFFER_SIZE];
#endif
void McuLog_Init(void) {
#if McuLog_CONFIG_USE_MUTEX
McuLog_ConfigData.McuLog_Mutex = xSemaphoreCreateRecursiveMutex();
if (McuLog_ConfigData.McuLog_Mutex==NULL) { /* semaphore creation failed */
for(;;) {} /* error, not enough memory? */
}
vQueueAddToRegistry(McuLog_ConfigData.McuLog_Mutex, "McuLog_Mutex");
McuLog_set_lock(LockUnlockCallback);
#endif
#if McuLog_CONFIG_USE_COLOR
McuLog_set_color(true);
#endif
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
McuLog_set_rtt_logger(true);
#endif
McuLog_ConfigData.consoleIo[0] = McuShell_GetStdio(); /* default */
McuLog_set_level(McuLog_CONFIG_DEFAULT_LEVEL); /* default level */
#if McuLog_CONFIG_USE_RTT_DATA_LOGGER
#if McuLib_CONFIG_SDK_USE_FREERTOS && configUSE_SEGGER_SYSTEM_VIEWER_HOOKS && McuSystemView_CONFIG_RTT_CHANNEL==McuLog_RTT_DATA_LOGGER_CHANNEL
#error "Both RTT Logger and SystemViewer are using the same channel! Change McuSystemView_CONFIG_RTT_CHANNEL to a different value."
#endif
SEGGER_RTT_ConfigUpBuffer(McuLog_RTT_DATA_LOGGER_CHANNEL, "Logger", &McuLog_RttUpBuffer[0], sizeof(McuLog_RttUpBuffer), McuLog_CONFIG_RTT_DATA_LOGGER_CHANNEL_MODE);
#endif
for(int i=0; i<McuLog_CONFIG_NOF_CONSOLE_LOGGER; i++) {
McuLog_set_console(NULL, i);
}
}
void McuLog_Deinit(void) {
#if McuLog_CONFIG_USE_MUTEX
vSemaphoreDelete(McuLog_ConfigData.McuLog_Mutex);
McuLog_ConfigData.McuLog_Mutex = NULL;
McuLog_set_lock(NULL);
#endif
}
#endif /* McuLog_CONFIG_IS_ENABLED */

View File

@@ -0,0 +1,123 @@
/**
* Copyright (c) 2017 rxi
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See `McuLog.c` for details.
*/
/* Original source is from https://github.com/rxi/log.c
* McuLib integration and extensions: Copyright (c) 2020 Erich Styger
*/
#ifndef MCULOG_H
#define MCULOG_H
#include "McuLogconfig.h"
#ifdef __cplusplus
extern "C" {
#endif
#if McuLog_CONFIG_IS_ENABLED
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#include "McuShell.h"
#if McuLog_CONFIG_USE_FILE
#include "McuFatFS.h"
#endif
#define McuLog_VERSION "0.1.2"
#define McuLog_RTT_DATA_LOGGER_CHANNEL (1) /* channel used for the RTT data logger */
typedef enum { McuLog_TRACE, McuLog_DEBUG, McuLog_INFO, McuLog_WARN, McuLog_ERROR, McuLog_FATAL } McuLog_Levels_e;
/* note: gcc supports __BASE_FILE__ instead of __FILE__ */
#ifndef __BASE_FILE__
#define __BASE_FILE__ __FILE__
#endif
#define McuLog_trace(...) McuLog_log(McuLog_TRACE, __BASE_FILE__, __LINE__, __VA_ARGS__)
#define McuLog_debug(...) McuLog_log(McuLog_DEBUG, __BASE_FILE__, __LINE__, __VA_ARGS__)
#define McuLog_info(...) McuLog_log(McuLog_INFO, __BASE_FILE__, __LINE__, __VA_ARGS__)
#define McuLog_warn(...) McuLog_log(McuLog_WARN, __BASE_FILE__, __LINE__, __VA_ARGS__)
#define McuLog_error(...) McuLog_log(McuLog_ERROR, __BASE_FILE__, __LINE__, __VA_ARGS__)
#define McuLog_fatal(...) McuLog_log(McuLog_FATAL, __BASE_FILE__, __LINE__, __VA_ARGS__)
#define McuLog_traceString(str) McuLog_logString(McuLog_TRACE, __BASE_FILE__, __LINE__, str)
#define McuLog_debugString(str) McuLog_logString(McuLog_DEBUG, __BASE_FILE__, __LINE__, str)
#define McuLog_infoString(str) McuLog_logString(McuLog_INFO, __BASE_FILE__, __LINE__, str)
#define McuLog_warnString(str) McuLog_logString(McuLog_WARN, __BASE_FILE__, __LINE__, str)
#define McuLog_errorString(str) McuLog_logString(McuLog_ERROR, __BASE_FILE__, __LINE__, str)
#define McuLog_fatalString(str) McuLog_logString(McuLog_FATAL, __BASE_FILE__, __LINE__, str)
void McuLog_set_console(McuShell_ConstStdIOType *io, uint8_t index);
#if McuLog_CONFIG_USE_MUTEX
typedef void (*log_LockFn)(void *udata, bool lock);
void McuLog_set_lock(log_LockFn fn);
void McuLog_set_udata(void *udata);
#endif
#if McuLog_CONFIG_USE_FILE
void McuLog_set_fp(McuFatFS_FIL *fp);
int McuLog_open_logfile(const unsigned char *logFileName); /* returns 0 on success */
int McuLog_close_logfile(void); /* returns 0 on success */
#endif
void McuLog_set_level(McuLog_Levels_e level);
void McuLog_set_quiet(bool enable);
#if McuLog_CONFIG_USE_COLOR
void McuLog_set_color(bool enable);
#endif
#if McuLog_CONFIG_USE_PRINTF_STYLE
void McuLog_log(McuLog_Levels_e level, const char *file, int line, const char *fmt, ...);
void McuLog_ChannelLog(uint8_t channel, McuLog_Levels_e level, const char *file, int line, const char *fmt, ...);
#endif
void McuLog_logString(McuLog_Levels_e level, const char *file, int line, const char *str);
#if McuLog_CONFIG_PARSE_COMMAND_ENABLED
uint8_t McuLog_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
#endif
void McuLog_Init(void);
void McuLog_Deinit(void);
#else /* not enabled: do not add anything to the code */
/* dummy implementation to 'nothing' */
#define McuLog_traceString(str) do{}while(0)
#define McuLog_debugString(str) do{}while(0)
#define McuLog_infoString(str) do{}while(0)
#define McuLog_warnString(str) do{}while(0)
#define McuLog_errorString(str) do{}while(0)
#define McuLog_fatalString(str) do{}while(0)
#define McuLog_trace(...) do{}while(0)
#define McuLog_debug(...) do{}while(0)
#define McuLog_info(...) do{}while(0)
#define McuLog_warn(...) do{}while(0)
#define McuLog_error(...) do{}while(0)
#define McuLog_fatal(...) do{}while(0)
#define McuLog_set_console(io,ch) do{}while(0)
#define McuLog_set_udata(udata) do{}while(0)
#define McuLog_set_lock(fn) do{}while(0)
#define McuLog_set_fp(fp) do{}while(0)
#define McuLog_set_level(level) do{}while(0)
#define McuLog_set_quiet(enable) do{}while(0)
#define McuLog_set_color(enable) do{}while(0)
#define McuLog_log(level, file, line, fmt, ...) do{}while(0)
#define McuLog_Init() do{}while(0)
#define McuLog_Deinit() do{}while(0)
#endif /* McuLog_CONFIG_IS_ENABLED */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MCULOG_H */

View File

@@ -0,0 +1,810 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuOneWire.h
** CDE edition : Community
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : OneWire
** Version : Component 01.154, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-10-13, 06:28, # CodeGen: 701
** Abstract :
** This is a component implementing the 1-Wire protocol.
** Settings :
** Component Name : McuOneWire
** Data Pin I/O : SDK_BitIO
** Write Pin : Disabled
** Timing :
** A: Write 1 Low time (us) : 6
** B: Write 1 High time (us) : 64
** C: Write 0 Low time (us) : 60
** D: Write 0 High time (us) : 10
** E: Read delay time (us) : 3
** A: Read Low time (us) : 6
** F: Read delay time : 55
** H: Reset low time (us) : 480
** I: Reset response time (us) : 70
** J: Reset wait time after reading device presence (us) : 410
** Total slot time (us) : 100
** Buffers :
** Input : RBInput
** Debug : Enabled
** Debug Read Pin : SDK_BitIO
** CriticalSection : McuCriticalSection
** Utility : McuUtility
** Wait : McuWait
** SDK : McuLib
** RTOS : Enabled
** RTOS : McuRTOS
** Shell : Enabled
** Shell : McuShell
** Contents :
** CalcCRC - uint8_t McuOneWire_CalcCRC(uint8_t *data, uint8_t dataSize);
** SendByte - uint8_t McuOneWire_SendByte(uint8_t data);
** SendBytes - uint8_t McuOneWire_SendBytes(uint8_t *data, uint8_t count);
** Receive - uint8_t McuOneWire_Receive(uint8_t counter);
** SendReset - uint8_t McuOneWire_SendReset(void);
** Count - uint8_t McuOneWire_Count(void);
** GetBytes - uint8_t McuOneWire_GetBytes(uint8_t *data, uint8_t count);
** GetByte - uint8_t McuOneWire_GetByte(uint8_t *data);
** strcatRomCode - uint8_t McuOneWire_strcatRomCode(uint8_t *buf, size_t bufSize, uint8_t...
** ReadRomCode - uint8_t McuOneWire_ReadRomCode(uint8_t *romCodeBuffer);
** ResetSearch - void McuOneWire_ResetSearch(void);
** TargetSearch - void McuOneWire_TargetSearch(uint8_t familyCode);
** Search - bool McuOneWire_Search(uint8_t *newAddr, bool search_mode);
** ParseCommand - uint8_t McuOneWire_ParseCommand(const unsigned char* cmd, bool *handled,...
** Deinit - void McuOneWire%.Init(void) McuOneWire_Deinit(void);
** Init - void McuOneWire%.Init(void) McuOneWire_Init(void);
**
** * Copyright (c) Original implementation: Omar Isa<73> Pinales Ayala, 2014, all rights reserved.
** * Updated and maintained by Erich Styger, 2014-2020
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuOneWire.h
** @version 01.00
** @brief
** This is a component implementing the 1-Wire protocol.
*/
/*!
** @addtogroup McuOneWire_module McuOneWire module documentation
** @{
*/
/* MODULE McuOneWire. */
#include "McuOneWire.h"
#include "DQ1.h" /* data pin */
#include "InputRB1.h" /* input ring buffer */
#include "McuUtility.h" /* Utility */
#include "McuWait.h" /* Waiting */
/* global search state and information */
static unsigned char ROM_NO[8];
static uint8_t LastDiscrepancy;
static uint8_t LastFamilyDiscrepancy;
static uint8_t LastDeviceFlag;
/* Rom commands */
#define RC_READ_ROM 0x33
#define RC_MATCH_ROM 0x55
#define RC_SKIP_ROM 0xCC
#define RC_SEARCH_COND 0xEC
#define RC_SEARCH 0xF0
#define RC_RELEASE 0xFF
#if McuOneWire_CONFIG_WRITE_PIN /* extra pin only for write bit */
#define DQ_Init DQ1_Init(); McuOneWire_CONFIG_WRITE_PIN_INIT
#define DQ_Deinit DQ1_Deinit(); McuOneWire_CONFIG_WRITE_PIN_DEINIT
#else
#define DQ_Init DQ1_Init()
#define DQ_Deinit DQ1_Deinit()
#endif
#if McuOneWire_CONFIG_WRITE_PIN /* using dedicated circuit with separate pin to control the 1-wire write */
#define DQ_SetLow McuOneWire_CONFIG_WRITE_PIN_SET_OUTPUT
#define DQ_Low McuOneWire_CONFIG_WRITE_PIN_HIGH
#define DQ_Floating McuOneWire_CONFIG_WRITE_PIN_LOW
#else
#define DQ_SetLow DQ1_ClrVal()
#define DQ_Low DQ1_SetOutput()
#define DQ_Floating DQ1_SetInput()
#endif
#if McuOneWire_CONFIG_DEBUG_READ_PIN_ENABLED
#define DBG_Init McuOneWire_CONFIG_DEBUG_READ_PIN_INIT
#define DBG_Deinit McuOneWire_CONFIG_DEBUG_READ_PIN_DEINIT
#define DQ_Read (McuOneWire_CONFIG_DEBUG_READ_PIN_TOGGLE, DQ1_GetVal()!=0)
#else
#define DBG_Init /* empty */
#define DBG_Deinit /* empty */
#define DQ_Read (DQ1_GetVal()!=0)
#endif
static uint8_t read_bit(void) {
uint8_t bit;
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
DQ_Low;
McuWait_Waitus(McuOneWire_CONFIG_A_READ_LOW_TIME);
DQ_Floating;
McuWait_Waitus(McuOneWire_CONFIG_E_BEFORE_READ_DELAY_TIME);
bit = DQ_Read;
McuCriticalSection_ExitCritical();
McuWait_Waitus(McuOneWire_CONFIG_F_AFTER_READ_DELAY_TIME);
return bit;
}
static void write_bit(uint8_t bit) {
McuCriticalSection_CriticalVariable();
if (bit&1) {
McuCriticalSection_EnterCritical();
DQ_Low;
McuWait_Waitus(McuOneWire_CONFIG_A_WRITE_1_LOW_TIME);
DQ_Floating;
McuWait_Waitus(McuOneWire_CONFIG_B_WRITE_1_HIGH_TIME);
McuCriticalSection_ExitCritical();
} else { /* zero bit */
McuCriticalSection_EnterCritical();
DQ_Low;
McuWait_Waitus(McuOneWire_CONFIG_C_WRITE_0_LOW_TIME);
DQ_Floating;
McuWait_Waitus(McuOneWire_CONFIG_D_WRITE_0_HIGH_TIME);
McuCriticalSection_ExitCritical();
}
}
#if McuOneWire_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
McuShell_SendStatusStr((unsigned char*)"McuOneWire", (unsigned char*)"\r\n", io->stdOut);
#if McuOneWire_CONFIG_DEBUG_READ_PIN_ENABLED
McuShell_SendStatusStr((unsigned char*)" debug pin", (unsigned char*)"yes\r\n", io->stdOut);
#else
McuShell_SendStatusStr((unsigned char*)" debug pin", (unsigned char*)"no\r\n", io->stdOut);
#endif
return ERR_OK;
}
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"McuOneWire", (unsigned char*)"Group of McuOneWire commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" reset", (unsigned char*)"Send a RESET sequence to the bus\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" read rom", (unsigned char*)"Send a READ ROM (0x33) to the bus\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" search", (unsigned char*)"Search for devices on the bus\r\n", io->stdOut);
return ERR_OK;
}
#endif /* McuOneWire_CONFIG_PARSE_COMMAND_ENABLED */
/*
** ===================================================================
** Method : SendReset (component OneWire)
**
** Description :
** Sends a reset to the bus
** Parameters : None
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_SendReset(void)
{
uint8_t bit;
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
DQ_Low;
McuWait_Waitus(McuOneWire_CONFIG_H_RESET_TIME);
DQ_Floating;
McuWait_Waitus(McuOneWire_CONFIG_I_RESET_RESPONSE_TIME);
bit = DQ_Read;
McuCriticalSection_ExitCritical();
McuWait_Waitus(McuOneWire_CONFIG_J_RESET_WAIT_TIME);
if (!bit) { /* a device pulled the data line low: at least one device is present */
return ERR_OK;
} else {
return ERR_BUSOFF; /* no device on the bus? */
}
}
/*
** ===================================================================
** Method : SendByte (component OneWire)
**
** Description :
** Sends a single byte
** Parameters :
** NAME - DESCRIPTION
** data - the data byte to be sent
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_SendByte(uint8_t data)
{
int i;
for(i=0;i<8;i++) {
write_bit(data&1); /* send LSB first */
data >>= 1; /* next bit */
} /* for */
return ERR_OK;
}
/*
** ===================================================================
** Method : SendBytes (component OneWire)
**
** Description :
** Sends multiple bytes
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to the array of bytes
** count - Number of bytes to be sent
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_SendBytes(uint8_t *data, uint8_t count)
{
uint8_t res;
while(count>0) {
res = McuOneWire_SendByte(*data);
if (res!=ERR_OK) {
return res; /* failed */
}
data++;
count--;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : Receive (component OneWire)
**
** Description :
** Programs a read operation after the master send all in
** output buffer. Don't use a SendReset while the data is
** coming.
** Parameters :
** NAME - DESCRIPTION
** counter - Number of bytes to receive from
** slave
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_Receive(uint8_t counter)
{
int i;
uint8_t val, mask;
while(counter>0) {
val = 0; mask = 1;
for(i=0;i<8;i++) {
if (read_bit()) { /* read bits (LSB first) */
val |= mask;
}
mask <<= 1; /* next bit */
} /* for */
(void)InputRB1_Put(val); /* put it into the queue so it can be retrieved by GetBytes() */
counter--;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : Count (component OneWire)
**
** Description :
** Returns the number of elements stored on input buffer that
** are ready to read.
** Parameters : None
** Returns :
** --- - number of elements
** ===================================================================
*/
uint8_t McuOneWire_Count(void)
{
return InputRB1_NofElements();
}
/*
** ===================================================================
** Method : GetByte (component OneWire)
**
** Description :
** Get a single byte from the bus
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to were to store the data
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_GetByte(uint8_t *data)
{
if (InputRB1_NofElements()==0) {
return ERR_FAILED;
}
(void)InputRB1_Get(data);
return ERR_OK;
}
/*
** ===================================================================
** Method : GetBytes (component OneWire)
**
** Description :
** Gets multiple bytes from the bus
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to where to store the data
** count - Number of bytes
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_GetBytes(uint8_t *data, uint8_t count)
{
if(count > InputRB1_NofElements()) {
return ERR_FAILED;
}
for(;count>0;count--) {
(void)InputRB1_Get(data);
data++;
}
return ERR_OK;
}
/*
** ===================================================================
** Method : CalcCRC (component OneWire)
**
** Description :
** Calculates the CRC over a number of bytes
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to data
** dataSize - number of data bytes
** Returns :
** --- - calculated CRC
** ===================================================================
*/
uint8_t McuOneWire_CalcCRC(uint8_t *data, uint8_t dataSize)
{
uint8_t crc, i, x, y;
crc = 0;
for(x=0;x<dataSize;x++){
y = data[x];
for(i=0;i<8;i++) { /* go through all bits of the data byte */
if((crc&0x01)^(y&0x01)) {
crc >>= 1;
crc ^= 0x8c;
} else {
crc >>= 1;
}
y >>= 1;
}
}
return crc;
}
/*
** ===================================================================
** Method : Init (component OneWire)
**
** Description :
** Initializes this device.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuOneWire_Init(void)
{
#if McuLib_CONFIG_NXP_SDK_USED
/* using SDK, need to initialize inherited components */
DQ_Init; /* data pin */
DBG_Init; /* optional debug pin */
InputRB1_Init(); /* input ring buffer */
#endif
DQ_Floating; /* input mode, let the pull-up take the signal high */
/* load LOW to output register. We won't change that value afterwards, we only switch between output and input/float mode */
DQ_SetLow;
}
/*
** ===================================================================
** Method : Deinit (component OneWire)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuOneWire_Deinit(void)
{
DQ_Deinit; /* data pin */
DQ_Floating; /* input mode, tristate pin */
DBG_Deinit; /* optional debug pin */
InputRB1_Deinit(); /* input ring buffer */
}
/*
** ===================================================================
** Method : ParseCommand (component OneWire)
**
** Description :
** Shell Command Line parser. Method is only available if Shell
** is enabled in the component properties.
** Parameters :
** NAME - DESCRIPTION
** cmd - command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuOneWire_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io)
{
#if McuOneWire_CONFIG_PARSE_COMMAND_ENABLED
uint8_t res = ERR_OK;
uint8_t buf[32];
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP) == 0
|| McuUtility_strcmp((char*)cmd, "McuOneWire help") == 0)
{
*handled = TRUE;
return PrintHelp(io);
} else if ( (McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0)
|| (McuUtility_strcmp((char*)cmd, "McuOneWire status")==0)
)
{
*handled = TRUE;
res = PrintStatus(io);
} else if (McuUtility_strcmp((char*)cmd, "McuOneWire read rom")==0) {
uint8_t rom[McuOneWire_ROM_CODE_SIZE];
*handled = TRUE;
res = McuOneWire_ReadRomCode(&rom[0]);
if (res!=ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ReadRomCode() ERROR (");
McuUtility_strcatNum8u(buf, sizeof(buf), res);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)")\r\n");
McuShell_SendStr(buf, io->stdErr);
} else {
buf[0] = '\0';
(void)McuOneWire_strcatRomCode(buf, sizeof(buf), &rom[0]);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStr(buf, io->stdOut);
}
} else if (McuUtility_strcmp((char*)cmd, "McuOneWire reset")==0) {
*handled = TRUE;
res = McuOneWire_SendReset();
if (res==ERR_OK) {
McuShell_SendStr((unsigned char*)"Device present\r\n", io->stdOut);
} else {
McuShell_SendStr((unsigned char*)"No device present?\r\n", io->stdErr);
}
} else if (McuUtility_strcmp((char*)cmd, "McuOneWire search")==0) {
uint8_t rom[McuOneWire_ROM_CODE_SIZE];
bool found;
int nofFound = 0;
*handled = TRUE;
McuOneWire_ResetSearch();
do {
found = McuOneWire_Search(&rom[0], TRUE);
if (found) {
nofFound++;
buf[0] = '\0';
(void)McuOneWire_strcatRomCode(buf, sizeof(buf), &rom[0]);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStr(buf, io->stdOut);
}
} while(found);
if (nofFound==0) {
McuShell_SendStr((unsigned char*)"No device found!\r\n", io->stdErr);
}
return ERR_OK;
}
return res;
#else
(void)cmd;
(void)handled;
(void)io;
return ERR_OK;
#endif
}
/*
** ===================================================================
** Method : ReadRomCode (component OneWire)
**
** Description :
** Read the ROM code. Only works with one device on the bus.
** Parameters :
** NAME - DESCRIPTION
** * romCodeBuffer - Pointer to a buffer
** with 8 bytes where the ROM code gets stored
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuOneWire_ReadRomCode(uint8_t *romCodeBuffer)
{
uint8_t res;
McuOneWire_SendReset();
McuOneWire_SendByte(RC_READ_ROM);
McuOneWire_Receive(McuOneWire_ROM_CODE_SIZE); /* 8 bytes for the ROM code */
McuOneWire_SendByte(RC_RELEASE);
/* copy ROM code */
res = McuOneWire_GetBytes(romCodeBuffer, McuOneWire_ROM_CODE_SIZE); /* 8 bytes */
if (res!=ERR_OK) {
return res; /* error */
}
/* index 0 : family code
index 1-6: 48bit serial number
index 7 : CRC
*/
if (McuOneWire_CalcCRC(&romCodeBuffer[0], McuOneWire_ROM_CODE_SIZE-1)!=romCodeBuffer[McuOneWire_ROM_CODE_SIZE-1]) {
return ERR_CRC; /* wrong CRC? */
}
return ERR_OK; /* ok */
}
/*
** ===================================================================
** Method : strcatRomCode (component OneWire)
**
** Description :
** Appends the ROM code to a string.
** Parameters :
** NAME - DESCRIPTION
** * buf - Pointer to zero terminated buffer
** bufSize - size of buffer
** * romCode - Pointer to 8 bytes of ROM Code
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_strcatRomCode(uint8_t *buf, size_t bufSize, uint8_t *romCode)
{
int j;
for(j=0;j<McuOneWire_ROM_CODE_SIZE;j++) {
McuUtility_strcatNum8Hex(buf, bufSize, romCode[j]);
if(j<McuOneWire_ROM_CODE_SIZE-1) {
McuUtility_chcat(buf, bufSize, '-');
}
}
return ERR_OK;
}
/*
** ===================================================================
** Method : ResetSearch (component OneWire)
**
** Description :
** Reset the search state
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuOneWire_ResetSearch(void)
{
/* reset the search state */
int i;
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
for(i = 7; ; i--) {
ROM_NO[i] = 0;
if (i==0) {
break;
}
}
}
/*
** ===================================================================
** Method : TargetSearch (component OneWire)
**
** Description :
**
** Parameters :
** NAME - DESCRIPTION
** familyCode - family code to restrict
** search for
** Returns : Nothing
** ===================================================================
*/
void McuOneWire_TargetSearch(uint8_t familyCode)
{
/* set the search state to find SearchFamily type devices */
int i;
ROM_NO[0] = familyCode;
for (i = 1; i < 8; i++) {
ROM_NO[i] = 0;
}
LastDiscrepancy = 64;
LastFamilyDiscrepancy = 0;
LastDeviceFlag = FALSE;
}
/*
** ===================================================================
** Method : Search (component OneWire)
**
** Description :
**
** Parameters :
** NAME - DESCRIPTION
** * newAddr - Pointer to 8 bytes of data where
** to store the new address
** search_mode -
** Returns :
** --- - TRUE if new device has been found, FALSE
** otherwise.
** ===================================================================
*/
bool McuOneWire_Search(uint8_t *newAddr, bool search_mode)
{
/* Version from https://raw.githubusercontent.com/PaulStoffregen/OneWire/master/OneWire.cpp */
/*-------------------------------------------------------------------------- */
/* Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing */
/* search state. */
/* Return TRUE : device found, ROM number in ROM_NO buffer */
/* FALSE : device not found, end of search */
uint8_t id_bit_number;
uint8_t last_zero, rom_byte_number, search_result;
uint8_t id_bit, cmp_id_bit;
unsigned char rom_byte_mask, search_direction;
uint8_t res;
/* initialize for search */
id_bit_number = 1;
last_zero = 0;
rom_byte_number = 0;
rom_byte_mask = 1;
search_result = 0;
/* if the last call was not the last one */
if (!LastDeviceFlag) {
/* 1-Wire reset */
res = McuOneWire_SendReset();
if (res!=ERR_OK) {
/* reset the search */
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
return FALSE;
}
/* issue the search command */
if (search_mode) {
McuOneWire_SendByte(RC_SEARCH); /* NORMAL SEARCH */
} else {
McuOneWire_SendByte(RC_SEARCH_COND); /* CONDITIONAL SEARCH */
}
/* loop to do the search */
do {
/* read a bit and its complement */
id_bit = read_bit();
cmp_id_bit = read_bit();
/* check for no devices on 1-wire */
if ((id_bit==1) && (cmp_id_bit==1)) {
break;
} else {
/* all devices coupled have 0 or 1 */
if (id_bit != cmp_id_bit) {
search_direction = id_bit; /* bit write value for search */
} else {
/* if this discrepancy if before the Last Discrepancy */
/* on a previous next then pick the same as last time */
if (id_bit_number < LastDiscrepancy) {
search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0);
} else {
/* if equal to last pick 1, if not then pick 0 */
search_direction = (id_bit_number == LastDiscrepancy);
}
/* if 0 was picked then record its position in LastZero */
if (search_direction == 0) {
last_zero = id_bit_number;
/* check for Last discrepancy in family */
if (last_zero < 9)
LastFamilyDiscrepancy = last_zero;
}
}
/* set or clear the bit in the ROM byte rom_byte_number */
/* with mask rom_byte_mask */
if (search_direction == 1) {
ROM_NO[rom_byte_number] |= rom_byte_mask;
} else {
ROM_NO[rom_byte_number] &= ~rom_byte_mask;
}
/* serial number search direction write bit */
write_bit(search_direction);
/* increment the byte counter id_bit_number */
/* and shift the mask rom_byte_mask */
id_bit_number++;
rom_byte_mask <<= 1;
/* if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask */
if (rom_byte_mask == 0) {
rom_byte_number++;
rom_byte_mask = 1;
}
}
}
while(rom_byte_number < 8); /* loop until through all ROM bytes 0-7 */
/* if the search was successful then */
if (!(id_bit_number < 65)) {
/* search successful so set LastDiscrepancy,LastDeviceFlag,search_result */
LastDiscrepancy = last_zero;
/* check for last device */
if (LastDiscrepancy == 0) {
LastDeviceFlag = TRUE;
}
search_result = TRUE;
}
}
/* if no device found then reset counters so next 'search' will be like a first */
if (!search_result || !ROM_NO[0]) {
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
search_result = FALSE;
} else {
int i;
for (i = 0; i < 8; i++) {
newAddr[i] = ROM_NO[i];
}
}
return search_result;
}
/* END McuOneWire. */
/*!
** @}
*/

View File

@@ -0,0 +1,364 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuOneWire.h
** CDE edition : Community
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : OneWire
** Version : Component 01.154, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-01-29, 06:51, # CodeGen: 595
** Abstract :
** This is a component implementing the 1-Wire protocol.
** Settings :
** Component Name : McuOneWire
** Data Pin I/O : SDK_BitIO
** Write Pin : Disabled
** Timing :
** A: Write 1 Low time (us) : 6
** B: Write 1 High time (us) : 64
** C: Write 0 Low time (us) : 60
** D: Write 0 High time (us) : 10
** E: Read delay time (us) : 3
** A: Read Low time (us) : 6
** F: Read delay time : 55
** H: Reset low time (us) : 480
** I: Reset response time (us) : 70
** J: Reset wait time after reading device presence (us) : 410
** Total slot time (us) : 100
** Buffers :
** Input : RBInput
** Debug : Enabled
** Debug Read Pin : SDK_BitIO
** CriticalSection : McuCriticalSection
** Utility : McuUtility
** Wait : McuWait
** SDK : McuLib
** RTOS : Enabled
** RTOS : McuRTOS
** Shell : Enabled
** Shell : McuShell
** Contents :
** CalcCRC - uint8_t McuOneWire_CalcCRC(uint8_t *data, uint8_t dataSize);
** SendByte - uint8_t McuOneWire_SendByte(uint8_t data);
** SendBytes - uint8_t McuOneWire_SendBytes(uint8_t *data, uint8_t count);
** Receive - uint8_t McuOneWire_Receive(uint8_t counter);
** SendReset - uint8_t McuOneWire_SendReset(void);
** Count - uint8_t McuOneWire_Count(void);
** GetBytes - uint8_t McuOneWire_GetBytes(uint8_t *data, uint8_t count);
** GetByte - uint8_t McuOneWire_GetByte(uint8_t *data);
** strcatRomCode - uint8_t McuOneWire_strcatRomCode(uint8_t *buf, size_t bufSize, uint8_t...
** ReadRomCode - uint8_t McuOneWire_ReadRomCode(uint8_t *romCodeBuffer);
** ResetSearch - void McuOneWire_ResetSearch(void);
** TargetSearch - void McuOneWire_TargetSearch(uint8_t familyCode);
** Search - bool McuOneWire_Search(uint8_t *newAddr, bool search_mode);
** ParseCommand - uint8_t McuOneWire_ParseCommand(const unsigned char* cmd, bool *handled,...
** Deinit - void McuOneWire%.Init(void) McuOneWire_Deinit(void);
** Init - void McuOneWire%.Init(void) McuOneWire_Init(void);
**
** * Copyright (c) Original implementation: Omar Isa<73> Pinales Ayala, 2014, all rights reserved.
** * Updated and maintained by Erich Styger, 2014-2020
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuOneWire.h
** @version 01.00
** @brief
** This is a component implementing the 1-Wire protocol.
*/
/*!
** @addtogroup McuOneWire_module McuOneWire module documentation
** @{
*/
#ifndef __McuOneWire_H
#define __McuOneWire_H
/* MODULE McuOneWire. */
#include "McuLib.h" /* SDK and API used */
#include "McuOneWireconfig.h" /* configuration */
#include "McuShell.h" /* Shell */
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
#define McuOneWire_ROM_CODE_SIZE (8)
/*!< Number of bytes for ROM code */
#define McuOneWire_PARSE_COMMAND_ENABLED McuOneWire_CONFIG_PARSE_COMMAND_ENABLED
/*!< set to 1 if method ParseCommand() is present, 0 otherwise */
/*
** ===================================================================
** Method : Count (component OneWire)
**
** Description :
** Returns the number of elements stored on input buffer that
** are ready to read.
** Parameters : None
** Returns :
** --- - number of elements
** ===================================================================
*/
uint8_t McuOneWire_Count(void);
/*
** ===================================================================
** Method : Receive (component OneWire)
**
** Description :
** Programs a read operation after the master send all in
** output buffer. Don't use a SendReset while the data is
** coming.
** Parameters :
** NAME - DESCRIPTION
** counter - Number of bytes to receive from
** slave
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_Receive(uint8_t counter);
/*
** ===================================================================
** Method : SendByte (component OneWire)
**
** Description :
** Sends a single byte
** Parameters :
** NAME - DESCRIPTION
** data - the data byte to be sent
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_SendByte(uint8_t data);
/*
** ===================================================================
** Method : SendBytes (component OneWire)
**
** Description :
** Sends multiple bytes
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to the array of bytes
** count - Number of bytes to be sent
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_SendBytes(uint8_t *data, uint8_t count);
/*
** ===================================================================
** Method : SendReset (component OneWire)
**
** Description :
** Sends a reset to the bus
** Parameters : None
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_SendReset(void);
/*
** ===================================================================
** Method : GetByte (component OneWire)
**
** Description :
** Get a single byte from the bus
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to were to store the data
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_GetByte(uint8_t *data);
/*
** ===================================================================
** Method : GetBytes (component OneWire)
**
** Description :
** Gets multiple bytes from the bus
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to where to store the data
** count - Number of bytes
** Returns :
** --- - error code
** ===================================================================
*/
uint8_t McuOneWire_GetBytes(uint8_t *data, uint8_t count);
/*
** ===================================================================
** Method : Init (component OneWire)
**
** Description :
** Initializes this device.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuOneWire_Init(void);
void McuOneWire_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component OneWire)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuOneWire_CalcCRC(uint8_t *data, uint8_t dataSize);
/*
** ===================================================================
** Method : CalcCRC (component OneWire)
**
** Description :
** Calculates the CRC over a number of bytes
** Parameters :
** NAME - DESCRIPTION
** * data - Pointer to data
** dataSize - number of data bytes
** Returns :
** --- - calculated CRC
** ===================================================================
*/
uint8_t McuOneWire_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component OneWire)
**
** Description :
** Shell Command Line parser. Method is only available if Shell
** is enabled in the component properties.
** Parameters :
** NAME - DESCRIPTION
** cmd - command string
** * handled - Pointer to variable which tells if
** the command has been handled or not
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuOneWire_ReadRomCode(uint8_t *romCodeBuffer);
/*
** ===================================================================
** Method : ReadRomCode (component OneWire)
**
** Description :
** Read the ROM code. Only works with one device on the bus.
** Parameters :
** NAME - DESCRIPTION
** * romCodeBuffer - Pointer to a buffer
** with 8 bytes where the ROM code gets stored
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuOneWire_strcatRomCode(uint8_t *buf, size_t bufSize, uint8_t *romCode);
/*
** ===================================================================
** Method : strcatRomCode (component OneWire)
**
** Description :
** Appends the ROM code to a string.
** Parameters :
** NAME - DESCRIPTION
** * buf - Pointer to zero terminated buffer
** bufSize - size of buffer
** * romCode - Pointer to 8 bytes of ROM Code
** Returns :
** --- - error code
** ===================================================================
*/
void McuOneWire_ResetSearch(void);
/*
** ===================================================================
** Method : ResetSearch (component OneWire)
**
** Description :
** Reset the search state
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuOneWire_TargetSearch(uint8_t familyCode);
/*
** ===================================================================
** Method : TargetSearch (component OneWire)
**
** Description :
**
** Parameters :
** NAME - DESCRIPTION
** familyCode - family code to restrict
** search for
** Returns : Nothing
** ===================================================================
*/
bool McuOneWire_Search(uint8_t *newAddr, bool search_mode);
/*
** ===================================================================
** Method : Search (component OneWire)
**
** Description :
**
** Parameters :
** NAME - DESCRIPTION
** * newAddr - Pointer to 8 bytes of data where
** to store the new address
** search_mode -
** Returns :
** --- - TRUE if new device has been found, FALSE
** otherwise.
** ===================================================================
*/
/* END McuOneWire. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuOneWire_H */
/*!
** @}
*/

View File

@@ -0,0 +1,912 @@
/*
* Copyright (c) 2023-2024, Erich Styger
*
* * Driver for the NXP PCF85063A I2C RTC.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuPCF85063A.h"
#include "McuShell.h"
#include "McuUtility.h"
#include "McuGenericI2C.h"
#include "McuXFormat.h"
#define McuPCF85063A_I2C_DEVICE_ADDRESS (0x51) /* 7bit I2C address, not-shifted value */
/* register memory map */
#define McuPCF85063A_ADDRESS_CONTROL_1 0x00
#define McuPCF85063A_ADDRESS_CONTROL_2 0x01
#define McuPCF85063A_ADDRESS_OFFSET 0x02
#define McuPCF85063A_ADDRESS_RAM_BYTE 0x03
#define McuPCF85063A_ADDRESS_TIME_DATE_START_ADDR 0x04 /* start address of time and date registers */
#define McuPCF85063A_ADDRESS_TIME_START_ADDR 0x04 /* start address of time registers */
#define McuPCF85063A_ADDRESS_DATE_START_ADDR 0x07 /* start address of time registers */
#define McuPCF85063A_ADDRESS_ALARM_START_ADDR 0x0B /* start address of alarm registers */
#define McuPCF85063A_ADDRESS_ALARM_SECOND 0x0B /* Second_alarm */
#define McuPCF85063A_ADDRESS_ALARM_MINUTE 0x0C /* Minute_alarm */
#define McuPCF85063A_ADDRESS_ALARM_HOUR 0x0D /* Hour_alarm */
#define McuPCF85063A_ADDRESS_ALARM_DAY 0x0E /* Hour_alarm */
#define McuPCF85063A_ADDRESS_ALARM_WEEKDAY 0x0F /* Weekday_alarm */
#define McuPCF85063A_TTIME_AMPM_AM 0 /* AM */
#define McuPCF85063A_TTIME_AMPM_PM 1 /* PM */
/* hour mode is set in 12_24 bit in Control_1 */
#define McuPCF85063A_TTIME_MODE_12H 0 /* 12 hour clock mode */
#define McuPCF85063A_TTIME_MODE_24H 1 /* 14 hour clock mode */
#define McuPCF85063A_MEMORY_TIME_SIZE (3) /* 0x4-0x6, number of bytes for time information on device */
#define McuPCF85063A_MEMORY_DATE_SIZE (4) /* 0x7-0xA, number of bytes for date information on device */
#define McuPCF85063A_MEMORY_TIME_DATE_SIZE (7) /* 0x4-0xA, number of bytes for data and time information on device */
typedef struct McuPCF85063A_TTIME { /* Time in binary format */
uint8_t hour; /* hours */
uint8_t min; /* minutes */
uint8_t sec; /* seconds */
uint8_t am_pm; /* 0: AM, 1: PM */
uint8_t mode; /* hour mode is set in 12_24 bit in Control_1 */
} McuPCF85063A_TTIME;
typedef struct McuPCF85063A_TDATE { /* Date in binary format */
uint8_t year; /* year */
uint8_t month; /* month */
uint8_t day; /* day */
uint8_t dayOfWeek; /* Day of week, where 0 is the first day. In the range of 0..6 */
} McuPCF85063A_TDATE;
uint8_t McuPCF85063A_ReadBlock(uint8_t addr, uint8_t *buf, size_t bufSize) {
return McuGenericI2C_ReadAddress(McuPCF85063A_I2C_DEVICE_ADDRESS, &addr, sizeof(addr), buf, bufSize);
}
uint8_t McuPCF85063A_WriteBlock(uint8_t addr, uint8_t *buf, size_t bufSize) {
return McuGenericI2C_WriteAddress(McuPCF85063A_I2C_DEVICE_ADDRESS, &addr, sizeof(addr), buf, bufSize);
}
uint8_t McuPCF85063A_ReadByte(uint8_t addr, uint8_t *data) {
return McuGenericI2C_ReadAddress(McuPCF85063A_I2C_DEVICE_ADDRESS, &addr, sizeof(addr), data, sizeof(*data));
}
uint8_t McuPCF85063A_WriteByte(uint8_t addr, uint8_t data) {
return McuGenericI2C_WriteAddress(McuPCF85063A_I2C_DEVICE_ADDRESS, &addr, sizeof(addr), &data, sizeof(data));
}
uint8_t McuPCF85063A_ReadControl1(uint8_t *data) {
return McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_CONTROL_1, data);
}
uint8_t McuPCF85063A_WriteControl1(uint8_t data) {
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_CONTROL_1, data);
}
uint8_t McuPCF85063A_WriteSoftwareReset(void) {
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_CONTROL_1, 0x58);
}
uint8_t McuPCF85063A_ReadControl2(uint8_t *data) {
return McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_CONTROL_2, data);
}
uint8_t McuPCF85063A_WriteControl2(uint8_t data) {
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_CONTROL_2, data);
}
uint8_t McuPCF85063A_WriteAlarmInterrupt(bool enable) {
uint8_t data;
if (McuPCF85063A_ReadControl2(&data)!=ERR_OK) { /* read current value */
return ERR_FAILED;
}
/* AIE 0: disabled; 1: enabled */
if (enable) {
data |= (1<<7); /* set AIE (Alarm Interrupt Enable) bit */
} else {
data &= (1<<7); /* clear AIE (Alarm Interrupt Enable) bit */
}
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_CONTROL_2, data);
}
uint8_t McuPCF85063A_WriteClockOutputFrequency(McuPCF85063A_COF_Frequency_e frequency) {
uint8_t data;
if (McuPCF85063A_ReadControl2(&data)!=ERR_OK) { /* read current value */
return ERR_FAILED;
}
/* Clock Output Frequency:
* 000: 32768
* 001: 16387
* 010: 8196
* 011: 4096
* 100: 2048
* 101: 1024
* 110: 1
* 111: CLKOUT=LOW */
if (frequency>7) {
return ERR_RANGE;
}
data |= (frequency&7); /* set COF bits [2:0] */
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_CONTROL_2, data);
}
uint8_t McuPCF85063A_WriteResetAlarmInterrupt(void) {
uint8_t data;
if (McuPCF85063A_ReadControl2(&data)!=ERR_OK) { /* read current value */
return ERR_FAILED;
}
/* AF: reset alarm flag with writing a 0 to it */
data &= ~(1<<6); /* clear AF (Alarm Flag) bit */
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_CONTROL_2, data);
}
uint8_t McuPCF85063A_ReadOffset(uint8_t *data) {
return McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_OFFSET, data);
}
uint8_t McuPCF85063A_WriteOffset(uint8_t data) {
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_OFFSET, data);
}
bool McuPCF85063A_Is24hMode(void) {
uint8_t res, ctrl;
res = McuPCF85063A_ReadControl1(&ctrl);
if (res!=ERR_OK) {
return true; /* default is 24h mode */
}
return (ctrl&(1<<1))==0; /* 0: 12-hour mode, 1: 24-hour mode */
}
uint8_t McuPCF85063A_ReadAlarmSecond(uint8_t *second, bool *enabled) {
uint8_t data, res;
res = McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_ALARM_SECOND, &data);
if (res!=ERR_OK) {
return ERR_FAILED;
}
*enabled = (data&(1<<7))==0; /* 1: disabled (default), 0: enabled */
*second = ((data&0x70)>>4)*10 + (data&0x0F); /* BCD encoded */
return ERR_OK;
}
uint8_t McuPCF85063A_WriteAlarmSecond(uint8_t second, bool enable) {
uint8_t data;
if (second>59) {
return ERR_RANGE;
}
data = ((second/10)<<4)|(second%10); /* encoded in BCD */
if (!enable) {
data |= (1<<7); /* 1: disabled (default), 0: enabled */
}
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_ALARM_SECOND, data);
}
uint8_t McuPCF85063A_ReadAlarmMinute(uint8_t *minute, bool *enabled) {
uint8_t data, res;
res = McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_ALARM_MINUTE, &data);
if (res!=ERR_OK) {
return ERR_FAILED;
}
*enabled = (data&(1<<7))==0; /* 1: disabled (default), 0: enabled */
*minute = ((data&0x70)>>4)*10 + (data&0x0F); /* BCD encoded */
return ERR_OK;
}
uint8_t McuPCF85063A_WriteAlarmMinute(uint8_t minute, bool enable) {
uint8_t data;
if (minute>59) {
return ERR_RANGE;
}
data = ((minute/10)<<4)|(minute%10); /* BCD encoded */
if (!enable) {
data |= (1<<7); /* 1: disabled (default), 0: enabled */
}
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_ALARM_MINUTE, data);
}
uint8_t McuPCF85063A_ReadAlarmHour(uint8_t *hour, bool *enabled, bool *is24h, bool *isAM) {
uint8_t data, res;
*is24h = McuPCF85063A_Is24hMode();
res = McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_ALARM_HOUR, &data);
if (res!=ERR_OK) {
return ERR_FAILED;
}
*enabled = (data&(1<<7))==0; /* 1: disabled (default), 0: enabled */
if (*is24h) {
*hour = ((data&0x30)>>4)*10 + (data&0x0F); /* BCD encoded */
*isAM = false;
} else {
*hour = ((data&0x70)>>4)*10 + (data&0x0F); /* BCD encoded */
*isAM = (data&(1<<5))==0;
}
return ERR_OK;
}
/* Note: expects 24h hour format! */
uint8_t McuPCF85063A_WriteAlarmHour(uint8_t hour, bool enable, bool is24h, bool isAM) {
uint8_t data;
if (is24h && hour>23) {
return ERR_RANGE;
} else if (!is24h && hour>12) {
return ERR_RANGE;
}
data = 0;
if (!enable) {
data |= (1<<7); /* 1: disabled (default), 0: enabled */
}
if (is24h) {
data |= ((hour/10)<<4)|(hour%10); /* BCD encoded */
} else {
if (hour>12) { /* PM */
hour -= 12;
data |= (1<<5); /* set PM bit */
}
data |= (hour<<4)|(hour%10);
}
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_ALARM_HOUR, data);
}
uint8_t McuPCF85063A_ReadAlarmDay(uint8_t *day, bool *enabled) {
uint8_t res, data;
res = McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_ALARM_DAY, &data);
if (res != ERR_OK) {
return ERR_FAILED;
}
*enabled = (data&(1<<7))==0; /* 1: disabled (default), 0: enabled */
*day = ((data&0x70)>>4)*10 + (data&0x0F); /* BCD encoded */
return ERR_OK;
}
uint8_t McuPCF85063A_WriteAlarmDay(uint8_t day, bool enable) {
uint8_t data;
data = 0;
if (!enable) {
data |= (1<<7); /* 1: disabled (default), 0: enabled */
}
data |= ((day/10)<<4)|(day%10); /* BCD encoded */
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_ALARM_DAY, data);
}
uint8_t McuPCF85063A_ReadAlarmWeekDay(uint8_t *weekDay, bool *enabled) {
uint8_t res, data;
res = McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_ALARM_WEEKDAY, &data);
if (res != ERR_OK) {
return ERR_FAILED;
}
*enabled = (data&(1<<7))==0; /* 1: disabled (default), 0: enabled */
*weekDay = ((data&0x70)>>4)*10 + (data&0x0F); /* BCD encoded */
return ERR_OK;
}
uint8_t McuPCF85063A_WriteAlarmWeekDay(uint8_t weekDay, bool enable) {
uint8_t data;
if (weekDay>6) {
return ERR_RANGE;
}
data = 0;
if (!enable) {
data |= (1<<7); /* 1: disabled (default), 0: enabled */
}
data |= ((weekDay/10)<<4)|(weekDay%10); /* BCD encoded */
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_ALARM_WEEKDAY, data);
}
uint8_t McuPCF85063A_ReadTimeDate(McuPCF85063A_TTIME *time, McuPCF85063A_TDATE *date) {
uint8_t buf[McuPCF85063A_MEMORY_TIME_DATE_SIZE];
bool is24hMode;
if (McuPCF85063A_ReadBlock(McuPCF85063A_ADDRESS_TIME_DATE_START_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
is24hMode = McuPCF85063A_Is24hMode();
time->sec = (uint8_t)(((buf[0]&0x70)>>4)*10 + (buf[0]&0x0F)); /* seconds in BCD format */
time->min = (uint8_t)((buf[1]>>4)*10 + (buf[1]&0x0F)); /* minutes in BCD format */
if (is24hMode) {
time->hour = (uint8_t)(((buf[2]&0x30)>>4)*10 + (buf[2]&0x0F)); /* hour in BCD format */
time->mode = McuPCF85063A_TTIME_MODE_24H;
} else {
time->hour = (uint8_t)(((buf[2]&0x10)>>4)*10 + (buf[2]&0x0F)); /* hour in BCD format */
time->am_pm = (uint8_t)((buf[2]&(1<<5))>>5); /* bit 5: AM/PM indicator. 0: AM, 1: PM */
time->mode = McuPCF85063A_TTIME_MODE_12H;
}
date->day = (uint8_t)((buf[3]>>4)*10 + (buf[3]&0x0F)); /* BCD format */
date->dayOfWeek =(uint8_t)(buf[4]); /* 0: Sunday, 1: Monday, ... 6: Saturday */
date->month = (uint8_t)((buf[5]>>4)*10 + (buf[5]&0x0F)); /* 1: January */
date->year = (uint8_t)((buf[6]>>4)*10 + (buf[6]&0x0F));
return ERR_OK;
}
uint8_t McuPCF85063A_WriteTimeDate(McuPCF85063A_TTIME *time, McuPCF85063A_TDATE *date) {
uint8_t buf[McuPCF85063A_MEMORY_TIME_DATE_SIZE];
if ( ((time->mode==McuPCF85063A_TTIME_MODE_12H)&&((time->hour>12)||(time->hour==0)))
|| ((time->mode==McuPCF85063A_TTIME_MODE_24H)&&(time->hour>23))
|| (time->min>59)||(time->sec>59)
|| (date->year>99)||(date->month>12)||(date->month==0)
|| (date->day>31)||(date->day==0)
|| (date->dayOfWeek>6))
{
return ERR_RANGE;
}
buf[0] = (uint8_t)(((time->sec/10)<<4) | (time->sec%10));
buf[1] = (uint8_t)(((time->min/10)<<4) | (time->min%10));
buf[2] = (uint8_t)(((time->hour/10)<<4) | (time->hour%10));
if (time->mode==McuPCF85063A_TTIME_MODE_12H) {
buf[2] |= (time->am_pm)?(1<<5):0;
}
buf[3] = (uint8_t)(((date->day/10)<<4) | (date->day%10));
buf[4] = (uint8_t)(date->dayOfWeek);
buf[5] = (uint8_t)(((date->month/10)<<4) | (date->month%10));
buf[6] = (uint8_t)(((date->year/10)<<4) | (date->year%10));
if (McuPCF85063A_WriteBlock(McuPCF85063A_ADDRESS_TIME_DATE_START_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
uint8_t McuPCF85063A_WriteDate(McuPCF85063A_TDATE *date) {
uint8_t buf[McuPCF85063A_MEMORY_DATE_SIZE];
if ( (date->year>99)
|| (date->month>12)||(date->month==0)
|| (date->day>31)||(date->day==0)
|| (date->dayOfWeek>6)
)
{
return ERR_RANGE;
}
buf[0] = (uint8_t)(((date->day/10)<<4) | (date->day%10));
buf[1] = (uint8_t)(date->dayOfWeek);
buf[2] = (uint8_t)(((date->month/10)<<4) | (date->month%10));
buf[3] = (uint8_t)(((date->year/10)<<4) | (date->year%10));
if (McuPCF85063A_WriteBlock(McuPCF85063A_ADDRESS_DATE_START_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
uint8_t McuPCF85063A_WriteTime(McuPCF85063A_TTIME *time) {
uint8_t buf[McuPCF85063A_MEMORY_TIME_SIZE];
if ( ((time->mode==McuPCF85063A_TTIME_MODE_12H)&&((time->hour>12)||(time->hour==0)))
|| ((time->mode==McuPCF85063A_TTIME_MODE_24H)&&(time->hour>23))
|| (time->min>59) || (time->sec>59)
)
{
return ERR_RANGE;
}
buf[0] = (uint8_t)(((time->sec/10)<<4) | (time->sec%10));
buf[1] = (uint8_t)(((time->min/10)<<4) | (time->min%10));
buf[2] = (uint8_t)(((time->hour/10)<<4) | (time->hour%10));
if (time->mode==McuPCF85063A_TTIME_MODE_12H) {
buf[2] |= (time->am_pm)?(1<<5):0;
}
if (McuPCF85063A_WriteBlock(McuPCF85063A_ADDRESS_TIME_START_ADDR, buf, sizeof(buf))!=ERR_OK) {
return ERR_FAILED;
}
return ERR_OK;
}
uint8_t McuPCF85063A_GetTime(TIMEREC *time) {
McuPCF85063A_TTIME ttime;
McuPCF85063A_TDATE tdate;
if (McuPCF85063A_ReadTimeDate(&ttime, &tdate)!=ERR_OK) {
return ERR_FAILED;
}
time->Hour = ttime.hour;
time->Min = ttime.min;
time->Sec = ttime.sec;
time->Sec100 = 0;
return ERR_OK;
}
uint8_t McuPCF85063A_SetTimeInfo(uint8_t Hour, uint8_t Min, uint8_t Sec, uint8_t Sec100) {
McuPCF85063A_TTIME ttime;
ttime.hour = Hour;
ttime.min = Min;
ttime.sec = Sec;
(void)Sec100; /* ignored, as cannot be stored on device */
ttime.mode = McuPCF85063A_TTIME_MODE_24H;
ttime.am_pm = McuPCF85063A_TTIME_AMPM_AM;
return McuPCF85063A_WriteTime(&ttime);
}
uint8_t McuPCF85063A_SetTime(TIMEREC *time) {
return McuPCF85063A_SetTimeInfo(time->Hour, time->Min, time->Sec, time->Sec100);
}
uint8_t McuPCF85063A_GetDate(DATEREC *date) {
McuPCF85063A_TTIME ttime;
McuPCF85063A_TDATE tdate;
if (McuPCF85063A_ReadTimeDate(&ttime, &tdate)!=ERR_OK) {
return ERR_FAILED;
}
date->Year = (uint16_t)(tdate.year+2000); /* assume we are after the year 2000 */
date->Month = tdate.month;
date->Day = tdate.day;
return ERR_OK;
}
uint8_t McuPCF85063A_SetDateInfo(uint16_t Year, uint8_t Month, uint8_t Day) {
McuPCF85063A_TDATE tdate;
if (Year>=2000) {
tdate.year = (uint8_t)(Year-2000);
} else if (Year>=1900) {
tdate.year = (uint8_t)(Year-1900);
} else {
tdate.year = Year%100;
}
tdate.month = Month;
tdate.day = Day;
tdate.dayOfWeek = McuUtility_WeekDay(Year, Month, Day);
return McuPCF85063A_WriteDate(&tdate);
}
uint8_t McuPCF85063A_SetDate(DATEREC *date) {
return McuPCF85063A_SetDateInfo(date->Year, date->Month, date->Day);
}
uint8_t McuPCF85063A_GetTimeDate(TIMEREC *time, DATEREC *date) {
McuPCF85063A_TTIME ttime;
McuPCF85063A_TDATE tdate;
if (McuPCF85063A_ReadTimeDate(&ttime, &tdate)!=ERR_OK) {
return ERR_FAILED;
}
time->Hour = ttime.hour;
time->Min = ttime.min;
time->Sec = ttime.sec;
time->Sec100 = 0;
date->Year = (uint16_t)(tdate.year+2000);
date->Month = tdate.month;
date->Day = tdate.day;
return ERR_OK;
}
uint8_t McuPCF85063A_ReadRamByte(uint8_t *data) {
return McuPCF85063A_ReadByte(McuPCF85063A_ADDRESS_RAM_BYTE, data);
}
uint8_t McuPCF85063A_WriteRamByte(uint8_t data) {
return McuPCF85063A_WriteByte(McuPCF85063A_ADDRESS_RAM_BYTE, data);
}
static const char *GetWeekDayString(uint8_t weekday) {
static const char *const weekDays[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
if (weekday<=sizeof(weekDays)/sizeof(weekDays[0])) {
return weekDays[weekday];
} else {
return "error";
}
}
static uint8_t StrCatHWTimeDate(uint8_t *buf, size_t bufSize) {
McuPCF85063A_TDATE tdate;
McuPCF85063A_TTIME ttime;
if (McuPCF85063A_ReadTimeDate(&ttime, &tdate)!=ERR_OK) {
return ERR_FAILED;
}
if (tdate.dayOfWeek<=6) {
McuUtility_strcat(buf, bufSize, (unsigned char*)GetWeekDayString(tdate.dayOfWeek));
}
McuUtility_chcat(buf, bufSize, ' ');
McuUtility_strcatNum16uFormatted(buf, bufSize, tdate.day, '0', 2);
McuUtility_chcat(buf, bufSize, '.');
McuUtility_strcatNum16uFormatted(buf, bufSize, tdate.month, '0', 2);
McuUtility_chcat(buf, bufSize, '.');
McuUtility_strcatNum16u(buf, bufSize, (uint16_t)tdate.year);
McuUtility_strcat(buf, bufSize, (unsigned char*)", ");
McuUtility_strcatNum16sFormatted(buf, bufSize, ttime.hour, '0', 2);
McuUtility_chcat(buf, bufSize, ':');
McuUtility_strcatNum16sFormatted(buf, bufSize, ttime.min, '0', 2);
McuUtility_chcat(buf, bufSize, ':');
McuUtility_strcatNum16sFormatted(buf, bufSize, ttime.sec, '0', 2);
if (ttime.mode==McuPCF85063A_TTIME_MODE_24H) {
McuUtility_strcat(buf, bufSize, (unsigned char*)" (24h)");
} else {
if (ttime.am_pm==McuPCF85063A_TTIME_AMPM_AM) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"am");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"pm");
}
}
return ERR_OK;
}
static uint8_t StrCatHWAlarm(unsigned char *buf, size_t bufSize) {
uint8_t res, data;
bool enabled;
bool is24h, isAM;
McuUtility_strcat(buf, bufSize, (unsigned char*)"h:");
res = McuPCF85063A_ReadAlarmHour(&data, &enabled, &is24h, &isAM);
if (res==ERR_OK) {
McuUtility_strcatNum8u(buf, bufSize, data);
if (!is24h) {
if (isAM) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"AM");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"PM");
}
}
McuUtility_strcat(buf, bufSize, (unsigned char*)" (");
if (enabled) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"on); ");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"off); ");
}
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"ERR");
}
McuUtility_strcat(buf, bufSize, (unsigned char*)"m:");
res = McuPCF85063A_ReadAlarmMinute(&data, &enabled);
if (res==ERR_OK) {
McuUtility_strcatNum8u(buf, bufSize, data);
McuUtility_strcat(buf, bufSize, (unsigned char*)" (");
if (enabled) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"on); ");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"off); ");
}
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"ERR");
}
McuUtility_strcat(buf, bufSize, (unsigned char*)"s:");
res = McuPCF85063A_ReadAlarmSecond(&data, &enabled);
if (res==ERR_OK) {
McuUtility_strcatNum8u(buf, bufSize, data);
McuUtility_strcat(buf, bufSize, (unsigned char*)" (");
if (enabled) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"on); ");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"off); ");
}
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"ERR");
}
McuUtility_strcat(buf, bufSize, (unsigned char*)"w:");
res = McuPCF85063A_ReadAlarmWeekDay(&data, &enabled);
if (res==ERR_OK) {
McuUtility_strcatNum8u(buf, bufSize, data);
McuUtility_strcat(buf, bufSize, (unsigned char*)", ");
McuUtility_strcat(buf, bufSize, (unsigned char*)GetWeekDayString(data));
McuUtility_strcat(buf, bufSize, (unsigned char*)" (");
if (enabled) {
McuUtility_strcat(buf, bufSize, (unsigned char*)"on); ");
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"off); ");
}
} else {
McuUtility_strcat(buf, bufSize, (unsigned char*)"ERR");
}
return ERR_OK;
}
static uint8_t DateCmd(const unsigned char *cmd, McuShell_ConstStdIOType *io) {
uint8_t day, month;
uint16_t year;
uint8_t res = ERR_OK;
if (McuUtility_ScanDate(&cmd, &day, &month, &year) == ERR_OK) { /* ok, format fine */
/* update real time clock */
res = McuPCF85063A_SetDateInfo(year, month, day);
if (res!=ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failure setting RTC\r\n", io->stdErr);
res = ERR_FAILED;
}
} else {
McuShell_SendStr((unsigned char*)"*** Error while reading command! ***", io->stdErr);
McuShell_SendStr((void *)cmd, io->stdErr);
McuShell_SendStr((unsigned char*)"\r\n", io->stdErr);
res = ERR_FAILED;
}
return res;
}
static uint8_t TimeCmd(const unsigned char *cmd, McuShell_ConstStdIOType *io) {
uint8_t hour, minute, second, hSecond;
uint8_t res = ERR_OK;
if (McuUtility_ScanTime(&cmd, &hour, &minute, &second, &hSecond)==ERR_OK) { /* format fine */
/* set RTC time */
res = McuPCF85063A_SetTimeInfo(hour, minute, second, hSecond);
if (res != ERR_OK) {
McuShell_SendStr((unsigned char*)"*** Failure setting RTC time\r\n", io->stdErr);
res = ERR_FAILED;
}
} else {
McuShell_SendStr((unsigned char*)"*** Error while reading command: ", io->stdErr);
McuShell_SendStr(cmd, io->stdErr);
McuShell_SendStr((unsigned char*)"\r\n", io->stdErr);
res = ERR_FAILED;
}
return res;
}
static uint8_t CmdAlarmEnable(const unsigned char *p, bool enable) {
uint8_t val;
bool dummy;
bool is24h, isAM;
if (*p=='s') {
if (McuPCF85063A_ReadAlarmSecond(&val, &dummy)!=ERR_OK) {
return ERR_FAILED;
}
return McuPCF85063A_WriteAlarmSecond(val, enable);
} else if (*p=='m') {
if (McuPCF85063A_ReadAlarmMinute(&val, &dummy)!=ERR_OK) {
return ERR_FAILED;
}
return McuPCF85063A_WriteAlarmMinute(val, enable);
} else if (*p=='h') {
if (McuPCF85063A_ReadAlarmHour(&val, &dummy, &is24h, &isAM)!=ERR_OK) {
return ERR_FAILED;
}
return McuPCF85063A_WriteAlarmHour(val, enable, is24h, isAM);
} else if (*p=='w') {
if (McuPCF85063A_ReadAlarmWeekDay(&val, &dummy)!=ERR_OK) {
return ERR_FAILED;
}
return McuPCF85063A_WriteAlarmWeekDay(val, enable);
}
return ERR_FAILED;
}
static uint8_t PrintStatus(McuShell_ConstStdIOType *io) {
unsigned char buf[96];
uint8_t res, data;
McuShell_SendStatusStr((unsigned char*)"rtc", (const unsigned char*)"Status of PCF85063A RTC\r\n", io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuPCF85063A_I2C_DEVICE_ADDRESS);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" address", buf, io->stdOut);
res = McuPCF85063A_ReadControl1(&data);
if (res==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), data);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)": ");
if (data&(1<<7)) { /* EXT_TEST */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"7:test(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"7:normal(0), ");
}
if (data&(1<<5)) { /* STOP*/
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"5:RCTstopped(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"5:RTCruns(0), ");
}
if (data&(1<<3)) { /* CIE: correction interrupt enable */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"3:CIEoff(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"3:CIEon(0), ");
}
if (data&(1<<1)) { /* 12_24 */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"1:12h(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"1:24h(0), ");
}
if (data&(1<<0)) { /* CAP_SEL */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"0:12.5pF(1)");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"0:7pF(0)");
}
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((uint8_t*)" Control_1", (unsigned char*)buf, io->stdOut);
res = McuPCF85063A_ReadControl2(&data);
if (res==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), data);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)": ");
if (data&(1<<7)) { /* AIE */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"7:AIEon(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"7:AIEoff(0), ");
}
if (data&(1<<6)) { /* AF */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"6:AFon(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"6:AFoff(0), ");
}
if (data&(1<<5)) { /* MI */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"5:MIon(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"5:MIoff(0), ");
}
if (data&(1<<4)) { /* HMI */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"4:HMIon(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"4:HMIoff(0), ");
}
if (data&(1<<3)) { /* TF */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"3:TFon(1), ");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"3:TFoff(0), ");
}
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"2..0:COF(");
McuUtility_strcatNum8u(buf, sizeof(buf), data&0x0);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)")\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((uint8_t*)" Control_2", (unsigned char*)buf, io->stdOut);
res = McuPCF85063A_ReadOffset(&data);
if (res==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), data);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((uint8_t*)" Offset", (unsigned char*)buf, io->stdOut);
res = McuPCF85063A_ReadRamByte(&data);
if (res==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), data);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((uint8_t*)" RAM byte", (unsigned char*)buf, io->stdOut);
buf[0] = '\0';
if (StrCatHWAlarm(buf, sizeof(buf))) {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
}
McuShell_SendStatusStr((unsigned char*)" alarm", buf, io->stdOut);
buf[0] = '\0';
if (StrCatHWTimeDate(buf, sizeof(buf))!=ERR_OK) {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
} else {
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
}
McuShell_SendStatusStr((unsigned char*)" time/date", buf, io->stdOut);
return ERR_OK;
}
uint8_t McuPCF85063A_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
int32_t val;
const unsigned char *p;
bool enabled;
uint8_t dummy;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, "rtc help")==0) {
*handled = true;
McuShell_SendHelpStr((unsigned char*)"rtc", (const unsigned char*)"Group of PCF85063 RTC commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (const unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" reset", (const unsigned char*)"Send software reset command to device\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" write ram <val>", (const unsigned char*)"Write a byte value to the RAM\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" write ctrl1 <val>", (const unsigned char*)"Write a byte to the Control_1 (00h) register\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" write ctrl2 <val>", (const unsigned char*)"Write a byte to the Control_2 (01h) register\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" write offset <val>", (const unsigned char*)"Write a byte to the Offset (02h) register\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" time [hh:mm:ss[,z]]", (const unsigned char*)"Set the current time\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" date [dd.mm.yyyy]", (const unsigned char*)"Set the current date\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" alarm s|m|h|w <v>", (const unsigned char*)"Set alarm value for second, minute, hour or weekday\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" alarm on|off s|m|h|w", (const unsigned char*)"Enable alarm for second, minute, hour or weekday\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" alarm AIE on|off", (const unsigned char*)"Enable alarm interrupt for second, minute or hour\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" alarm reset AF", (const unsigned char*)"Reset alarm interrupt flag\r\n", io->stdOut);
return ERR_OK;
} else if ((McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0) || (McuUtility_strcmp((char*)cmd, "rtc status")==0)) {
*handled = true;
return PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, "rtc write ram ", sizeof("rtc write ram ")-1)==0) {
*handled = true;
p = cmd + sizeof("rtc write ram ")-1;
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=0xff) {
return McuPCF85063A_WriteRamByte(val);
}
} else if (McuUtility_strncmp((char*)cmd, "rtc write ctrl1 ", sizeof("rtc write ctrl1 ")-1)==0) {
*handled = true;
p = cmd + sizeof("rtc write ctrl1 ")-1;
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=0xff) {
return McuPCF85063A_WriteControl1(val);
}
} else if (McuUtility_strncmp((char*)cmd, "rtc write ctrl2 ", sizeof("rtc write ctrl2 ")-1)==0) {
*handled = true;
p = cmd + sizeof("rtc write ctrl2 ")-1;
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=0xff) {
return McuPCF85063A_WriteControl2(val);
}
} else if (McuUtility_strncmp((char*)cmd, "rtc write offset ", sizeof("rtc write offset ")-1)==0) {
*handled = true;
p = cmd + sizeof("rtc write offset ")-1;
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=0xff) {
return McuPCF85063A_WriteOffset(val);
}
} else if (McuUtility_strncmp((char*)cmd, "rtc date ", sizeof("rtc date ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("rtc date ")-1;
return DateCmd(p, io);
} else if (McuUtility_strncmp((char*)cmd, "rtc time ", sizeof("rtc time ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("rtc time ")-1;
return TimeCmd(p, io);
} else if (McuUtility_strncmp((char*)cmd, "rtc alarm s ", sizeof("rtc alarm s ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("rtc alarm s ")-1;
if (McuPCF85063A_ReadAlarmSecond(&dummy, &enabled)!=ERR_OK) { /* get enabled state */
return ERR_FAILED;
}
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=59) {
return McuPCF85063A_WriteAlarmSecond(val, enabled);
}
return ERR_FAILED;
} else if (McuUtility_strncmp((char*)cmd, "rtc alarm m ", sizeof("rtc alarm m ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("rtc alarm m")-1;
if (McuPCF85063A_ReadAlarmMinute(&dummy, &enabled)!=ERR_OK) { /* get enabled state */
return ERR_FAILED;
}
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=59) {
return McuPCF85063A_WriteAlarmMinute(val, enabled);
}
return ERR_FAILED;
} else if (McuUtility_strncmp((char*)cmd, "rtc alarm h ", sizeof("rtc alarm h ")-1)==0) {
bool is24h, isAM;
*handled = TRUE;
p = cmd + sizeof("rtc alarm h")-1;
if (McuPCF85063A_ReadAlarmHour(&dummy, &enabled, &is24h, &isAM)!=ERR_OK) { /* get enabled state */
return ERR_FAILED;
}
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=23) {
return McuPCF85063A_WriteAlarmHour(val, enabled, true, false); /* only supporting 24h format */
}
return ERR_FAILED;
} else if (McuUtility_strncmp((char*)cmd, "rtc alarm w ", sizeof("rtc alarm w ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("rtc alarm w")-1;
if (McuPCF85063A_ReadAlarmWeekDay(&dummy, &enabled)!=ERR_OK) { /* get enabled state */
return ERR_FAILED;
}
if (McuUtility_xatoi(&p, &val)==ERR_OK && val>=0 && val<=6) {
return McuPCF85063A_WriteAlarmWeekDay(val, enabled);
}
return ERR_FAILED;
} else if (McuUtility_strcmp((char*)cmd, "rtc reset")==0) {
*handled = true;
return McuPCF85063A_WriteSoftwareReset();
} else if (McuUtility_strcmp((char*)cmd, "rtc alarm AIE on")==0) {
*handled = true;
return McuPCF85063A_WriteAlarmInterrupt(true);
} else if (McuUtility_strcmp((char*)cmd, "rtc alarm AIE off")==0) {
*handled = true;
return McuPCF85063A_WriteAlarmInterrupt(false);
} else if (McuUtility_strcmp((char*)cmd, "rtc alarm reset AF")==0) {
*handled = true;
return McuPCF85063A_WriteResetAlarmInterrupt();
} else if (McuUtility_strncmp((char*)cmd, "rtc alarm on ", sizeof("rtc alarm on ")-1)==0) {
*handled = true;
return CmdAlarmEnable(cmd+sizeof("rtc alarm on ")-1, true);
} else if (McuUtility_strncmp((char*)cmd, "rtc alarm off ", sizeof("rtc alarm off ")-1)==0) {
*handled = true;
return CmdAlarmEnable(cmd+sizeof("rtc alarm off ")-1, false);
}
return ERR_OK;
}
void McuPCF85063A_Init(void) {
}

View File

@@ -0,0 +1,221 @@
/*
* Copyright (c) 2023-2024, Erich Styger
*
* Driver for the NXP PCF85063A I2C RTC.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MCUPCF85063A_H_
#define MCUPCF85063A_H_
#include "McuPCF85063A_config.h"
#include "McuShell.h"
#include "McuTimeDate.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Shell command line parser.
* \param cmd Shell command string
* \param handled Set to true if command was handled, untouched otherwise
* \param io Standard I/O handler to be used
* \return Error code, ERR_OK if no failure
*/
uint8_t McuPCF85063A_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*!
* \brief Get the RTC time.
* \param time Pointer store the time information
* \return Error code, ERR_OK if no failure
*/
uint8_t McuPCF85063A_GetTime(TIMEREC *time);
/*!
* \brief Get the RTC date.
* \param date Pointer to store the date information
* \return Error code, ERR_OK if no failure
*/
uint8_t McuPCF85063A_GetDate(DATEREC *date);
/*!
* \brief Set the RTC time.
* \param time Pointer to time information
* \return Error code, ERR_OK if no failure
*/
uint8_t McuPCF85063A_SetTime(TIMEREC *time);
/*!
* \brief Set the RTC date.
* \param date Pointer to date information
* \return Error code, ERR_OK if no failure
*/
uint8_t McuPCF85063A_SetDate(DATEREC *date);
/*!
* \brief Get the current time and date from the RTC
* \param time Pointer where to store the time
* \param date Pointer where to store the date
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_GetTimeDate(TIMEREC *time, DATEREC *date);
/*!
* \brief Set the RTC time information
* \param Hour The hour, in the range of 0-23
* \param Min The minute, in the range of 0-59
* \param Sec The second, in the range of 0-59
* \praam Sec100 The 0.01 sec part, in the range of 0-99
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_SetTimeInfo(uint8_t Hour, uint8_t Min, uint8_t Sec, uint8_t Sec100);
/*!
* \brief set the RTC date information
* \param Year The year, for example 2024
* \param Month The month, for example 11
* \param Day The day of the month, in the range of 0-31, depending of the month
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_SetDateInfo(uint16_t Year, uint8_t Month, uint8_t Day);
/*! \brief different RTC clock output frequencies */
typedef enum McuPCF85063A_COF_Frequency_e {
McuPCF85063A_COF_FREQ_32768 = 0,
McuPCF85063A_COF_FREQ_16384 = 1,
McuPCF85063A_COF_FREQ_8192 = 2,
McuPCF85063A_COF_FREQ_4096 = 3,
McuPCF85063A_COF_FREQ_2048 = 4,
McuPCF85063A_COF_FREQ_1024 = 5,
McuPCF85063A_COF_FREQ_1 = 6,
McuPCF85063A_COF_FREQ_OFF = 7
} McuPCF85063A_COF_Frequency_e;
/*!
* \brief Configure a new clock output frequency
* \param Frequency Frequency to use
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteClockOutputFrequency(McuPCF85063A_COF_Frequency_e frequency);
/*!
* \brief Read the alarm second time value
* \param second Pointer to store the value
* \param enabled Returns if the alarm is enabled or not.
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_ReadAlarmSecond(uint8_t *second, bool *enabled);
/*!
* \brief Write the Alarm second time value
* \param second Second time alarm value
* \param enabled true to enable the alarm, false otherwise
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteAlarmSecond(uint8_t second, bool enable);
/*!
* \brief Read the alarm minute value
* \param minute Where to store the minute value
* \param enabled Returns if the alarm is enabled or not.
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_ReadAlarmMinute(uint8_t *minute, bool *enabled);
/*!
* \brief Write the alarm minute value
* \param minute Minute value to write
* \param enable If the alarm has to be enabled or not
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteAlarmMinute(uint8_t minute, bool enable);
/*!
* \brief Read the alarm hour value
* \param hour Where to store the alarm hour value
* \param enabled Returns if the alarm is enabled or not.
* \param is24h Returns true if the hour format is 24 hours, false otherwise
* \param isAM Returns true if the hour is an AM value, false otherwise
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_ReadAlarmHour(uint8_t *hour, bool *enabled, bool *is24h, bool *isAM);
/*!
* \brief Write the alarm hour value
* \param hour Hour value
* \param enable If the alarm has to be enabled or not
* \param is24h true if hour value is for 24h format, false otherwise
* \param isAM true if hour value is AM, false otherwise
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteAlarmHour(uint8_t hour, bool enable, bool is24h, bool isAM);
/*!
* \brief Read the alarm day
* \param day Used to store the alarm day value
* \param enabled Returns if the alarm is enabled or not.
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_ReadAlarmDay(uint8_t *day, bool *enabled);
/*!
* \brief Write the alarm day value
* \param day Day value for the alarm
* \param enable If the alarm has to be enabled or not
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteAlarmDay(uint8_t day, bool enable);
/*!
* \brief Read the alarm week day
* \param weekDay Used to store the day
* \param enabled Returns if the alarm is enabled or not.
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_ReadAlarmWeekDay(uint8_t *weekDay, bool *enabled);
/*!
* \brief Write the alarm week day
* \param weekDay The day of week (0-6)
* \param enable If alarm is enabled
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteAlarmWeekDay(uint8_t weekDay, bool enable);
/*!
* \brief Perform a software reset
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteSoftwareReset(void);
/*!
* \brief Write the alarm interrupt flag setting
* \param enable Use true to enable it, false otherwise
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteAlarmInterrupt(bool enable);
/*!
* \brief Reset the alarm interrupt flag
* \return Error code, ERR_OK if no failure.
*/
uint8_t McuPCF85063A_WriteResetAlarmInterrupt(void);
/*!
* \brief Driver de-initialization.
*/
void McuPCF85063A_Deinit(void);
/*!
* \brief Driver initialization.
*/
void McuPCF85063A_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MCUPCF85063A_H_ */

View File

@@ -0,0 +1,186 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuPidFloat.h
** CDE edition : Community
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : PID_Float
** Version : Component 01.007, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
** Settings :
** Contents :
** Control - void McuPidFloat_Control(float error, void* *u);
** Reset - void McuPidFloat_Reset(void);
** Set_K - void McuPidFloat_Set_K(float k);
** Set_Ti - void McuPidFloat_Set_Ti(float t);
** Set_Td - void McuPidFloat_Set_Td(float t);
**
** * (c) Copyright Carlos Alvarez, 2013-2020
** * For non-commercial use only.
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** ###################################################################*/
/*!
** @file McuPidFloat.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuPidFloat_module McuPidFloat module documentation
** @{
*/
/* MODULE McuPidFloat. */
#include "McuPidFloat.h"
#define K_VAL 0.1 /* Constante proporcional */
#define TI_VAL 100 /* Tiempo integrativo */
#define TD_VAL 0 /* Tiempo derivativo */
#define T_VAL 0.01 /* Per<65>odo de control */
#define U_MIN 0 /* Valor de salida m<>nimo */
#define U_MAX 65000 /* Valor de salida m<>ximo */
#define U_CHG_MAX 0 /* Cambio m<>ximo en cada ciclo de control */
/* Coeficientes del control PID */
#define K1 (McuPidFloat_K*(1+(McuPidFloat_Td/T_VAL)))
#define K2 (-McuPidFloat_K*(1+((2*McuPidFloat_Td)/T_VAL)-(T_VAL/McuPidFloat_Ti)))
#define K3 (McuPidFloat_K*(McuPidFloat_Td/T_VAL))
/* Variable para la constante proporcional */
static float McuPidFloat_K = K_VAL;
/* Variable para el tiempo integrativo */
static float McuPidFloat_Ti = TI_VAL;
/* Variable para el tiempo derivativo */
static float McuPidFloat_Td = TD_VAL;
/* Variable que almacena los errores */
float McuPidFloat_error[2] = {0.0, 0.0};
/*
** ===================================================================
** Method : Set_Td (component PID_Float)
**
** Description :
** Change the Td parameter.
** Parameters :
** NAME - DESCRIPTION
** t - New Td value.
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Set_Td(float t)
{
if(t < 0) {
return;
}
McuPidFloat_Td = t;
}
/*
** ===================================================================
** Method : Set_Ti (component PID_Float)
**
** Description :
** Change the Ti parameter.
** Parameters :
** NAME - DESCRIPTION
** t - New Ti value.
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Set_Ti(float t)
{
if (t <= 0) {
return;
}
McuPidFloat_Ti = t;
}
/*
** ===================================================================
** Method : Set_K (component PID_Float)
**
** Description :
** Change the K parameter.
** Parameters :
** NAME - DESCRIPTION
** k - New K value.
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Set_K(float k)
{
if(k < 0) {
return;
}
McuPidFloat_K = k;
}
/*
** ===================================================================
** Method : Reset (component PID_Float)
**
** Description :
** Reset the PID.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Reset(void)
{
McuPidFloat_error[0] = 0.0;
McuPidFloat_error[1] = 0.0;
}
/*
** ===================================================================
** Method : Control (component PID_Float)
**
** Description :
** Control function. Must be called every T time.
** Parameters :
** NAME - DESCRIPTION
** error - Error signal. (Reference -
** SystemOutput).
** * u - Pointer to the control variable.
** Returns : Nothing
** ===================================================================
*/
#ifdef __HIWARE__
#pragma MESSAGE DISABLE C5900
#pragma MESSAGE DISABLE C5917
#endif
void McuPidFloat_Control(float error, uint16_t *u)
{
float ut = 0.0;
ut = (float) *u;
ut += K1 * error;
ut += K2 * McuPidFloat_error[0];
ut += K3 * McuPidFloat_error[1];
McuPidFloat_error[1] = McuPidFloat_error[0];
McuPidFloat_error[0] = error;
if (ut > U_MAX) {
*u = (uint16_t) U_MAX;
} else if (ut < U_MIN) {
*u = (uint16_t) U_MIN;
} else {
*u = (uint16_t) ut;
}
}
#ifdef __HIWARE__
#pragma MESSAGE DISABLE C5919
#endif
/* END McuPidFloat. */
/*!
** @}
*/

View File

@@ -0,0 +1,128 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuPidFloat.h
** CDE edition : Community
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : PID_Float
** Version : Component 01.007, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
** Settings :
** Contents :
** Control - void McuPidFloat_Control(float error, void* *u);
** Reset - void McuPidFloat_Reset(void);
** Set_K - void McuPidFloat_Set_K(float k);
** Set_Ti - void McuPidFloat_Set_Ti(float t);
** Set_Td - void McuPidFloat_Set_Td(float t);
**
** * (c) Copyright Carlos Alvarez, 2013-2020
** * For non-commercial use only.
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** ###################################################################*/
/*!
** @file McuPidFloat.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuPidFloat_module McuPidFloat module documentation
** @{
*/
#ifndef __McuPidFloat_H
#define __McuPidFloat_H
/* MODULE McuPidFloat. */
#include "McuLib.h" /* SDK and API used */
#include "McuPidFloatconfig.h" /* configuration */
/* Include inherited components */
#include "McuLib.h"
void McuPidFloat_Set_Td(float t);
/*
** ===================================================================
** Method : Set_Td (component PID_Float)
**
** Description :
** Change the Td parameter.
** Parameters :
** NAME - DESCRIPTION
** t - New Td value.
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Set_Ti(float t);
/*
** ===================================================================
** Method : Set_Ti (component PID_Float)
**
** Description :
** Change the Ti parameter.
** Parameters :
** NAME - DESCRIPTION
** t - New Ti value.
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Set_K(float k);
/*
** ===================================================================
** Method : Set_K (component PID_Float)
**
** Description :
** Change the K parameter.
** Parameters :
** NAME - DESCRIPTION
** k - New K value.
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Reset(void);
/*
** ===================================================================
** Method : Reset (component PID_Float)
**
** Description :
** Reset the PID.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuPidFloat_Control(float error, uint16_t *u);
/*
** ===================================================================
** Method : Control (component PID_Float)
**
** Description :
** Control function. Must be called every T time.
** Parameters :
** NAME - DESCRIPTION
** error - Error signal. (Reference -
** SystemOutput).
** * u - Pointer to the control variable.
** Returns : Nothing
** ===================================================================
*/
/* END McuPidFloat. */
#endif
/* ifndef __McuPidFloat_H */
/*!
** @}
*/

View File

@@ -0,0 +1,184 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuPidInt.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : PID_Int
** Version : Component 01.010, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
** Settings :
** Component name : McuPidInt
** Variable for controller set point : no
** P - Proportional : Enabled
** constant : yes
** Kp Factor : 1
** Kp Divisor : 8
** I - Integral : Enabled
** constant : yes
** Ki Factor : 1
** Ki Divisor : 512
** Anti Wind-Up : Enabled
** constant : yes
** Value : 1024
** D - Differential : Enabled
** constant : yes
** Kd Factor : 4
** Kd Divisor : 1
** Hardware : Disabled
** System :
** SDK : McuLib
** Contents :
** PID - int32_t McuPidInt_PID(int32_t setPoint, int32_t currValue);
** Control - void McuPidInt_Control(void);
** SetPoint - void McuPidInt_SetPoint(int32_t value);
** GetPoint - int32_t McuPidInt_GetPoint(void);
**
** * Copyright (c) 2012-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuPidInt.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuPidInt_module McuPidInt module documentation
** @{
*/
/* MODULE McuPidInt. */
#include "McuPidInt.h"
static int McuPidInt_setPoint; /* the value to be reached by the PID algorithm */
static const int32_t McuPidInt_KpMul = 1, McuPidInt_KpDiv = 8; /* the Kp adjustment values */
static const int32_t McuPidInt_KiMul = 1, McuPidInt_KiDiv = 512; /* the Ki adjustment values */
static const int32_t McuPidInt_KdMul = 4, McuPidInt_KdDiv = 1; /* the Kd adjustment values */
/*
** ===================================================================
** Method : PID (component PID_Int)
**
** Description :
** Performs PID calculation
** Parameters :
** NAME - DESCRIPTION
** setPoint - current setpoint (desired value)
** currValue - current sensor value
** Returns :
** --- - output of PID calculation
** ===================================================================
*/
#ifdef __HIWARE__
#pragma MESSAGE DISABLE C5904 /* Division by one */
#pragma MESSAGE DISABLE C5905 /* Multiplication with one */
#endif
int32_t McuPidInt_PID(int32_t setPoint, int32_t currValue)
{
/* Performs a PID calculation */
int32_t regDifferential; /* temporary variable for the D part */
static int32_t oldDiff = 0; /*!< Remember error for next round (for D part) */
static int32_t regIntegral = 0; /*!< Remember integral part for next iteration */
int32_t diff; /* actual error */
int32_t pid; /* pid calculation value */
pid = 0; /* initialize */
diff = setPoint-currValue;
/* P-Part */
pid += (McuPidInt_KpMul*diff)/McuPidInt_KpDiv;
/* I-Part */
regIntegral += diff; /* integrate error */
if (regIntegral > 1024) { /* anti wind-up */
regIntegral = 1024;
} else if (regIntegral < -1024) {
regIntegral = -1024;
}
pid += (McuPidInt_KiMul*regIntegral)/McuPidInt_KiDiv;
/* D-Part */
regDifferential = diff-oldDiff;
oldDiff = diff; /* remember for next iteration */
pid += (McuPidInt_KdMul*regDifferential)/McuPidInt_KdDiv; /* add D part */
return pid;
}
/*
** ===================================================================
** Method : Control (component PID_Int)
**
** Description :
** Performs the PID control calculation.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuPidInt_Control(void)
{
return; /* hardware for sensor and actuator not enabled: enable them in the properties or use the PID() function instead */
}
/*
** ===================================================================
** Method : SetPoint (component PID_Int)
**
** Description :
** Specifies the value to be reached by the PID controller.
** Parameters :
** NAME - DESCRIPTION
** value - The value to be reached.
** Returns : Nothing
** ===================================================================
*/
void McuPidInt_SetPoint(int32_t value)
{
McuPidInt_setPoint = value;
}
/*
** ===================================================================
** Method : GetPoint (component PID_Int)
**
** Description :
** Returns the current set point value
** Parameters : None
** Returns :
** --- - The current set point
** ===================================================================
*/
int32_t McuPidInt_GetPoint(void)
{
return McuPidInt_setPoint;
}
/* END McuPidInt. */
/*!
** @}
*/

View File

@@ -0,0 +1,151 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuPidInt.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : PID_Int
** Version : Component 01.010, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
** Settings :
** Component name : McuPidInt
** Variable for controller set point : no
** P - Proportional : Enabled
** constant : yes
** Kp Factor : 1
** Kp Divisor : 8
** I - Integral : Enabled
** constant : yes
** Ki Factor : 1
** Ki Divisor : 512
** Anti Wind-Up : Enabled
** constant : yes
** Value : 1024
** D - Differential : Enabled
** constant : yes
** Kd Factor : 4
** Kd Divisor : 1
** Hardware : Disabled
** System :
** SDK : McuLib
** Contents :
** PID - int32_t McuPidInt_PID(int32_t setPoint, int32_t currValue);
** Control - void McuPidInt_Control(void);
** SetPoint - void McuPidInt_SetPoint(int32_t value);
** GetPoint - int32_t McuPidInt_GetPoint(void);
**
** * Copyright (c) 2012-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuPidInt.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuPidInt_module McuPidInt module documentation
** @{
*/
#ifndef __McuPidInt_H
#define __McuPidInt_H
/* MODULE McuPidInt. */
#include "McuLib.h" /* SDK and API used */
#include "McuPidIntconfig.h" /* configuration */
/* Include inherited components */
#include "McuLib.h"
void McuPidInt_Control(void);
/*
** ===================================================================
** Method : Control (component PID_Int)
**
** Description :
** Performs the PID control calculation.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuPidInt_SetPoint(int32_t value);
/*
** ===================================================================
** Method : SetPoint (component PID_Int)
**
** Description :
** Specifies the value to be reached by the PID controller.
** Parameters :
** NAME - DESCRIPTION
** value - The value to be reached.
** Returns : Nothing
** ===================================================================
*/
int32_t McuPidInt_GetPoint(void);
/*
** ===================================================================
** Method : GetPoint (component PID_Int)
**
** Description :
** Returns the current set point value
** Parameters : None
** Returns :
** --- - The current set point
** ===================================================================
*/
int32_t McuPidInt_PID(int32_t setPoint, int32_t currValue);
/*
** ===================================================================
** Method : PID (component PID_Int)
**
** Description :
** Performs PID calculation
** Parameters :
** NAME - DESCRIPTION
** setPoint - current setpoint (desired value)
** currValue - current sensor value
** Returns :
** --- - output of PID calculation
** ===================================================================
*/
/* END McuPidInt. */
#endif
/* ifndef __McuPidInt_H */
/*!
** @}
*/

View File

@@ -0,0 +1,487 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuQuadCounter.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : QuadCounter
** Version : Component 01.034, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-12-02, 11:59, # CodeGen: 723
** Abstract :
**
This driver implements a quadrature encoder using two signals (C1 and C2) to generate position information.
** Settings :
** Component name : McuQuadCounter
** C1 and C2 swapped : no
** Counter Type : 32bit
** Method :
** Sampling : Enabled
** Error Correction : no
** C1 : SDK_BitIO
** C2 : SDK_BitIO
** Input Capture : Disabled
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** GetPos - McuQuadCounter_QuadCntrType McuQuadCounter_GetPos(void);
** SetPos - void McuQuadCounter_SetPos(McuQuadCounter_QuadCntrType pos);
** GetVal - uint8_t McuQuadCounter_GetVal(void);
** Sample - void McuQuadCounter_Sample(void);
** NofErrors - uint16_t McuQuadCounter_NofErrors(void);
** SwapPins - uint8_t McuQuadCounter_SwapPins(bool swap);
** Deinit - void McuQuadCounter_Deinit(void);
** Init - void McuQuadCounter_Init(void);
** ParseCommand - uint8_t McuQuadCounter_ParseCommand(const unsigned char *cmd, bool *handled,...
**
** * Copyright (c) 2014-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuQuadCounter.h
** @version 01.00
** @brief
**
This driver implements a quadrature encoder using two signals (C1 and C2) to generate position information.
*/
/*!
** @addtogroup McuQuadCounter_module McuQuadCounter module documentation
** @{
*/
/* MODULE McuQuadCounter. */
#include "McuQuadCounter.h"
#if McuQuadCounter_SWAP_PINS_AT_RUNTIME
static bool McuQuadCounter_swappedPins = FALSE;
#endif
/* The decoder has 4 different states, together with the previous state the table has 16 entries.
The value in the table (0,1,-1) indicates the steps taken since previous sample. */
#define QUAD_ERROR 3 /*!< Value to indicate an error in impulse detection. Has to be different from 0,1,-1 */
#if McuQuadCounter_CONFIG_USE_ERROR_CORRECTION
static uint8_t McuQuadCounter_prevlast_quadrature_value; /*! Value of C1&C2 before last_quadrature_value. */
static const signed char McuQuadCounter_Quad_Table[4][4][4] =
{ /* pprev prev new */
{ /* c12 c12 c12, c1 leading is backward, c2 leading is forward */
{
0, /* 00 00 00 no change or missed a step? */
1, /* 00 00 01 */
-1, /* 00 00 10 */
QUAD_ERROR, /* 00 00 11 error, lost impulse */
},
{
-1, /* 00 01 00 */
0, /* 00 01 01 */
2, /* 00 01 10 lost impulse, correct error */
1, /* 00 01 11 */
},
{
1, /* 00 10 00 */
-2, /* 00 10 01 lost impulse, correct error */
0, /* 00 10 10 */
-1, /* 00 10 11 */
},
{
QUAD_ERROR, /* 00 11 00 error */
-1, /* 00 11 01 lost impulse, correct error */
1, /* 00 11 10 */
0, /* 00 11 11 */
}
},
{ /* c12 c12 c12 */
{
0, /* 01 00 00 */
1, /* 01 00 01 */
-1, /* 01 00 10 */
-2, /* 01 00 11 lost impulse, correct error */
},
{
-1, /* 01 01 00 */
0, /* 01 01 01 */
QUAD_ERROR, /* 01 01 10 error */
1, /* 01 01 11 */
},
{
1, /* 01 10 00 */
QUAD_ERROR, /* 01 10 01 error */
0, /* 01 10 10 */
-1, /* 01 10 11 */
},
{
2, /* 01 11 00 lost impulse, correct error */
-1, /* 01 11 01 */
1, /* 01 11 10 */
0, /* 01 11 11 */
}
},
{ /* c12 c12 c12 */
{
0, /* 10 00 00 */
1, /* 10 00 01 */
-1, /* 10 00 10 */
2, /* 10 00 11 lost impulse, correct error */
},
{
-1, /* 10 01 00 */
0, /* 10 01 01 */
QUAD_ERROR, /* 10 01 10 error */
1, /* 10 01 11 */
},
{
1, /* 10 10 00 */
QUAD_ERROR, /* 10 10 01 error */
0, /* 10 10 10 */
-1, /* 10 10 11 */
},
{
-2, /* 10 11 00 lost impulse, correct error */
-1, /* 10 11 01 */
1, /* 10 11 10 */
0, /* 10 11 11 */
}
},
{ /* c12 c12 c12 */
{
0, /* 11 00 00 */
1, /* 11 00 01 */
-1, /* 11 00 10 */
QUAD_ERROR, /* 11 00 11 error */
},
{
-1, /* 11 01 00 */
0, /* 11 01 01 */
-2, /* 11 01 10 lost impulse, correct error */
1, /* 11 01 11 */
},
{
1, /* 11 10 00 */
2, /* 11 10 01 lost impulse, correct error */
0, /* 11 10 10 */
-1, /* 11 10 11 */
},
{
QUAD_ERROR, /* 11 11 00 error */
-1, /* 11 11 01 */
1, /* 11 11 10 */
0, /* 11 11 11 */
}
}
};
#else
static const signed char McuQuadCounter_Quad_Table[4][4] =
{ /* prev new */
{ /* c1 c2 c1 c2 */
0, /* 0 0 0 0 no change or missed a step? */
1, /* 0 0 0 1 */
-1, /* 0 0 1 0 */
QUAD_ERROR /* 0 0 1 1 error, lost impulse */
},
{ /* c1 c2 c1 c2 */
-1, /* 0 1 0 0 */
0, /* 0 1 0 1 no change or missed a step? */
QUAD_ERROR, /* 0 1 1 0 error, lost impulse */
1 /* 0 1 1 1 */
},
{ /* c1 c2 c1 c2 */
1, /* 1 0 0 0 */
QUAD_ERROR, /* 1 0 0 1 error, lost impulse */
0, /* 1 0 1 0 no change or missed a step? */
-1 /* 1 0 1 1 */
},
{ /* c1 c2 c1 c2 */
QUAD_ERROR, /* 1 1 0 0 error, lost impulse */
-1, /* 1 1 0 1 */
1, /* 1 1 1 0 */
0 /* 1 1 1 1 no change or missed a step? */
}
};
#endif /* McuQuadCounter_CONFIG_USE_ERROR_CORRECTION */
static uint8_t McuQuadCounter_last_quadrature_value; /*! Value of C1&C2 during last round. */
static McuQuadCounter_QuadCntrType McuQuadCounter_currPos = 0; /*!< Current position */
#if McuQuadCounter_CONFIG_COUNT_ERRORS
static uint16_t McuQuadCounter_nofErrors = 0;
#endif
/*
** ===================================================================
** Method : SetPos (component QuadCounter)
**
** Description :
** Sets the position information. Can be used as well to reset
** the position information.
** Parameters :
** NAME - DESCRIPTION
** pos - Position value to be set.
** Returns : Nothing
** ===================================================================
*/
void McuQuadCounter_SetPos(McuQuadCounter_QuadCntrType pos)
{
McuQuadCounter_currPos = pos;
}
/*
** ===================================================================
** Method : GetPos (component QuadCounter)
**
** Description :
** Returns the current position based on the encoder tracking.
** Parameters : None
** Returns :
** --- - position
** ===================================================================
*/
McuQuadCounter_QuadCntrType McuQuadCounter_GetPos(void)
{
return McuQuadCounter_currPos;
}
/*
** ===================================================================
** Method : GetVal (component QuadCounter)
**
** Description :
** Returns the quadrature value (0, 1, 2 or 3)
** Parameters : None
** Returns :
** --- - Quadrature value (0-3)
** ===================================================================
*/
uint8_t McuQuadCounter_GetVal(void)
{
#if McuQuadCounter_SWAP_PINS_AT_RUNTIME
if (McuQuadCounter_swappedPins) {
return McuQuadCounter_GET_C1_C2_PINS_SWAPPED();
} else {
return McuQuadCounter_GET_C1_C2_PINS();
}
#else
return McuQuadCounter_GET_C1_C2_PINS();
#endif
}
/*
** ===================================================================
** Method : Sample (component QuadCounter)
**
** Description :
** Call this method to periodically sample the signals.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuQuadCounter_Sample(void)
{
signed char new_step;
uint8_t c12; /* value of the two sensor input */
c12 = McuQuadCounter_GetVal();
#if McuQuadCounter_CONFIG_USE_ERROR_CORRECTION
new_step = McuQuadCounter_Quad_Table[McuQuadCounter_prevlast_quadrature_value][McuQuadCounter_last_quadrature_value][c12];
McuQuadCounter_prevlast_quadrature_value = McuQuadCounter_last_quadrature_value;
#else
new_step = McuQuadCounter_Quad_Table[McuQuadCounter_last_quadrature_value][c12];
#endif
McuQuadCounter_last_quadrature_value = c12;
if (new_step == QUAD_ERROR) {
#if McuQuadCounter_CONFIG_COUNT_ERRORS
McuQuadCounter_nofErrors++;
#endif
} else if (new_step != 0) {
McuQuadCounter_currPos += new_step;
}
}
/*
** ===================================================================
** Method : NofErrors (component QuadCounter)
**
** Description :
** Returns the number of decoding errors
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint16_t McuQuadCounter_NofErrors(void)
{
#if McuQuadCounter_CONFIG_COUNT_ERRORS
return McuQuadCounter_nofErrors;
#else
return 0;
#endif
}
/*
** ===================================================================
** Method : Deinit (component QuadCounter)
**
** Description :
** Module de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuQuadCounter_Deinit(void)
{
/* nothing needed */
}
/*
** ===================================================================
** Method : Init (component QuadCounter)
**
** Description :
** Module initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuQuadCounter_Init(void)
{
McuQuadCounter_currPos = 0;
McuQuadCounter_last_quadrature_value = McuQuadCounter_GET_C1_C2_PINS();
#if McuQuadCounter_CONFIG_USE_ERROR_CORRECTION
McuQuadCounter_prevlast_quadrature_value = McuQuadCounter_last_quadrature_value;
#endif
#if McuQuadCounter_CONFIG_COUNT_ERRORS
McuQuadCounter_nofErrors = 0;
#endif
#if McuQuadCounter_SWAP_PINS_AT_RUNTIME
McuQuadCounter_swappedPins = FALSE;
#endif
}
/*
** ===================================================================
** Method : ParseCommand (component QuadCounter)
**
** Description :
** Handler to process shell commands
** Parameters :
** NAME - DESCRIPTION
** cmd - Command string to be parsed
** * handled - Pointer to boolean. The handler
** sets this variable to TRUE if command was
** handled, otherwise let it untouched.
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
/*!
* \brief Parses a command
* \param cmd Command string to be parsed
* \param handled Sets this variable to TRUE if command was handled
* \param io I/O stream to be used for input/output
* \return Error code, ERR_OK if everything was fine
*/
uint8_t McuQuadCounter_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io)
{
uint8_t res=ERR_OK;
if (McuUtility_strcmp((const char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((const char *)cmd, "McuQuadCounter help")==0) {
McuShell_SendHelpStr((const unsigned char*)"McuQuadCounter", (const unsigned char*)"McuQuadCounter command group\r\n", io->stdOut);
McuShell_SendHelpStr((const unsigned char*)" help|status", (const unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((const unsigned char*)" reset", (const unsigned char*)"Reset the current position counter\r\n", io->stdOut);
*handled = TRUE;
} else if (McuUtility_strcmp((const char*)cmd, McuShell_CMD_STATUS)==0 || McuUtility_strcmp((const char*)cmd, "McuQuadCounter status")==0) {
McuShell_SendStr((const unsigned char*)"McuQuadCounter:\r\n", io->stdOut);
McuShell_SendStatusStr((const unsigned char*)" pos", (const unsigned char*)"", io->stdOut);
#if McuQuadCounter_CNTR_BITS==16
McuShell_SendNum16u(McuQuadCounter_currPos, io->stdOut);
#elif McuQuadCounter_CNTR_BITS==32
McuShell_SendNum32u(McuQuadCounter_currPos, io->stdOut);
#else
#error "unknown counter size!"
#endif
McuShell_SendStr((const unsigned char*)", ", io->stdOut);
#if McuQuadCounter_CNTR_BITS==16
McuShell_SendNum16s((int16_t)McuQuadCounter_currPos, io->stdOut);
#elif McuQuadCounter_CNTR_BITS==32
McuShell_SendNum32s((int32_t)McuQuadCounter_currPos, io->stdOut);
#else
#error "unknown counter size!"
#endif
McuShell_SendStr((const unsigned char*)"\r\n", io->stdOut);
McuShell_SendStatusStr((const unsigned char*)" C1 C2", (const unsigned char*)"", io->stdOut);
if (McuQuadCounter_GET_C1_PIN()!=0) {
McuShell_SendStr((const unsigned char*)"1 ", io->stdOut);
} else {
McuShell_SendStr((const unsigned char*)"0 ", io->stdOut);
}
if (McuQuadCounter_GET_C2_PIN()!=0) {
McuShell_SendStr((const unsigned char*)"1\r\n", io->stdOut);
} else {
McuShell_SendStr((const unsigned char*)"0\r\n", io->stdOut);
}
#if McuQuadCounter_CONFIG_COUNT_ERRORS
McuShell_SendStatusStr((const unsigned char*)" errors", (const unsigned char*)"", io->stdOut);
McuShell_SendNum16u(McuQuadCounter_nofErrors, io->stdOut);
McuShell_SendStr((const unsigned char*)"\r\n", io->stdOut);
#endif
*handled = TRUE;
} else if (McuUtility_strcmp((const char*)cmd, "McuQuadCounter reset")==0) {
McuQuadCounter_SetPos(0);
#if McuQuadCounter_CONFIG_COUNT_ERRORS
McuQuadCounter_nofErrors = 0;
#endif
*handled = TRUE;
}
return res;
}
/*
** ===================================================================
** Method : SwapPins (component QuadCounter)
**
** Description :
** Swap the two pins
** Parameters :
** NAME - DESCRIPTION
** swap - if C1 and C2 pins shall be swapped.
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuQuadCounter_SwapPins(bool swap)
{
McuQuadCounter_swappedPins = swap;
return ERR_OK;
}
/* END McuQuadCounter. */
/*!
** @}
*/

View File

@@ -0,0 +1,240 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuQuadCounter.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : QuadCounter
** Version : Component 01.034, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-12-02, 10:47, # CodeGen: 721
** Abstract :
**
This driver implements a quadrature encoder using two signals (C1 and C2) to generate position information.
** Settings :
** Component name : McuQuadCounter
** C1 and C2 swapped : no
** Counter Type : 32bit
** Method :
** Sampling : Enabled
** Error Correction : no
** C1 : SDK_BitIO
** C2 : SDK_BitIO
** Input Capture : Disabled
** Shell : Enabled
** Shell : McuShell
** Utility : McuUtility
** Contents :
** GetPos - McuQuadCounter_QuadCntrType McuQuadCounter_GetPos(void);
** SetPos - void McuQuadCounter_SetPos(McuQuadCounter_QuadCntrType pos);
** GetVal - uint8_t McuQuadCounter_GetVal(void);
** Sample - void McuQuadCounter_Sample(void);
** NofErrors - uint16_t McuQuadCounter_NofErrors(void);
** SwapPins - uint8_t McuQuadCounter_SwapPins(bool swap);
** Deinit - void McuQuadCounter_Deinit(void);
** Init - void McuQuadCounter_Init(void);
** ParseCommand - uint8_t McuQuadCounter_ParseCommand(const unsigned char *cmd, bool *handled,...
**
** * Copyright (c) 2014-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuQuadCounter.h
** @version 01.00
** @brief
**
This driver implements a quadrature encoder using two signals (C1 and C2) to generate position information.
*/
/*!
** @addtogroup McuQuadCounter_module McuQuadCounter module documentation
** @{
*/
#ifndef __McuQuadCounter_H
#define __McuQuadCounter_H
/* MODULE McuQuadCounter. */
#include "McuLib.h" /* SDK and API used */
#include "McuQuadCounterconfig.h" /* configuration */
/* Include inherited components */
#include "C11.h"
#include "C21.h"
#include "McuShell.h"
#include "McuUtility.h"
#include "McuLib.h"
#define McuQuadCounter_SWAP_PINS 0 /* 1: C1 and C2 are swapped */
#define McuQuadCounter_SWAP_PINS_AT_RUNTIME 1 /* 1: C1 and C2 are swapped at runtime, if SwapPins() method is available */
#define McuQuadCounter_GET_C1_PIN() (C11_GetVal())
#define McuQuadCounter_GET_C2_PIN() (C21_GetVal())
#if McuQuadCounter_SWAP_PINS
#define McuQuadCounter_GET_C1_C2_PINS() ((McuQuadCounter_GET_C2_PIN()!=0?2:0)|(McuQuadCounter_GET_C1_PIN()!=0?1:0))
#define McuQuadCounter_GET_C1_C2_PINS_SWAPPED() ((McuQuadCounter_GET_C1_PIN()!=0?2:0)|(McuQuadCounter_GET_C2_PIN()!=0?1:0))
#else
#define McuQuadCounter_GET_C1_C2_PINS() ((McuQuadCounter_GET_C1_PIN()!=0?2:0)|(McuQuadCounter_GET_C2_PIN()!=0?1:0))
#define McuQuadCounter_GET_C1_C2_PINS_SWAPPED() ((McuQuadCounter_GET_C2_PIN()!=0?2:0)|(McuQuadCounter_GET_C1_PIN()!=0?1:0))
#endif
typedef uint32_t McuQuadCounter_QuadCntrType;
#define McuQuadCounter_CNTR_BITS 32
/*!< Number of bits in counter */
#define McuQuadCounter_PARSE_COMMAND_ENABLED 1 /* set to 1 if method ParseCommand() is present, 0 otherwise */
void McuQuadCounter_SetPos(McuQuadCounter_QuadCntrType pos);
/*
** ===================================================================
** Method : SetPos (component QuadCounter)
**
** Description :
** Sets the position information. Can be used as well to reset
** the position information.
** Parameters :
** NAME - DESCRIPTION
** pos - Position value to be set.
** Returns : Nothing
** ===================================================================
*/
McuQuadCounter_QuadCntrType McuQuadCounter_GetPos(void);
/*
** ===================================================================
** Method : GetPos (component QuadCounter)
**
** Description :
** Returns the current position based on the encoder tracking.
** Parameters : None
** Returns :
** --- - position
** ===================================================================
*/
void McuQuadCounter_Sample(void);
/*
** ===================================================================
** Method : Sample (component QuadCounter)
**
** Description :
** Call this method to periodically sample the signals.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint16_t McuQuadCounter_NofErrors(void);
/*
** ===================================================================
** Method : NofErrors (component QuadCounter)
**
** Description :
** Returns the number of decoding errors
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
void McuQuadCounter_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component QuadCounter)
**
** Description :
** Module de-initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuQuadCounter_Init(void);
/*
** ===================================================================
** Method : Init (component QuadCounter)
**
** Description :
** Module initialization method
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuQuadCounter_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io);
/*
** ===================================================================
** Method : ParseCommand (component QuadCounter)
**
** Description :
** Handler to process shell commands
** Parameters :
** NAME - DESCRIPTION
** cmd - Command string to be parsed
** * handled - Pointer to boolean. The handler
** sets this variable to TRUE if command was
** handled, otherwise let it untouched.
** io - Pointer to I/O structure
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuQuadCounter_GetVal(void);
/*
** ===================================================================
** Method : GetVal (component QuadCounter)
**
** Description :
** Returns the quadrature value (0, 1, 2 or 3)
** Parameters : None
** Returns :
** --- - Quadrature value (0-3)
** ===================================================================
*/
uint8_t McuQuadCounter_SwapPins(bool swap);
/*
** ===================================================================
** Method : SwapPins (component QuadCounter)
**
** Description :
** Swap the two pins
** Parameters :
** NAME - DESCRIPTION
** swap - if C1 and C2 pins shall be swapped.
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuQuadCounter. */
#endif
/* ifndef __McuQuadCounter_H */
/*!
** @}
*/

View File

@@ -0,0 +1,220 @@
/*
* Copyright (c) 2019, Erich Styger
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuRBconfig.h"
#include "McuRB.h"
#include <string.h> /* for memcpy() */
#include <stdlib.h> /* for malloc() */
#include <assert.h>
#include "McuCriticalSection.h"
#if MCURB_CONFIG_USE_FREERTOS_HEAP
#include "McuRTOS.h"
#endif
/* default configuration, used for initializing the config */
static const McuRB_Config_t defaultConfig =
{
.nofElements = 32,
.elementSize = 1,
};
typedef struct {
size_t maxElements;
size_t elementSize;
size_t inSize;
size_t inIdx;
size_t outIdx;
void *data;
} McuRB_t;
void McuRB_GetDefaultconfig(McuRB_Config_t *config) {
assert(config!=NULL);
McuCriticalSection_CriticalVariable()
McuCriticalSection_EnterCritical();
memcpy(config, &defaultConfig, sizeof(*config));
McuCriticalSection_ExitCritical();
}
McuRB_Handle_t McuRB_InitRB(McuRB_Config_t *config) {
McuRB_t *handle;
assert(config!=NULL);
#if MCURB_CONFIG_USE_FREERTOS_HEAP
handle = (McuRB_t*)pvPortMalloc(sizeof(McuRB_t)); /* get a new device descriptor */
#else
handle = malloc(sizeof(McuRB_t)); /* get a new descriptor */
#endif
assert(handle!=NULL);
if (handle!=NULL) { /* if malloc failed, will return NULL pointer */
memset(handle, 0, sizeof(McuRB_t)); /* init all fields */
handle->elementSize = config->elementSize;
handle->maxElements = config->nofElements;
#if MCURB_CONFIG_USE_FREERTOS_HEAP
handle->data = pvPortMalloc(handle->maxElements*handle->elementSize);
#else
handle->data = malloc(handle->maxElements*handle->elementSize);
#endif
assert(handle->data!=NULL);
}
return handle;
}
McuRB_Handle_t McuRB_DeinitRB(McuRB_Handle_t rb) {
assert(rb!=NULL);
McuRB_t *handle = (McuRB_t*)rb;
assert(handle->data!=NULL);
#if MCURB_CONFIG_USE_FREERTOS_HEAP
vPortFree(handle->data);
#else
free(handle->data);
#endif
handle->data = NULL;
#if MCURB_CONFIG_USE_FREERTOS_HEAP
vPortFree(rb);
#else
free(rb);
#endif
return NULL;
}
size_t McuRB_NofElements(McuRB_Handle_t rb) {
McuRB_t *handle = (McuRB_t*)rb;
assert(rb!=NULL);
return handle->inSize;
}
size_t McuRB_NofFreeElements(McuRB_Handle_t rb) {
McuRB_t *handle = (McuRB_t*)rb;
assert(rb!=NULL);
return handle->maxElements-handle->inSize;
}
void McuRB_Clear(McuRB_Handle_t rb) {
McuCriticalSection_CriticalVariable()
McuRB_t *handle = (McuRB_t*)rb;
assert(rb!=NULL);
McuCriticalSection_EnterCritical();
handle->inIdx = 0;
handle->outIdx = 0;
handle->inSize = 0;
McuCriticalSection_ExitCritical();
}
uint8_t McuRB_Put(McuRB_Handle_t rb, void *data) {
McuRB_t *handle = (McuRB_t*)rb;
int res = ERR_OK;
McuCriticalSection_CriticalVariable()
assert(rb!=NULL && data!=NULL);
McuCriticalSection_EnterCritical();
if (handle->inSize==handle->maxElements) {
res = ERR_OVERFLOW; /* full */
} else {
memcpy(((uint8_t*)handle->data) + handle->inIdx*handle->elementSize, data, handle->elementSize);
handle->inIdx++;
if (handle->inIdx==handle->maxElements) {
handle->inIdx = 0;
}
handle->inSize++;
}
McuCriticalSection_ExitCritical();
return res;
}
uint8_t McuRB_Putn(McuRB_Handle_t rb, void *data, size_t nof) {
McuRB_t *handle = (McuRB_t*)rb;
uint8_t res = ERR_OK;
uint8_t *p = (uint8_t*)data;
while(nof>0) {
res = McuRB_Put(rb, p);
if (res!=ERR_OK) {
break;
}
p += handle->elementSize;
nof--;
}
return res;
}
uint8_t McuRB_Get(McuRB_Handle_t rb, void *data) {
McuCriticalSection_CriticalVariable()
McuRB_t *handle = (McuRB_t*)rb;
int res = ERR_OK;
assert(rb!=NULL && data!=NULL);
if (handle->inSize==0) {
res = ERR_NOTAVAIL; /* empty */
} else {
memcpy(data, ((uint8_t*)handle->data) + handle->outIdx*handle->elementSize, handle->elementSize);
McuCriticalSection_EnterCritical();
handle->inSize--;
handle->outIdx++;
if (handle->outIdx==handle->maxElements) {
handle->outIdx = 0;
}
McuCriticalSection_ExitCritical();
}
return res;
}
uint8_t McuRB_Peek(McuRB_Handle_t rb, size_t index, void *data) {
uint8_t res = ERR_OK;
int idx; /* index inside ring buffer */
McuRB_t *handle = (McuRB_t*)rb;
unsigned char *p;
McuCriticalSection_CriticalVariable()
McuCriticalSection_EnterCritical();
if (index>=handle->maxElements) {
res = ERR_OVERFLOW; /* asking for an element outside of ring buffer size */
} else if (index<handle->inSize) {
idx = (handle->outIdx+index)%handle->maxElements;
p = (unsigned char*)handle->data + idx*handle->elementSize;
memcpy(data, p, handle->elementSize);
} else { /* asking for an element which does not exist */
res = ERR_RXEMPTY;
}
McuCriticalSection_ExitCritical();
return res;
}
uint8_t McuRB_Compare(McuRB_Handle_t rb, size_t index, void *data, size_t nof) {
McuRB_t *handle = (McuRB_t*)rb;
uint8_t cmpResult = 0;
uint8_t res;
uint8_t val[handle->elementSize]; /* caution: dynamic array! */
unsigned char *p = data;
while(nof>0) {
res = McuRB_Peek(rb, index, &val);
if (res!=ERR_OK) { /* general failure? */
cmpResult = (uint8_t)-1; /* no match */
break;
}
if (memcmp(&val[0], p, handle->elementSize)!=0) { /* mismatch */
cmpResult = (uint8_t)-1; /* no match */
break;
}
p += handle->elementSize;
index++;
nof--;
}
return cmpResult;
}
void McuRB_Deinit(void) {
/* nothing to do */
}
void McuRB_Init(void) {
/* nothing to do */
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 2019, Erich Styger
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MCURINGBUFFER_H_
#define MCURINGBUFFER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "McuRBconfig.h"
typedef void *McuRB_Handle_t; /* handle to be used in API */
typedef struct {
size_t nofElements; /* max number of elements in buffer */
size_t elementSize; /* size of element in bytes */
} McuRB_Config_t;
/* return number of elements in ring buffer */
size_t McuRB_NofElements(McuRB_Handle_t rb);
/* return number of free elements in ring buffer */
size_t McuRB_NofFreeElements(McuRB_Handle_t rb);
/* put an element into the ring buffer. Returns ERR_OK if OK. */
uint8_t McuRB_Put(McuRB_Handle_t rb, void *data);
/* put a number of elements into the buffer */
uint8_t McuRB_Putn(McuRB_Handle_t rb, void *data, size_t nof);
/* clear the ring buffer */
void McuRB_Clear(McuRB_Handle_t rb);
/* get an element from the ring buffer. Returns ERR_OK if OKy. */
uint8_t McuRB_Get(McuRB_Handle_t rb, void *data);
/* peek an element of the ring buffer without removing it */
uint8_t McuRB_Peek(McuRB_Handle_t rb, size_t index, void *data);
/* compare elements in the ring buffer with data. Returns 0 if the data is the same, -1 otherwise */
uint8_t McuRB_Compare(McuRB_Handle_t rb, size_t index, void *data, size_t nof);
/* return a default ring buffer configuration */
void McuRB_GetDefaultconfig(McuRB_Config_t *config);
/* initialize a new ring buffer and return a handle for it */
McuRB_Handle_t McuRB_InitRB(McuRB_Config_t *config);
/* de-initialize a ring buffer */
McuRB_Handle_t McuRB_DeinitRB(McuRB_Handle_t rb);
/* de-initialize the module */
void McuRB_Deinit(void);
/* initialize the module */
void McuRB_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MCURINGBUFFER_H_ */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,579 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuRTT.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SeggerRTT
** Version : Component 01.092, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2021-12-17, 13:26, # CodeGen: 759
** Abstract :
**
** Settings :
** Component name : McuRTT
** Version : V6.86e
** Number of Up Channels : 3
** Number of Down Channels : 3
** Max Blocked Interrupt Level : 3
** Syscalls : no
** Channel 0 : Enabled
** Name : "Terminal"
** Up Buffer Size (Tx) : 512
** Down Buffer Size (Rx) : 64
** Up Buffer Mode : Skip (Default)
** Down Buffer Mode : Skip (Default)
** Blocking Send : Disabled
** Printf Buffer Size : 64
** SDK : McuLib
** Shell : McuShell
** Source Folders :
** Source Folder : SEGGER_RTT
** Config Folder : SEGGER_RTT
** Contents :
** Read - int McuRTT_Read(unsigned BufferIndex, const char* pBuffer, unsigned NumBytes);
** Write - int McuRTT_Write(unsigned BufferIndex, char* pBuffer, unsigned BufferSize);
** WriteString - unsigned McuRTT_WriteString(unsigned BufferIndex, const char* s);
** printf - int McuRTT_printf(unsigned BufferIndex, const char* sFormat, ...);
** GetKey - dword McuRTT_GetKey(void);
** WaitKey - long McuRTT_WaitKey(void);
** HasKey - long McuRTT_HasKey(void);
** SetTerminal - int McuRTT_SetTerminal(char TerminalId);
** TerminalOut - int McuRTT_TerminalOut(char TerminalId, const char* s);
** ConfigUpBuffer - int McuRTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, char*...
** ConfigDownBuffer - int McuRTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, char*...
** RecvChar - uint8_t McuRTT_RecvChar(uint8_t *c);
** SendChar - uint8_t McuRTT_SendChar(uint8_t ch);
** GetCharsInRxBuf - uint16_t McuRTT_GetCharsInRxBuf(void);
** StdIOKeyPressed - bool McuRTT_StdIOKeyPressed(void);
** StdIOReadChar - void McuRTT_StdIOReadChar(uint8_t *c);
** StdIOSendChar - void McuRTT_StdIOSendChar(uint8_t ch);
** GetStdio - %@Shell@'ModuleName'%.ConstStdIOTypePtr McuRTT_GetStdio(void);
** Deinit - void McuRTT_Deinit(void);
** Init - void McuRTT_Init(void);
**
** * (c) Copyright Segger, 2020-2021
** * http : www.segger.com
** * See separate Segger licensing terms.
** *
** * Processor Expert port: Copyright (c) 2016-2021 Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuRTT.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuRTT_module McuRTT module documentation
** @{
*/
/* MODULE McuRTT. */
#include "McuRTT.h"
#if McuRTT_CONFIG_BLOCKING_SEND
#include "McuWait.h"
#endif
/* default standard I/O struct */
McuShell_ConstStdIOType McuRTT_stdio = {
.stdIn = (McuShell_StdIO_In_FctType)McuRTT_StdIOReadChar,
.stdOut = (McuShell_StdIO_OutErr_FctType)McuRTT_StdIOSendChar,
.stdErr = (McuShell_StdIO_OutErr_FctType)McuRTT_StdIOSendChar,
.keyPressed = McuRTT_StdIOKeyPressed, /* if input is not empty */
#if McuShell_CONFIG_ECHO_ENABLED
.echoEnabled = false,
#endif
};
uint8_t McuRTT_DefaultShellBuffer[McuShell_DEFAULT_SHELL_BUFFER_SIZE]; /* default buffer which can be used by the application */
/*
** ===================================================================
** Method : Read (component SeggerRTT)
**
** Description :
** Read from buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer/channel to be used.
** 0 for terminal.
** * pBuffer - Pointer to buffer
** BufferSize - Number of bytes to write
** Returns :
** --- - Number of bytes that have been read
** ===================================================================
*/
/**
int McuRTT_Read(unsigned BufferIndex, const char* pBuffer, unsigned NumBytes)
{
Implemented as macro in the header file.
}
*/
/*
** ===================================================================
** Method : Write (component SeggerRTT)
**
** Description :
** Write to buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer/channel to be used.
** 0 for terminal.
** * pBuffer - Pointer to buffer
** BufferSize - Size of buffer
** Returns :
** --- - Number of bytes which have been written to
** the up buffer
** ===================================================================
*/
/**
int McuRTT_Write(unsigned BufferIndex, char* pBuffer, unsigned BufferSize)
{
Implemented as macro in the header file.
}
*/
/*
** ===================================================================
** Method : WriteString (component SeggerRTT)
**
** Description :
** Write to buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer/channel to be used.
** 0 for terminal.
** * s - Pointer to
** Returns :
** --- - Number of bytes which have been stored in
** the "Up"-buffer.
** ===================================================================
*/
/**
unsigned McuRTT_WriteString(unsigned BufferIndex, const char* s)
{
Implemented as macro in the header file.
}
*/
/*
** ===================================================================
** Method : GetKey (component SeggerRTT)
**
** Description :
** Returns a character/key
** Parameters : None
** Returns :
** --- - character code
** ===================================================================
*/
/**
dword McuRTT_GetKey(void)
{
Implemented as macro in the header file.
}
*/
/*
** ===================================================================
** Method : WaitKey (component SeggerRTT)
**
** Description :
** Waits for a key and returns it.
** Parameters : None
** Returns :
** --- - >=0 Character which has been read.
** ===================================================================
*/
/**
long McuRTT_WaitKey(void)
{
Implemented as macro in the header file.
}
*/
/*
** ===================================================================
** Method : HasKey (component SeggerRTT)
**
** Description :
** Checks if at least one character for reading is available in
** the SEGGER RTT buffer
** Parameters : None
** Returns :
** --- - 0: No characters are available to read; 1:
** At least one character is available.
** ===================================================================
*/
/**
long McuRTT_HasKey(void)
{
Implemented as macro in the header file.
}
*/
/*
** ===================================================================
** Method : StdIOKeyPressed (component SeggerRTT)
**
** Description :
** StdIO handler for Shell
** Parameters : None
** Returns :
** --- - True if there are characters in teh input
** buffer
** ===================================================================
*/
bool McuRTT_StdIOKeyPressed(void)
{
return McuRTT_HasKey()!=0;
}
/*
** ===================================================================
** Method : StdIOReadChar (component SeggerRTT)
**
** Description :
** StdIO Handler for reading a character. It returns a zero
** byte if there is no character in input buffer.
** Parameters :
** NAME - DESCRIPTION
** * c - Pointer to where to store the received
** character
** Returns : Nothing
** ===================================================================
*/
void McuRTT_StdIOReadChar(uint8_t *c)
{
int res;
res = McuRTT_GetKey();
if (res==-1) { /* no character present */
*c = '\0';
} else {
*c = (uint8_t)res; /* return character */
}
}
/*
** ===================================================================
** Method : StdIOSendChar (component SeggerRTT)
**
** Description :
** StdIO handler to sends a character.
** Parameters :
** NAME - DESCRIPTION
** ch - Character to send
** Returns : Nothing
** ===================================================================
*/
void McuRTT_StdIOSendChar(uint8_t ch)
{
#if McuRTT_CONFIG_BLOCKING_SEND
#if McuRTT_CONFIG_BLOCKING_SEND_WAIT_MS>0
#define RTT_STDIO_CNTR (100)
static uint8_t cntr = 0; /* counter to avoid blocking too long if there is no RTT client on the host */
#endif
#if McuRTT_CONFIG_BLOCKING_SEND_TIMEOUT_MS>0 && McuRTT_CONFIG_BLOCKING_SEND_WAIT_MS>0
int timeoutMs = McuRTT_CONFIG_BLOCKING_SEND_TIMEOUT_MS;
#endif
for(;;) { /* will break */
if (McuRTT_Write(0, (const char*)&ch, 1)==1) { /* non blocking send, check that we were able to send */
#if McuRTT_CONFIG_BLOCKING_SEND_WAIT_MS>0
if (cntr>0) {
cntr--;
}
#endif
break; /* was able to send character, get out of waiting loop */
}
#if McuRTT_CONFIG_BLOCKING_SEND_WAIT_MS>0
cntr++;
if (cntr>=RTT_STDIO_CNTR) { /* waiting for too long, give up */
cntr = RTT_STDIO_CNTR;
return;
}
McuWait_WaitOSms(McuRTT_CONFIG_BLOCKING_SEND_WAIT_MS);
#if McuRTT_CONFIG_BLOCKING_SEND_TIMEOUT_MS>0
if(timeoutMs<=0) {
break; /* timeout */
}
timeoutMs -= McuRTT_CONFIG_BLOCKING_SEND_WAIT_MS;
#endif
#endif
} /* for */
#else
(void)McuRTT_Write(0, &ch, 1); /* non blocking send, might loose characters */
#endif
}
/*
** ===================================================================
** Method : RecvChar (component SeggerRTT)
**
** Description :
** Receives a character from channel 0. Returns ERR_RXEMPTY if
** no character available
** Parameters :
** NAME - DESCRIPTION
** * c - Pointer to where to store the received
** character
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRTT_RecvChar(uint8_t *c)
{
int res;
res = McuRTT_GetKey();
if (res==-1) { /* no character present */
return ERR_RXEMPTY;
}
*c = (uint8_t)res; /* return character */
return ERR_OK;
}
/*
** ===================================================================
** Method : SendChar (component SeggerRTT)
**
** Description :
** Sends a character to channel 0.
** Parameters :
** NAME - DESCRIPTION
** ch - Character to send
** Returns :
** --- - Error code. ERR_OK if character has been
** sent, ERR_TXFULL otherwise.
** ===================================================================
*/
uint8_t McuRTT_SendChar(uint8_t ch)
{
int res;
res = SEGGER_RTT_Write(0, (const char*)&ch, 1);
if (res!=1) {
return ERR_TXFULL; /* character not sent? */
}
return ERR_OK;
}
/*
** ===================================================================
** Method : GetCharsInRxBuf (component SeggerRTT)
**
** Description :
** Returns the number of characters in the receive buffer.
** Parameters : None
** Returns :
** --- - Number of characters in the input buffer,
** zero for none available.
** ===================================================================
*/
/**
uint16_t McuRTT_GetCharsInRxBuf(void)
{
// Function is implemented as macro in the header file
if (SEGGER_RTT_HasKey()) {
return 1; // at least one available
}
return 0; // none available
}
*/
/*
** ===================================================================
** Method : TerminalOut (component SeggerRTT)
**
** Description :
** Writes a string to the given terminal without changing the
** terminal for channel 0.
** Parameters :
** NAME - DESCRIPTION
** TerminalId - TerminalId, 0..15
** * s - Pointer to string
** Returns :
** --- - Error code
** ===================================================================
*/
/**
int McuRTT_TerminalOut(char TerminalId, const char* s)
{
Function is implemented as macro in the header file
}
*/
/*
** ===================================================================
** Method : SetTerminal (component SeggerRTT)
**
** Description :
** Sets the terminal to be used for output on channel 0.
** Parameters :
** NAME - DESCRIPTION
** TerminalId - Terminal ID, 0..15
** Returns :
** --- - Error code
** ===================================================================
*/
/**
int McuRTT_SetTerminal(char TerminalId)
{
Function is implemented as macro in the header file
}
*/
/*
** ===================================================================
** Method : ConfigUpBuffer (component SeggerRTT)
**
** Description :
** Configures the Up (device to host) buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer index
** sName - Buffer name
** * pBuffer - Pointer to buffer
** intBufferSize - Size of buffer in bytes
** Flags - SEGGER_RTT_MODE_NO_BLOCK_SKIP,
** SEGGER_RTT_MODE_NO_BLOCK_TRIM or
** SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL
** Returns :
** --- - Error code, >=0 OK, <0 Error
** ===================================================================
*/
/**
int McuRTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, char* pBuffer, int BufferSize, int Flags)
{
Function is implemented as macro in the header file
}
*/
/*
** ===================================================================
** Method : ConfigDownBuffer (component SeggerRTT)
**
** Description :
** Configures the Down (host to device) buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer index
** sName - Buffer name
** * pBuffer - Pointer to buffer
** intBufferSize - Size of buffer in bytes
** Flags - SEGGER_RTT_MODE_NO_BLOCK_SKIP,
** SEGGER_RTT_MODE_NO_BLOCK_TRIM or
** SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL
** Returns :
** --- - Error code, >=0 OK, <0 Error
** ===================================================================
*/
/**
int McuRTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, char* pBuffer, int BufferSize, int Flags)
{
Function is implemented as macro in the header file
}
*/
/*
** ===================================================================
** Method : printf (component SeggerRTT)
**
** Description :
** Stores a formatted string in SEGGER RTT control block. This
** data is sent to the host.
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Index of "Up"-buffer to be
** used. (e.g. 0 for "Terminal")
** sFormat - Pointer to format string, followed
** by the arguments for conversion
** Returns :
** --- - Error code
** ===================================================================
*/
/**
int McuRTT_printf(unsigned BufferIndex, const char* sFormat, ...)
{
Function is implemented as macro in the header file
}
*/
/*
** ===================================================================
** Method : Deinit (component SeggerRTT)
**
** Description :
** Driver deinitialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuRTT_Deinit(void)
{
/* noting to de-initialize */
}
/*
** ===================================================================
** Method : Init (component SeggerRTT)
**
** Description :
** Initializes the RTT Control Block.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuRTT_Init(void)
{
SEGGER_RTT_Init();
}
/*
** ===================================================================
** Method : GetStdio (component SeggerRTT)
**
** Description :
** Returns a pointer to the standard I/O
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
McuShell_ConstStdIOTypePtr McuRTT_GetStdio(void)
{
return &McuRTT_stdio;
}
/* END McuRTT. */
/*!
** @}
*/

View File

@@ -0,0 +1,472 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuRTT.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SeggerRTT
** Version : Component 01.092, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2021-12-17, 13:26, # CodeGen: 759
** Abstract :
**
** Settings :
** Component name : McuRTT
** Version : V6.86e
** Number of Up Channels : 3
** Number of Down Channels : 3
** Max Blocked Interrupt Level : 3
** Syscalls : no
** Channel 0 : Enabled
** Name : "Terminal"
** Up Buffer Size (Tx) : 512
** Down Buffer Size (Rx) : 64
** Up Buffer Mode : Skip (Default)
** Down Buffer Mode : Skip (Default)
** Blocking Send : Disabled
** Printf Buffer Size : 64
** SDK : McuLib
** Shell : McuShell
** Source Folders :
** Source Folder : SEGGER_RTT
** Config Folder : SEGGER_RTT
** Contents :
** Read - int McuRTT_Read(unsigned BufferIndex, const char* pBuffer, unsigned NumBytes);
** Write - int McuRTT_Write(unsigned BufferIndex, char* pBuffer, unsigned BufferSize);
** WriteString - unsigned McuRTT_WriteString(unsigned BufferIndex, const char* s);
** printf - int McuRTT_printf(unsigned BufferIndex, const char* sFormat, ...);
** GetKey - dword McuRTT_GetKey(void);
** WaitKey - long McuRTT_WaitKey(void);
** HasKey - long McuRTT_HasKey(void);
** SetTerminal - int McuRTT_SetTerminal(char TerminalId);
** TerminalOut - int McuRTT_TerminalOut(char TerminalId, const char* s);
** ConfigUpBuffer - int McuRTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, char*...
** ConfigDownBuffer - int McuRTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, char*...
** RecvChar - uint8_t McuRTT_RecvChar(uint8_t *c);
** SendChar - uint8_t McuRTT_SendChar(uint8_t ch);
** GetCharsInRxBuf - uint16_t McuRTT_GetCharsInRxBuf(void);
** StdIOKeyPressed - bool McuRTT_StdIOKeyPressed(void);
** StdIOReadChar - void McuRTT_StdIOReadChar(uint8_t *c);
** StdIOSendChar - void McuRTT_StdIOSendChar(uint8_t ch);
** GetStdio - %@Shell@'ModuleName'%.ConstStdIOTypePtr McuRTT_GetStdio(void);
** Deinit - void McuRTT_Deinit(void);
** Init - void McuRTT_Init(void);
**
** * (c) Copyright Segger, 2020-2021
** * http : www.segger.com
** * See separate Segger licensing terms.
** *
** * Processor Expert port: Copyright (c) 2016-2021 Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuRTT.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuRTT_module McuRTT module documentation
** @{
*/
#ifndef __McuRTT_H
#define __McuRTT_H
/* MODULE McuRTT. */
#include "McuLib.h" /* SDK and API used */
#include "McuRTTconfig.h" /* configuration */
/* Include inherited components */
#include "McuLib.h"
#include "McuShell.h"
#include "SEGGER_RTT.h"
#define McuRTT_RTT_CHANNEL_0_ENABLED 1 /* 0: channel disabled, 1: channel enabled */
extern uint8_t McuRTT_DefaultShellBuffer[McuShell_DEFAULT_SHELL_BUFFER_SIZE]; /* default buffer which can be used by the application */
extern McuShell_ConstStdIOType McuRTT_stdio; /* default standard I/O */
#ifdef __cplusplus
extern "C" {
#endif
#define McuRTT_Read(BufferIndex, pBuffer, NumBytes) \
SEGGER_RTT_Read(BufferIndex, pBuffer, NumBytes)
/*
** ===================================================================
** Method : Read (component SeggerRTT)
**
** Description :
** Read from buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer/channel to be used.
** 0 for terminal.
** * pBuffer - Pointer to buffer
** BufferSize - Number of bytes to write
** Returns :
** --- - Number of bytes that have been read
** ===================================================================
*/
#define McuRTT_Write(BufferIndex, pBuffer, BufferSize) \
SEGGER_RTT_Write(BufferIndex, pBuffer, BufferSize)
/*
** ===================================================================
** Method : Write (component SeggerRTT)
**
** Description :
** Write to buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer/channel to be used.
** 0 for terminal.
** * pBuffer - Pointer to buffer
** BufferSize - Size of buffer
** Returns :
** --- - Number of bytes which have been written to
** the up buffer
** ===================================================================
*/
#define McuRTT_WriteString(BufferIndex, s) \
SEGGER_RTT_WriteString(BufferIndex, s)
/*
** ===================================================================
** Method : WriteString (component SeggerRTT)
**
** Description :
** Write to buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer/channel to be used.
** 0 for terminal.
** * s - Pointer to
** Returns :
** --- - Number of bytes which have been stored in
** the "Up"-buffer.
** ===================================================================
*/
#define McuRTT_GetKey() \
SEGGER_RTT_GetKey()
/*
** ===================================================================
** Method : GetKey (component SeggerRTT)
**
** Description :
** Returns a character/key
** Parameters : None
** Returns :
** --- - character code
** ===================================================================
*/
#define McuRTT_WaitKey() \
SEGGER_RTT_WaitKey()
/*
** ===================================================================
** Method : WaitKey (component SeggerRTT)
**
** Description :
** Waits for a key and returns it.
** Parameters : None
** Returns :
** --- - >=0 Character which has been read.
** ===================================================================
*/
#define McuRTT_HasKey() \
SEGGER_RTT_HasKey()
/*
** ===================================================================
** Method : HasKey (component SeggerRTT)
**
** Description :
** Checks if at least one character for reading is available in
** the SEGGER RTT buffer
** Parameters : None
** Returns :
** --- - 0: No characters are available to read; 1:
** At least one character is available.
** ===================================================================
*/
bool McuRTT_StdIOKeyPressed(void);
/*
** ===================================================================
** Method : StdIOKeyPressed (component SeggerRTT)
**
** Description :
** StdIO handler for Shell
** Parameters : None
** Returns :
** --- - True if there are characters in teh input
** buffer
** ===================================================================
*/
void McuRTT_StdIOReadChar(uint8_t *c);
/*
** ===================================================================
** Method : StdIOReadChar (component SeggerRTT)
**
** Description :
** StdIO Handler for reading a character. It returns a zero
** byte if there is no character in input buffer.
** Parameters :
** NAME - DESCRIPTION
** * c - Pointer to where to store the received
** character
** Returns : Nothing
** ===================================================================
*/
void McuRTT_StdIOSendChar(uint8_t ch);
/*
** ===================================================================
** Method : StdIOSendChar (component SeggerRTT)
**
** Description :
** StdIO handler to sends a character.
** Parameters :
** NAME - DESCRIPTION
** ch - Character to send
** Returns : Nothing
** ===================================================================
*/
uint8_t McuRTT_RecvChar(uint8_t *c);
/*
** ===================================================================
** Method : RecvChar (component SeggerRTT)
**
** Description :
** Receives a character from channel 0. Returns ERR_RXEMPTY if
** no character available
** Parameters :
** NAME - DESCRIPTION
** * c - Pointer to where to store the received
** character
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRTT_SendChar(uint8_t ch);
/*
** ===================================================================
** Method : SendChar (component SeggerRTT)
**
** Description :
** Sends a character to channel 0.
** Parameters :
** NAME - DESCRIPTION
** ch - Character to send
** Returns :
** --- - Error code. ERR_OK if character has been
** sent, ERR_TXFULL otherwise.
** ===================================================================
*/
#define McuRTT_GetCharsInRxBuf() \
SEGGER_RTT_HasKey()
/*
** ===================================================================
** Method : GetCharsInRxBuf (component SeggerRTT)
**
** Description :
** Returns the number of characters in the receive buffer.
** Parameters : None
** Returns :
** --- - Number of characters in the input buffer,
** zero for none available.
** ===================================================================
*/
void McuRTT_Init(void);
/*
** ===================================================================
** Method : Init (component SeggerRTT)
**
** Description :
** Initializes the RTT Control Block.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
#define McuRTT_TerminalOut(TerminalId, s) \
SEGGER_RTT_TerminalOut(TerminalId, s)
/*
** ===================================================================
** Method : TerminalOut (component SeggerRTT)
**
** Description :
** Writes a string to the given terminal without changing the
** terminal for channel 0.
** Parameters :
** NAME - DESCRIPTION
** TerminalId - TerminalId, 0..15
** * s - Pointer to string
** Returns :
** --- - Error code
** ===================================================================
*/
#define McuRTT_SetTerminal(TerminalId) \
SEGGER_RTT_SetTerminal(TerminalId)
/*
** ===================================================================
** Method : SetTerminal (component SeggerRTT)
**
** Description :
** Sets the terminal to be used for output on channel 0.
** Parameters :
** NAME - DESCRIPTION
** TerminalId - Terminal ID, 0..15
** Returns :
** --- - Error code
** ===================================================================
*/
#define McuRTT_ConfigUpBuffer(BufferIndex, sName, pBuffer, BufferSize, Flags) \
SEGGER_RTT_ConfigUpBuffer(BufferIndex, sName, pBuffer, BufferSize, Flags)
/*
** ===================================================================
** Method : ConfigUpBuffer (component SeggerRTT)
**
** Description :
** Configures the Up (device to host) buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer index
** sName - Buffer name
** * pBuffer - Pointer to buffer
** intBufferSize - Size of buffer in bytes
** Flags - SEGGER_RTT_MODE_NO_BLOCK_SKIP,
** SEGGER_RTT_MODE_NO_BLOCK_TRIM or
** SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL
** Returns :
** --- - Error code, >=0 OK, <0 Error
** ===================================================================
*/
#define McuRTT_ConfigDownBuffer(BufferIndex, sName, pBuffer, BufferSize, Flags) \
SEGGER_RTT_ConfigDownBuffer(BufferIndex, sName, pBuffer, BufferSize, Flags)
/*
** ===================================================================
** Method : ConfigDownBuffer (component SeggerRTT)
**
** Description :
** Configures the Down (host to device) buffer
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Buffer index
** sName - Buffer name
** * pBuffer - Pointer to buffer
** intBufferSize - Size of buffer in bytes
** Flags - SEGGER_RTT_MODE_NO_BLOCK_SKIP,
** SEGGER_RTT_MODE_NO_BLOCK_TRIM or
** SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL
** Returns :
** --- - Error code, >=0 OK, <0 Error
** ===================================================================
*/
#define McuRTT_printf \
SEGGER_RTT_printf
/*
** ===================================================================
** Method : printf (component SeggerRTT)
**
** Description :
** Stores a formatted string in SEGGER RTT control block. This
** data is sent to the host.
** Parameters :
** NAME - DESCRIPTION
** BufferIndex - Index of "Up"-buffer to be
** used. (e.g. 0 for "Terminal")
** sFormat - Pointer to format string, followed
** by the arguments for conversion
** Returns :
** --- - Error code
** ===================================================================
*/
void McuRTT_Deinit(void);
/*
** ===================================================================
** Method : Deinit (component SeggerRTT)
**
** Description :
** Driver deinitialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
McuShell_ConstStdIOTypePtr McuRTT_GetStdio(void);
/*
** ===================================================================
** Method : GetStdio (component SeggerRTT)
**
** Description :
** Returns a pointer to the standard I/O
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuRTT. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuRTT_H */
/*!
** @}
*/

View File

@@ -0,0 +1,437 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuRingbuffer.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : RingBuffer
** Version : Component 01.054, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
** This component implements a ring buffer for different integer data type.
** Settings :
** Component name : McuRingbuffer
** Buffer Size : 64
** Contents :
** Clear - void McuRingbuffer_Clear(void);
** Put - uint8_t McuRingbuffer_Put(McuRingbuffer_ElementType elem);
** Get - uint8_t McuRingbuffer_Get(McuRingbuffer_ElementType *elemP);
** Peek - uint8_t McuRingbuffer_Peek(McuRingbuffer_BufSizeType index,...
** Update - uint8_t McuRingbuffer_Update(McuRingbuffer_BufSizeType index,...
** Putn - uint8_t McuRingbuffer_Putn(McuRingbuffer_ElementType *elem,...
** Getn - uint8_t McuRingbuffer_Getn(McuRingbuffer_ElementType *buf,...
** Compare - uint8_t McuRingbuffer_Compare(McuRingbuffer_BufSizeType index,...
** Delete - uint8_t McuRingbuffer_Delete(void);
** NofElements - McuRingbuffer_BufSizeType McuRingbuffer_NofElements(void);
** NofFreeElements - McuRingbuffer_BufSizeType McuRingbuffer_NofFreeElements(void);
** Deinit - void McuRingbuffer_Deinit(void);
** Init - void McuRingbuffer_Init(void);
**
** * Copyright (c) 2014-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuRingbuffer.h
** @version 01.00
** @brief
** This component implements a ring buffer for different integer data type.
*/
/*!
** @addtogroup McuRingbuffer_module McuRingbuffer module documentation
** @{
*/
/* MODULE McuRingbuffer. */
#include "McuRingbuffer.h"
#if McuRingbuffer_CONFIG_REENTRANT
#define McuRingbuffer_DEFINE_CRITICAL() McuCriticalSection_CriticalVariable()
#define McuRingbuffer_ENTER_CRITICAL() McuCriticalSection_EnterCritical()
#define McuRingbuffer_EXIT_CRITICAL() McuCriticalSection_ExitCritical()
#else
#define McuRingbuffer_DEFINE_CRITICAL() /* nothing */
#define McuRingbuffer_ENTER_CRITICAL() /* nothing */
#define McuRingbuffer_EXIT_CRITICAL() /* nothing */
#endif
static McuRingbuffer_ElementType McuRingbuffer_buffer[McuRingbuffer_CONFIG_BUF_SIZE]; /* ring buffer */
static McuRingbuffer_BufSizeType McuRingbuffer_inIdx; /* input index */
static McuRingbuffer_BufSizeType McuRingbuffer_outIdx; /* output index */
static McuRingbuffer_BufSizeType McuRingbuffer_inSize; /* size data in buffer */
/*
** ===================================================================
** Method : Put (component RingBuffer)
**
** Description :
** Puts a new element into the buffer
** Parameters :
** NAME - DESCRIPTION
** elem - New element to be put into the buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Put(McuRingbuffer_ElementType elem)
{
uint8_t res = ERR_OK;
McuRingbuffer_DEFINE_CRITICAL();
McuRingbuffer_ENTER_CRITICAL();
if (McuRingbuffer_inSize==McuRingbuffer_CONFIG_BUF_SIZE) {
res = ERR_TXFULL;
} else {
McuRingbuffer_buffer[McuRingbuffer_inIdx] = elem;
McuRingbuffer_inIdx++;
if (McuRingbuffer_inIdx==McuRingbuffer_CONFIG_BUF_SIZE) {
McuRingbuffer_inIdx = 0;
}
McuRingbuffer_inSize++;
}
McuRingbuffer_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Putn (component RingBuffer)
**
** Description :
** Put a number new element into the buffer.
** Parameters :
** NAME - DESCRIPTION
** * elem - Pointer to new elements to be put into
** the buffer
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Putn(McuRingbuffer_ElementType *elem, McuRingbuffer_BufSizeType nof)
{
uint8_t res = ERR_OK;
while(nof>0) {
res = McuRingbuffer_Put(*elem);
if (res!=ERR_OK) {
break;
}
elem++; nof--;
}
return res;
}
/*
** ===================================================================
** Method : Get (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters :
** NAME - DESCRIPTION
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Get(McuRingbuffer_ElementType *elemP)
{
uint8_t res = ERR_OK;
McuRingbuffer_DEFINE_CRITICAL();
McuRingbuffer_ENTER_CRITICAL();
if (McuRingbuffer_inSize==0) {
res = ERR_RXEMPTY;
} else {
*elemP = McuRingbuffer_buffer[McuRingbuffer_outIdx];
McuRingbuffer_inSize--;
McuRingbuffer_outIdx++;
if (McuRingbuffer_outIdx==McuRingbuffer_CONFIG_BUF_SIZE) {
McuRingbuffer_outIdx = 0;
}
}
McuRingbuffer_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Getn (component RingBuffer)
**
** Description :
** Get a number elements into a buffer.
** Parameters :
** NAME - DESCRIPTION
** * buf - Pointer to buffer where to store the
** elements
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Getn(McuRingbuffer_ElementType *buf, McuRingbuffer_BufSizeType nof)
{
uint8_t res = ERR_OK;
while(nof>0) {
res = McuRingbuffer_Get(buf);
if (res!=ERR_OK) {
break;
}
buf++; nof--;
}
return res;
}
/*
** ===================================================================
** Method : NofElements (component RingBuffer)
**
** Description :
** Returns the actual number of elements in the buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
McuRingbuffer_BufSizeType McuRingbuffer_NofElements(void)
{
return McuRingbuffer_inSize;
}
/*
** ===================================================================
** Method : NofFreeElements (component RingBuffer)
**
** Description :
** Returns the actual number of free elements/space in the
** buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
McuRingbuffer_BufSizeType McuRingbuffer_NofFreeElements(void)
{
return (McuRingbuffer_BufSizeType)(McuRingbuffer_CONFIG_BUF_SIZE-McuRingbuffer_inSize);
}
/*
** ===================================================================
** Method : Init (component RingBuffer)
**
** Description :
** Initializes the data structure
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuRingbuffer_Init(void)
{
McuRingbuffer_inIdx = 0;
McuRingbuffer_outIdx = 0;
McuRingbuffer_inSize = 0;
}
/*
** ===================================================================
** Method : Clear (component RingBuffer)
**
** Description :
** Clear (empty) the ring buffer.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuRingbuffer_Clear(void)
{
McuRingbuffer_DEFINE_CRITICAL();
McuRingbuffer_ENTER_CRITICAL();
McuRingbuffer_Init();
McuRingbuffer_EXIT_CRITICAL();
}
/*
** ===================================================================
** Method : Peek (component RingBuffer)
**
** Description :
** Returns an element of the buffer without removiing it.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Peek(McuRingbuffer_BufSizeType index, McuRingbuffer_ElementType *elemP)
{
uint8_t res = ERR_OK;
int idx; /* index inside ring buffer */
McuRingbuffer_DEFINE_CRITICAL();
McuRingbuffer_ENTER_CRITICAL();
if (index>=McuRingbuffer_CONFIG_BUF_SIZE) {
res = ERR_OVERFLOW; /* asking for an element outside of ring buffer size */
} else if (index<McuRingbuffer_inSize) {
idx = (McuRingbuffer_outIdx+index)%McuRingbuffer_CONFIG_BUF_SIZE;
*elemP = McuRingbuffer_buffer[idx];
} else { /* asking for an element which does not exist */
res = ERR_RXEMPTY;
}
McuRingbuffer_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Compare (component RingBuffer)
**
** Description :
** Compares the elements in the buffer.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to elements to compare with
** nof - number of elements to compare
** Returns :
** --- - zero if elements are the same, -1 otherwise
** ===================================================================
*/
uint8_t McuRingbuffer_Compare(McuRingbuffer_BufSizeType index, McuRingbuffer_ElementType *elemP, McuRingbuffer_BufSizeType nof)
{
uint8_t cmpResult = 0;
uint8_t res;
McuRingbuffer_ElementType val;
while(nof>0) {
res = McuRingbuffer_Peek(index, &val);
if (res!=ERR_OK) { /* general failure? */
cmpResult = (uint8_t)-1; /* no match */
break;
}
if (val!=*elemP) { /* mismatch */
cmpResult = (uint8_t)-1; /* no match */
break;
}
elemP++; index++; nof--;
}
return cmpResult;
}
/*
** ===================================================================
** Method : Deinit (component RingBuffer)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
/**
void McuRingbuffer_Deinit(void)
{
** Function is implemented as macro in the header file
}
*/
/*
** ===================================================================
** Method : Delete (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Delete(void)
{
uint8_t res = ERR_OK;
McuRingbuffer_DEFINE_CRITICAL();
McuRingbuffer_ENTER_CRITICAL();
if (McuRingbuffer_inSize==0) {
res = ERR_RXEMPTY;
} else {
McuRingbuffer_inSize--;
McuRingbuffer_outIdx++;
if (McuRingbuffer_outIdx==McuRingbuffer_CONFIG_BUF_SIZE) {
McuRingbuffer_outIdx = 0;
}
}
McuRingbuffer_EXIT_CRITICAL();
return res;
}
/*
** ===================================================================
** Method : Update (component RingBuffer)
**
** Description :
** Updates the data of an element.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Update(McuRingbuffer_BufSizeType index, McuRingbuffer_ElementType *elemP)
{
uint8_t res = ERR_OK;
int idx; /* index inside ring buffer */
McuRingbuffer_DEFINE_CRITICAL();
McuRingbuffer_ENTER_CRITICAL();
if (index>=McuRingbuffer_CONFIG_BUF_SIZE) {
res = ERR_OVERFLOW; /* asking for an element outside of ring buffer size */
} else if (index<McuRingbuffer_inSize) {
idx = (McuRingbuffer_outIdx+index)%McuRingbuffer_CONFIG_BUF_SIZE;
McuRingbuffer_buffer[idx] = *elemP; /* replace element */
} else { /* asking for an element which does not exist */
res = ERR_RXEMPTY;
}
McuRingbuffer_EXIT_CRITICAL();
return res;
}
/* END McuRingbuffer. */
/*!
** @}
*/

View File

@@ -0,0 +1,305 @@
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuRingbuffer.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : RingBuffer
** Version : Component 01.054, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
** This component implements a ring buffer for different integer data type.
** Settings :
** Component name : McuRingbuffer
** Buffer Size : 64
** Contents :
** Clear - void McuRingbuffer_Clear(void);
** Put - uint8_t McuRingbuffer_Put(McuRingbuffer_ElementType elem);
** Get - uint8_t McuRingbuffer_Get(McuRingbuffer_ElementType *elemP);
** Peek - uint8_t McuRingbuffer_Peek(McuRingbuffer_BufSizeType index,...
** Update - uint8_t McuRingbuffer_Update(McuRingbuffer_BufSizeType index,...
** Putn - uint8_t McuRingbuffer_Putn(McuRingbuffer_ElementType *elem,...
** Getn - uint8_t McuRingbuffer_Getn(McuRingbuffer_ElementType *buf,...
** Compare - uint8_t McuRingbuffer_Compare(McuRingbuffer_BufSizeType index,...
** Delete - uint8_t McuRingbuffer_Delete(void);
** NofElements - McuRingbuffer_BufSizeType McuRingbuffer_NofElements(void);
** NofFreeElements - McuRingbuffer_BufSizeType McuRingbuffer_NofFreeElements(void);
** Deinit - void McuRingbuffer_Deinit(void);
** Init - void McuRingbuffer_Init(void);
**
** * Copyright (c) 2014-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuRingbuffer.h
** @version 01.00
** @brief
** This component implements a ring buffer for different integer data type.
*/
/*!
** @addtogroup McuRingbuffer_module McuRingbuffer module documentation
** @{
*/
#ifndef __McuRingbuffer_H
#define __McuRingbuffer_H
/* MODULE McuRingbuffer. */
#include "McuLib.h" /* SDK and API used */
#include "McuRingbufferconfig.h" /* configuration */
/* Include inherited components */
#include "McuLib.h"
#include "McuCriticalSection.h"
#ifdef __cplusplus
extern "C" {
#endif
#if McuRingbuffer_CONFIG_ELEM_SIZE==1
typedef uint8_t McuRingbuffer_ElementType; /* type of single element */
#elif McuRingbuffer_CONFIG_ELEM_SIZE==2
typedef uint16_t McuRingbuffer_ElementType; /* type of single element */
#elif McuRingbuffer_CONFIG_ELEM_SIZE==4
typedef uint32_t McuRingbuffer_ElementType; /* type of single element */
#else
#error "illegal element type size in properties"
#endif
#if McuRingbuffer_CONFIG_BUF_SIZE<256
typedef uint8_t McuRingbuffer_BufSizeType; /* up to 255 elements (index 0x00..0xff) */
#else
typedef uint16_t McuRingbuffer_BufSizeType; /* more than 255 elements, up to 2^16 */
#endif
uint8_t McuRingbuffer_Put(McuRingbuffer_ElementType elem);
/*
** ===================================================================
** Method : Put (component RingBuffer)
**
** Description :
** Puts a new element into the buffer
** Parameters :
** NAME - DESCRIPTION
** elem - New element to be put into the buffer
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Get(McuRingbuffer_ElementType *elemP);
/*
** ===================================================================
** Method : Get (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters :
** NAME - DESCRIPTION
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
McuRingbuffer_BufSizeType McuRingbuffer_NofElements(void);
/*
** ===================================================================
** Method : NofElements (component RingBuffer)
**
** Description :
** Returns the actual number of elements in the buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
void McuRingbuffer_Init(void);
/*
** ===================================================================
** Method : Init (component RingBuffer)
**
** Description :
** Initializes the data structure
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
McuRingbuffer_BufSizeType McuRingbuffer_NofFreeElements(void);
/*
** ===================================================================
** Method : NofFreeElements (component RingBuffer)
**
** Description :
** Returns the actual number of free elements/space in the
** buffer.
** Parameters : None
** Returns :
** --- - Number of elements in the buffer.
** ===================================================================
*/
void McuRingbuffer_Clear(void);
/*
** ===================================================================
** Method : Clear (component RingBuffer)
**
** Description :
** Clear (empty) the ring buffer.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuRingbuffer_Peek(McuRingbuffer_BufSizeType index, McuRingbuffer_ElementType *elemP);
/*
** ===================================================================
** Method : Peek (component RingBuffer)
**
** Description :
** Returns an element of the buffer without removiing it.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
#define McuRingbuffer_Deinit() \
/* nothing to deinitialize */
/*
** ===================================================================
** Method : Deinit (component RingBuffer)
**
** Description :
** Driver de-initialization
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
uint8_t McuRingbuffer_Delete(void);
/*
** ===================================================================
** Method : Delete (component RingBuffer)
**
** Description :
** Removes an element from the buffer
** Parameters : None
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Putn(McuRingbuffer_ElementType *elem, McuRingbuffer_BufSizeType nof);
/*
** ===================================================================
** Method : Putn (component RingBuffer)
**
** Description :
** Put a number new element into the buffer.
** Parameters :
** NAME - DESCRIPTION
** * elem - Pointer to new elements to be put into
** the buffer
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Compare(McuRingbuffer_BufSizeType index, McuRingbuffer_ElementType *elemP, McuRingbuffer_BufSizeType nof);
/*
** ===================================================================
** Method : Compare (component RingBuffer)
**
** Description :
** Compares the elements in the buffer.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to elements to compare with
** nof - number of elements to compare
** Returns :
** --- - zero if elements are the same, -1 otherwise
** ===================================================================
*/
uint8_t McuRingbuffer_Getn(McuRingbuffer_ElementType *buf, McuRingbuffer_BufSizeType nof);
/*
** ===================================================================
** Method : Getn (component RingBuffer)
**
** Description :
** Get a number elements into a buffer.
** Parameters :
** NAME - DESCRIPTION
** * buf - Pointer to buffer where to store the
** elements
** nof - number of elements
** Returns :
** --- - Error code
** ===================================================================
*/
uint8_t McuRingbuffer_Update(McuRingbuffer_BufSizeType index, McuRingbuffer_ElementType *elemP);
/*
** ===================================================================
** Method : Update (component RingBuffer)
**
** Description :
** Updates the data of an element.
** Parameters :
** NAME - DESCRIPTION
** index - Index of element. 0 peeks the top
** element, 1 the next, and so on.
** * elemP - Pointer to where to store the received
** element
** Returns :
** --- - Error code
** ===================================================================
*/
/* END McuRingbuffer. */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
/* ifndef __McuRingbuffer_H */
/*!
** @}
*/

View File

@@ -0,0 +1,438 @@
/*
* Copyright (c) 2024, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Input -> McuSDEP_callbacks.receive_char() -> sdepTask()
* SDEP / \
* Output <- McuSDEP_callbacks.send_char() <-/ \-> McuSDEP_callbacks.forward_char() (e.g. to shell)
*/
#include "McuSDEP.h"
#if McuSDEP_CONFIG_IS_ENABLED
#include "McuLib.h"
#include "McuRTOS.h"
#include "McuLog.h"
#include "McuArmTools.h"
#include "McuRB.h"
#include "McuUtility.h"
#include "McuIO.h"
#if McuLib_CONFIG_CPU_IS_RPxxxx
#include "pico/util/queue.h"
#endif
/* --------------------------------------------------------------------------------- */
/* Logging channel configuration */
/* --------------------------------------------------------------------------------- */
static uint8_t logChannel = 0;
void McuSDEP_SetLogChannel(uint8_t channel) {
logChannel = channel;
}
uint8_t McuSDEP_GetLogChannel(void) {
return logChannel;
}
/* --------------------------------------------------------------------------------- */
/* Buffers and IO for incoming rx data for SDEP */
/* --------------------------------------------------------------------------------- */
#if McuSDEP_CONFIG_USE_FREERTOS
static QueueHandle_t rxDataBuffer; /* using FreeRTOS queue */
#else
static McuRB_Handle_t rxDataBuffer; /* using bare metal ring buffer */
#endif
static McuIO_Desc_t *McuSDEP_SdepIO = NULL; /* I/O buffer for incoming data: SDEP and non-SDEP shell data */
static void (*McuSDEP_txToShell_cb)(char) = NULL; /* callback to write non-SDEP messages to the console */
static int (*McuSDEP_rxToBuffer_cb)(void) = NULL; /* callback to get data from the rx buffer (e.g. queue from USB Host CDC) */
void McuSDEP_SetForwardCharCallback(void (*forward_char_cb)(char)) {
McuSDEP_txToShell_cb = forward_char_cb;
}
void McuSDEP_SetRxToBufferCallback(int (*rx_cb)(void)) {
McuSDEP_rxToBuffer_cb = rx_cb;
}
void McuSDEP_SetSdepIO(McuIO_Desc_t *io) {
McuSDEP_SdepIO = io;
}
McuIO_Desc_t *McuSDEP_GetSdepIO(void) {
return McuSDEP_SdepIO;
}
void McuSDEP_StoreCharInSdepBuffer(char ch) { /* callback set with McuShellCdcDevice_SetBufferRxCharCallback(): needs void(*cp)(char) */
McuIO_Desc_t *io = McuSDEP_GetSdepIO();
(void)io->buffer.write(io, ch);
}
/* --------------------------------------------------------------------------------- */
static uint8_t crc8_bytecalc(unsigned char byte, uint8_t* seed) {
#define CRC8_POLYNOM (0x07)
uint8_t i;
uint8_t flag;
uint8_t polynom = CRC8_POLYNOM;
for (i = 0; i < 8; i++) {
if (*seed & 0x80) {
flag = 1;
} else {
flag = 0;
}
*seed <<= 1;
if (byte & 0x80) {
*seed |= 1;
}
byte <<= 1;
if (flag) {
*seed ^= polynom;
}
}
return *seed;
}
static uint8_t crc8_messagecalc(unsigned char *msg, uint8_t len, uint8_t* seed) {
for (int i = 0; i < len; i++) {
crc8_bytecalc(msg[i], seed);
}
uint8_t crc = crc8_bytecalc(0, seed);
return crc;
}
static uint8_t McuSDEP_Crc8(McuSDEPmessage_t *message) {
uint8_t crc, seed = 0;
crc = crc8_bytecalc(message->type, &seed);
crc = crc8_bytecalc((uint8_t) message->cmdId, &seed);
crc = crc8_bytecalc((uint8_t) (message->cmdId >> 8), &seed);
crc = crc8_bytecalc(message->payloadSize, &seed);
crc = crc8_messagecalc((unsigned char*) message->payload, message->payloadSize & ~McuSDEP_PAYLOADBYTE_MORE_DATA_BIT, &seed);
return crc;
}
static void DecodeMessage(McuSDEPmessage_t *msg, unsigned char *buf, size_t bufSize) {
McuUtility_strcpy(buf, bufSize, "type:");
switch(msg->type) {
case McuSDEP_MSG_TYPE_COMMAND:
McuUtility_strcat(buf, bufSize, "CMD");
break;
case McuSDEP_MSG_TYPE_RESPONSE:
McuUtility_strcat(buf, bufSize, "RSP");
break;
case McuSDEP_MSG_TYPE_ALERT:
McuUtility_strcat(buf, bufSize, "ALE");
break;
case McuSDEP_MSG_TYPE_ERROR:
McuUtility_strcat(buf, bufSize, "ERR");
break;
default: break;
}
McuUtility_strcat(buf, bufSize, " cmd:");
McuUtility_strcatNum16Hex(buf, bufSize, msg->cmdId);
McuUtility_strcat(buf, bufSize, " size:");
McuUtility_strcatNum8Hex(buf, bufSize, msg->payloadSize);
if (msg->payloadSize>0) {
McuUtility_strcat(buf, bufSize, " data:");
for(int i=0; i<msg->payloadSize; i++) {
McuUtility_strcatNum8Hex(buf, bufSize, msg->payload[i]);
if (i<msg->payloadSize-1) { /* not for the last byte */
McuUtility_chcat(buf, bufSize, ' ');
}
}
}
McuUtility_strcat(buf, bufSize, " crc:");
McuUtility_strcatNum8Hex(buf, bufSize, msg->crc);
}
static void sendBlock(McuIO_Desc_t *io, char *data, size_t count) {
for(int i=0; i<count; i++) {
io->out.write(data[i]);
}
}
uint8_t McuSDEP_SendMessage(McuIO_Desc_t *io, McuSDEPmessage_t *msg) {
msg->crc = McuSDEP_Crc8(msg);
#if McuSDEP_CONFIG_USE_FRAMING
McuSDEP_SendByte(McuSDEP_CONFIG_MSG_FRAMING_START);
#endif
io->out.write(msg->type);
io->out.write(msg->cmdId); /* send little endian first */
io->out.write((msg->cmdId >> 8));
io->out.write(msg->payloadSize);
sendBlock(io, msg->payload, msg->payloadSize & ~McuSDEP_PAYLOADBYTE_MORE_DATA_BIT);
io->out.write(msg->crc);
#if McuSDEP_CONFIG_USE_FRAMING
McuSDEP_SendByte(McuSDEP_CONFIG_MSG_FRAMING_END);
#endif
io->out.flush();
unsigned char buf[96];
DecodeMessage(msg, buf, sizeof(buf));
McuSDEP_Log("Tx: %s", buf);
return ERR_OK;
}
static uint8_t McuSDEP_SendResponseForCmd(McuIO_Desc_t *io, uint16_t cmdId) {
McuSDEPmessage_t msg;
msg.type = McuSDEP_MSG_TYPE_COMMAND;
msg.cmdId = cmdId;
msg.payload = NULL;
msg.payloadSize = 0;
msg.crc = McuSDEP_Crc8(&msg);
McuSDEP_ID_HandleIncommingMessage(&msg);
return ERR_OK;
}
static uint8_t McuSDEP_SendCommand(McuIO_Desc_t *io, uint16_t cmdId) {
McuSDEPmessage_t msg;
msg.type = McuSDEP_MSG_TYPE_COMMAND;
msg.cmdId = cmdId;
msg.payload = NULL;
msg.payloadSize = 0;
msg.crc = McuSDEP_Crc8(&msg);
McuSDEP_SendMessage(io, &msg);
return ERR_OK;
}
static uint8_t McuSDEP_SendError(McuIO_Desc_t *io, uint16_t cmdErrorId) {
McuSDEPmessage_t msg;
msg.type = McuSDEP_MSG_TYPE_ERROR;
msg.cmdId = cmdErrorId;
msg.payload = NULL;
msg.payloadSize = 0;
msg.crc = McuSDEP_Crc8(&msg);
McuSDEP_SendMessage(io, &msg);
return ERR_OK;
}
static inline bool isValidSDEPType(unsigned char ch) {
return ch == McuSDEP_MSG_TYPE_COMMAND
|| ch == McuSDEP_MSG_TYPE_RESPONSE
|| ch == McuSDEP_MSG_TYPE_ERROR
|| ch == McuSDEP_MSG_TYPE_ALERT;
}
static uint8_t readByte(unsigned char *buf, size_t bufSize, size_t *currBufIdx, McuIO_Desc_t *io) {
int ch;
if (*currBufIdx>=bufSize) {
return ERR_OVERFLOW;
}
if (io->buffer.nofData(io)==0) {
return ERR_NOTAVAIL;
}
ch = io->buffer.read(io);
if (ch==EOF) { /* no data available */
return ERR_NOTAVAIL;
}
buf[(*currBufIdx)++] = ch;
return ERR_OK;
}
static uint8_t McuSDEP_ParseSDEPMessage(McuIO_Desc_t *io, unsigned char *buf, size_t bufSize, size_t *currBufIdx, McuSDEPmessage_t *msg) {
uint8_t res;
/* 0: message type: 8 bits */
if (*currBufIdx==0) { /* at the start */
res = readByte(buf, bufSize, currBufIdx, io);
if (res!=ERR_OK) {
return res;
}
if (!isValidSDEPType(buf[(*currBufIdx)-1])) {
return ERR_FAILED; /* not valid message type */
}
msg->type = buf[(*currBufIdx)-1];
/* initialize other fields */
msg->cmdId = 0;
msg->payloadSize = 0;
msg->payload = 0;
msg->crc = 0;
memset(buf+1, 0, bufSize-1); /* initialize buffer, except the first byte */
}
/* 1: message command ID: low byte*/
if (*currBufIdx==1) { /* first byte of cmd */
res = readByte(buf, bufSize, currBufIdx, io);
if (res!=ERR_OK) {
return res;
}
msg->cmdId = buf[(*currBufIdx)-1]; /* low byte */
}
/* 2: message command ID: high byte*/
if (*currBufIdx==2) { /* second byte of cmd */
res = readByte(buf, bufSize, currBufIdx, io);
if (res!=ERR_OK) {
return res;
}
msg->cmdId |= buf[(*currBufIdx)-1]<<8; /* high byte */
if (!McuSDEP_ID_isValidSDEPCommand(msg->cmdId)) {
return ERR_FAILED; /* not valid message type */
}
}
/* 3: message payload size: 8 bits */
if (*currBufIdx==3) {
res = readByte(buf, bufSize, currBufIdx, io);
if (res!=ERR_OK) {
return res;
}
msg->payloadSize = buf[(*currBufIdx)-1];
}
/* 4: payload, if any, followed by CRC */
if (*currBufIdx>=4 && msg->payloadSize!=0 && *currBufIdx<3+msg->payloadSize+1) { /* with payload: read data first */
do { /* read payload */
res = readByte(buf, bufSize, currBufIdx, io);
if (res!=ERR_OK) {
return res;
}
} while(*currBufIdx<3+msg->payloadSize+1);
/* finished reading payload: point to beginning of data: */
msg->payload = &buf[*currBufIdx - msg->payloadSize];
}
/* last item: CRC */
res = readByte(buf, bufSize, currBufIdx, io);
if (res!=ERR_OK) {
return res;
}
msg->crc = buf[(*currBufIdx)-1];
if (McuSDEP_Crc8(msg) != msg->crc) {
return ERR_CRC; /* crc does not match */
}
return ERR_OK; /* valid message */
}
static uint8_t PrintHelp(McuShell_ConstStdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"McuSDEP", (const unsigned char*)"Group of McuSDEP commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (const unsigned char*)"Print help or status information\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" cmd <id>", (const unsigned char*)"Send command\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" resp <id>", (const unsigned char*)"Send response for command\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" text <txt>", (const unsigned char*)"Send text\r\n", io->stdOut);
return ERR_OK;
}
static uint8_t PrintStatus(McuShell_ConstStdIOType *io) {
unsigned char buf[16];
McuShell_SendStatusStr((const unsigned char*)"McuSDEP", (const unsigned char*)"McuSDEP module status\r\n", io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), "channel: ");
McuUtility_strcatNum8u(buf, sizeof(buf), logChannel);
McuUtility_strcat(buf, sizeof(buf), "\r\n");
McuShell_SendStatusStr((const unsigned char*)" log", buf, io->stdOut);
return ERR_OK;
}
uint8_t McuSDEP_ParseCommand(const uint8_t *cmd, bool *handled, McuShell_ConstStdIOType *io) {
const unsigned char *p;
uint32_t val;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, "McuSDEP help")==0) {
*handled = TRUE;
return PrintHelp(io);
} else if ((McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0) || (McuUtility_strcmp((char*)cmd, "McuSDEP status")==0)) {
*handled = TRUE;
return PrintStatus(io);
} else if (McuUtility_strncmp((char*)cmd, "McuSDEP cmd ", sizeof("McuSDEP cmd ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("McuSDEP cmd ")-1;
if (McuUtility_xatoi(&p, &val)!=ERR_OK) {
return ERR_FAILED;
}
return McuSDEP_SendCommand(McuSDEP_GetSdepIO(), val);
} else if (McuUtility_strncmp((char*)cmd, "McuSDEP resp ", sizeof("McuSDEP resp ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("McuSDEP resp ")-1;
if (McuUtility_xatoi(&p, &val)!=ERR_OK) {
return ERR_FAILED;
}
return McuSDEP_SendResponseForCmd(McuSDEP_GetSdepIO(), val);
} else if (McuUtility_strncmp((char*)cmd, "McuSDEP text ", sizeof("McuSDEP text ")-1)==0) {
*handled = TRUE;
p = cmd + sizeof("McuSDEP text ")-1;
McuIO_Desc_t *io = McuSDEP_GetSdepIO();
while(*p!='\0') {
io->out.write(*p);
p++;
}
io->out.write('\n');
io->out.flush();
return ERR_OK;
}
return ERR_OK;
}
static void sdepTask(void *pv) {
uint8_t res;
uint8_t buf[McuSDEP_MESSAGE_MAX_NOF_BYTES + 1];
uint8_t debugBuf[64];
size_t bufIdx = 0;
McuSDEPmessage_t msg;
bool checkingSDEP = false;
int timeoutMs;
McuIO_Desc_t *io = McuSDEP_GetSdepIO();
for(;;) {
if (McuSDEP_rxToBuffer_cb!=NULL) { /* have valid callback? Read data from Rx buffer */
/* try to transfer data from Rx buffer quickly to the SDEP buffer */
while(io->buffer.nofFree(io)>0) {
int ch = McuSDEP_rxToBuffer_cb(); /* check if we have data */
if (ch==EOF) { /* no data from available: get out of loop */
break;
}
io->buffer.write(io, ch); /* store in our own buffer */
} /* while */
}
if (io->buffer.nofData(io)>0) { /* have data to handle in SDEP buffer */
timeoutMs = 0;
res = McuSDEP_ParseSDEPMessage(io, buf, sizeof(buf), &bufIdx, &msg);
if (res==ERR_OK) { /* parsed a valid SDEP message */
bufIdx = 0; /* start for new iteration */
DecodeMessage(&msg, debugBuf, sizeof(debugBuf));
McuSDEP_Log("Rx: %s", debugBuf);
McuSDEP_ID_HandleIncommingMessage(&msg);
} else if (res==ERR_NOTAVAIL) { /* need to read more data */
vTaskDelay(pdMS_TO_TICKS(5));
} else if (res==ERR_FAILED) { /* not SDEP, forward to shell */
if (McuSDEP_txToShell_cb!=NULL) {
for(int i=0; i<bufIdx; i++) {
McuSDEP_txToShell_cb(buf[i]); /* forward character */
}
}
bufIdx = 0; /* start for new iteration */
} else if (res==ERR_OVERFLOW) { /* buffer overflow */
McuSDEP_SendError(io, McuSDEP_CMD_TYPE_ERROR_OVERFLOW);
bufIdx = 0; /* start for new iteration */
} else if (res==ERR_CRC) { /* CRC error*/
McuSDEP_SendError(io, McuSDEP_CMD_TYPE_ERROR_INVALIDCRC);
bufIdx = 0; /* start for new iteration */
}
} else {
vTaskDelay(pdMS_TO_TICKS(20));
timeoutMs += 20;
if (bufIdx>0 && timeoutMs>500) { /* we have data in the buffer and expect it an SDEP, but takes too long? */
/* abort and forward it */
if (McuSDEP_txToShell_cb!=NULL) {
for(int i=0; i<bufIdx; i++) {
McuSDEP_txToShell_cb(buf[i]); /* forward character */
}
}
bufIdx = 0; /* start for new iteration */
}
} /* if */
} /* for */
}
void McuSDEP_Deinit(void) {
/* \todo */
}
void McuSDEP_Init(void) {
#if McuSDEP_CONFIG_USE_FREERTOS
BaseType_t res = xTaskCreate(sdepTask, "sdepTask", 1*1024/sizeof(StackType_t), NULL, tskIDLE_PRIORITY+2, NULL);
if (res!=pdPASS) {
McuLog_fatal("creating sdepTask task failed!");
for(;;) {}
}
#endif
}
#endif /* McuSDEP_CONFIG_IS_ENABLED */

View File

@@ -0,0 +1,112 @@
/*
* Copyright (c) 2024, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
* SDEP (Simple Data Exchange Protocol) has been developed by Adafruit
* (see https://learn.adafruit.com/introducing-the-adafruit-bluefruit-spi-breakout/sdep-spi-data-transport)
*/
#ifndef _MCUSDEP_H_
#define _MCUSDEP_H_
#include "McuSDEPconfig.h"
#if McuSDEP_CONFIG_IS_ENABLED
#include <stdbool.h>
#include <stdint.h>
#include "McuShell.h"
#include "McuIO.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct McuSDEPmessage_t {
uint8_t type; /* message type, e.g. McuSDEP_MSG_TYPE_COMMAND */
uint16_t cmdId; /* command ID, e.g. McuSDEP_CMD_TYPE_PING */
uint8_t payloadSize; /* number of payload bytes */
uint8_t *payload; /* payload of data */
uint8_t crc; /* CRC8 of the message */
} McuSDEPmessage_t;
#define McuSDEP_MESSAGE_MAX_NOF_BYTES 131
#define McuSDEP_MESSAGE_MAX_PAYLOAD_BYTES 127
#define McuSDEP_PAYLOADBYTE_MORE_DATA_BIT 0x80
/* message types (U8) */
#define McuSDEP_MSG_TYPE_COMMAND 0x10
#define McuSDEP_MSG_TYPE_RESPONSE 0x20
#define McuSDEP_MSG_TYPE_ALERT 0x40
#define McuSDEP_MSG_TYPE_ERROR 0x80
#include "McuSDEP_IDs.h" /* application specific SDEP IDs */
/* --------------------------------------------------------------------------------- */
/* optional buffer incoming rx data for SDEP */
/* --------------------------------------------------------------------------------- */
void McuSDEP_SetSdepIO(McuIO_Desc_t *io);
McuIO_Desc_t *McuSDEP_GetSdepIO(void);
void McuSDEP_StoreCharInSdepBuffer(char ch);
/* --------------------------------------------------------------------------------- */
/*!
* \brief Set a callback to forward non-SDEP characters.
* \param forward_char_cb Callback to be called for forwarding. Can be NULL.
*/
void McuSDEP_SetForwardCharCallback(void (*forward_char_cb)(char));
/*!
* \brief Set a callback to get data into SDEP buffer.
* \param rx_cb Callback to be called for getting data. Can be NULL.
*/
void McuSDEP_SetRxToBufferCallback(int (*rx_cb)(void));
/*!
* \brief Send an SDEP message.
* \param io I/O to be used.
* \param msg Message to be sent.
* \return ERR_OK for success.
*/
uint8_t McuSDEP_SendMessage(McuIO_Desc_t *io, McuSDEPmessage_t *msg);
/*!
* \brief Shell command line handler
* \param cmd String to command to be parsed
* \param handled Returns if command has been handled
* \param io I/O channel
* \return Error code, ERR_OK if everything is ok
*/
uint8_t McuSDEP_ParseCommand(const uint8_t *cmd, bool *handled, McuShell_ConstStdIOType *io);
/*!
* \brief Set the current McuLog channel. Preferred to use RTT or a non-SDEP channel.
*/
void McuSDEP_SetLogChannel(uint8_t channel);
/*!
* \brief Get the current McuLog channel.
* \return The current log channel number.
*/
uint8_t McuSDEP_GetLogChannel(void);
/*!
* \brief Define which can be used to log an SDEP related message. That way does not interfer with SDEP communication channel.
*/
#define McuSDEP_Log(...) McuLog_ChannelLog(McuSDEP_GetLogChannel(), McuLog_TRACE, __BASE_FILE__, __LINE__, __VA_ARGS__)
/*!
* \brief Driver de-initialization.
*/
void McuSDEP_Deinit(void);
/*!
* \brief Driver initialization.
*/
void McuSDEP_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* McuSDEP_CONFIG_IS_ENABLED */
#endif /* _MCUSDEP_H_ */

View File

@@ -0,0 +1,195 @@
/*
* Copyright (c) 2019, Erich Styger
* All rights reserved.
*
* Driver for the SHT31 Temperature/Humidity sensor
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuSHT31config.h"
#include "McuSHT31.h"
#include "McuGenericI2C.h"
#include "McuUtility.h"
#include <stddef.h> /* for NULL */
#define SHT31_MEAS_HIGHREP_STRETCH 0x2C06
#define SHT31_MEAS_MEDREP_STRETCH 0x2C0D
#define SHT31_MEAS_LOWREP_STRETCH 0x2C10
#define SHT31_MEAS_HIGHREP 0x2400
#define SHT31_MEAS_MEDREP 0x240B
#define SHT31_MEAS_LOWREP 0x2416
#define SHT31_READSTATUS 0xF32D
#define SHT31_CLEARSTATUS 0x3041
#define SHT31_SOFTRESET 0x30A2
#define SHT31_HEATEREN 0x306D
#define SHT31_HEATERDIS 0x3066
/* status bits of the Status register (0xF32D) */
#define SHT31_STATUS_ALERT_PENDING (1<<15) /* 0: no pending alert, 1: at least one pending alert */
#define SHT31_STATUS_HEATER_ON (1<<13) /* 0: heater OFF, 1: heater ON */
#define SHT31_STATUS_RH_TRACKING_ALERT (1<<11) /* 0: no RH tracking alert, 1: alert */
#define SHT31_STATUS_T_TRACKING_ALERT (1<<10) /* 0: no T tracking alert, 1: alert */
#define SHT31_STATUS_SYSTEM_RESET (1<<4) /* 0: no reset detected since last clear status register command, 1: reset detected (hard reset, soft reset or supply fail */
#define SHT31_STATUS_CMD_STATUS (1<<1) /* 0: last command executed successfully; 1: last command not processed, it was either invalid, failed the internal command checksum */
#define SHT31_STATUS_WRITE_CRC_STATUS (1<<0) /* 0: checksum of last write transfer was correct, 1: checksum of last write transfer failed */
#define SHT31_CRC8_POLYNOMIAL 0x31 /* Seed for CRC polynomial */
#define SHT31_CRC8_INIT 0xFF /* Init value for CRC */
static uint8_t SHT31_GenerateCRC(uint8_t *data, uint8_t datalen) {
/* calculates 8-Bit checksum with given polynomial */
uint8_t crc = SHT31_CRC8_INIT;
uint8_t b;
uint8_t i;
for (i=0; i<datalen; i++) {
crc ^= data[i];
for (b=0; b<8; b++) {
if (crc & 0x80) {
crc = (crc<<1)^SHT31_CRC8_POLYNOMIAL;
} else {
crc <<= 1;
}
}
}
return crc;
}
static uint8_t SHT31_WriteCommand(uint16_t cmd) {
uint8_t buf[2];
buf[0] = cmd>>8;
buf[1] = cmd&0xff;
return McuGenericI2C_WriteAddress(McuSHT31_CONFIG_I2C_ADDR, buf, sizeof(buf), NULL, 0);
}
uint8_t SHT31_ReadStatus(uint16_t *status) {
uint8_t res;
uint8_t cmd[2];
uint8_t stat[3];
uint8_t crc;
cmd[0] = SHT31_READSTATUS>>8;
cmd[1] = SHT31_READSTATUS&0xff;
res = McuGenericI2C_ReadAddress(McuSHT31_CONFIG_I2C_ADDR, cmd, sizeof(cmd), stat, sizeof(stat));
if (res!=ERR_OK) {
*status = 0;
return res;
}
crc = SHT31_GenerateCRC(stat, 2);
if (crc!=stat[2]) {
return ERR_CRC; /* wrong CRC */
}
*status = (stat[0]<<8)+stat[1]; /* ignore CRC */
return res;
}
uint8_t McuSHT31_Heater(bool on) {
return SHT31_WriteCommand(on?SHT31_HEATEREN:SHT31_HEATERDIS);
}
uint8_t McuSHT31_Reset(void) {
return SHT31_WriteCommand(SHT31_SOFTRESET);
}
uint8_t McuSHT31_ReadTempHum(float *temperature, float *humidity) {
uint16_t ST, SRH;
uint8_t readbuffer[6];
uint8_t res;
uint8_t cmd[2];
cmd[0] = SHT31_MEAS_HIGHREP>>8;
cmd[1] = SHT31_MEAS_HIGHREP&0xff;
res = McuGenericI2C_ReadAddressWait(McuSHT31_CONFIG_I2C_ADDR, cmd, sizeof(cmd), McuSHT31_CONFIG_READ_WAIT_MS, readbuffer, sizeof(readbuffer));
if (res!=ERR_OK) {
return res;
}
ST = (readbuffer[0]<<8)|readbuffer[1];
if (readbuffer[2] != SHT31_GenerateCRC(readbuffer, 2)) {
return ERR_CRC;
}
SRH = (readbuffer[3]<<8)|readbuffer[4];
if (readbuffer[5] != SHT31_GenerateCRC(readbuffer+3, 2)) {
return ERR_CRC;
}
/* source: https://github.com/adafruit/Adafruit_SHT31/blob/master/Adafruit_SHT31.cpp */
int32_t stemp = (int32)ST;
/* simplified (65536 instead of 65535) integer version of:
* temp = (stemp * 175.0f) / 65535.0f - 45.0f;
*/
stemp = ((4375 * stemp) >> 14) - 4500;
*temperature = (float)stemp / 100.0f;
/* source: https://github.com/adafruit/Adafruit_SHT31/blob/master/Adafruit_SHT31.cpp */
uint32_t shum = (uint32_t)SRH;
/* simplified (65536 instead of 65535) integer version of:
* humidity = (shum * 100.0f) / 65535.0f;
*/
shum = (625 * shum) >> 12;
*humidity = (float)shum / 100.0f;
return ERR_OK;
}
#if MCUSHT31_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
uint8_t buf[32];
float temperature, humidity;
McuShell_SendStatusStr((unsigned char*)"SHT31", (unsigned char*)"Sensirion SHT31 sensor status\r\n", io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuSHT31_CONFIG_I2C_ADDR);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" addr", buf, io->stdOut);
if(McuSHT31_ReadTempHum(&temperature, &humidity)==ERR_OK) {
McuUtility_NumFloatToStr(buf, sizeof(buf), temperature, 2);
McuUtility_chcat(buf, sizeof(buf), '\xB0'); /* add '°' (ASCII 0xB0) it as single char, as with UTF-8 it might end up in two bytes inside a string */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"C\r\n");
McuShell_SendStatusStr((unsigned char*)" temp", buf, io->stdOut);
McuUtility_NumFloatToStr(buf, sizeof(buf), humidity, 2);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" RH\r\n");
McuShell_SendStatusStr((unsigned char*)" humidity", buf, io->stdOut);
} else {
McuShell_SendStatusStr((unsigned char*)" ERROR:", (unsigned char*)" *** ERROR reading sensor values\r\n", io->stdOut);
}
return ERR_OK;
}
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"SHT31", (unsigned char*)"Group of SHT31 commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
return ERR_OK;
}
#endif /* MCUSHT31_CONFIG_PARSE_COMMAND_ENABLED */
#if MCUSHT31_CONFIG_PARSE_COMMAND_ENABLED
uint8_t McuSHT31_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io) {
uint8_t res = ERR_OK;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP) == 0
|| McuUtility_strcmp((char*)cmd, "SHT31 help") == 0)
{
*handled = TRUE;
return PrintHelp(io);
} else if ( (McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0)
|| (McuUtility_strcmp((char*)cmd, "SHT31 status")==0)
)
{
*handled = TRUE;
res = PrintStatus(io);
}
return res;
}
#endif /* SHT31_CONFIG_PARSE_COMMAND_ENABLED */
void McuSHT31_Init(void) {
/* noting to do */
}
void McuSHT31_Deinit(void) {
/* nothing to do */
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright (c) 2019, Erich Styger
* All rights reserved.
*
* Driver for the Sensirion SHT31 Temperature/Humidity sensor
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef SOURCES_MCUSHT31_H_
#define SOURCES_MCUSHT31_H_
#include "McuSHT31config.h"
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
#if MCUSHT31_CONFIG_PARSE_COMMAND_ENABLED
#include "McuShell.h"
/*!
* \brief Shell command line handler
* \param cmd Pointer to the command string
* \param handled Return value to indicate if command has been recognized
* \param io I/O handler for input/output
* \return Error code, ERR_OK for no error
*/
uint8_t McuSHT31_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io);
#endif
/*!
* \brief Perform a soft reset
* \return Error code, ERR_OK for no error
*/
uint8_t McuSHT31_Reset(void);
/*!
* \brief Turn the heater on or off
* \param on If heater has to be turned on or off
* \return Error code, ERR_OK for no error
*/
uint8_t McuSHT31_Heater(bool on);
/*!
* \brief Reads the device status register
* \param status Where to store the status
* \return Error code, ERR_OK for no error
*/
uint8_t SHT31_ReadStatus(uint16_t *status);
/*!
* \brief Read temperature and relative humidity
* \param temperature Pointer to where to store the value
* \param humidity Pointer to where to store the value
* \return Error code, ERR_OK for no error
*/
uint8_t McuSHT31_ReadTempHum(float *temperature, float *humidity);
/*!
* \brief Module de-initialization
*/
void McuSHT31_Deinit(void);
/*!
* \brief Module initialization
*/
void McuSHT31_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* SOURCES_MCUSHT31_H_ */

View File

@@ -0,0 +1,212 @@
/*
* Copyright (c) 2019, 2022 Erich Styger
* All rights reserved.
*
* Driver for the Sensirion SHT40 Temperature/Humidity sensor
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "McuSHT40config.h"
#include "McuSHT40.h"
#include "McuGenericI2C.h"
#include "McuUtility.h"
#include <stddef.h> /* for NULL */
#define SHT40_MEAS_HIGHREP 0xFD
#define SHT40_MEAS_MEDREP 0xF6
#define SHT40_MEAS_LOWREP 0xE0
#define SHT40_READSERIALNUM 0x89
#define SHT40_SOFTRESET 0x94
#define SHT40_HEATER_200MW_1000MS_PRECISION_HIGH 0x39 /* activate heater with 200mW for 1s, including a high precision measurement just before deactivation */
#define SHT40_HEATER_200MW_100MS_PRECISION_HIGH 0x32 /* activate heater with 200mW for 0.1s, including a high precision measurement just before deactivation */
#define SHT40_HEATER_110MW_1000MS_PRECISION_HIGH 0x2F /* activate heater with 110mW for 1s, including a high precision measurement just before deactivation */
#define SHT40_HEATER_110MW_100MS_PRECISION_HIGH 0x24 /* activate heater with 110mW for 0.1s, including a high precision measurement just before deactivation */
#define SHT40_HEATER_20MW_1000MS_PRECISION_HIGH 0x1E /* activate heater with 20mW for 1s, including a high precision measurement just before deactivation */
#define SHT40_HEATER_20MW_100MS_PRECISION_HIGH 0x15 /* activate heater with 20mW for 0.1s, including a high precision measurement just before deactivation */
/* status bits of the Status register (0xF32D) */
#define SHT40_STATUS_ALERT_PENDING (1<<15) /* 0: no pending alert, 1: at least one pending alert */
#define SHT40_STATUS_HEATER_ON (1<<13) /* 0: heater OFF, 1: heater ON */
#define SHT40_STATUS_RH_TRACKING_ALERT (1<<11) /* 0: no RH tracking alert, 1: alert */
#define SHT40_STATUS_T_TRACKING_ALERT (1<<10) /* 0: no T tracking alert, 1: alert */
#define SHT40_STATUS_SYSTEM_RESET (1<<4) /* 0: no reset detected since last clear status register command, 1: reset detected (hard reset, soft reset or supply fail */
#define SHT40_STATUS_CMD_STATUS (1<<1) /* 0: last command executed successfully; 1: last command not processed, it was either invalid, failed the internal command checksum */
#define SHT40_STATUS_WRITE_CRC_STATUS (1<<0) /* 0: checksum of last write transfer was correct, 1: checksum of last write transfer failed */
#define SHT40_CRC8_POLYNOMIAL 0x31 /* Seed for CRC polynomial */
#define SHT40_CRC8_INIT 0xFF /* Init value for CRC */
static uint8_t SHT40_GenerateCRC(uint8_t *data, uint8_t datalen) {
/* calculates 8-Bit checksum with given polynomial */
uint8_t crc = SHT40_CRC8_INIT;
uint8_t b;
uint8_t i;
for (i=0; i<datalen; i++) {
crc ^= data[i];
for (b=0; b<8; b++) {
if (crc & 0x80) {
crc = (crc<<1)^SHT40_CRC8_POLYNOMIAL;
} else {
crc <<= 1;
}
}
}
return crc;
}
static uint8_t SHT40_WriteCommand(uint16_t cmd) {
uint8_t buf[2];
buf[0] = cmd>>8;
buf[1] = cmd&0xff;
return McuGenericI2C_WriteAddress(McuSHT40_CONFIG_I2C_ADDR, buf, sizeof(buf), NULL, 0);
}
uint8_t SHT40_ReadSerialNumber(uint32_t *serial) {
uint8_t res;
uint8_t cmd[1];
uint8_t readbuffer[6];
cmd[0] = SHT40_READSERIALNUM;
res = McuGenericI2C_ReadAddressWait(McuSHT40_CONFIG_I2C_ADDR, cmd, sizeof(cmd), 20, readbuffer, sizeof(readbuffer));
if (res!=ERR_OK) {
*serial = 0;
return res;
}
*serial = (readbuffer[0]<<24)|(readbuffer[1]<<16);
if (readbuffer[2] != SHT40_GenerateCRC(readbuffer, 2)) {
return ERR_CRC;
}
*serial |= (readbuffer[3]<<8)|readbuffer[4];
if (readbuffer[5] != SHT40_GenerateCRC(readbuffer+3, 2)) {
return ERR_CRC;
}
return res;
}
uint8_t McuSHT40_Reset(void) {
return SHT40_WriteCommand(SHT40_SOFTRESET);
}
uint8_t McuSHT40_ReadTempHum(float *temperature, float *humidity) {
float stemp, shum;
uint16_t ST, SRH;
uint8_t readbuffer[6];
uint8_t res;
uint8_t cmd[1];
cmd[0] = SHT40_MEAS_HIGHREP;
res = McuGenericI2C_ReadAddressWait(McuSHT40_CONFIG_I2C_ADDR, cmd, sizeof(cmd), 20, readbuffer, sizeof(readbuffer));
if (res!=ERR_OK) {
return res;
}
ST = (readbuffer[0]<<8)|readbuffer[1];
if (readbuffer[2] != SHT40_GenerateCRC(readbuffer, 2)) {
return ERR_CRC;
}
SRH = (readbuffer[3]<<8)|readbuffer[4];
if (readbuffer[5] != SHT40_GenerateCRC(readbuffer+3, 2)) {
return ERR_CRC;
}
stemp = ST;
stemp *= 175;
stemp /= 0xffff;
stemp = -45 + stemp;
*temperature = stemp;
shum = SRH;
shum *= 125;
shum /= 0xFFFF;
shum = -6 + shum;
if (shum>100.0f) {
shum = 100.0f;
} else if (shum<0.0f) {
shum = 0.0f;
}
*humidity = shum;
return ERR_OK;
}
#if MCUSHT40_CONFIG_PARSE_COMMAND_ENABLED
static uint8_t PrintStatus(const McuShell_StdIOType *io) {
uint8_t buf[32];
uint32_t serial;
float temperature, humidity;
uint8_t res;
McuShell_SendStatusStr((unsigned char*)"SHT40", (unsigned char*)"Sensirion SHT40 sensor status\r\n", io->stdOut);
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum8Hex(buf, sizeof(buf), McuSHT40_CONFIG_I2C_ADDR);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr((unsigned char*)" addr", buf, io->stdOut);
res = SHT40_ReadSerialNumber(&serial);
if (res==ERR_OK) {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"0x");
McuUtility_strcatNum32Hex(buf, sizeof(buf), serial);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
} else {
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"ERROR\r\n");
}
McuShell_SendStatusStr((unsigned char*)" serial", buf, io->stdOut);
if(McuSHT40_ReadTempHum(&temperature, &humidity)==ERR_OK) {
McuUtility_NumFloatToStr(buf, sizeof(buf), temperature, 2);
McuUtility_chcat(buf, sizeof(buf), '\xB0'); /* add '°' (ASCII 0xB0) it as single char, as with UTF-8 it might end up in two bytes inside a string */
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"C\r\n");
McuShell_SendStatusStr((unsigned char*)" temp", buf, io->stdOut);
McuUtility_NumFloatToStr(buf, sizeof(buf), humidity, 2);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" RH\r\n");
McuShell_SendStatusStr((unsigned char*)" humidity", buf, io->stdOut);
} else {
McuShell_SendStatusStr((unsigned char*)" ERROR:", (unsigned char*)" *** ERROR reading sensor values\r\n", io->stdOut);
}
return ERR_OK;
}
static uint8_t PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"SHT40", (unsigned char*)"Group of SHT40 commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
return ERR_OK;
}
#endif /* MCUSHT40_CONFIG_PARSE_COMMAND_ENABLED */
#if MCUSHT40_CONFIG_PARSE_COMMAND_ENABLED
uint8_t McuSHT40_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io) {
uint8_t res = ERR_OK;
if (McuUtility_strcmp((char*)cmd, McuShell_CMD_HELP) == 0
|| McuUtility_strcmp((char*)cmd, "SHT40 help") == 0)
{
*handled = TRUE;
return PrintHelp(io);
} else if ( (McuUtility_strcmp((char*)cmd, McuShell_CMD_STATUS)==0)
|| (McuUtility_strcmp((char*)cmd, "SHT40 status")==0)
)
{
*handled = TRUE;
res = PrintStatus(io);
}
return res;
}
#endif /* SHT40_CONFIG_PARSE_COMMAND_ENABLED */
void McuSHT40_Init(void) {
/* noting to do */
}
void McuSHT40_Deinit(void) {
/* nothing to do */
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 2019, 2022 Erich Styger
* All rights reserved.
*
* Driver for the Sensirion SHT40 Temperature/Humidity sensor
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef SOURCES_MCUSHT40_H_
#define SOURCES_MCUSHT40_H_
#include "McuSHT40config.h"
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
#if MCUSHT40_CONFIG_PARSE_COMMAND_ENABLED
#include "McuShell.h"
/*!
* \brief Shell command line handler
* \param cmd Pointer to the command string
* \param handled Return value to indicate if command has been recognized
* \param io I/O handler for input/output
* \return Error code, ERR_OK for no error
*/
uint8_t McuSHT40_ParseCommand(const unsigned char* cmd, bool *handled, const McuShell_StdIOType *io);
#endif
/*!
* \brief Perform a soft reset
* \return Error code, ERR_OK for no error
*/
uint8_t McuSHT40_Reset(void);
/*!
* \brief Read temperature and relative humidity
* \param temperature Pointer to where to store the value
* \param humidity Pointer to where to store the value
* \return Error code, ERR_OK for no error
*/
uint8_t McuSHT40_ReadTempHum(float *temperature, float *humidity);
/*!
* \brief Module de-initialization
*/
void McuSHT40_Deinit(void);
/*!
* \brief Module initialization
*/
void McuSHT40_Init(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* SOURCES_MCUSHT40_H_ */

Some files were not shown because too many files have changed in this diff Show More