From 261e0f9801abc7f6d13afcad51b5feadd19f50ee Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 4 Dec 2018 16:06:50 +0700 Subject: [PATCH] adding lpc40xx support --- hw/bsp/ea4088qs/board_ea4088qs.c | 53 + hw/bsp/ea4088qs/board_ea4088qs.h | 51 + hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c | 2 +- hw/bsp/readme.md | 11 +- hw/mcu/nxp/lpc_chip_40xx/.cproject | 219 ++ hw/mcu/nxp/lpc_chip_40xx/.project | 26 + hw/mcu/nxp/lpc_chip_40xx/inc/adc_17xx_40xx.h | 263 +++ hw/mcu/nxp/lpc_chip_40xx/inc/can_17xx_40xx.h | 1130 +++++++++++ hw/mcu/nxp/lpc_chip_40xx/inc/chip.h | 152 ++ .../nxp/lpc_chip_40xx/inc/chip_lpc175x_6x.h | 190 ++ .../nxp/lpc_chip_40xx/inc/chip_lpc177x_8x.h | 203 ++ .../nxp/lpc_chip_40xx/inc/chip_lpc407x_8x.h | 206 ++ .../nxp/lpc_chip_40xx/inc/clock_17xx_40xx.h | 896 +++++++++ hw/mcu/nxp/lpc_chip_40xx/inc/cmp_17xx_40xx.h | 408 ++++ hw/mcu/nxp/lpc_chip_40xx/inc/cmsis.h | 66 + hw/mcu/nxp/lpc_chip_40xx/inc/cmsis_40xx.h | 171 ++ hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4.h | 1772 +++++++++++++++++ hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4_simd.h | 673 +++++++ hw/mcu/nxp/lpc_chip_40xx/inc/core_cmFunc.h | 636 ++++++ hw/mcu/nxp/lpc_chip_40xx/inc/core_cmInstr.h | 688 +++++++ hw/mcu/nxp/lpc_chip_40xx/inc/crc_17xx_40xx.h | 236 +++ hw/mcu/nxp/lpc_chip_40xx/inc/dac_17xx_40xx.h | 166 ++ .../nxp/lpc_chip_40xx/inc/eeprom_17xx_40xx.h | 320 +++ hw/mcu/nxp/lpc_chip_40xx/inc/emc_17xx_40xx.h | 358 ++++ hw/mcu/nxp/lpc_chip_40xx/inc/enet_17xx_40xx.h | 914 +++++++++ hw/mcu/nxp/lpc_chip_40xx/inc/error.h | 184 ++ hw/mcu/nxp/lpc_chip_40xx/inc/fmc_17xx_40xx.h | 133 ++ hw/mcu/nxp/lpc_chip_40xx/inc/fpu_init.h | 52 + .../nxp/lpc_chip_40xx/inc/gpdma_17xx_40xx.h | 450 +++++ hw/mcu/nxp/lpc_chip_40xx/inc/gpio_17xx_40xx.h | 491 +++++ .../nxp/lpc_chip_40xx/inc/gpioint_17xx_40xx.h | 227 +++ hw/mcu/nxp/lpc_chip_40xx/inc/i2c_17xx_40xx.h | 541 +++++ hw/mcu/nxp/lpc_chip_40xx/inc/i2s_17xx_40xx.h | 534 +++++ hw/mcu/nxp/lpc_chip_40xx/inc/iap.h | 184 ++ .../nxp/lpc_chip_40xx/inc/iocon_17xx_40xx.h | 274 +++ hw/mcu/nxp/lpc_chip_40xx/inc/lcd_17xx_40xx.h | 387 ++++ hw/mcu/nxp/lpc_chip_40xx/inc/lpc_types.h | 216 ++ .../nxp/lpc_chip_40xx/inc/mcpwm_17xx_40xx.h | 80 + hw/mcu/nxp/lpc_chip_40xx/inc/pmu_17xx_40xx.h | 135 ++ hw/mcu/nxp/lpc_chip_40xx/inc/qei_17xx_40xx.h | 86 + hw/mcu/nxp/lpc_chip_40xx/inc/ring_buffer.h | 188 ++ .../nxp/lpc_chip_40xx/inc/ritimer_17xx_40xx.h | 199 ++ .../nxp/lpc_chip_40xx/inc/romapi_17xx_40xx.h | 91 + hw/mcu/nxp/lpc_chip_40xx/inc/rtc_17xx_40xx.h | 646 ++++++ hw/mcu/nxp/lpc_chip_40xx/inc/sdc_17xx_40xx.h | 583 ++++++ hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc.h | 450 +++++ .../nxp/lpc_chip_40xx/inc/sdmmc_17xx_40xx.h | 202 ++ hw/mcu/nxp/lpc_chip_40xx/inc/spi_17xx_40xx.h | 416 ++++ .../nxp/lpc_chip_40xx/inc/spifi_17xx_40xx.h | 79 + hw/mcu/nxp/lpc_chip_40xx/inc/ssp_17xx_40xx.h | 598 ++++++ hw/mcu/nxp/lpc_chip_40xx/inc/stopwatch.h | 137 ++ hw/mcu/nxp/lpc_chip_40xx/inc/sys_config.h | 42 + .../nxp/lpc_chip_40xx/inc/sysctl_17xx_40xx.h | 360 ++++ .../nxp/lpc_chip_40xx/inc/timer_17xx_40xx.h | 445 +++++ hw/mcu/nxp/lpc_chip_40xx/inc/uart_17xx_40xx.h | 814 ++++++++ hw/mcu/nxp/lpc_chip_40xx/inc/usb_17xx_40xx.h | 160 ++ hw/mcu/nxp/lpc_chip_40xx/inc/wwdt_17xx_40xx.h | 276 +++ hw/mcu/nxp/lpc_chip_40xx/src/adc_17xx_40xx.c | 256 +++ hw/mcu/nxp/lpc_chip_40xx/src/can_17xx_40xx.c | 1507 ++++++++++++++ hw/mcu/nxp/lpc_chip_40xx/src/chip_17xx_40xx.c | 110 + .../nxp/lpc_chip_40xx/src/clock_17xx_40xx.c | 516 +++++ hw/mcu/nxp/lpc_chip_40xx/src/cmp_17xx_40xx.c | 64 + hw/mcu/nxp/lpc_chip_40xx/src/crc_17xx_40xx.c | 110 + hw/mcu/nxp/lpc_chip_40xx/src/dac_17xx_40xx.c | 84 + .../nxp/lpc_chip_40xx/src/eeprom_17xx_40xx.c | 258 +++ hw/mcu/nxp/lpc_chip_40xx/src/emc_17xx_40xx.c | 282 +++ hw/mcu/nxp/lpc_chip_40xx/src/enet_17xx_40xx.c | 289 +++ hw/mcu/nxp/lpc_chip_40xx/src/fpu_init.c | 97 + .../nxp/lpc_chip_40xx/src/gpdma_17xx_40xx.c | 704 +++++++ hw/mcu/nxp/lpc_chip_40xx/src/gpio_17xx_40xx.c | 46 + .../nxp/lpc_chip_40xx/src/gpioint_17xx_40xx.c | 46 + hw/mcu/nxp/lpc_chip_40xx/src/i2c_17xx_40xx.c | 561 ++++++ hw/mcu/nxp/lpc_chip_40xx/src/i2s_17xx_40xx.c | 260 +++ hw/mcu/nxp/lpc_chip_40xx/src/iap.c | 175 ++ .../nxp/lpc_chip_40xx/src/iocon_17xx_40xx.c | 83 + hw/mcu/nxp/lpc_chip_40xx/src/lcd_17xx_40xx.c | 210 ++ hw/mcu/nxp/lpc_chip_40xx/src/pmu_17xx_40xx.c | 118 ++ hw/mcu/nxp/lpc_chip_40xx/src/ring_buffer.c | 167 ++ .../nxp/lpc_chip_40xx/src/ritimer_17xx_40xx.c | 100 + hw/mcu/nxp/lpc_chip_40xx/src/rtc_17xx_40xx.c | 221 ++ hw/mcu/nxp/lpc_chip_40xx/src/sdc_17xx_40xx.c | 247 +++ .../nxp/lpc_chip_40xx/src/sdmmc_17xx_40xx.c | 1196 +++++++++++ hw/mcu/nxp/lpc_chip_40xx/src/spi_17xx_40xx.c | 227 +++ hw/mcu/nxp/lpc_chip_40xx/src/ssp_17xx_40xx.c | 478 +++++ .../lpc_chip_40xx/src/stopwatch_17xx_40xx.c | 110 + .../nxp/lpc_chip_40xx/src/sysctl_17xx_40xx.c | 70 + .../nxp/lpc_chip_40xx/src/sysinit_17xx_40xx.c | 178 ++ .../nxp/lpc_chip_40xx/src/timer_17xx_40xx.c | 116 ++ hw/mcu/nxp/lpc_chip_40xx/src/uart_17xx_40xx.c | 533 +++++ hw/mcu/nxp/lpc_chip_40xx/src/wwdt_17xx_40xx.c | 72 + .../dcd_lpc17_40.c} | 1180 +++++------ .../dcd_lpc17_40.h} | 0 .../hal_lpc17_40.c} | 216 +- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 15 +- src/portable/nxp/lpc18_43/dcd_lpc18_43.h | 4 - src/tusb_option.h | 5 +- 96 files changed, 29667 insertions(+), 714 deletions(-) create mode 100644 hw/bsp/ea4088qs/board_ea4088qs.c create mode 100644 hw/bsp/ea4088qs/board_ea4088qs.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/.cproject create mode 100644 hw/mcu/nxp/lpc_chip_40xx/.project create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/adc_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/can_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/chip.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc175x_6x.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc177x_8x.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc407x_8x.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/clock_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/cmp_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/cmsis.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/cmsis_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4_simd.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/core_cmFunc.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/core_cmInstr.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/crc_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/dac_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/eeprom_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/emc_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/enet_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/error.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/fmc_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/fpu_init.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/gpdma_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/gpio_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/gpioint_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/i2c_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/i2s_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/iap.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/iocon_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/lcd_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/lpc_types.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/mcpwm_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/pmu_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/qei_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/ring_buffer.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/ritimer_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/romapi_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/rtc_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/sdc_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/spi_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/spifi_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/ssp_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/stopwatch.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/sys_config.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/sysctl_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/timer_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/uart_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/usb_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/inc/wwdt_17xx_40xx.h create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/adc_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/can_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/chip_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/clock_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/cmp_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/crc_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/dac_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/eeprom_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/emc_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/enet_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/fpu_init.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/gpdma_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/gpio_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/gpioint_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/i2c_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/i2s_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/iap.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/iocon_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/lcd_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/pmu_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/ring_buffer.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/ritimer_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/rtc_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/sdc_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/sdmmc_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/spi_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/ssp_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/stopwatch_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/sysctl_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/sysinit_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/timer_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/uart_17xx_40xx.c create mode 100644 hw/mcu/nxp/lpc_chip_40xx/src/wwdt_17xx_40xx.c rename src/portable/nxp/{lpc17xx/dcd_lpc175x_6x.c => lpc17_40/dcd_lpc17_40.c} (96%) rename src/portable/nxp/{lpc17xx/dcd_lpc175x_6x.h => lpc17_40/dcd_lpc17_40.h} (100%) rename src/portable/nxp/{lpc17xx/hal_lpc175x_6x.c => lpc17_40/hal_lpc17_40.c} (95%) diff --git a/hw/bsp/ea4088qs/board_ea4088qs.c b/hw/bsp/ea4088qs/board_ea4088qs.c new file mode 100644 index 000000000..9df56c183 --- /dev/null +++ b/hw/bsp/ea4088qs/board_ea4088qs.c @@ -0,0 +1,53 @@ +/**************************************************************************/ +/*! + @file board_ea4088qs.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. 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. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 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. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#ifdef BOARD_EA4088QS + +#include "../board.h" + +#define LED_PORT 0 +#define LED_PIN 22 + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ + + +//------------- IMPLEMENTATION -------------// + +#endif diff --git a/hw/bsp/ea4088qs/board_ea4088qs.h b/hw/bsp/ea4088qs/board_ea4088qs.h new file mode 100644 index 000000000..dc5854ada --- /dev/null +++ b/hw/bsp/ea4088qs/board_ea4088qs.h @@ -0,0 +1,51 @@ +/**************************************************************************/ +/*! + @file board_ea4088qs.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. 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. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 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. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ +#ifndef BOARD_EA4088QS_H_ +#define BOARD_EA4088QS_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "chip.h" + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_EA4088QS_H_ */ diff --git a/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c b/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c index 7e5529709..a17454d29 100644 --- a/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c +++ b/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c @@ -39,7 +39,7 @@ #ifdef BOARD_LPCXPRESSO1769 -#include "bsp/board.h" +#include "../board.h" #define LED_PORT 0 #define LED_PIN 22 diff --git a/hw/bsp/readme.md b/hw/bsp/readme.md index 3f6f7eb8a..4b4e928ae 100644 --- a/hw/bsp/readme.md +++ b/hw/bsp/readme.md @@ -6,11 +6,12 @@ This code base already had supported for a handful of boards. However due to my ### NXP MCU ### -- LPCXpresso 11U68 -- [**LPCXpresso 1347**](http://www.embeddedartists.com/products/lpcxpresso/lpc1347_xpr.php) with base board (for some peripherals to work) -- [**LPCXpresso 1769**](http://www.embeddedartists.com/products/lpcxpresso/lpc1347_xpr.php) with base board (for some peripherals to work) -- [Keil MCB1800 Evaluation Board](http://www.keil.com/mcb1800) -- [**Embedded Artists LPC4357 OEM & Base board**](http://www.embeddedartists.com/products/kits/lpc4357_kit.php) +- [**LPCXpresso 11U68**](https://www.nxp.com/support/developer-resources/evaluation-and-development-boards/lpcxpresso-boards/lpcxpresso-board-for-lpc11u68:OM13058) +- [**LPCXpresso 1347**](https://www.nxp.com/support/developer-resources/evaluation-and-development-boards/lpcxpresso-boards/lpcxpresso-board-for-lpc1347:OM13045) +- [**LPCXpresso 1769**](https://www.nxp.com/support/developer-resources/evaluation-and-development-boards/lpcxpresso-boards/lpcxpresso-board-for-lpc1769:OM13000) +- [**Keil MCB1800 Evaluation Board**](http://www.keil.com/mcb1800) +- [**Embedded Artists LPC4088 Quick Start board**](https://www.embeddedartists.com/products/lpc4088-quickstart-board) +- [**Embedded Artists LPC4357 Developer Kit**](http://www.embeddedartists.com/products/kits/lpc4357_kit.php) ### MicroChip SAMD ### diff --git a/hw/mcu/nxp/lpc_chip_40xx/.cproject b/hw/mcu/nxp/lpc_chip_40xx/.cproject new file mode 100644 index 000000000..debdb475a --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/.cproject @@ -0,0 +1,219 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <?xml version="1.0" encoding="UTF-8"?> +<TargetConfig> +<Properties property_0="" property_2="LPC177x_8x_407x_8x_512.cfx" property_3="NXP" property_4="LPC4088" property_count="5" version="70002"/> +<infoList vendor="NXP"> +<info chip="LPC4088" flash_driver="LPC177x_8x_407x_8x_512.cfx" match_id="0x481D3F47" name="LPC4088" stub="crt_emu_cm3_nxp"> +<chip> +<name>LPC4088</name> +<family>LPC407x_8x</family> +<vendor>NXP (formerly Philips)</vendor> +<reset board="None" core="Real" sys="Real"/> +<clock changeable="TRUE" freq="12MHz" is_accurate="TRUE"/> +<memory can_program="true" id="Flash" is_ro="true" type="Flash"/> +<memory id="RAM" type="RAM"/> +<memory id="Periph" is_volatile="true" type="Peripheral"/> +<memoryInstance derived_from="Flash" id="MFlash512" location="0x0" size="0x80000"/> +<memoryInstance derived_from="RAM" id="RamLoc64" location="0x10000000" size="0x10000"/> +<memoryInstance derived_from="RAM" id="RamPeriph32" location="0x20000000" size="0x8000"/> +<prog_flash blocksz="0x1000" location="0x0" maxprgbuff="0x1000" progwithcode="TRUE" size="0x10000"/> +<prog_flash blocksz="0x8000" location="0x10000" maxprgbuff="0x1000" progwithcode="TRUE" size="0x70000"/> +<peripheralInstance derived_from="V7M_MPU" determined="infoFile" id="MPU" location="0xe000ed90"/> +<peripheralInstance derived_from="V7M_NVIC" determined="infoFile" id="NVIC" location="0xe000e000"/> +<peripheralInstance derived_from="V7M_DCR" determined="infoFile" id="DCR" location="0xe000edf0"/> +<peripheralInstance derived_from="V7M_ITM" determined="infoFile" id="ITM" location="0xe0000000"/> +<peripheralInstance derived_from="FLASHCTRL" determined="infoFile" id="FLASHCTRL" location="0x200000"/> +<peripheralInstance derived_from="GPDMA" determined="infoFile" id="GPDMA" location="0x20080000"/> +<peripheralInstance derived_from="ETHERNET" determined="infoFile" id="ETHERNET" location="0x20084000"/> +<peripheralInstance derived_from="LCD" determined="infoFile" id="LCD" location="0x20088000"/> +<peripheralInstance derived_from="USB" determined="infoFile" id="USB" location="0x2008c000"/> +<peripheralInstance derived_from="CRC" determined="infoFile" id="CRC" location="0x20090000"/> +<peripheralInstance derived_from="GPIO" determined="infoFile" id="GPIO" location="0x20098000"/> +<peripheralInstance derived_from="EMC" determined="infoFile" id="EMC" location="0x2009c000"/> +<peripheralInstance derived_from="WWDT" determined="infoFile" id="WWDT" location="0x40000000"/> +<peripheralInstance derived_from="TIMER0" determined="infoFile" id="TIMER0" location="0x40004000"/> +<peripheralInstance derived_from="TIMER1" determined="infoFile" id="TIMER1" location="0x40008000"/> +<peripheralInstance derived_from="UART0" determined="infoFile" id="UART0" location="0x4000c000"/> +<peripheralInstance derived_from="UART1" determined="infoFile" id="UART1" location="0x40010000"/> +<peripheralInstance derived_from="PWM0" determined="infoFile" id="PWM0" location="0x40014000"/> +<peripheralInstance derived_from="PWM1" determined="infoFile" id="PWM1" location="0x40018000"/> +<peripheralInstance derived_from="I2C0" determined="infoFile" id="I2C0" location="0x4001c000"/> +<peripheralInstance derived_from="COMPARATOR" determined="infoFile" id="COMPARATOR" location="0x40020000"/> +<peripheralInstance derived_from="RTC" determined="infoFile" id="RTC" location="0x40024000"/> +<peripheralInstance derived_from="GPIOINT" determined="infoFile" id="GPIOINT" location="0x40028080"/> +<peripheralInstance derived_from="IOCON" determined="infoFile" id="IOCON" location="0x4002c000"/> +<peripheralInstance derived_from="SSP1" determined="infoFile" id="SSP1" location="0x40030000"/> +<peripheralInstance derived_from="ADC" determined="infoFile" id="ADC" location="0x40034000"/> +<peripheralInstance derived_from="CANAFRAM" determined="infoFile" id="CANAFRAM" location="0x40038000"/> +<peripheralInstance derived_from="CANAF" determined="infoFile" id="CANAF" location="0x4003c000"/> +<peripheralInstance derived_from="CCAN" determined="infoFile" id="CCAN" location="0x40040000"/> +<peripheralInstance derived_from="CAN1" determined="infoFile" id="CAN1" location="0x40044000"/> +<peripheralInstance derived_from="CAN2" determined="infoFile" id="CAN2" location="0x40048000"/> +<peripheralInstance derived_from="I2C1" determined="infoFile" id="I2C1" location="0x4005c000"/> +<peripheralInstance derived_from="SSP0" determined="infoFile" id="SSP0" location="0x40088000"/> +<peripheralInstance derived_from="DAC" determined="infoFile" id="DAC" location="0x4008c000"/> +<peripheralInstance derived_from="TIMER2" determined="infoFile" id="TIMER2" location="0x40090000"/> +<peripheralInstance derived_from="TIMER3" determined="infoFile" id="TIMER3" location="0x40094000"/> +<peripheralInstance derived_from="UART2" determined="infoFile" id="UART2" location="0x40098000"/> +<peripheralInstance derived_from="UART3" determined="infoFile" id="UART3" location="0x4009c000"/> +<peripheralInstance derived_from="I2C2" determined="infoFile" id="I2C2" location="0x400a0000"/> +<peripheralInstance derived_from="UART4" determined="infoFile" id="UART4" location="0x400a4000"/> +<peripheralInstance derived_from="I2S" determined="infoFile" id="I2S" location="0x400a8000"/> +<peripheralInstance derived_from="SSP2" determined="infoFile" id="SSP2" location="0x400ac000"/> +<peripheralInstance derived_from="MCPWM" determined="infoFile" id="MCPWM" location="0x400b8000"/> +<peripheralInstance derived_from="QEI" determined="infoFile" id="QEI" location="0x400bc000"/> +<peripheralInstance derived_from="SDMMC" determined="infoFile" id="SDMMC" location="0x400c0000"/> +<peripheralInstance derived_from="SYSCON" determined="infoFile" id="SYSCON" location="0x400fc000"/> +</chip> +<processor> +<name gcc_name="cortex-m4">Cortex-M4</name> +<family>Cortex-M</family> +</processor> +<link href="nxp_lpc407x_8x_peripheral.xme" show="embed" type="simple"/> +</info> +</infoList> +</TargetConfig> + + diff --git a/hw/mcu/nxp/lpc_chip_40xx/.project b/hw/mcu/nxp/lpc_chip_40xx/.project new file mode 100644 index 000000000..33c983c4b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/.project @@ -0,0 +1,26 @@ + + + lpc_chip_40xx + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/adc_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/adc_17xx_40xx.h new file mode 100644 index 000000000..7c705704c --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/adc_17xx_40xx.h @@ -0,0 +1,263 @@ +/* + * @brief LPC17xx/40xx A/D conversion driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __ADC_17XX_40XX_H_ +#define __ADC_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup ADC_17XX_40XX CHIP: LPC17xx/40xx A/D conversion driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#define ADC_ACC_12BITS +#define ADC_TRIM_SUPPORT + +#if defined(CHIP_LPC175X_6X) +#define ADC_MAX_SAMPLE_RATE 200000 +#else +#define ADC_MAX_SAMPLE_RATE 400000 +#endif + +/** + * @brief 10 or 12-bit ADC register block structure + */ +typedef struct { /*!< ADCn Structure */ + __IO uint32_t CR; /*!< A/D Control Register. The AD0CR register must be written to select the operating mode before A/D conversion can occur. */ + __I uint32_t GDR; /*!< A/D Global Data Register. Contains the result of the most recent A/D conversion. */ + __I uint32_t RESERVED0; + __IO uint32_t INTEN; /*!< A/D Interrupt Enable Register. This register contains enable bits that allow the DONE flag of each A/D channel to be included or excluded from contributing to the generation of an A/D interrupt. */ + __I uint32_t DR[8]; /*!< A/D Channel Data Register. This register contains the result of the most recent conversion completed on channel n. */ + __I uint32_t STAT; /*!< A/D Status Register. This register contains DONE and OVERRUN flags for all of the A/D channels, as well as the A/D interrupt flag. */ +#if defined(ADC_TRIM_SUPPORT) + __IO uint32_t ADTRM; +#endif +} LPC_ADC_T; + +/** + * @brief ADC register support bitfields and mask + */ +#if defined(ADC_ACC_12BITS) + #define ADC_DR_RESULT(n) ((((n) >> 4) & 0xFFF)) /*!< Mask for getting the 12 bits ADC data read value */ +#else + #define ADC_DR_RESULT(n) ((((n) >> 6) & 0x3FF)) /*!< Mask for getting the 10 bits ADC data read value */ + #define ADC_CR_BITACC(n) ((((n) & 0x7) << 17)) /*!< Number of ADC accuracy bits */ +#endif + +#define ADC_DR_DONE(n) (((n) >> 31)) /*!< Mask for reading the ADC done status */ +#define ADC_DR_OVERRUN(n) ((((n) >> 30) & (1UL))) /*!< Mask for reading the ADC overrun status */ +#define ADC_CR_CH_SEL(n) ((1UL << (n))) /*!< Selects which of the AD0.0:7 pins is (are) to be sampled and converted */ +#define ADC_CR_CLKDIV(n) ((((n) & 0xFF) << 8)) /*!< The APB clock (PCLK) is divided by (this value plus one) to produce the clock for the A/D */ +#define ADC_CR_BURST ((1UL << 16)) /*!< Repeated conversions A/D enable bit */ +#define ADC_CR_PDN ((1UL << 21)) /*!< ADC convert is operational */ +#define ADC_CR_START_MASK ((7UL << 24)) /*!< ADC start mask bits */ +#define ADC_CR_START_MODE_SEL(SEL) ((SEL << 24)) /*!< Select Start Mode */ +#define ADC_CR_START_NOW ((1UL << 24)) /*!< Start conversion now */ +#define ADC_CR_START_CTOUT15 ((2UL << 24)) /*!< Start conversion when the edge selected by bit 27 occurs on CTOUT_15 */ +#define ADC_CR_START_CTOUT8 ((3UL << 24)) /*!< Start conversion when the edge selected by bit 27 occurs on CTOUT_8 */ +#define ADC_CR_START_ADCTRIG0 ((4UL << 24)) /*!< Start conversion when the edge selected by bit 27 occurs on ADCTRIG0 */ +#define ADC_CR_START_ADCTRIG1 ((5UL << 24)) /*!< Start conversion when the edge selected by bit 27 occurs on ADCTRIG1 */ +#define ADC_CR_START_MCOA2 ((6UL << 24)) /*!< Start conversion when the edge selected by bit 27 occurs on Motocon PWM output MCOA2 */ +#define ADC_CR_EDGE ((1UL << 27)) /*!< Start conversion on a falling edge on the selected CAP/MAT signal */ +#if defined(ADC_ACC_12BITS) +#define ADC_SAMPLE_RATE_CONFIG_MASK (ADC_CR_CLKDIV(0xFF)) +#else +#define ADC_SAMPLE_RATE_CONFIG_MASK (ADC_CR_CLKDIV(0xFF) | ADC_CR_BITACC(0x07)) +#endif + +/** + * @brief ADC status register used for IP drivers + */ +typedef enum IP_ADC_STATUS { + ADC_DR_DONE_STAT, /*!< ADC data register staus */ + ADC_DR_OVERRUN_STAT,/*!< ADC data overrun staus */ + ADC_DR_ADINT_STAT /*!< ADC interrupt status */ +} ADC_STATUS_T; + +/** The channels on one ADC peripheral*/ +typedef enum CHIP_ADC_CHANNEL { + ADC_CH0 = 0, /**< ADC channel 0 */ + ADC_CH1, /**< ADC channel 1 */ + ADC_CH2, /**< ADC channel 2 */ + ADC_CH3, /**< ADC channel 3 */ + ADC_CH4, /**< ADC channel 4 */ + ADC_CH5, /**< ADC channel 5 */ + ADC_CH6, /**< ADC channel 6 */ + ADC_CH7, /**< ADC channel 7 */ +} ADC_CHANNEL_T; + +/** Edge configuration, which controls rising or falling edge on the selected signal for the start of a conversion */ +typedef enum CHIP_ADC_EDGE_CFG { + ADC_TRIGGERMODE_RISING = 0, /**< Trigger event: rising edge */ + ADC_TRIGGERMODE_FALLING, /**< Trigger event: falling edge */ +} ADC_EDGE_CFG_T; + +/** Start mode, which controls the start of an A/D conversion when the BURST bit is 0. */ +typedef enum CHIP_ADC_START_MODE { + ADC_NO_START = 0, + ADC_START_NOW, /*!< Start conversion now */ + ADC_START_ON_CTOUT15, /*!< Start conversion when the edge selected by bit 27 occurs on CTOUT_15 */ + ADC_START_ON_CTOUT8, /*!< Start conversion when the edge selected by bit 27 occurs on CTOUT_8 */ + ADC_START_ON_ADCTRIG0, /*!< Start conversion when the edge selected by bit 27 occurs on ADCTRIG0 */ + ADC_START_ON_ADCTRIG1, /*!< Start conversion when the edge selected by bit 27 occurs on ADCTRIG1 */ + ADC_START_ON_MCOA2 /*!< Start conversion when the edge selected by bit 27 occurs on Motocon PWM output MCOA2 */ +} ADC_START_MODE_T; + +/** Clock setup structure for ADC controller passed to the initialize function */ +typedef struct { + uint32_t adcRate; /*!< ADC rate */ + uint8_t bitsAccuracy; /*!< ADC bit accuracy */ + bool burstMode; /*!< ADC Burt Mode */ +} ADC_CLOCK_SETUP_T; + +/** + * @brief Initialize the ADC peripheral and the ADC setup structure to default value + * @param pADC : The base of ADC peripheral on the chip + * @param ADCSetup : ADC setup structure to be set + * @return Nothing + * @note Default setting for ADC is 400kHz - 10bits + */ +void Chip_ADC_Init(LPC_ADC_T *pADC, ADC_CLOCK_SETUP_T *ADCSetup); + +/** + * @brief Shutdown ADC + * @param pADC : The base of ADC peripheral on the chip + * @return Nothing + */ +void Chip_ADC_DeInit(LPC_ADC_T *pADC); + +/** + * @brief Read the ADC value from a channel + * @param pADC : The base of ADC peripheral on the chip + * @param channel : ADC channel to read + * @param data : Pointer to where to put data + * @return SUCCESS or ERROR if no conversion is ready + */ +Status Chip_ADC_ReadValue(LPC_ADC_T *pADC, uint8_t channel, uint16_t *data); + +/** + * @brief Read the ADC value and convert it to 8bits value + * @param pADC : The base of ADC peripheral on the chip + * @param channel: selected channel + * @param data : Storage for data + * @return Status : ERROR or SUCCESS + */ +Status Chip_ADC_ReadByte(LPC_ADC_T *pADC, ADC_CHANNEL_T channel, uint8_t *data); + +/** + * @brief Read the ADC channel status + * @param pADC : The base of ADC peripheral on the chip + * @param channel : ADC channel to read + * @param StatusType : Status type of ADC_DR_* + * @return SET or RESET + */ +FlagStatus Chip_ADC_ReadStatus(LPC_ADC_T *pADC, uint8_t channel, uint32_t StatusType); + +/** + * @brief Enable/Disable interrupt for ADC channel + * @param pADC : The base of ADC peripheral on the chip + * @param channel : ADC channel to read + * @param NewState : New state, ENABLE or DISABLE + * @return SET or RESET + */ +void Chip_ADC_Int_SetChannelCmd(LPC_ADC_T *pADC, uint8_t channel, FunctionalState NewState); + +/** + * @brief Enable/Disable global interrupt for ADC channel + * @param pADC : The base of ADC peripheral on the chip + * @param NewState : New state, ENABLE or DISABLE + * @return Nothing + */ +STATIC INLINE void Chip_ADC_Int_SetGlobalCmd(LPC_ADC_T *pADC, FunctionalState NewState) +{ + Chip_ADC_Int_SetChannelCmd(pADC, 8, NewState); +} + +/** + * @brief Select the mode starting the AD conversion + * @param pADC : The base of ADC peripheral on the chip + * @param mode : Stating mode, should be : + * - ADC_NO_START : Must be set for Burst mode + * - ADC_START_NOW : Start conversion now + * - ADC_START_ON_CTOUT15 : Start conversion when the edge selected by bit 27 occurs on CTOUT_15 + * - ADC_START_ON_CTOUT8 : Start conversion when the edge selected by bit 27 occurs on CTOUT_8 + * - ADC_START_ON_ADCTRIG0 : Start conversion when the edge selected by bit 27 occurs on ADCTRIG0 + * - ADC_START_ON_ADCTRIG1 : Start conversion when the edge selected by bit 27 occurs on ADCTRIG1 + * - ADC_START_ON_MCOA2 : Start conversion when the edge selected by bit 27 occurs on Motocon PWM output MCOA2 + * @param EdgeOption : Stating Edge Condition, should be : + * - ADC_TRIGGERMODE_RISING : Trigger event on rising edge + * - ADC_TRIGGERMODE_FALLING : Trigger event on falling edge + * @return Nothing + */ +void Chip_ADC_SetStartMode(LPC_ADC_T *pADC, ADC_START_MODE_T mode, ADC_EDGE_CFG_T EdgeOption); + +/** + * @brief Set the ADC Sample rate + * @param pADC : The base of ADC peripheral on the chip + * @param ADCSetup : ADC setup structure to be modified + * @param rate : Sample rate, should be set so the clock for A/D converter is less than or equal to 4.5MHz. + * @return Nothing + */ +void Chip_ADC_SetSampleRate(LPC_ADC_T *pADC, ADC_CLOCK_SETUP_T *ADCSetup, uint32_t rate); + +/** + * @brief Enable or disable the ADC channel on ADC peripheral + * @param pADC : The base of ADC peripheral on the chip + * @param channel : Channel to be enable or disable + * @param NewState : New state, should be: + * - ENABLE + * - DISABLE + * @return Nothing + */ +void Chip_ADC_EnableChannel(LPC_ADC_T *pADC, ADC_CHANNEL_T channel, FunctionalState NewState); + +/** + * @brief Enable burst mode + * @param pADC : The base of ADC peripheral on the chip + * @param NewState : New state, should be: + * - ENABLE + * - DISABLE + * @return Nothing + */ +void Chip_ADC_SetBurstCmd(LPC_ADC_T *pADC, FunctionalState NewState); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __ADC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/can_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/can_17xx_40xx.h new file mode 100644 index 000000000..e842dc27b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/can_17xx_40xx.h @@ -0,0 +1,1130 @@ +/* + * @brief LPC17xx/40xx CAN driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CAN_17XX_40XX_H_ +#define __CAN_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup CAN_17XX_40XX CHIP: LPC17xx/40xx CAN driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** The number of entry in AF RAM region */ +#define CANAF_RAM_ENTRY_NUM 512 + +/** + * @brief CAN AF RAM section definitions + */ +typedef enum { + CANAF_RAM_FULLCAN_SEC, /*!> 16) & 0xFF) + +/** CAN Current value of the Tx Error Counter */ +#define CAN_GSR_TXERR(n) ((uint32_t) ((n >> 24) & 0xFF) + +/* + * @brief CAN Interrupt and Capture register definitions + */ +/** CAN Interrupt and Capture Registe Bitmask */ +#define CAN_ICR_BITMASK (0xFFFF07FF) + +/** CAN Receive Interrupt (A new message was received)*/ +#define CAN_ICR_RI ((uint32_t) (1)) + +/** CAN Transmit Interrupt (Transmit buffer 1 is available) */ +#define CAN_ICR_TI1 ((uint32_t) (1 << 1)) + +/** CAN Error Warning Interrupt */ +#define CAN_ICR_EI ((uint32_t) (1 << 2)) + +/** CAN Data Overrun Interrupt */ +#define CAN_ICR_DOI ((uint32_t) (1 << 3)) + +/** CAN Wake-Up Interrupt */ +#define CAN_ICR_WUI ((uint32_t) (1 << 4)) + +/** CAN Error Passive Interrupt */ +#define CAN_ICR_EPI ((uint32_t) (1 << 5)) + +/** CAN Arbitration Lost Interrupt */ +#define CAN_ICR_ALI ((uint32_t) (1 << 6)) + +/** CAN Bus Error Interrupt */ +#define CAN_ICR_BEI ((uint32_t) (1 << 7)) + +/** CAN ID Ready Interrupt */ +#define CAN_ICR_IDI ((uint32_t) (1 << 8)) + +/** CAN Transmit Interrupt 2 (Transmit buffer 2 is available) */ +#define CAN_ICR_TI2 ((uint32_t) (1 << 9)) + +/** CAN Transmit Interrupt 3 (Transmit buffer 3 is available)*/ +#define CAN_ICR_TI3 ((uint32_t) (1 << 10)) + +/** CAN Error Code Capture (Error Location)*/ +#define CAN_ICR_ERRBIT_VAL(n) ((uint32_t) (((n) >> 16) & 0x1F)) +/** Start of Frame error value */ +#define CAN_ICR_ERR_SOF (3) +/** ID28...ID21 Error value */ +#define CAN_ICR_ERR_ID28_ID21 (2) +/** ID28...ID21 Error value */ +#define CAN_ICR_ERR_ID20_ID18 (6) +/**SRTR Bit Error value */ +#define CAN_ICR_ERR_SRTR (4) +/**IDE Bit Error value */ +#define CAN_ICR_ERR_IDE (5) +/** ID17...ID13 Error value */ +#define CAN_ICR_ERR_ID17_ID13 (7) +/** ID12...ID15 Error value */ +#define CAN_ICR_ERR_ID12_ID5 (0x0F) +/** ID4...ID0 Error value */ +#define CAN_ICR_ERR_ID4_ID0 (0x0E) +/**RTR Bit Error value */ +#define CAN_ICR_ERR_RTR (0x0C) +/**Reserved Bit 1 Error value */ +#define CAN_ICR_ERR_ReservedBit_1 (0x0D) +/**Reserved Bit 0 Error value */ +#define CAN_ICR_ERR_ReservedBit_0 (0x09) +/** DLC Error value */ +#define CAN_ICR_ERR_DLC (0x0B) +/** Data Field Error value */ +#define CAN_ICR_ERR_DATA_FIELD (0x0A) +/** CRC Sequence Error value */ +#define CAN_ICR_ERR_CRC_SEQ (0x08) +/** CRC Delimiter Error value */ +#define CAN_ICR_ERR_CRC_DELIMITER (0x18) +/** ACK Error value */ +#define CAN_ICR_ERR_ACK (0x19) +/** ACK Delimiter Error value */ +#define CAN_ICR_ERR_ACK_DELIMITER (0x1B) +/** EOF Error value */ +#define CAN_ICR_ERR_EOF (0x1A) +/** Intermission Error value */ +#define CAN_ICR_ERR_INTERMISSION (0x12) + +/** CAN Error Direction */ +#define CAN_ICR_ERRDIR_RECEIVE ((uint32_t) (1 << 21)) + +/** CAN Error Type Capture */ +#define CAN_ICR_ERRC_VAL(n) ((uint32_t) (((n) >> 22) & 0x3)) +#define CAN_ICR_BIT_ERROR (0) +#define CAN_ICR_FORM_ERROR (1) +#define CAN_ICR_STUFF_ERROR (2) +#define CAN_ICR_OTHER_ERROR (3) + +/** CAN Arbitration Lost Capture */ +#define CAN_ICR_ALCBIT_VAL(n) ((uint32_t) (((n) >> 24) & 0xFF)) + +/* + * @brief CAN Interrupt Enable register definitions + */ +/** CAN Interrupt Enable Register Bitmask */ +#define CAN_IER_BITMASK (0x7FF) + +/** CAN Receive Interrupt Enable */ +#define CAN_IER_RIE ((uint32_t) (1)) + +/** CAN Transmit Interrupt Enable for buffer 1 */ +#define CAN_IER_TIE1 ((uint32_t) (1 << 1)) + +/** CAN Error Warning Interrupt Enable */ +#define CAN_IER_EIE ((uint32_t) (1 << 2)) + +/** CAN Data Overrun Interrupt Enable */ +#define CAN_IER_DOIE ((uint32_t) (1 << 3)) + +/** CAN Wake-Up Interrupt Enable */ +#define CAN_IER_WUIE ((uint32_t) (1 << 4)) + +/** CAN Error Passive Interrupt Enable */ +#define CAN_IER_EPIE ((uint32_t) (1 << 5)) + +/** CAN Arbitration Lost Interrupt Enable */ +#define CAN_IER_ALIE ((uint32_t) (1 << 6)) + +/** CAN Bus Error Interrupt Enable */ +#define CAN_IER_BEIE ((uint32_t) (1 << 7)) + +/** CAN ID Ready Interrupt Enable */ +#define CAN_IER_IDIE ((uint32_t) (1 << 8)) + +/** CAN Transmit Enable Interrupt for Buffer 2 */ +#define CAN_IER_TIE2 ((uint32_t) (1 << 9)) + +/** CAN Transmit Enable Interrupt for Buffer 3 */ +#define CAN_IER_TIE3 ((uint32_t) (1 << 10)) + +/* + * @brief CAN Bus Timing register definitions + */ +/** CAN Bus Timing Register Bitmask */ +#define CAN_BTR_BITMASK (0xFFC3FF) + +/** CAN Baudrate Prescaler */ +#define CAN_BTR_BRP(n) ((uint32_t) ((n) & 0x3FF)) + +/** CAN Synchronization Jump Width */ +#define CAN_BTR_SJW(n) ((uint32_t) (((n) & 0x3) << 14)) + +/** CAN Time Segment 1 */ +#define CAN_BTR_TESG1(n) ((uint32_t) (((n) & 0xF) << 16)) + +/** CAN Time Segment 2 */ +#define CAN_BTR_TESG2(n) ((uint32_t) (((n) & 0xF) << 20)) + +/** CAN Sampling */ +#define CAN_BTR_SAM ((uint32_t) (1 << 23)) + +/* + * @brief CAN Error Warning Limit register definitions + */ +/** CAN Error Warning Limit Register Bitmask */ +#define CAN_EWL_BITMASK (0xFF) + +/** CAN Error Warning Limit */ +#define CAN_EWL_VAL(n) ((uint32_t) ((n) & 0xFF)) + +/* + * @brief CAN Status Registe definitions + */ +/** CAN Status Registe Bitmask */ +#define CAN_SR_BITMASK (0xFFFFFF) + +/** CAN Receive Buffer Status (Bit 0, 8, 16 are the same)*/ +#define CAN_SR_RBS(n) ((uint32_t) (1 << ((n) * 8))) + +/** CAN Data Overrun Status (Bit 1, 9, 17 are the same)*/ +#define CAN_SR_DOS(n) ((uint32_t) (1 << (1 + (n) * 8))) + +/** CAN Transmit Buffer Status (Tx Buffer n=0/1/2 is available)*/ +#define CAN_SR_TBS(n) ((uint32_t) (1 << (2 + (n) * 8))) + +/** CAN Transmission Complete Status (The request on Tx Buffer n=0/1/2 has been completed) */ +#define CAN_SR_TCS(n) ((uint32_t) (1 << (3 + (n) * 8))) + +/** CAN Receive Status (Bit 4, 12, 20 are the same)*/ +#define CAN_SR_RS(n) ((uint32_t) (1 << (4 + (n) * 8))) + +/** CAN Transmit Status (The CAN controller is sending a message in Tx Buffer n=0/1/2) */ +#define CAN_SR_TS(n) ((uint32_t) (1 << (5 + (n) * 8))) + +/** CAN Error Status (Bit 6, 14, 22 are the same)*/ +#define CAN_SR_ES(n) ((uint32_t) (1 << (6 + (n) * 8))) + +/** CAN Bus Status (Bit 7, 15, 23 are the same)*/ +#define CAN_SR_BS(n) ((uint32_t) (1 << (7 + (n) * 8))) + +/* + * @brief CAN Receive Frame Status register definitions + */ +/** CAN Receive Frame Status Register Bitmask */ +#define CAN_RFS_BITMASK (0xC00F07FF) + +/** CAN ID Index */ +#define CAN_RFS_ID_INDEX(n) ((uint32_t) ((n) & 0x3FF)) + +/** CAN Bypass */ +#define CAN_RFS_BP ((uint32_t) (1 << 10)) + +/** CAN Data Length Code */ +#define CAN_RFS_DLC(n) ((uint32_t) ((n >> 16) & 0x0F)) + +/** CAN Remote Transmission Request */ +#define CAN_RFS_RTR ((uint32_t) (1 << 30)) + +/** CAN control 11 bit or 29 bit Identifier */ +#define CAN_RFS_FF ((uint32_t) ((uint32_t) 1 << 31)) + +/* + * @brief CAN Receive Identifier Register definitions + */ +/** CAN 11 bit Identifier */ +#define CAN_RID_ID_11(n) ((uint32_t) ((n) & 0x7FF)) + +/** CAN 29 bit Identifier */ +#define CAN_RID_ID_29(n) ((uint32_t) ((n) & 0x1FFFFFFF)) + +/* + * @brief CAN Transmit Frame Information register definitions + */ +/** CAN Transmit Frame Information Register Bitmask */ +#define CAN_TFI_BITMASK (0xC00F00FF) + +/** CAN Priority */ +#define CAN_TFI_PRIO(n) ((uint32_t) ((n) & 0xFF)) + +/** CAN Data Length Code */ +#define CAN_TFI_DLC(n) ((uint32_t) (((n) & 0xF) << 16)) + +/** CAN Remote Frame Transmission */ +#define CAN_TFI_RTR ((uint32_t) (1 << 30)) + +/** CAN control 11-bit or 29-bit Identifier */ +#define CAN_TFI_FF ((uint32_t) ((uint32_t) 1 << 31)) + +/* + * @brief CAN Transfer Identifier register definitions + */ +/** CAN 11-bit Identifier */ +#define CAN_TID_ID11(n) ((uint32_t) ((n) & 0x7FF)) + +/** CAN 11-bit Identifier */ +#define CAN_TID_ID29(n) ((uint32_t) ((n) & 0x1FFFFFFF)) + +/* + * @brief CAN Central transmit Status register definitions + */ +/** CAN Central transmit Status Register Bitmask */ +#define CAN_TSR_BITMASK (0x30303) + +/** Bit indicate CAN n (0/1) is sending a message */ +#define CAN_TSR_TS(n) ((uint32_t) (1 << (n + 0))) + +/** Bit indicate all 3 Tx buffer of CAN n (0/1) are available */ +#define CAN_TSR_TBS(n) ((uint32_t) (1 << (n + 8))) + +/** Bit indicate all requested transmissions have been completed successfully by the CAN n(0/1) */ +#define CAN_TSR_TCS(n) ((uint32_t) (1 << (n + 16))) + +/* + * @brief CAN Central Receive Status register definitions + */ +/** CAN Central Receive Status Register Bitmask */ +#define CAN_RSR_BITMASK (0x30303) + +/** Bit indicate CAN n (0/1) is receiving a message */ +#define CAN_RSR_RS(n) ((uint32_t) (1 << (n + 0))) + +/** Bit indicate a received message is available in CAN n (0/1) */ +#define CAN_RSR_RBS(n) ((uint32_t) (1 << (n + 8))) + +/** Bit indicate a message was lost because the preceding message to CAN n(0/1) controller was not + read out quickly enough*/ +#define CAN_RSR_DOS(n) ((uint32_t) (1 << (n + 16))) + +/* + * @brief CAN Central Miscellaneous Status register definitions + */ +/** CAN Central Receive Status Register Bitmask */ +#define CAN_MSR_BITMASK (0x303) + +/** Bit indicate Tx/Rx Error Counter has reached the limit set in CAN n (0/1) */ +#define CAN_MSR_E(n) ((uint32_t) (1 << (n + 0))) + +/** Bit indicate CAN n (0/1) is currently involved in bus activities*/ +#define CAN_MSR_BS(n) ((uint32_t) (1 << (n + 8))) + +/* + * @brief Acceptance Filter Mode register definitions + */ +/** CAN Acceptance Filter Operation mode */ +#define CANAF_AFMR_OPERATION ((uint32_t) (0)) + +/** CAN Acceptance Filter Off mode */ +#define CANAF_AFMR_ACCOFF ((uint32_t) (1)) + +/** CAN Acceptance File Bypass mode */ +#define CANAF_AFMR_ACCBP ((uint32_t) (1 << 1)) + +/** FullCAN Mode Enhancements */ +#define CANAF_AFMR_EFCAN ((uint32_t) (1 << 2)) + +/* + * @brief Extended Frame Group Start Address register definitions + */ +/** The start address of the table of grouped Extended Identifier */ +#define CANAF_ENDADDR(n) ((uint32_t) (((n) & 0x3FF) << 2)) +#define CANAF_ENDADDR_VAL(n) ((uint32_t) ((n >> 2) & 0x3FF)) + +/* + * @brief LUT Error Address register definitions + */ +/** CAN Look-Up Table Error Address */ +#define CANAF_LUTERRAD(n) ((uint32_t) (((n) & 0x1FF) << 2)) + +/* + * @brief LUT Error register definitions + */ +/** CAN Look-Up Table Error */ +#define CANAF_LUTERR ((uint32_t) (1)) + +/* + * @brief Global FullCANInterrupt Enable register definitions + */ +/** Global FullCANInterrupt Enable Register Bitmask */ +#define CANAF_FCANIE_BITMASK (0x01) + +/** Global FullCANInterrupt Enable */ +#define CANAF_FCANIE ((uint32_t) (1)) + +/* + * @brief FullCAN Message Layout definitions + */ + +/** FF Bit Position*/ +#define CANAF_FULLCAN_MSG_FF_POS (31) +/** RTR Bit Position*/ +#define CANAF_FULLCAN_MSG_RTR_POS (30) +/** Message Lost Bit Position*/ +#define CANAF_FULLCAN_MSG_LOST_POS (26) +/** SEM Bit Position*/ +#define CANAF_FULLCAN_MSG_SEM_POS (24) +/** SEM Bit Mask*/ +#define CANAF_FULLCAN_MSG_SEM_BITMASK (0x03) +/** DLC Bit Position*/ +#define CANAF_FULLCAN_MSG_DLC_POS (16) +/** DLC Bit Mask*/ +#define CANAF_FULLCAN_MSG_DLC_BITMASK (0x0F) +/** SCC Bit Position*/ +#define CANAF_FULLCAN_MSG_SCC_POS (13) +/** SCC Bit Mask*/ +#define CANAF_FULLCAN_MSG_SCC_BITMASK (0x07) +/** 11bit-ID Bit Position*/ +#define CANAF_FULLCAN_MSG_ID11_POS (0) +/** 11bit-ID Bit Mask*/ +#define CANAF_FULLCAN_MSG_ID11_BITMASK (0x7FF) + +/* + * @brief FullCAN Message Status + */ +/** AF is updating FullCAN Message*/ +#define CANAF_FULCAN_MSG_AF_UPDATING (0x01) +/** AF has finished updating FullCAN Message*/ +#define CANAF_FULCAN_MSG_AF_FINISHED (0x03) +/** CPU is in process of reading FullCAN Message*/ +#define CANAF_FULCAN_MSG_CPU_READING (0x0) + +/* + * @brief FullCAN Interrupt and Capture register definitions + */ +/** FullCAN Interrupt and Capture (0-31)*/ +#define CANAF_FCAN_IC_INTPND(n) ((n >= 32) ? ((uint32_t) (1 << (n - 32))) : ((uint32_t) (1 << n))) + +/* + * @brief Standard ID Entry definitions + */ +/** Start position of Controller Number Bits */ +#define CAN_STD_ENTRY_CTRL_NO_POS (13 ) +/** Mask of Controller Number Bits */ +#define CAN_STD_ENTRY_CTRL_NO_MASK (0x07) +/** Start position of Disable bit */ +#define CAN_STD_ENTRY_DISABLE_POS (12 ) +/** Mask of Disable Bit */ +#define CAN_STD_ENTRY_DISABLE_MASK (0x01) +/** Start position of Interrupt Enable bit (FullCAN entry only)*/ +#define CAN_STD_ENTRY_IE_POS (11 ) +/** Mask of Interrupt Enable bit (FullCAN entry only)*/ +#define CAN_STD_ENTRY_IE_MASK (0x01) +/** Start position of ID bit */ +#define CAN_STD_ENTRY_ID_POS (0 ) +/** Mask of ID Bit */ +#define CAN_STD_ENTRY_ID_MASK (0x7FF) + +/* + * @brief Extended ID Entry definitions + */ +/** Start position of Controller Number Bits */ +#define CAN_EXT_ENTRY_CTRL_NO_POS (29 ) +/** Mask of Controller Number Bits */ +#define CAN_EXT_ENTRY_CTRL_NO_MASK (0x07) +/** Start position of ID bit */ +#define CAN_EXT_ENTRY_ID_POS (0 ) +/** Mask of ID Bit */ +#define CAN_EXT_ENTRY_ID_MASK (0x1FFFFFFF) + +/* + * @brief CAN Message Type definitions + */ + +/** Remote Message */ +#define CAN_REMOTE_MSG ((uint32_t) (1 << 0)) + +/** Message use Extend ID*/ +#define CAN_EXTEND_ID_USAGE ((uint32_t) (1 << 30)) + +/** The maximum data length in CAN Message */ +#define CAN_MSG_MAX_DATA_LEN (8) + +/** + * @brief CAN Buffer ID definition + */ +typedef enum { + CAN_BUFFER_1 = 0, /*!< Buffer 1 */ + CAN_BUFFER_2, /*!< Buffer 2 */ + CAN_BUFFER_3, /*!< Buffer 3 */ + CAN_BUFFER_LAST, /*!< Last Buffer */ +} CAN_BUFFER_ID_T; + +/** + * @brief CAN Message Object Structure + */ +typedef struct /*!< Message structure */ +{ + uint32_t ID; /*!< Message Identifier. If 30th-bit is set, this is 29-bit ID, othewise 11-bit ID */ + uint32_t Type; /*!< Message Type. which can include: - CAN_REMOTE_MSG type*/ + uint32_t DLC; /*!< Message Data Length: 0~8 */ + uint8_t Data[CAN_MSG_MAX_DATA_LEN];/*!< Message Data */ +} CAN_MSG_T; + +/** + * @brief CAN Bus Timing Structure + */ +typedef struct /*!< Bus Timing structure */ +{ + uint16_t BRP; /*!< Baud Rate Prescaler */ + uint8_t SJW; /*!< SJW value*/ + uint8_t TESG1; /*!< TESG1 value */ + uint8_t TESG2; /*!< TESG2 value */ + uint8_t SAM; /*!<0: The bus is sampled once, 1: sampled 3 times */ +} IP_CAN_BUS_TIMING_T; + +/** + * @brief Standard ID Entry structure + */ +typedef struct { + uint8_t CtrlNo; /*!CMR = command; +} + +/** + * @brief Set Error Warning Limit for the CAN Controller + * @param pCAN : Pointer to CAN peripheral block + * @param ewl : expected limit + * @return None + */ +STATIC INLINE void Chip_CAN_SetEWL(LPC_CAN_T *pCAN, uint32_t ewl) +{ + pCAN->EWL = ewl & CAN_EWL_BITMASK; +} + +/** + * @brief Get Error Warning Limit of the CAN Controller + * @param pCAN : Pointer to CAN peripheral block + * @return Error warning limit value + */ +STATIC INLINE uint8_t Chip_CAN_GetEWL(LPC_CAN_T *pCAN) +{ + return CAN_EWL_VAL(pCAN->EWL); +} + +/** + * @brief Get global status register contents of the CAN Controller + * @param pCAN : Pointer to CAN peripheral block + * @return Gloabl Status register contents (Or'ed bit values of CAN_GSR_*) + */ +STATIC INLINE uint32_t Chip_CAN_GetGlobalStatus(LPC_CAN_T *pCAN) +{ + return pCAN->GSR; +} + +/** + * @brief Get the status of the CAN Controller + * @param pCAN : Pointer to CAN controller register block + * @return Status (Or'ed bit values of CAN_SR_*(n) with n = CAN_BUFFER_1/2/3). + */ +STATIC INLINE uint32_t Chip_CAN_GetStatus(LPC_CAN_T *pCAN) +{ + return pCAN->SR; +} + +/** + * @brief Enable the CAN Interrupts + * @param pCAN : Pointer to CAN controller register block + * @param IntMask : Interrupt Mask (Or-ed bits value of CAN_IER_*) + * @return Nothing + */ +STATIC INLINE void Chip_CAN_EnableInt(LPC_CAN_T *pCAN, uint32_t IntMask) +{ + pCAN->IER |= IntMask; +} + +/** + * @brief Disable the CAN Interrupts + * @param pCAN : Pointer to CAN controller register block + * @param IntMask : Interrupt Mask (Or-ed bits value of CAN_IER_*) + * @return Nothing + */ +STATIC INLINE void Chip_CAN_DisableInt(LPC_CAN_T *pCAN, uint32_t IntMask) +{ + pCAN->IER &= (~IntMask) & CAN_IER_BITMASK; +} + +/** + * @brief Get interrupt status of the given CAN Controller + * @param pCAN : Pointer to CAN controller register block + * @return Status (Or'ed bit values of CAN_ICR_* ) + */ +STATIC INLINE uint32_t Chip_CAN_GetIntStatus(LPC_CAN_T *pCAN) +{ + return pCAN->ICR; +} + +/** + * @brief Enable/Disable CAN controller FullCAN Interrupts + * @param pCANAF : Pointer to CAN AF Register block + * @param NewState : Enable/Disable + * @return Nothing + */ +void Chip_CAN_ConfigFullCANInt(LPC_CANAF_T *pCANAF, FunctionalState NewState); + +/** + * @brief Get FullCAN interrupt status of the given object + * @param pCANAF : Pointer to CAN AF Register block + * @param ObjID : Object ID + * @return Status + */ +uint32_t Chip_CAN_GetFullCANIntStatus(LPC_CANAF_T *pCANAF, uint8_t ObjID); + +/** + * @brief Set CAN controller enter/exit to a given mode + * @param pCAN : Pointer to CAN controller register block + * @param Mode : Mode selected + * @param NewState : ENABLE: enter, DISABLE: exit + * @return None + */ +void Chip_CAN_SetMode(LPC_CAN_T *pCAN, CAN_MODE_T Mode, FunctionalState NewState); + +/** + * @brief Get current mode register settings of the CAN controller + * @param pCAN : Pointer to CAN peripheral block + * @return Current Mode register value of the CAN Controller (Bit values of CAN_MOD_*) + */ +STATIC INLINE CAN_MODE_T Chip_CAN_GetMode(LPC_CAN_T *pCAN) +{ + return (CAN_MODE_T) (pCAN->MOD & CAN_MOD_BITMASK); +} + +/** + * @brief Set CAN AF Mode + * @param pCANAF : Pointer to CAN AF Register block + * @param AfMode : Mode selected + * @return None + */ +STATIC INLINE void Chip_CAN_SetAFMode(LPC_CANAF_T *pCANAF, CAN_AF_MODE_T AfMode) +{ + pCANAF->AFMR = AfMode; +} + +/** + * @brief Get CAN AF Mode + * @param pCanAF : Pointer to CAN AF Register block + * @return Mode + */ +STATIC INLINE CAN_AF_MODE_T Chip_CAN_GetAFMode(LPC_CANAF_T *pCanAF) +{ + return (CAN_AF_MODE_T) pCanAF->AFMR; +} + +/** + * @brief Set CAN AF LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param pAFSections : Pointer to buffer storing AF Section Data + * @return SUCCESS/ERROR + */ +Status Chip_CAN_SetAFLUT(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CANAF_LUT_T *pAFSections); + +/** + * @brief Insert a FullCAN Entry into the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param pEntry : Pointer to the entry which will be inserted + * @return SUCCESS/ERROR + */ +Status Chip_CAN_InsertFullCANEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CAN_STD_ID_ENTRY_T *pEntry); + +/** + * @brief Insert an individual Standard Entry into the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param pEntry : Pointer to the entry which will be inserted + * @return SUCCESS/ERROR + */ +Status Chip_CAN_InsertSTDEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CAN_STD_ID_ENTRY_T *pEntry); + +/** + * @brief Insert an Group Standard Entry into the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param pEntry : Pointer to the entry which will be inserted + * @return SUCCESS/ERROR + */ +Status Chip_CAN_InsertGroupSTDEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CAN_STD_ID_RANGE_ENTRY_T *pEntry); + +/** + * @brief Insert an individual Extended Entry into the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param pEntry : Pointer to the entry which will be inserted + * @return SUCCESS/ERROR + */ +Status Chip_CAN_InsertEXTEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CAN_EXT_ID_ENTRY_T *pEntry); + +/** + * @brief Insert an Group Extended Entry into the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param pEntry : Pointer to the entry which will be inserted + * @return SUCCESS/ERROR + */ +Status Chip_CAN_InsertGroupEXTEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CAN_EXT_ID_RANGE_ENTRY_T *pEntry); + +/** + * @brief Remove a FullCAN Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry removed + * @return SUCCESS/ERROR + */ +Status Chip_CAN_RemoveFullCANEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, int16_t Position); + +/** + * @brief Remove an individual Standard Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry removed + * @return SUCCESS/ERROR + */ +Status Chip_CAN_RemoveSTDEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, int16_t Position); + +/** + * @brief Remove an Group Standard Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry removed + * @return SUCCESS/ERROR + */ +Status Chip_CAN_RemoveGroupSTDEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, int16_t Position); + +/** + * @brief Remove an individual Extended Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry removed + * @return SUCCESS/ERROR + */ +Status Chip_CAN_RemoveEXTEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, int16_t Position); + +/** + * @brief Remove an Group Extended Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry removed + * @return SUCCESS/ERROR + */ +Status Chip_CAN_RemoveGroupEXTEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, int16_t Position); + +/** + * @brief Get the number of entries in the given section + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param SectionID : Section ID + * @return Number of entries + */ +uint16_t Chip_CAN_GetEntriesNum(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CANAF_RAM_SECTION_T SectionID); + +/** + * @brief Read a FullCAN Entry into from current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry in the given section (started from 0) + * @param pEntry : Pointer to the entry which will be read + * @return SUCCESS/ERROR + */ +Status Chip_CAN_ReadFullCANEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, uint16_t Position, + CAN_STD_ID_ENTRY_T *pEntry); + +/** + * @brief Read an individual Standard Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry in the given section (started from 0) + * @param pEntry : Pointer to the entry which will be read + * @return SUCCESS/ERROR + */ +Status Chip_CAN_ReadSTDEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, uint16_t Position, + CAN_STD_ID_ENTRY_T *pEntry); + +/** + * @brief Read an Group Standard Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry in the given section (started from 0) + * @param pEntry : Pointer to the entry which will be read + * @return SUCCESS/ERROR + */ +Status Chip_CAN_ReadGroupSTDEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, uint16_t Position, + CAN_STD_ID_RANGE_ENTRY_T *pEntry); + +/** + * @brief Read an individual Extended Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry in the given section (started from 0) + * @param pEntry : Pointer to the entry which will be read + * @return SUCCESS/ERROR + */ +Status Chip_CAN_ReadEXTEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, uint16_t Position, + CAN_EXT_ID_ENTRY_T *pEntry); + +/** + * @brief Read an Group Extended Entry from the current LUT + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param Position : Position of the entry in the given section (started from 0) + * @param pEntry : Pointer to the entry which will be read + * @return SUCCESS/ERROR + */ +Status Chip_CAN_ReadGroupEXTEntry(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, uint16_t Position, + CAN_EXT_ID_RANGE_ENTRY_T *pEntry); + +/** + * @brief Initialize CAN Interface + * @param pCAN : Pointer to CAN controller register block + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @return Nothing + */ +void Chip_CAN_Init(LPC_CAN_T *pCAN, LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam); + +/** + * @brief De-Initialize CAN Interface + * @param pCAN : Pointer to CAN controller register block + * @return Nothing + */ +void Chip_CAN_DeInit(LPC_CAN_T *pCAN); + +/** + * @brief Set CAN bitrate + * @param pCAN : Pointer to CAN controller register block + * @param BitRate : Expected bitrate + * @return SUCCESS/ERROR + */ +Status Chip_CAN_SetBitRate(LPC_CAN_T *pCAN, uint32_t BitRate); + +/** + * @brief Get Free TxBuffer + * @param pCAN : Pointer to CAN controller register block + * @return Buffer ID + */ +CAN_BUFFER_ID_T Chip_CAN_GetFreeTxBuf(LPC_CAN_T *pCAN); + +/** + * @brief Request the given CAN Controller to send message + * @param pCAN : Pointer to CAN controller register block + * @param TxBufID : ID of the buffer which will be used for transmission + * @param pMsg : Pointer to the buffer of message which will be sent + * @return SUCCESS (message information saved) or ERROR (no message received) + */ +Status Chip_CAN_Send(LPC_CAN_T *pCAN, CAN_BUFFER_ID_T TxBufID, CAN_MSG_T *pMsg); + +/** + * @brief Get message received by the CAN Controller + * @param pCAN : Pointer to CAN controller register block + * @param pMsg : Pointer to the buffer storing the information of the received message + * @return SUCCESS (message information saved) or ERROR (no message received) + */ +Status Chip_CAN_Receive(LPC_CAN_T *pCAN, CAN_MSG_T *pMsg); + +/** + * @brief Get message received automatically by the AF + * @param pCANAF : Pointer to CAN AF Register block + * @param pCANAFRam : Pointer to CAN AF RAM Register block + * @param ObjID : Object ID + * @param pMsg : Pointer to the buffer storing the information of the received message + * @param pSCC : Pointer to the buffer storing the controller ID of the received message + * @return SUCCESS (message information saved) or ERROR (no message received) + */ +Status Chip_CAN_FullCANReceive(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + uint8_t ObjID, + CAN_MSG_T *pMsg, + uint8_t *pSCC); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CAN_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/chip.h b/hw/mcu/nxp/lpc_chip_40xx/inc/chip.h new file mode 100644 index 000000000..e63ae952c --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/chip.h @@ -0,0 +1,152 @@ +/* + * @brief LPC17xx/LPC40xx basic chip inclusion file + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CHIP_H_ +#define __CHIP_H_ + +#include "lpc_types.h" +#include "sys_config.h" +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @ingroup CHIP_17XX_40XX_DRIVER_OPTIONS + * @{ + */ + +/** + * @brief System oscillator rate + * This value is defined externally to the chip layer and contains + * the value in Hz for the external oscillator for the board. If using the + * internal oscillator, this rate can be 0. + */ +extern const uint32_t OscRateIn; + +/** + * @brief RTC oscillator rate + * This value is defined externally to the chip layer and contains + * the value in Hz for the RTC oscillator for the board. This is + * usually 32KHz (32768). If not using the RTC, this rate can be 0. + */ +extern const uint32_t RTCOscRateIn; + +/** + * @} + */ + +/** @defgroup SUPPORT_17XX_40XX_FUNC CHIP: LPC17xx/40xx support functions + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief Current system clock rate, mainly used for sysTick + */ +extern uint32_t SystemCoreClock; + +/** + * @brief Update system core clock rate, should be called if the + * system has a clock rate change + * @return None + */ +void SystemCoreClockUpdate(void); + +/** + * @brief Set up and initialize hardware prior to call to main() + * @return None + * @note Chip_SystemInit() is called prior to the application and sets up + * system clocking prior to the application starting. + */ +void Chip_SystemInit(void); + +/** + * @brief USB Pin and clock initialization + * Calling this function will initialize the USB pins and the clock + * @return None + * @note This function will assume that the chip is clocked by an + * external crystal oscillator of frequency 12MHz and the Oscillator + * is running. + */ +void Chip_USB_Init(void); + +/** + * @brief Clock and PLL initialization based on the external oscillator + * @return None + * @note This function assumes an external crystal oscillator + * frequency of 12MHz. + */ +void Chip_SetupXtalClocking(void); + +/** + * @brief Clock and PLL initialization based on the internal oscillator + * @return None + */ +void Chip_SetupIrcClocking(void); + +/** + * @} + */ + +#if defined(CHIP_LPC175X_6X) || defined(CHIP_LPC177X_8X) + +#ifndef CORE_M3 +#error CORE_M3 is not defined for the LPC17xx architecture +#error CORE_M3 should be defined as part of your compiler define list +#endif + +#elif defined(CHIP_LPC40XX) + +#ifndef CORE_M4 +#error CORE_M4 is not defined for the LPC40xx architecture +#error CORE_M4 should be defined as part of your compiler define list +#endif + +#elif defined(CHIP_LPC40XX) +#error CHIP_LPC175X_6X/CHIP_LPC177X_8X/CHIP_LPC40XX is not defined! +#endif + +#if defined(CHIP_LPC175X_6X) +#include "chip_lpc175x_6x.h" + +#elif defined(CHIP_LPC177X_8X) +#include "chip_lpc177x_8x.h" + +#elif defined(CHIP_LPC40XX) +#include "chip_lpc407x_8x.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __CHIP_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc175x_6x.h b/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc175x_6x.h new file mode 100644 index 000000000..c7280a8a6 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc175x_6x.h @@ -0,0 +1,190 @@ +/* + * @brief LPC175x/6x basic chip inclusion file + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CHIP_LPC175X_6X_H_ +#define __CHIP_LPC175X_6X_H_ + +#include "lpc_types.h" +#include "sys_config.h" +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(CORE_M3) +#error CORE_M3 is not defined for the LPC175x/6x architecture +#error CORE_M3 should be defined as part of your compiler define list +#endif + +#ifndef CHIP_LPC175X_6X +#error CHIP_LPC175X_6X is not defined! +#endif + +/** @defgroup PERIPH_175X_6X_BASE CHIP: LPC175x/6x Peripheral addresses and register set declarations + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#define LPC_GPIO0_BASE 0x2009C000 +#define LPC_GPIO1_BASE 0x2009C020 +#define LPC_GPIO2_BASE 0x2009C040 +#define LPC_GPIO3_BASE 0x2009C060 +#define LPC_GPIO4_BASE 0x2009C080 + +/* APB0 peripheral */ +#define LPC_WWDT_BASE 0x40000000 +#define LPC_TIMER0_BASE 0x40004000 +#define LPC_TIMER1_BASE 0x40008000 +#define LPC_UART0_BASE 0x4000C000 +#define LPC_UART1_BASE 0x40010000 +#define LPC_PWM1_BASE 0x40018000 +#define LPC_I2C0_BASE 0x4001C000 +#define LPC_SPI_BASE 0x40020000 +#define LPC_RTC_BASE 0x40024000 +#define LPC_REGFILE_BASE 0x40024044 +#define LPC_GPIOINT_BASE 0x40028080 +#define LPC_IOCON_BASE 0x4002C000 +#define LPC_SSP1_BASE 0x40030000 +#define LPC_ADC_BASE 0x40034000 +#define LPC_CANAF_RAM_BASE 0x40038000 +#define LPC_CANAF_BASE 0x4003C000 +#define LPC_CANCR_BASE 0x40040000 +#define LPC_CAN1_BASE 0x40044000 +#define LPC_CAN2_BASE 0x40048000 +#define LPC_I2C1_BASE 0x4005C000 + +/* APB1 peripheral */ +#define LPC_FMC_BASE 0x40084000 +#define LPC_SSP0_BASE 0x40088000 +#define LPC_DAC_BASE 0x4008C000 +#define LPC_TIMER2_BASE 0x40090000 +#define LPC_TIMER3_BASE 0x40094000 +#define LPC_UART2_BASE 0x40098000 +#define LPC_UART3_BASE 0x4009C000 +#define LPC_I2C2_BASE 0x400A0000 +#define LPC_I2S_BASE 0x400A8000 +#define LPC_RITIMER_BASE 0x400B0000 +#define LPC_MCPWM_BASE 0x400B8000 +#define LPC_QEI_BASE 0x400BC000 +#define LPC_SYSCTL_BASE 0x400FC000 +#define LPC_PMU_BASE 0x400FC0C0 + +/* AHB peripheral */ +#define LPC_ENET_BASE 0x50000000 +#define LPC_GPDMA_BASE 0x50004000 +#define LPC_USB_BASE 0x5000C000 + +/* Assign LPC_* names to structures mapped to addresses */ +#define LPC_PMU ((LPC_PMU_T *) LPC_PMU_BASE) +#define LPC_GPDMA ((LPC_GPDMA_T *) LPC_GPDMA_BASE) +#define LPC_USB ((LPC_USB_T *) LPC_USB_BASE) +#define LPC_ETHERNET ((LPC_ENET_T *) LPC_ENET_BASE) +#define LPC_GPIO ((LPC_GPIO_T *) LPC_GPIO0_BASE) +#define LPC_GPIO1 ((LPC_GPIO_T *) LPC_GPIO1_BASE) +#define LPC_GPIO2 ((LPC_GPIO_T *) LPC_GPIO2_BASE) +#define LPC_GPIO3 ((LPC_GPIO_T *) LPC_GPIO3_BASE) +#define LPC_GPIO4 ((LPC_GPIO_T *) LPC_GPIO4_BASE) +#define LPC_GPIOINT ((LPC_GPIOINT_T *) LPC_GPIOINT_BASE) +#define LPC_RTC ((LPC_RTC_T *) LPC_RTC_BASE) +#define LPC_REGFILE ((LPC_REGFILE_T *) LPC_REGFILE_BASE) +#define LPC_WWDT ((LPC_WWDT_T *) LPC_WWDT_BASE) +#define LPC_UART0 ((LPC_USART_T *) LPC_UART0_BASE) +#define LPC_UART1 ((LPC_USART_T *) LPC_UART1_BASE) +#define LPC_UART2 ((LPC_USART_T *) LPC_UART2_BASE) +#define LPC_UART3 ((LPC_USART_T *) LPC_UART3_BASE) +#define LPC_SPI ((LPC_SPI_T *) LPC_SPI_BASE) +#define LPC_SSP0 ((LPC_SSP_T *) LPC_SSP0_BASE) +#define LPC_SSP1 ((LPC_SSP_T *) LPC_SSP1_BASE) +#define LPC_TIMER0 ((LPC_TIMER_T *) LPC_TIMER0_BASE) +#define LPC_TIMER1 ((LPC_TIMER_T *) LPC_TIMER1_BASE) +#define LPC_TIMER2 ((LPC_TIMER_T *) LPC_TIMER2_BASE) +#define LPC_TIMER3 ((LPC_TIMER_T *) LPC_TIMER3_BASE) +#define LPC_MCPWM ((LPC_MCPWM_T *) LPC_MCPWM_BASE) +#define LPC_I2C0 ((LPC_I2C_T *) LPC_I2C0_BASE) +#define LPC_I2C1 ((LPC_I2C_T *) LPC_I2C1_BASE) +#define LPC_I2C2 ((LPC_I2C_T *) LPC_I2C2_BASE) +#define LPC_I2S ((LPC_I2S_T *) LPC_I2S_BASE) +#define LPC_QEI ((LPC_QEI_T *) LPC_QEI_BASE) +#define LPC_DAC ((LPC_DAC_T *) LPC_DAC_BASE) +#define LPC_ADC ((LPC_ADC_T *) LPC_ADC_BASE) +#define LPC_IOCON ((LPC_IOCON_T *) LPC_IOCON_BASE) +#define LPC_SYSCTL ((LPC_SYSCTL_T *) LPC_SYSCTL_BASE) +#define LPC_SYSCON ((LPC_SYSCTL_T *) LPC_SYSCTL_BASE) /* Alias for LPC_SYSCTL */ +#define LPC_CANAF_RAM ((LPC_CANAF_RAM_T *) LPC_CANAF_RAM_BASE) +#define LPC_CANAF ((LPC_CANAF_T *) LPC_CANAF_BASE) +#define LPC_CANCR ((LPC_CANCR_T *) LPC_CANCR_BASE) +#define LPC_CAN1 ((LPC_CAN_T *) LPC_CAN1_BASE) +#define LPC_CAN2 ((LPC_CAN_T *) LPC_CAN2_BASE) +#define LPC_RITIMER ((LPC_RITIMER_T *) LPC_RITIMER_BASE) +#define LPC_FMC ((LPC_FMC_T *) LPC_FMC_BASE) + +/* IRQ Handler Alias list */ +#define UART_IRQHandler UART0_IRQHandler +#define I2C_IRQHandler I2C0_IRQHandler +#define SSP_IRQHandler SSP0_IRQHandler + +/** + * @} + */ + +#include "sysctl_17xx_40xx.h" +#include "clock_17xx_40xx.h" +#include "iocon_17xx_40xx.h" +#include "adc_17xx_40xx.h" +#include "can_17xx_40xx.h" +#include "dac_17xx_40xx.h" +#include "enet_17xx_40xx.h" +#include "gpdma_17xx_40xx.h" +#include "gpio_17xx_40xx.h" +#include "gpioint_17xx_40xx.h" +#include "i2c_17xx_40xx.h" +#include "i2s_17xx_40xx.h" +#include "mcpwm_17xx_40xx.h" +#include "pmu_17xx_40xx.h" +#include "qei_17xx_40xx.h" +#include "ritimer_17xx_40xx.h" +#include "rtc_17xx_40xx.h" +#include "spi_17xx_40xx.h" +#include "ssp_17xx_40xx.h" +#include "timer_17xx_40xx.h" +#include "uart_17xx_40xx.h" +#include "usb_17xx_40xx.h" +#include "wwdt_17xx_40xx.h" +#include "fmc_17xx_40xx.h" +#include "romapi_17xx_40xx.h" +/* FIXME : PWM drivers */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CHIP_LPC175X_6X_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc177x_8x.h b/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc177x_8x.h new file mode 100644 index 000000000..8e3b65cd2 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc177x_8x.h @@ -0,0 +1,203 @@ +/* + * @brief LPC177x/8x basic chip inclusion file + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CHIP_LPC177X_8X_H_ +#define __CHIP_LPC177X_8X_H_ + +#include "lpc_types.h" +#include "sys_config.h" +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(CORE_M3) +#error CORE_M3 is not defined for the LPC177x/8x architecture +#error CORE_M3 should be defined as part of your compiler define list +#endif + +#ifndef CHIP_LPC177X_8X +#error CHIP_LPC177X_8X is not defined! +#endif + +/** @defgroup PERIPH_177X_8X_BASE CHIP: LPC177x/8x Peripheral addresses and register set declarations + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#define LPC_FMC_BASE 0x00200000 +#define LPC_EEPROM_BASE 0x00200080 +#define LPC_GPDMA_BASE 0x20080000 +#define LPC_ENET_BASE 0x20084000 +#define LPC_LCD_BASE 0x20088000 +#define LPC_USB_BASE 0x2008C000 +#define LPC_CRC_BASE 0x20090000 +#define LPC_SPIFI_BASE 0x20094000 +#define LPC_GPIO0_BASE 0x20098000 +#define LPC_GPIO1_BASE 0x20098020 +#define LPC_GPIO2_BASE 0x20098040 +#define LPC_GPIO3_BASE 0x20098060 +#define LPC_GPIO4_BASE 0x20098080 +#define LPC_GPIO5_BASE 0x200980A0 +#define LPC_EMC_BASE 0x2009C000 +#define LPC_RTC_BASE 0x40024000 +#define LPC_REGFILE_BASE 0x40024044 +#define LPC_WWDT_BASE 0x40000000 +#define LPC_UART0_BASE 0x4000C000 +#define LPC_UART1_BASE 0x40010000 +#define LPC_UART2_BASE 0x40098000 +#define LPC_UART3_BASE 0x4009C000 +#define LPC_UART4_BASE 0x400A4000 +#define LPC_SSP0_BASE 0x40088000 +#define LPC_SSP1_BASE 0x40030000 +#define LPC_SSP2_BASE 0x400AC000 +#define LPC_TIMER0_BASE 0x40004000 +#define LPC_TIMER1_BASE 0x40008000 +#define LPC_TIMER2_BASE 0x40090000 +#define LPC_TIMER3_BASE 0x40094000 +#define LPC_MCPWM_BASE 0x400B8000 +#define LPC_PWM0_BASE 0x40014000 +#define LPC_PWM1_BASE 0x40018000 +#define LPC_I2C0_BASE 0x4001C000 +#define LPC_I2C1_BASE 0x4005C000 +#define LPC_I2C2_BASE 0x400A0000 +#define LPC_I2S_BASE 0x400A8000 +#define LPC_CANAF_RAM_BASE 0x40038000 +#define LPC_CANAF_BASE 0x4003C000 +#define LPC_CANCR_BASE 0x40040000 +#define LPC_CAN1_BASE 0x40044000 +#define LPC_CAN2_BASE 0x40048000 +#define LPC_QEI_BASE 0x400BC000 +#define LPC_DAC_BASE 0x4008C000 +#define LPC_ADC_BASE 0x40034000 +#define LPC_GPIOINT_BASE 0x40028080 +#define LPC_IOCON_BASE 0x4002C000 +#define LPC_SDC_BASE 0x400C0000 +#define LPC_SYSCTL_BASE 0x400FC000 +#define LPC_PMU_BASE 0x400FC0C0 + +/* Assign LPC_* names to structures mapped to addresses */ +#define LPC_PMU ((LPC_PMU_T *) LPC_PMU_BASE) +#define LPC_EEPROM ((LPC_EEPROM_T *) LPC_EEPROM_BASE) +#define LPC_GPDMA ((LPC_GPDMA_T *) LPC_GPDMA_BASE) +#define LPC_EMC ((LPC_EMC_T *) LPC_EMC_BASE) +#define LPC_USB ((LPC_USB_T *) LPC_USB_BASE) +#define LPC_LCD ((LPC_LCD_T *) LPC_LCD_BASE) +#define LPC_ETHERNET ((LPC_ENET_T *) LPC_ENET_BASE) +#define LPC_GPIO ((LPC_GPIO_T *) LPC_GPIO0_BASE) +#define LPC_GPIO1 ((LPC_GPIO_T *) LPC_GPIO1_BASE) +#define LPC_GPIO2 ((LPC_GPIO_T *) LPC_GPIO2_BASE) +#define LPC_GPIO3 ((LPC_GPIO_T *) LPC_GPIO3_BASE) +#define LPC_GPIO4 ((LPC_GPIO_T *) LPC_GPIO4_BASE) +#define LPC_GPIO5 ((LPC_GPIO_T *) LPC_GPIO5_BASE) +#define LPC_GPIOINT ((LPC_GPIOINT_T *) LPC_GPIOINT_BASE) +#define LPC_RTC ((LPC_RTC_T *) LPC_RTC_BASE) +#define LPC_REGFILE ((LPC_REGFILE_T *) LPC_REGFILE_BASE) +#define LPC_WWDT ((LPC_WWDT_T *) LPC_WWDT_BASE) +#define LPC_UART0 ((LPC_USART_T *) LPC_UART0_BASE) +#define LPC_UART1 ((LPC_USART_T *) LPC_UART1_BASE) +#define LPC_UART2 ((LPC_USART_T *) LPC_UART2_BASE) +#define LPC_UART3 ((LPC_USART_T *) LPC_UART3_BASE) +#define LPC_UART4 ((LPC_USART_T *) LPC_UART4_BASE) +#define LPC_SSP0 ((LPC_SSP_T *) LPC_SSP0_BASE) +#define LPC_SSP1 ((LPC_SSP_T *) LPC_SSP1_BASE) +#define LPC_SSP2 ((LPC_SSP_T *) LPC_SSP2_BASE) +#define LPC_TIMER0 ((LPC_TIMER_T *) LPC_TIMER0_BASE) +#define LPC_TIMER1 ((LPC_TIMER_T *) LPC_TIMER1_BASE) +#define LPC_TIMER2 ((LPC_TIMER_T *) LPC_TIMER2_BASE) +#define LPC_TIMER3 ((LPC_TIMER_T *) LPC_TIMER3_BASE) +#define LPC_MCPWM ((LPC_MCPWM_T *) LPC_MCPWM_BASE) +#define LPC_I2C0 ((LPC_I2C_T *) LPC_I2C0_BASE) +#define LPC_I2C1 ((LPC_I2C_T *) LPC_I2C1_BASE) +#define LPC_I2C2 ((LPC_I2C_T *) LPC_I2C2_BASE) +#define LPC_I2S ((LPC_I2S_T *) LPC_I2S_BASE) +#define LPC_QEI ((LPC_QEI_T *) LPC_QEI_BASE) +#define LPC_DAC ((LPC_DAC_T *) LPC_DAC_BASE) +#define LPC_ADC ((LPC_ADC_T *) LPC_ADC_BASE) +#define LPC_IOCON ((LPC_IOCON_T *) LPC_IOCON_BASE) +#define LPC_SDC ((LPC_SDC_T *) LPC_SDC_BASE) +#define LPC_SYSCTL ((LPC_SYSCTL_T *) LPC_SYSCTL_BASE) +#define LPC_SYSCON ((LPC_SYSCTL_T *) LPC_SYSCTL_BASE) /* Alias for LPC_SYSCTL */ +#define LPC_CANAF_RAM ((LPC_CANAF_RAM_T *) LPC_CANAF_RAM_BASE) +#define LPC_CANAF ((LPC_CANAF_T *) LPC_CANAF_BASE) +#define LPC_CANCR ((LPC_CANCR_T *) LPC_CANCR_BASE) +#define LPC_CAN1 ((LPC_CAN_T *) LPC_CAN1_BASE) +#define LPC_CAN2 ((LPC_CAN_T *) LPC_CAN2_BASE) +#define LPC_CRC ((LPC_CRC_T *) LPC_CRC_BASE) +#define LPC_FMC ((LPC_FMC_T *) LPC_FMC_BASE) + +/* IRQ Handler Alias list */ +#define UART_IRQHandler UART0_IRQHandler +#define I2C_IRQHandler I2C0_IRQHandler +#define SSP_IRQHandler SSP0_IRQHandler + + +/** + * @} + */ + +#include "sysctl_17xx_40xx.h" +#include "clock_17xx_40xx.h" +#include "iocon_17xx_40xx.h" +#include "adc_17xx_40xx.h" +#include "can_17xx_40xx.h" +#include "crc_17xx_40xx.h" +#include "dac_17xx_40xx.h" +#include "eeprom_17xx_40xx.h" +#include "emc_17xx_40xx.h" +#include "enet_17xx_40xx.h" +#include "gpdma_17xx_40xx.h" +#include "gpio_17xx_40xx.h" +#include "gpioint_17xx_40xx.h" +#include "i2c_17xx_40xx.h" +#include "i2s_17xx_40xx.h" +#include "lcd_17xx_40xx.h" +#include "mcpwm_17xx_40xx.h" +#include "pmu_17xx_40xx.h" +#include "qei_17xx_40xx.h" +#include "rtc_17xx_40xx.h" +#include "sdc_17xx_40xx.h" +#include "sdmmc_17xx_40xx.h" +#include "ssp_17xx_40xx.h" +#include "timer_17xx_40xx.h" +#include "uart_17xx_40xx.h" +#include "usb_17xx_40xx.h" +#include "wwdt_17xx_40xx.h" +#include "fmc_17xx_40xx.h" +#include "romapi_17xx_40xx.h" +/* FIXME - missing PWM and possibly CREG drivers */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CHIP_LPC177X_8X_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc407x_8x.h b/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc407x_8x.h new file mode 100644 index 000000000..aca840079 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/chip_lpc407x_8x.h @@ -0,0 +1,206 @@ +/* + * @brief LPC407x/8x basic chip inclusion file + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CHIP_LPC40XX_H_ +#define __CHIP_LPC40XX_H_ + +#include "lpc_types.h" +#include "sys_config.h" +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(CORE_M4) +#error CORE_M4 is not defined for the LPC407x/8x architecture +#error CORE_M4 should be defined as part of your compiler define list +#endif + +#ifndef CHIP_LPC40XX +#error CHIP_LPC40XX is not defined! +#endif + +/** @defgroup PERIPH_407X_8X_BASE CHIP: LPC407x/8x Peripheral addresses and register set declarations + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ +#define LPC_FMC_BASE 0x00200000 +#define LPC_EEPROM_BASE 0x00200080 +#define LPC_GPDMA_BASE 0x20080000 +#define LPC_ENET_BASE 0x20084000 +#define LPC_LCD_BASE 0x20088000 +#define LPC_USB_BASE 0x2008C000 +#define LPC_CRC_BASE 0x20090000 +#define LPC_SPIFI_BASE 0x20094000 +#define LPC_GPIO0_BASE 0x20098000 +#define LPC_GPIO1_BASE 0x20098020 +#define LPC_GPIO2_BASE 0x20098040 +#define LPC_GPIO3_BASE 0x20098060 +#define LPC_GPIO4_BASE 0x20098080 +#define LPC_GPIO5_BASE 0x200980A0 +#define LPC_EMC_BASE 0x2009C000 +#define LPC_RTC_BASE 0x40024000 +#define LPC_REGFILE_BASE 0x40024044 +#define LPC_WWDT_BASE 0x40000000 +#define LPC_UART0_BASE 0x4000C000 +#define LPC_UART1_BASE 0x40010000 +#define LPC_UART2_BASE 0x40098000 +#define LPC_UART3_BASE 0x4009C000 +#define LPC_UART4_BASE 0x400A4000 +#define LPC_SSP0_BASE 0x40088000 +#define LPC_SSP1_BASE 0x40030000 +#define LPC_SSP2_BASE 0x400AC000 +#define LPC_TIMER0_BASE 0x40004000 +#define LPC_TIMER1_BASE 0x40008000 +#define LPC_TIMER2_BASE 0x40090000 +#define LPC_TIMER3_BASE 0x40094000 +#define LPC_MCPWM_BASE 0x400B8000 +#define LPC_PWM0_BASE 0x40014000 +#define LPC_PWM1_BASE 0x40018000 +#define LPC_I2C0_BASE 0x4001C000 +#define LPC_I2C1_BASE 0x4005C000 +#define LPC_I2C2_BASE 0x400A0000 +#define LPC_I2S_BASE 0x400A8000 +#define LPC_CANAF_RAM_BASE 0x40038000 +#define LPC_CANAF_BASE 0x4003C000 +#define LPC_CANCR_BASE 0x40040000 +#define LPC_CAN1_BASE 0x40044000 +#define LPC_CAN2_BASE 0x40048000 +#define LPC_QEI_BASE 0x400BC000 +#define LPC_DAC_BASE 0x4008C000 +#define LPC_ADC_BASE 0x40034000 +#define LPC_GPIOINT_BASE 0x40028080 +#define LPC_IOCON_BASE 0x4002C000 +#define LPC_SDC_BASE 0x400C0000 +#define LPC_SYSCTL_BASE 0x400FC000 +#define LPC_CMP_BASE 0x40020000 +#define LPC_PMU_BASE 0x400FC0C0 + +/* Assign LPC_* names to structures mapped to addresses */ +#define LPC_PMU ((LPC_PMU_T *) LPC_PMU_BASE) +#define LPC_EEPROM ((LPC_EEPROM_T *) LPC_EEPROM_BASE) +#define LPC_GPDMA ((LPC_GPDMA_T *) LPC_GPDMA_BASE) +#define LPC_EMC ((LPC_EMC_T *) LPC_EMC_BASE) +#define LPC_USB ((LPC_USB_T *) LPC_USB_BASE) +#define LPC_LCD ((LPC_LCD_T *) LPC_LCD_BASE) +#define LPC_ETHERNET ((LPC_ENET_T *) LPC_ENET_BASE) +#define LPC_GPIO ((LPC_GPIO_T *) LPC_GPIO0_BASE) +#define LPC_GPIO1 ((LPC_GPIO_T *) LPC_GPIO1_BASE) +#define LPC_GPIO2 ((LPC_GPIO_T *) LPC_GPIO2_BASE) +#define LPC_GPIO3 ((LPC_GPIO_T *) LPC_GPIO3_BASE) +#define LPC_GPIO4 ((LPC_GPIO_T *) LPC_GPIO4_BASE) +#define LPC_GPIO5 ((LPC_GPIO_T *) LPC_GPIO5_BASE) +#define LPC_GPIOINT ((LPC_GPIOINT_T *) LPC_GPIOINT_BASE) +#define LPC_RTC ((LPC_RTC_T *) LPC_RTC_BASE) +#define LPC_REGFILE ((LPC_REGFILE_T *) LPC_REGFILE_BASE) +#define LPC_WWDT ((LPC_WWDT_T *) LPC_WWDT_BASE) +#define LPC_UART0 ((LPC_USART_T *) LPC_UART0_BASE) +#define LPC_UART1 ((LPC_USART_T *) LPC_UART1_BASE) +#define LPC_UART2 ((LPC_USART_T *) LPC_UART2_BASE) +#define LPC_UART3 ((LPC_USART_T *) LPC_UART3_BASE) +#define LPC_UART4 ((LPC_USART_T *) LPC_UART4_BASE) +#define LPC_SSP0 ((LPC_SSP_T *) LPC_SSP0_BASE) +#define LPC_SSP1 ((LPC_SSP_T *) LPC_SSP1_BASE) +#define LPC_SSP2 ((LPC_SSP_T *) LPC_SSP2_BASE) +#define LPC_TIMER0 ((LPC_TIMER_T *) LPC_TIMER0_BASE) +#define LPC_TIMER1 ((LPC_TIMER_T *) LPC_TIMER1_BASE) +#define LPC_TIMER2 ((LPC_TIMER_T *) LPC_TIMER2_BASE) +#define LPC_TIMER3 ((LPC_TIMER_T *) LPC_TIMER3_BASE) +#define LPC_MCPWM ((LPC_MCPWM_T *) LPC_MCPWM_BASE) +#define LPC_I2C0 ((LPC_I2C_T *) LPC_I2C0_BASE) +#define LPC_I2C1 ((LPC_I2C_T *) LPC_I2C1_BASE) +#define LPC_I2C2 ((LPC_I2C_T *) LPC_I2C2_BASE) +#define LPC_I2S ((LPC_I2S_T *) LPC_I2S_BASE) +#define LPC_QEI ((LPC_QEI_T *) LPC_QEI_BASE) +#define LPC_DAC ((LPC_DAC_T *) LPC_DAC_BASE) +#define LPC_ADC ((LPC_ADC_T *) LPC_ADC_BASE) +#define LPC_IOCON ((LPC_IOCON_T *) LPC_IOCON_BASE) +#define LPC_SDC ((LPC_SDC_T *) LPC_SDC_BASE) +#define LPC_SYSCTL ((LPC_SYSCTL_T *) LPC_SYSCTL_BASE) +#define LPC_SYSCON ((LPC_SYSCTL_T *) LPC_SYSCTL_BASE) /* Alias for LPC_SYSCTL */ +#define LPC_CMP ((LPC_CMP_T *) LPC_CMP_BASE) +#define LPC_CANAF_RAM ((LPC_CANAF_RAM_T *) LPC_CANAF_RAM_BASE) +#define LPC_CANAF ((LPC_CANAF_T *) LPC_CANAF_BASE) +#define LPC_CANCR ((LPC_CANCR_T *) LPC_CANCR_BASE) +#define LPC_CAN1 ((LPC_CAN_T *) LPC_CAN1_BASE) +#define LPC_CAN2 ((LPC_CAN_T *) LPC_CAN2_BASE) +#define LPC_CRC ((LPC_CRC_T *) LPC_CRC_BASE) +#define LPC_FMC ((LPC_FMC_T *) LPC_FMC_BASE) + +/* IRQ Handler Alias list */ +#define UART_IRQHandler UART0_IRQHandler +#define I2C_IRQHandler I2C0_IRQHandler +#define SSP_IRQHandler SSP0_IRQHandler + +/** + * @} + */ + +#include "sysctl_17xx_40xx.h" +#include "clock_17xx_40xx.h" +#include "iocon_17xx_40xx.h" +#include "adc_17xx_40xx.h" +#include "can_17xx_40xx.h" +#include "cmp_17xx_40xx.h" +#include "crc_17xx_40xx.h" +#include "dac_17xx_40xx.h" +#include "eeprom_17xx_40xx.h" +#include "emc_17xx_40xx.h" +#include "enet_17xx_40xx.h" +#include "gpdma_17xx_40xx.h" +#include "gpio_17xx_40xx.h" +#include "gpioint_17xx_40xx.h" +#include "i2c_17xx_40xx.h" +#include "i2s_17xx_40xx.h" +#include "lcd_17xx_40xx.h" +#include "pmu_17xx_40xx.h" +#include "mcpwm_17xx_40xx.h" +#include "qei_17xx_40xx.h" +#include "rtc_17xx_40xx.h" +#include "sdc_17xx_40xx.h" +#include "sdmmc_17xx_40xx.h" +#include "spifi_17xx_40xx.h" +#include "ssp_17xx_40xx.h" +#include "timer_17xx_40xx.h" +#include "uart_17xx_40xx.h" +#include "usb_17xx_40xx.h" +#include "wwdt_17xx_40xx.h" +#include "fmc_17xx_40xx.h" +#include "romapi_17xx_40xx.h" +#include "fpu_init.h" +/* FIXME - missing PWM and possibly CREG drivers */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CHIP_LPC40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/clock_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/clock_17xx_40xx.h new file mode 100644 index 000000000..b687114a8 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/clock_17xx_40xx.h @@ -0,0 +1,896 @@ +/* + * @brief LPC17XX/40XX Clock control functions + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CLOCK_17XX_40XX_H_ +#define __CLOCK_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup CLOCK_17XX_40XX CHIP: LPC17xx/40xx Clock Driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#define SYSCTL_OSCRANGE_15_25 (1 << 4) /*!< SCS register - main oscillator range 15 to 25MHz */ +#define SYSCTL_OSCEC (1 << 5) /*!< SCS register - main oscillator enable */ +#define SYSCTL_OSCSTAT (1 << 6) /*!< SCS register - main oscillator is ready status */ + +/*!< Internal oscillator frequency */ +#if defined(CHIP_LPC175X_6X) +#define SYSCTL_IRC_FREQ (4000000) +#else +#define SYSCTL_IRC_FREQ (12000000) +#endif + +#define SYSCTL_PLL_ENABLE (1 << 0)/*!< PLL enable flag */ +#if defined(CHIP_LPC175X_6X) +#define SYSCTL_PLL_CONNECT (1 << 1) /*!< PLL connect flag only applies to 175x/6x */ +#endif + +/** + * @brief Enables or connects a PLL + * @param PLLNum: PLL number + * @param flags: SYSCTL_PLL_ENABLE or SYSCTL_PLL_CONNECT + * @return Nothing + * @note This will also perform a PLL feed sequence. Connect only applies to the + * LPC175x/6x devices. + */ +void Chip_Clock_EnablePLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t flags); + +/** + * @brief Disables or disconnects a PLL + * @param PLLNum: PLL number + * @param flags: SYSCTL_PLL_ENABLE or SYSCTL_PLL_CONNECT + * @return Nothing + * @note This will also perform a PLL feed sequence. Connect only applies to the + * LPC175x/6x devices. + */ +void Chip_Clock_DisablePLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t flags); + +/** + * @brief Sets up a PLL + * @param PLLNum: PLL number + * @param msel: PLL Multiplier value (Must be pre-decremented) + * @param psel: PLL Divider value (Must be pre-decremented) + * @note See the User Manual for limitations on these values for stable PLL + * operation. Be careful with these values - they must be safe values for the + * msl, nsel, and psel registers so must be already decremented by 1 or the + * the correct value for psel (0 = div by 1, 1 = div by 2, etc.). + * @return Nothing + */ +void Chip_Clock_SetupPLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t msel, uint32_t psel); + +#if defined(CHIP_LPC175X_6X) +#define SYSCTL_PLL0STS_ENABLED (1 << 24) /*!< PLL0 enable flag */ +#define SYSCTL_PLL0STS_CONNECTED (1 << 25) /*!< PLL0 connect flag */ +#define SYSCTL_PLL0STS_LOCKED (1 << 26) /*!< PLL0 connect flag */ +#define SYSCTL_PLL1STS_ENABLED (1 << 8) /*!< PLL1 enable flag */ +#define SYSCTL_PLL1STS_CONNECTED (1 << 9) /*!< PLL1 connect flag */ +#define SYSCTL_PLL1STS_LOCKED (1 << 10) /*!< PLL1 connect flag */ +#else +#define SYSCTL_PLLSTS_ENABLED (1 << 8) /*!< PLL enable flag */ +#define SYSCTL_PLLSTS_LOCKED (1 << 10) /*!< PLL connect flag */ +#endif + +/** + * @brief Returns PLL status + * @param PLLNum: PLL number + * @return Current enabled flags, Or'ed SYSCTL_PLLSTS_* states + * @note Note flag positions for PLL0 and PLL1 differ on the LPC175x/6x devices. + */ +STATIC INLINE uint32_t Chip_Clock_GetPLLStatus(CHIP_SYSCTL_PLL_T PLLNum) +{ + return LPC_SYSCTL->PLL[PLLNum].PLLSTAT; +} + +/** + * @brief Read PLL0 enable status + * @return true of the PLL0 is enabled. false if not enabled + */ +STATIC INLINE bool Chip_Clock_IsMainPLLEnabled(void) +{ +#if defined(CHIP_LPC175X_6X) + return (bool) ((LPC_SYSCTL->PLL[0].PLLSTAT & SYSCTL_PLL0STS_ENABLED) != 0); +#else + return (bool) ((LPC_SYSCTL->PLL[0].PLLSTAT & SYSCTL_PLLSTS_ENABLED) != 0); +#endif +} + +/** + * @brief Read PLL1 enable status + * @return true of the PLL1 is enabled. false if not enabled + */ +STATIC INLINE bool Chip_Clock_IsUSBPLLEnabled(void) +{ +#if defined(CHIP_LPC175X_6X) + return (bool) ((LPC_SYSCTL->PLL[1].PLLSTAT & SYSCTL_PLL1STS_ENABLED) != 0); +#else + return (bool) ((LPC_SYSCTL->PLL[1].PLLSTAT & SYSCTL_PLLSTS_ENABLED) != 0); +#endif +} + +/** + * @brief Read PLL0 lock status + * @return true of the PLL0 is locked. false if not locked + */ +STATIC INLINE bool Chip_Clock_IsMainPLLLocked(void) +{ +#if defined(CHIP_LPC175X_6X) + return (bool) ((LPC_SYSCTL->PLL[0].PLLSTAT & SYSCTL_PLL0STS_LOCKED) != 0); +#else + return (bool) ((LPC_SYSCTL->PLL[0].PLLSTAT & SYSCTL_PLLSTS_LOCKED) != 0); +#endif +} + +/** + * @brief Read PLL1 lock status + * @return true of the PLL1 is locked. false if not locked + */ +STATIC INLINE bool Chip_Clock_IsUSBPLLLocked(void) +{ +#if defined(CHIP_LPC175X_6X) + return (bool) ((LPC_SYSCTL->PLL[1].PLLSTAT & SYSCTL_PLL1STS_LOCKED) != 0); +#else + return (bool) ((LPC_SYSCTL->PLL[1].PLLSTAT & SYSCTL_PLLSTS_LOCKED) != 0); +#endif +} + +#if defined(CHIP_LPC175X_6X) +/** + * @brief Read PLL0 connect status + * @return true of the PLL0 is connected. false if not connected + */ +STATIC INLINE bool Chip_Clock_IsMainPLLConnected(void) +{ + return (bool) ((LPC_SYSCTL->PLL[0].PLLSTAT & SYSCTL_PLL0STS_CONNECTED) != 0); +} + +/** + * @brief Read PLL1 lock status + * @return true of the PLL1 is connected. false if not connected + */ +STATIC INLINE bool Chip_Clock_IsUSBPLLConnected(void) +{ + return (bool) ((LPC_SYSCTL->PLL[1].PLLSTAT & SYSCTL_PLL1STS_CONNECTED) != 0); +} +#endif + +/** + * @brief Enables the external Crystal oscillator + * @return Nothing + */ +STATIC INLINE void Chip_Clock_EnableCrystal(void) +{ + LPC_SYSCTL->SCS |= SYSCTL_OSCEC; +} + +/** + * @brief Checks if the external Crystal oscillator is enabled + * @return true if enabled, false otherwise + */ +STATIC INLINE bool Chip_Clock_IsCrystalEnabled(void) +{ + return (LPC_SYSCTL->SCS & SYSCTL_OSCSTAT) != 0; +} + +/** + * @brief Sets the external crystal oscillator range to 15Mhz - 25MHz + * @return Nothing + */ +STATIC INLINE void Chip_Clock_SetCrystalRangeHi(void) +{ + LPC_SYSCTL->SCS |= SYSCTL_OSCRANGE_15_25; +} + +/** + * @brief Sets the external crystal oscillator range to 1Mhz - 20MHz + * @return Nothing + */ +STATIC INLINE void Chip_Clock_SetCrystalRangeLo(void) +{ + LPC_SYSCTL->SCS &= ~SYSCTL_OSCRANGE_15_25; +} + +/** + * @brief Feeds a PLL + * @param PLLNum: PLL number + * @return Nothing + */ +STATIC INLINE void Chip_Clock_FeedPLL(CHIP_SYSCTL_PLL_T PLLNum) +{ + LPC_SYSCTL->PLL[PLLNum].PLLFEED = 0xAA; + LPC_SYSCTL->PLL[PLLNum].PLLFEED = 0x55; +} + +/** + * Power control for peripherals + */ +typedef enum CHIP_SYSCTL_CLOCK { +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLOCK_RSVD0, +#else + SYSCTL_CLOCK_LCD, /*!< LCD clock */ +#endif + SYSCTL_CLOCK_TIMER0, /*!< Timer 0 clock */ + SYSCTL_CLOCK_TIMER1, /*!< Timer 1 clock */ + SYSCTL_CLOCK_UART0, /*!< UART 0 clock */ + SYSCTL_CLOCK_UART1, /*!< UART 1 clock */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLOCK_RSVD5, +#else + SYSCTL_CLOCK_PWM0, /*!< PWM0 clock */ +#endif + SYSCTL_CLOCK_PWM1, /*!< PWM1 clock */ + SYSCTL_CLOCK_I2C0, /*!< I2C0 clock */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLOCK_SPI, /*!< SPI clock */ +#else + SYSCTL_CLOCK_UART4, /*!< UART 4 clock */ +#endif + SYSCTL_CLOCK_RTC, /*!< RTC clock */ + SYSCTL_CLOCK_SSP1, /*!< SSP1 clock */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLOCK_RSVD11, +#else + SYSCTL_CLOCK_EMC, /*!< EMC clock */ +#endif + SYSCTL_CLOCK_ADC, /*!< ADC clock */ + SYSCTL_CLOCK_CAN1, /*!< CAN1 clock */ + SYSCTL_CLOCK_CAN2, /*!< CAN2 clock */ + SYSCTL_CLOCK_GPIO, /*!< GPIO clock */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLOCK_RIT, /*!< RIT clock */ +#else + SYSCTL_CLOCK_SPIFI, /*!< SPIFI clock */ +#endif + SYSCTL_CLOCK_MCPWM, /*!< MCPWM clock */ + SYSCTL_CLOCK_QEI, /*!< QEI clock */ + SYSCTL_CLOCK_I2C1, /*!< I2C1 clock */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLOCK_RSVD20, +#else + SYSCTL_CLOCK_SSP2, /*!< SSP2 clock */ +#endif + SYSCTL_CLOCK_SSP0, /*!< SSP0 clock */ + SYSCTL_CLOCK_TIMER2, /*!< Timer 2 clock */ + SYSCTL_CLOCK_TIMER3, /*!< Timer 3 clock */ + SYSCTL_CLOCK_UART2, /*!< UART 2 clock */ + SYSCTL_CLOCK_UART3, /*!< UART 3 clock */ + SYSCTL_CLOCK_I2C2, /*!< I2C2 clock */ + SYSCTL_CLOCK_I2S, /*!< I2S clock */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLOCK_RSVD28, +#else + SYSCTL_CLOCK_SDC, /*!< SD Card interface clock */ +#endif + SYSCTL_CLOCK_GPDMA, /*!< GP DMA clock */ + SYSCTL_CLOCK_ENET, /*!< EMAC/Ethernet clock */ + SYSCTL_CLOCK_USB, /*!< USB clock */ + SYSCTL_CLOCK_RSVD32, + SYSCTL_CLOCK_RSVD33, + SYSCTL_CLOCK_RSVD34, +#if defined(CHIP_LPC40XX) + SYSCTL_CLOCK_CMP, /*!< Comparator clock (PCONP1) */ +#else + SYSCTL_CLOCK_RSVD35, +#endif +} CHIP_SYSCTL_CLOCK_T; + +/** + * @brief Enables power and clocking for a peripheral + * @param clk: Clock to enable + * @return Nothing + * @note Only peripheral clocks that are defined in the PCONP registers of the clock + * and power controller can be enabled and disabled with this function. + * Some clocks need to be enabled elsewhere (ie, USB) and will return + * false to indicate it can't be enabled with this function. + */ +void Chip_Clock_EnablePeriphClock(CHIP_SYSCTL_CLOCK_T clk); + +/** + * @brief Disables power and clocking for a peripheral + * @param clk: Clock to disable + * @return Nothing + * @note Only peripheral clocks that are defined in the PCONP registers of the clock + * and power controller can be enabled and disabled with this function. + * Some clocks need to be disabled elsewhere (ie, USB) and will return + * false to indicate it can't be disabled with this function. + */ +void Chip_Clock_DisablePeriphClock(CHIP_SYSCTL_CLOCK_T clk); + +/** + * @brief Returns power enables state for a peripheral + * @param clk: Clock to check + * @return true if the clock is enabled, false if disabled + */ +bool Chip_Clock_IsPeripheralClockEnabled(CHIP_SYSCTL_CLOCK_T clk); + +#if !defined(CHIP_LPC175X_6X) +/** + * EMC clock divider values + */ +typedef enum CHIP_SYSCTL_EMC_DIV { + SYSCTL_EMC_DIV1 = 0, + SYSCTL_EMC_DIV2 = 1, +} CHIP_SYSCTL_EMC_DIV_T; + +/** + * @brief Selects a EMC divider rate + * @param emcDiv: Source clock for PLL + * @return Nothing + * @note This function controls division of the clock before it is used by the EMC. + * The EMC uses the same base clock as the CPU and the APB peripherals. The + * EMC clock can tun at half or the same as the CPU clock. This is intended to + * be used primarily when the CPU is running faster than the external bus can + * support. + */ +STATIC INLINE void Chip_Clock_SetEMCClockDiv(CHIP_SYSCTL_EMC_DIV_T emcDiv) +{ + LPC_SYSCTL->EMCCLKSEL = (uint32_t) emcDiv; +} + +/** + * @brief Get EMC divider rate + * @return divider value + */ +STATIC INLINE uint32_t Chip_Clock_GetEMCClockDiv(void) +{ + return ((uint32_t) LPC_SYSCTL->EMCCLKSEL) + 1; +} + +#endif + +/** + * Selectable CPU clock sources + */ +typedef enum CHIP_SYSCTL_CCLKSRC { + SYSCTL_CCLKSRC_SYSCLK, /*!< Select Sysclk as the input to the CPU clock divider. */ + SYSCTL_CCLKSRC_MAINPLL, /*!< Select the output of the Main PLL as the input to the CPU clock divider. */ +} CHIP_SYSCTL_CCLKSRC_T; + +/** + * @brief Sets the current CPU clock source + * @param src Source selected + * @return Nothing + * @note When setting the clock source to the PLL, it should + * be enabled and locked. + */ +void Chip_Clock_SetCPUClockSource(CHIP_SYSCTL_CCLKSRC_T src); + +/** + * @brief Returns the current CPU clock source + * @return CPU clock source + * @note On 177x/8x and 407x/8x devices, this is also the peripheral + * clock source. + */ +CHIP_SYSCTL_CCLKSRC_T Chip_Clock_GetCPUClockSource(void); + +/** + * @brief Sets the CPU clock divider + * @param div: CPU clock divider, between 1 and divider max + * @return Nothing + * @note The maximum divider for the 175x/6x is 256. The maximum divider for + * the 177x/8x and 407x/8x is 32. Note on 175x/6x devices, the divided CPU + * clock rate is used as the input to the peripheral clock dividers, + * while 177x/8x and 407x/8x devices use the undivided CPU clock rate. + */ +void Chip_Clock_SetCPUClockDiv(uint32_t div); + +/** + * @brief Gets the CPU clock divider + * @return CPU clock divider, between 1 and divider max + * @note The maximum divider for the 175x/6x is 256. The maximum divider for + * the 177x/8x and 407x/8x is 32. Note on 175x/6x devices, the divided CPU + * clock rate is used as the input to the peripheral clock dividers, + * while 177x/8x and 407x/8x devices use the undivided CPU clock rate. + */ +uint32_t Chip_Clock_GetCPUClockDiv(void); + +#if !defined(CHIP_LPC175X_6X) +/** + * Clock sources for the USB divider. On 175x/6x devices, only the USB + * PLL1 can be used as an input for the USB divider + */ +typedef enum CHIP_SYSCTL_USBCLKSRC { + SYSCTL_USBCLKSRC_SYSCLK, /*!< SYSCLK clock as USB divider source */ + SYSCTL_USBCLKSRC_MAINPLL, /*!< PLL0 clock as USB divider source */ + SYSCTL_USBCLKSRC_USBPLL, /*!< PLL1 clock as USB divider source */ + SYSCTL_USBCLKSRC_RESERVED +} CHIP_SYSCTL_USBCLKSRC_T; + +/** + * @brief Sets the USB clock divider source + * @param src: USB clock divider source clock + * @return Nothing + * @note This function doesn't apply for LPC175x/6x devices. The divider must be + * be selected with the selected source to give a valid USB clock with a + * rate of 48MHz. + */ +void Chip_Clock_SetUSBClockSource(CHIP_SYSCTL_USBCLKSRC_T src); + +/** + * @brief Gets the USB clock divider source + * @return USB clock divider source clock + */ +STATIC INLINE CHIP_SYSCTL_USBCLKSRC_T Chip_Clock_GetUSBClockSource(void) +{ + return (CHIP_SYSCTL_USBCLKSRC_T) ((LPC_SYSCTL->USBCLKSEL >> 8) & 0x3); +} + +#endif /* !defined(CHIP_LPC175X_6X)*/ + +/** + * @brief Sets the USB clock divider + * @param div: USB clock divider to generate 48MHz from USB source clock + * @return Nothing + * @note Divider values are between 1 and 32 (16 max for 175x/6x) + */ +void Chip_Clock_SetUSBClockDiv(uint32_t div); + +/** + * @brief Gets the USB clock divider + * @return USB clock divider + * @note Divider values are between 1 and 32 (16 max for 175x/6x) + */ +uint32_t Chip_Clock_GetUSBClockDiv(void); + +/** + * PLL source clocks + */ +typedef enum CHIP_SYSCTL_PLLCLKSRC { + SYSCTL_PLLCLKSRC_IRC, /*!< PLL is sourced from the internal oscillator (IRC) */ + SYSCTL_PLLCLKSRC_MAINOSC, /*!< PLL is sourced from the main oscillator */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_PLLCLKSRC_RTC, /*!< PLL is sourced from the RTC oscillator */ +#else + SYSCTL_PLLCLKSRC_RESERVED1, +#endif + SYSCTL_PLLCLKSRC_RESERVED2 +} CHIP_SYSCTL_PLLCLKSRC_T; + +/** + * @brief Selects a input clock source for SYSCLK + * @param src: input clock source for SYSCLK + * @return Nothing + * @note SYSCLK is used for sourcing PLL0, SPIFI FLASH, the USB clock + * divider, and the CPU clock divider. + */ +STATIC INLINE void Chip_Clock_SetMainPLLSource(CHIP_SYSCTL_PLLCLKSRC_T src) +{ + LPC_SYSCTL->CLKSRCSEL = src; +} + +/** + * @brief Returns the input clock source for SYSCLK + * @return input clock source for SYSCLK + */ +STATIC INLINE CHIP_SYSCTL_PLLCLKSRC_T Chip_Clock_GetMainPLLSource(void) +{ + return (CHIP_SYSCTL_PLLCLKSRC_T) (LPC_SYSCTL->CLKSRCSEL & 0x3); +} + +#if defined(CHIP_LPC175X_6X) +/** + * Clock and power peripheral clock divider rates used with the + * Clock_CLKDIVSEL_T clock types (devices only) + */ +typedef enum { + SYSCTL_CLKDIV_4, /*!< Divider by 4 */ + SYSCTL_CLKDIV_1, /*!< Divider by 1 */ + SYSCTL_CLKDIV_2, /*!< Divider by 2 */ + SYSCTL_CLKDIV_8, /*!< Divider by 8, not for use with CAN */ + SYSCTL_CLKDIV_6_CCAN = SYSCTL_CLKDIV_8 /*!< Divider by 6, CAN only */ +} CHIP_SYSCTL_CLKDIV_T; + +/** + * Peripheral clock selection for LPC175x/6x + * This is a list of clocks that can be divided on the 175x/6x + */ +typedef enum { + SYSCTL_PCLK_WDT, /*!< Watchdog divider */ + SYSCTL_PCLK_TIMER0, /*!< Timer 0 divider */ + SYSCTL_PCLK_TIMER1, /*!< Timer 1 divider */ + SYSCTL_PCLK_UART0, /*!< UART 0 divider */ + SYSCTL_PCLK_UART1, /*!< UART 1 divider */ + SYSCTL_PCLK_RSVD5, + SYSCTL_PCLK_PWM1, /*!< PWM 1 divider */ + SYSCTL_PCLK_I2C0, /*!< I2C 0 divider */ + SYSCTL_PCLK_SPI, /*!< SPI divider */ + SYSCTL_PCLK_RSVD9, + SYSCTL_PCLK_SSP1, /*!< SSP 1 divider */ + SYSCTL_PCLK_DAC, /*!< DAC divider */ + SYSCTL_PCLK_ADC, /*!< ADC divider */ + SYSCTL_PCLK_CAN1, /*!< CAN 1 divider */ + SYSCTL_PCLK_CAN2, /*!< CAN 2 divider */ + SYSCTL_PCLK_ACF, /*!< ACF divider */ + SYSCTL_PCLK_QEI, /*!< QEI divider */ + SYSCTL_PCLK_GPIOINT, /*!< GPIOINT divider */ + SYSCTL_PCLK_PCB, /*!< PCB divider */ + SYSCTL_PCLK_I2C1, /*!< I2C 1 divider */ + SYSCTL_PCLK_RSVD20, + SYSCTL_PCLK_SSP0, /*!< SSP 0 divider */ + SYSCTL_PCLK_TIMER2, /*!< Timer 2 divider */ + SYSCTL_PCLK_TIMER3, /*!< Timer 3 divider */ + SYSCTL_PCLK_UART2, /*!< UART 2 divider */ + SYSCTL_PCLK_UART3, /*!< UART 3 divider */ + SYSCTL_PCLK_I2C2, /*!< I2C 2 divider */ + SYSCTL_PCLK_I2S, /*!< I2S divider */ + SYSCTL_PCLK_RSVD28, + SYSCTL_PCLK_RIT, /*!< Repetitive timer divider */ + SYSCTL_PCLK_SYSCON, /*!< SYSCON divider */ + SYSCTL_PCLK_MCPWM /*!< Motor control PWM divider */ +} CHIP_SYSCTL_PCLK_T; + +/** + * @brief Selects a clock divider for a peripheral + * @param clk: Clock to set divider for + * @param div: Divider for the clock + * @return Nothing + * @note Selects the divider for a peripheral. A peripheral clock is generated + * from the CPU clock divided by its peripheral clock divider. + * Only peripheral clocks that are defined in the PCLKSEL registers of + * the clock and power controller can used this function. + * (LPC175X/6X only) + */ +void Chip_Clock_SetPCLKDiv(CHIP_SYSCTL_PCLK_T clk, CHIP_SYSCTL_CLKDIV_T div); + +/** + * @brief Gets a clock divider for a peripheral + * @param clk: Clock to set divider for + * @return The divider for the clock + * @note Selects the divider for a peripheral. A peripheral clock is generated + * from the CPU clock divided by its peripheral clock divider. + * Only peripheral clocks that are defined in the PCLKSEL registers of + * the clock and power controller can used this function. + * (LPC175X/6X only) + */ +uint32_t Chip_Clock_GetPCLKDiv(CHIP_SYSCTL_PCLK_T clk); + +#else +/** + * @brief Sets a clock divider for all peripherals + * @param div: Divider for all peripherals, 0 = disable + * @return Nothing + * @note All the peripherals in the device use the same clock divider. The + * divider is based on the CPU's clock rate. Use 0 to disable all + * peripheral clocks or a divider of 1 to 15. (LPC177X/8X and 407X/8X) + */ +STATIC INLINE void Chip_Clock_SetPCLKDiv(uint32_t div) +{ + LPC_SYSCTL->PCLKSEL = div; +} + +/** + * @brief Gets the clock divider for all peripherals + * @return Divider for all peripherals, 0 = disabled + * @note All the peripherals in the device use the same clock divider. The + * divider is based on the CPU's clock rate. (LPC177X/8X and 407X/8X) + */ +STATIC INLINE uint32_t Chip_Clock_GetPCLKDiv(void) +{ + return LPC_SYSCTL->PCLKSEL & 0x1F; +} + +#endif + +#if !defined(CHIP_LPC175X_6X) +/** + * Clock sources for the SPIFI clock divider + */ +typedef enum CHIP_SYSCTL_SPIFICLKSRC { + SYSCTL_SPIFICLKSRC_SYSCLK, /*!< SYSCLK clock as SPIFI divider source */ + SYSCTL_SPIFICLKSRC_MAINPLL, /*!< PLL0 clock as SPIFI divider source */ + SYSCTL_SPIFICLKSRC_USBPLL, /*!< PLL1 clock as SPIFI divider source */ + SYSCTL_SPIFICLKSRC_RESERVED +} CHIP_SYSCTL_SPIFICLKSRC_T; + +/** + * @brief Sets the SPIFI clock divider source + * @param src: SPIFI clock divider source clock + * @return Nothing + */ +void Chip_Clock_SetSPIFIClockSource(CHIP_SYSCTL_SPIFICLKSRC_T src); + +/** + * @brief Gets the SPIFI clock divider source + * @return SPIFI clock divider source clock + */ +STATIC INLINE CHIP_SYSCTL_SPIFICLKSRC_T Chip_Clock_GetSPIFIClockSource(void) +{ + return (CHIP_SYSCTL_SPIFICLKSRC_T) ((LPC_SYSCTL->SPIFICLKSEL >> 8) & 0x3); +} + +/** + * @brief Sets the SPIFI clock divider + * @param div: SPIFI clock divider, 0 to disable + * @return Nothing + * @note Divider values are between 1 and 31 + */ +void Chip_Clock_SetSPIFIClockDiv(uint32_t div); + +/** + * @brief Gets the SPIFI clock divider + * @return SPIFI clock divider + * @note Divider values are between 1 and 31, 0 is disabled + */ +STATIC INLINE uint32_t Chip_Clock_GetSPIFIClockDiv(void) +{ + return LPC_SYSCTL->SPIFICLKSEL & 0x1F; +} + +/** + * @brief Set the LCD clock prescaler + * @param div: Divider value, minimum of 1 + * @return Nothing + */ +STATIC INLINE void Chip_Clock_SetLCDClockDiv(uint32_t div) +{ + LPC_SYSCTL->LCD_CFG = (div - 1); +} + +/** + * @brief Get the LCD clock prescaler + * @return Current divider value + */ +STATIC INLINE uint32_t Chip_Clock_GetLCDClockDiv(void) +{ + return (LPC_SYSCTL->LCD_CFG & 0x1F) + 1; +} + +#endif + +/** + * Clock sources for the CLKOUT pin + */ +typedef enum { + SYSCTL_CLKOUTSRC_CPU, /*!< CPU clock as CLKOUT source */ + SYSCTL_CLKOUTSRC_MAINOSC, /*!< Main oscillator clock as CLKOUT source */ + SYSCTL_CLKOUTSRC_IRC, /*!< IRC oscillator clock as CLKOUT source */ + SYSCTL_CLKOUTSRC_USB, /*!< USB clock as CLKOUT source */ + SYSCTL_CLKOUTSRC_RTC, /*!< RTC clock as CLKOUT source */ +#if defined(CHIP_LPC175X_6X) + SYSCTL_CLKOUTSRC_RESERVED1, + SYSCTL_CLKOUTSRC_RESERVED2, +#else + SYSCTL_CLKOUTSRC_SPIFI, /*!< SPIFI clock as CLKOUT source */ + SYSCTL_CLKOUTSRC_WATCHDOGOSC, /*!< Watchdog oscillator as CLKOUT source */ +#endif + SYSCTL_CLKOUTSRC_RESERVED3 +} CHIP_SYSCTL_CLKOUTSRC_T; + +/** + * @brief Selects a source clock and divider rate for the CLKOUT pin + * @param src: source selected + * @param div: Divider for the clock source on CLKOUT, 1 to 16 + * @return Nothing + * @note This function will disable the CLKOUT signal if its enabled. Use + * Chip_Clock_EnableCLKOUT to re-enable CLKOUT after a call to this + * function. + */ +void Chip_Clock_SetCLKOUTSource(CHIP_SYSCTL_CLKOUTSRC_T src, uint32_t div); + +/** + * @brief Enables the clock on the CLKOUT pin + * @return Nothing + */ +STATIC INLINE void Chip_Clock_EnableCLKOUT(void) +{ + LPC_SYSCTL->CLKOUTCFG |= (1 << 8); +} + +/** + * @brief Disables the clock on the CLKOUT pin + * @return Nothing + */ +STATIC INLINE void Chip_Clock_DisableCLKOUT(void) +{ + LPC_SYSCTL->CLKOUTCFG &= ~(1 << 8); +} + +/** + * @brief Returns the CLKOUT activity indication status + * @return true if CLKOUT is enabled, false if disabled and stopped + * @note CLKOUT activity indication. Reads as true when CLKOUT is + * enabled. Read as false when CLKOUT has been disabled via + * the CLKOUT_EN bit and the clock has completed being stopped. + */ +STATIC INLINE bool Chip_Clock_IsCLKOUTEnabled(void) +{ + return (bool) ((LPC_SYSCTL->CLKOUTCFG & (1 << 9)) != 0); +} + +/** + * @brief Returns the main oscillator clock rate + * @return main oscillator clock rate + */ +STATIC INLINE uint32_t Chip_Clock_GetMainOscRate(void) +{ + return OscRateIn; +} + +/** + * @brief Returns the internal oscillator (IRC) clock rate + * @return internal oscillator (IRC) clock rate + */ +STATIC INLINE uint32_t Chip_Clock_GetIntOscRate(void) +{ + return SYSCTL_IRC_FREQ; +} + +/** + * @brief Returns the RTC oscillator clock rate + * @return RTC oscillator clock rate + */ +STATIC INLINE uint32_t Chip_Clock_GetRTCOscRate(void) +{ + return RTCOscRateIn; +} + +/** + * @brief Returns the current SYSCLK clock rate + * @return SYSCLK clock rate + * @note SYSCLK is used for sourcing PLL0, SPIFI FLASH, the USB clock + * divider, and the CPU clock divider. + */ +uint32_t Chip_Clock_GetSYSCLKRate(void); + +/** + * @brief Return Main PLL (PLL0) input clock rate + * @return PLL0 input clock rate + */ +STATIC INLINE uint32_t Chip_Clock_GetMainPLLInClockRate(void) +{ + return Chip_Clock_GetSYSCLKRate(); +} + +/** + * @brief Return PLL0 (Main PLL) output clock rate + * @return PLL0 output clock rate + */ +uint32_t Chip_Clock_GetMainPLLOutClockRate(void); + +/** + * @brief Return USB PLL input clock rate + * @return USB PLL input clock rate + */ +STATIC INLINE uint32_t Chip_Clock_GetUSBPLLInClockRate(void) +{ + return Chip_Clock_GetMainOscRate(); +} + +/** + * @brief Return USB PLL output clock rate + * @return USB PLL output clock rate + */ +uint32_t Chip_Clock_GetUSBPLLOutClockRate(void); + +/** + * @brief Return main clock rate + * @return main clock rate + */ +uint32_t Chip_Clock_GetMainClockRate(void); + +/** + * @brief Return system clock rate + * @return system clock rate + */ +uint32_t Chip_Clock_GetSystemClockRate(void); + +/** + * @brief Gets the USB clock (USB_CLK) rate + * @return USB clock (USB_CLK) clock rate + * @note The clock source and divider are used to generate the USB clock rate. + */ +uint32_t Chip_Clock_GetUSBClockRate(void); + +#if !defined(CHIP_LPC175X_6X) + +/** + * @brief Returns the SPIFI clock rate + * @return SPIFI clock clock rate + */ +uint32_t Chip_Clock_GetSPIFIClockRate(void); + +/** + * @brief Returns clock rate for EMC + * @return Clock rate for the peripheral + */ +STATIC INLINE uint32_t Chip_Clock_GetEMCClockRate(void) +{ + return Chip_Clock_GetSystemClockRate() / Chip_Clock_GetEMCClockDiv(); +} + +#endif + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) +/** + * @brief Returns clock rate for a peripheral (from peripheral clock) + * @param clk: Clock to get rate of + * @return Clock rate for the peripheral + * @note This covers most common peripheral clocks, but not every clock + * in the system. LPC177x/8x and LPC407x/8x devices use the same + * clock for all periphreals, while the LPC175x/6x have unique + * dividers (except to RTC ) that may alter the peripheral clock rate. + */ +uint32_t Chip_Clock_GetPeripheralClockRate(void); + +#else +/** + * @brief Returns clock rate for a peripheral (from peripheral clock) + * @param clk: Clock to get rate of + * @return Clock rate for the peripheral + * @note This covers most common peripheral clocks, but not every clock + * in the system. LPC177x/8x and LPC407x/8x devices use the same + * clock for all periphreals, while the LPC175x/6x have unique + * dividers (except to RTC ) that may alter the peripheral clock rate. + */ +uint32_t Chip_Clock_GetPeripheralClockRate(CHIP_SYSCTL_PCLK_T clk); + +/** + * @brief Returns clock rate for RTC + * @return Clock rate for the peripheral + */ +STATIC INLINE uint32_t Chip_Clock_GetRTCClockRate(void) +{ + return Chip_Clock_GetSystemClockRate() / 8; +} + +#endif + +/** + * @brief Returns clock rate for Ethernet + * @return Clock rate for the peripheral + */ +STATIC INLINE uint32_t Chip_Clock_GetENETClockRate(void) +{ + return Chip_Clock_GetSystemClockRate(); +} + +/** + * @brief Returns clock rate for GPDMA + * @return Clock rate for the peripheral + */ +STATIC INLINE uint32_t Chip_Clock_GetGPDMAClockRate(void) +{ + return Chip_Clock_GetSystemClockRate(); +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CLOCK_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/cmp_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/cmp_17xx_40xx.h new file mode 100644 index 000000000..91adff2d3 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/cmp_17xx_40xx.h @@ -0,0 +1,408 @@ +/* + * @brief LPC40xx Comparator driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licenser disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CMP_17XX_40XX_H_ +#define __CMP_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup CMP_17XX_40XX CHIP: LPC40xx Comparator driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC40XX) + +/** The number of embeded comparators supported */ +#define CMP_NUM 2 + +/** + * @brief Comparator (CMP) register block structure + */ +typedef struct { /*!< Comparator structure */ + __IO uint32_t CMP_CTRL; /*!< Comparator block control register */ + __IO uint32_t CMP_CTRLx[CMP_NUM]; /*!< Specific comparator control register */ +} LPC_CMP_T; + +/** + * @brief Comparator control definition + */ +typedef enum { + CMP_ENCTRL_DISABLE, /*!< Disable */ + CMP_ENCTRL_DIS_IN_DS_PWD, /*!< Disable in deep sleep mode and power down mode*/ + CMP_ENCTRL_DIS_IN_PWD, /*!< Disable in power down mode*/ + CMP_ENCTRL_ENABLE, /*!< Enable/Power-up*/ +} CMP_ENCTRL_T; + +/*!< Comparator control register Bitmask */ +#define CMP_CTRL_BITMASK (0xF30F) +/*!< The comparator current source control bitmask*/ +#define CMP_CTRL_PD_IREF_BITMASK (0x03) +/*!< Control the comparator current source (n is CMP_ENCTRL_T value)*/ +#define CMP_CTRL_PD_IREF(n) ((((uint32_t) (n)) & 0x03)) +/*!< The comparator bandgap reference control bitmask*/ +#define CMP_CTRL_PD_VBG_BITMASK (((uint32_t) 0x03) << 2) +/*!< Control the comparator bandgap reference (n is CMP_ENCTRL_T value)*/ +#define CMP_CTRL_PD_VBG(n) ((((uint32_t) (n)) & 0x03) << 2) +/*!< The CMP_ROSC ouput control bitmask */ +#define CMP_CTRL_ROSC_BITMASK ((uint32_t) 0x300) +/*!< The CMP_ROSC output is set by CMP1, reset by CMP0 */ +#define CMP_CTRL_ROSCCTL_CMP1 (0x00) +/*!< The CMP_ROSC output is set by CMP0, reset by CMP1 */ +#define CMP_CTRL_ROSCCTL_CMP0 (((uint32_t) 0x01) << 8) +/*!< The CMP_ROSC output is reset by the internal chip reset */ +#define CMP_CTRL_EXT_RESET_INTERNAL (0x00) +/*!< The CMP_ROSC output is reset by the CMP_RESET input */ +#define CMP_CTRL_EXT_RESET_CMPRESET (((uint32_t) 0x01) << 9) +/*!< Timer Capture input control bitmask */ +#define CMP_CTRL_TIMERCAPTURE_BITMASK ((uint32_t) 0xF000) +/*!< Selects the comparator 0 level output as the input for Timer0 capture input 2 */ +#define CMP_CTRL_T0CAP2_0LEVEL (0x00) +/*!< Selects the comparator 1 level output as the input for Timer0 capture input 2 */ +#define CMP_CTRL_T0CAP2_1LEVEL (((uint32_t) 0x01) << 12) +/*!< Selects the comparator 0 edge output as the input for Timer0 capture input 3 */ +#define CMP_CTRL_T0CAP3_0EDGE (0x00) +/*!< Selects the comparator 1 edge output as the input for Timer0 capture input 3 */ +#define CMP_CTRL_T0CAP3_1EDGE (((uint32_t) 0x01) << 13) +/*!< Selects the comparator 1 edge output as the input for Timer1 capture input 2 */ +#define CMP_CTRL_T1CAP2_1EDGE (0x00) +/*!< Selects the comparator 0 level output as the input for Timer1 capture input 2 */ +#define CMP_CTRL_T1CAP2_0LEVEL (((uint32_t) 0x01) << 14) +/*!< Selects the comparator 1 level output as the input for Timer1 capture input 3 */ +#define CMP_CTRL_T1CAP3_1LEVEL (0x00) +/*!< Selects the comparator 0 edge output as the input for Timer1 capture input 3 */ +#define CMP_CTRL_T1CAP3_0EDGE (((uint32_t) 0x01) << 15) + +/*!< The comparator x control register Bitmask */ +#define CMP_CTRLx_BITMASK ((uint32_t) 0x1F7FF77F) +/*!< The comparator x enable bitmask*/ +#define CMP_CTRLx_EN_BITMASK (0x03) +/*!< Control the comparator x (n is CMP_ENCTRL_T value)*/ +#define CMP_CTRLx_EN(n) ((((uint32_t) (n)) & 0x03)) +/*!< Enable the output of compartor x */ +#define CMP_CTRLx_OE (((uint32_t) 0x01) << 2) +/*!< The status of compartor x, reflects the comparator x output*/ +#define CMP_CTRLx_STAT (((uint32_t) 0x01) << 3) +/*!< Comparator VM input control bitmask */ +#define CMP_CTRLx_VM_BITMASK (((uint32_t) 0x07) << 4) +/*!< Select the VM input*/ +#define CMP_CTRLx_VM(n) ((((uint32_t) (n)) & 0x07) << 4) +/*!< Comparator VP input control bitmask */ +#define CMP_CTRLx_VP_BITMASK (((uint32_t) 0x07) << 8) +/*!< Select the VP input */ +#define CMP_CTRLx_VP(n) ((((uint32_t) (n)) & 0x07) << 8) +/*!< Synchronize the Comparator x output with the internal bus clock for outpur to other peripherals */ +#define CMP_CTRLx_SYNC (((uint32_t) 0x01) << 12) +/*!< Comparator Hysteresis control bitmask */ +#define CMP_CTRLx_HYS_BITMASK (((uint32_t) 0x03) << 13) +/*!< Determine the difference required between the comparator inputs before the comparator output switch*/ +#define CMP_CTRLx_HYS(n) ((((uint32_t) (n)) & 0x03) << 13) +/*!< Interrupt control bitmask */ +#define CMP_CTRLx_INTCTRL_BITMASK ((uint32_t) 0x78000) +/*!< Comparator output is used as-is for generating interrupts. */ +#define CMP_CTRLx_INTPOL_NORMAL (0x00) +/*!< Comparator output is used inverted for generating interrupts. */ +#define CMP_CTRLx_INTPOL_INV (((uint32_t) 0x01) << 15) +/*!< Comparator x interrupt is edge triggered. */ +#define CMP_CTRLx_INTTYPE_EDGE (0x00) +/*!< Comparator x interrupt is level triggered.*/ +#define CMP_CTRLx_INTTYPE_LEVEL (((uint32_t) 0x01) << 16) +/*!< Comparator x interrupt edge control bitmask */ +#define CMP_CTRLx_INTEDGE_BITMASK (((uint32_t) 0x03) << 17) +/*!< Select edge on which triggered interrupt is active*/ +#define CMP_CTRLx_INTEDGE(n) ((((uint32_t) (n)) & 0x03) << 17) +/*!< Comparator interrupt flag */ +#define CMP_CTRLx_INTFLAG (((uint32_t) 0x01) << 19) +/*!< The VLAD Enable bitmask*/ +#define CMP_CTRLx_VLADEN_BITMASK (((uint32_t) 0x03) << 20) +/*!< Control the comparator x (n is CMP_ENCTRL_T value)*/ +#define CMP_CTRLx_VLADEN(n) ((((uint32_t) (n)) & 0x03) << 20) +/*!< Select VREF_CMP pin as voltage reference for comparator voltage ladder */ +#define CMP_CTRLx_VLADREF_VREFCMP (0x00) +/*!< Select VDDA pin as voltage reference for comparator voltage ladder */ +#define CMP_CTRLx_VLADREF_VDDA (((uint32_t) 0x01) << 22) +/*!< Volatge ladder value bitmask */ +#define CMP_CTRLx_VSEL_BITMASK ((uint32_t) ((0x1F) << 24)) +/*!< Voltage ladder value for Comparator */ +#define CMP_CTRLx_VSEL(n) ((((uint32_t) (n)) & 0x1F) << 24) + +/** + * @brief Comparator VM/VP input definitions + */ +typedef enum { + CMP_INPUT_VREF_DIV, /*!< Vref divider.*/ + CMP_INPUT_CMPx_IN0, /*!< Use the input 0 of the comparator*/ + CMP_INPUT_CMPx_IN1, /*!< Use the input 1 of the comparator*/ + CMP_INPUT_CMPx_IN2, /*!< Use the input 2 of the comparator*/ + CMP_INPUT_CMPx_IN3, /*!< Use the input 3 of the comparator*/ + CMP_INPUT_CMP_OTHER_IN0, /*!< Use the input 0 of the other comparator.*/ + CMP_INPUT_INTERNAL_09VBG, /*!< internal 0.9 V band gap reference.*/ +} CMP_INPUT_T; + +/** + * @brief Comparator hysteresis selection definitions + */ +typedef enum { + CMP_HYS_NONE = CMP_CTRLx_HYS(0), /*!CMP_CTRL = (LPC_CMP->CMP_CTRL & (~CMP_CTRL_PD_IREF_BITMASK)) | CMP_CTRL_PD_IREF(en); +} + +/** + * @brief Enables comparator bandgap reference + * @param en : Enable mode + * @return Nothing + */ +STATIC INLINE void Chip_CMP_EnableBandGap(CMP_ENCTRL_T en) +{ + LPC_CMP->CMP_CTRL = (LPC_CMP->CMP_CTRL & (~CMP_CTRL_PD_VBG_BITMASK)) | CMP_CTRL_PD_VBG(en); +} + +/** + * @brief Control CMP_ROSC + * @param flag : Or-ed bit value of CMP_CTRL_ROSCCTL_* and CMP_CTRL_EXT_RESET_* + * @return Nothing + */ +STATIC INLINE void Chip_CMP_ControlROSC(uint32_t flag) +{ + LPC_CMP->CMP_CTRL = (LPC_CMP->CMP_CTRL & (~CMP_CTRL_ROSC_BITMASK)) | flag; +} + +/** + * @brief Control CMP_ROSC + * @param flag : Or-ed bit value of CMP_CTRL_T*CAP* + * @return Nothing + */ +STATIC INLINE void Chip_CMP_SetTimerCapInput(uint32_t flag) +{ + LPC_CMP->CMP_CTRL = (LPC_CMP->CMP_CTRL & (~CMP_CTRL_TIMERCAPTURE_BITMASK)) | flag; +} + +/** + * @brief Sets up voltage ladder + * @param id : Comparator ID + * @param ladSel : Voltage ladder value (0~31). + * @param flag :0(CMP_VREF used)/CMP_CTRLx_VLADREF_VDDA (VDDA used) + * @return Nothing + * @note VREF divider 0 = ladSel*VRef0/31 + */ +STATIC INLINE void Chip_CMP_SetupVoltLadder(uint8_t id, + uint16_t ladSel, uint32_t flag) +{ + LPC_CMP->CMP_CTRLx[id] = + (LPC_CMP->CMP_CTRLx[id] & (~(CMP_CTRLx_VSEL_BITMASK | CMP_CTRLx_VLADREF_VDDA))) | CMP_CTRLx_VSEL( + ladSel) | flag; +} + +/** + * @brief Enables voltage ladder + * @param id : Comparator ID + * @param en : enable option + * @return Nothing + */ +STATIC INLINE void Chip_CMP_EnableVoltLadder(uint8_t id, CMP_ENCTRL_T en) +{ + LPC_CMP->CMP_CTRLx[id] = (LPC_CMP->CMP_CTRLx[id] & (~CMP_CTRLx_VLADEN_BITMASK)) | CMP_CTRLx_VLADEN(en); +} + +/** + * @brief Selects positive voltage input + * @param id : Comparator ID + * @param input : Selected input + * @return Nothing + */ +STATIC INLINE void Chip_CMP_SetPosVoltRef(uint8_t id, CMP_INPUT_T input) +{ + LPC_CMP->CMP_CTRLx[id] = (LPC_CMP->CMP_CTRLx[id] & (~CMP_CTRLx_VP_BITMASK)) | CMP_CTRLx_VP(input); +} + +/** + * @brief Selects negative voltage input + * @param id : Comparator ID + * @param input : Selected input + * @return Nothing + */ +STATIC INLINE void Chip_CMP_SetNegVoltRef(uint8_t id, CMP_INPUT_T input) +{ + LPC_CMP->CMP_CTRLx[id] = (LPC_CMP->CMP_CTRLx[id] & (~CMP_CTRLx_VM_BITMASK)) | CMP_CTRLx_VM(input); +} + +/** + * @brief Selects hysteresis level + * @param id : Comparator ID + * @param hys : Selected Hysteresis level + * @return Nothing + */ +STATIC INLINE void Chip_CMP_SetHysteresis(uint8_t id, CMP_HYS_T hys) +{ + LPC_CMP->CMP_CTRLx[id] = (LPC_CMP->CMP_CTRLx[id] & (~CMP_CTRLx_HYS_BITMASK)) | hys; +} + +/** + * @brief Enables specified comparator + * @param id : Comparator ID + * @param en : Enable mode + * @return Nothing + */ +STATIC INLINE void Chip_CMP_Enable(uint8_t id, CMP_ENCTRL_T en) +{ + LPC_CMP->CMP_CTRLx[id] = (LPC_CMP->CMP_CTRLx[id] & (~CMP_CTRLx_EN_BITMASK)) | CMP_CTRLx_EN(en); +} + +/** + * @brief Returns the current comparator status + * @param id : Comparator Id (0/1) + * @return SET/RESET + */ +STATIC INLINE FlagStatus Chip_CMP_GetCmpStatus(uint8_t id) +{ + return (LPC_CMP->CMP_CTRLx[id] & CMP_CTRLx_STAT) ? SET : RESET; +} + +/** + * @brief Enable comparator output + * @param id : Comparator ID + * @return Nothing + */ +STATIC INLINE void Chip_CMP_EnableOuput(uint8_t id) +{ + LPC_CMP->CMP_CTRLx[id] |= CMP_CTRLx_OE; +} + +/** + * @brief Disable comparator output + * @param id : Comparator ID + * @return Nothing + */ +STATIC INLINE void Chip_CMP_DisableOutput(uint8_t id) +{ + LPC_CMP->CMP_CTRLx[id] &= ~CMP_CTRLx_OE; +} + +/** + * @brief Synchronizes Comparator output to bus clock + * @param id : Comparator ID + * @return Nothing + */ +STATIC INLINE void Chip_CMP_EnableSyncCmpOut(uint8_t id) +{ + LPC_CMP->CMP_CTRLx[id] |= CMP_CTRLx_SYNC; +} + +/** + * @brief Sets comparator output to be used directly (no sync) + * @param id : Comparator ID + * @return Nothing + */ +STATIC INLINE void Chip_CMP_DisableSyncCmpOut(uint8_t id) +{ + LPC_CMP->CMP_CTRLx[id] &= ~CMP_CTRLx_SYNC; +} + +/** + * @brief Sets up comparator interrupt + * @param id : Comparator ID + * @param intFlag : Or-ed value of CMP_CTRLx_INTTYPE_*, CMP_CTRLx_INTPOL_* + * @param edgeSel : the edge on which interrupt occurs. + * @return Nothing + */ +STATIC INLINE void Chip_CMP_ConfigInt(uint8_t id, + uint32_t intFlag, + CMP_INTEDGE_T edgeSel) +{ + LPC_CMP->CMP_CTRLx[id] = (LPC_CMP->CMP_CTRLx[id] & (~CMP_CTRLx_INTCTRL_BITMASK)) | intFlag | edgeSel; +} + +/** + * @brief Get the CMP interrupt status + * @param id : Comparator ID + * @return SET/RESET + */ +STATIC INLINE FlagStatus Chip_CMP_GetIntStatus(uint8_t id) +{ + return (LPC_CMP->CMP_CTRLx[id] & CMP_CTRLx_INTFLAG) ? SET : RESET; +} + +/** + * @brief Clears the CMP interrupt + * @param id : Comparator ID + * @return Nothing + */ +STATIC INLINE void Chip_CMP_ClearIntStatus(uint8_t id) +{ + LPC_CMP->CMP_CTRLx[id] |= CMP_CTRLx_INTFLAG; +} + +#endif /* defined(CHIP_LPC40XX) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CMP_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/cmsis.h b/hw/mcu/nxp/lpc_chip_40xx/inc/cmsis.h new file mode 100644 index 000000000..7f55fbfc3 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/cmsis.h @@ -0,0 +1,66 @@ +/* + * @brief LPC17xx/40xx selective CMSIS inclusion file + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CMSIS_H_ +#define __CMSIS_H_ + +#include "lpc_types.h" +#include "sys_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Select correct CMSIS include file based on CHIP_* definition */ +#if defined(CHIP_LPC175X_6X) +#include "cmsis_175x_6x.h" +typedef LPC175X_6X_IRQn_Type IRQn_Type; +#include "core_cm3.h" /*!< Cortex-M3 processor and core peripherals */ + +#elif defined(CHIP_LPC177X_8X) +#include "cmsis_177x_8x.h" +typedef LPC177X_8X_IRQn_Type IRQn_Type; +#include "core_cm3.h" /*!< Cortex-M3 processor and core peripherals */ + +#elif defined(CHIP_LPC40XX) +#include "cmsis_40xx.h" +typedef LPC40XX_IRQn_Type IRQn_Type; +#include "core_cm4.h" /*!< Cortex-M4 processor and core peripherals */ + +#else +#error "No CHIP_* definition is defined" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __CMSIS_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/cmsis_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/cmsis_40xx.h new file mode 100644 index 000000000..8cbb0ead2 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/cmsis_40xx.h @@ -0,0 +1,171 @@ +/* + * @brief Basic CMSIS include file for LPC40xx + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CMSIS_40XX_H_ +#define __CMSIS_40XX_H_ + +#include "lpc_types.h" +#include "sys_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup CMSIS_40XX CHIP: LPC40xx CMSIS include file + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(__ARMCC_VERSION) +// Kill warning "#pragma push with no matching #pragma pop" + #pragma diag_suppress 2525 + #pragma push + #pragma anon_unions +#elif defined(__CWCC__) + #pragma push + #pragma cpp_extensions on +#elif defined(__GNUC__) +/* anonymous unions are enabled by default */ +#elif defined(__IAR_SYSTEMS_ICC__) +// #pragma push // FIXME not usable for IAR + #pragma language=extended +#else + #error Not supported compiler type +#endif + +/* + * ========================================================================== + * ---------- Interrupt Number Definition ----------------------------------- + * ========================================================================== + */ +#if !defined(CHIP_LPC40XX) +#error Incorrect or missing device variant (CHIP_LPC40XX) +#endif + +/** @defgroup CMSIS_40XX_IRQ CHIP_40XX: LPC40xx peripheral interrupt numbers + * @{ + */ + +typedef enum { + /* ------------------------- Cortex-M4 Processor Exceptions Numbers ----------------------------- */ + Reset_IRQn = -15, /*!< 1 Reset Vector, invoked on Power up and warm reset */ + NonMaskableInt_IRQn = -14, /*!< 2 Non maskable Interrupt, cannot be stopped or preempted */ + HardFault_IRQn = -13, /*!< 3 Hard Fault, all classes of Fault */ + MemoryManagement_IRQn = -12, /*!< 4 Memory Management, MPU mismatch, including Access Violation and No Match */ + BusFault_IRQn = -11, /*!< 5 Bus Fault, Pre-Fetch-, Memory Access Fault, other address/memory related Fault */ + UsageFault_IRQn = -10, /*!< 6 Usage Fault, i.e. Undef Instruction, Illegal State Transition */ + SVCall_IRQn = -5, /*!< 11 System Service Call via SVC instruction */ + DebugMonitor_IRQn = -4, /*!< 12 CDebug Monitor */ + PendSV_IRQn = -2, /*!< 14 Pendable request for system service */ + SysTick_IRQn = -1, /*!< 15 System Tick Interrupt */ + + /* --------------------------- LPC40xx Specific Interrupt Numbers ------------------------------- */ + WDT_IRQn = 0, /*!< Watchdog Timer Interrupt */ + TIMER0_IRQn = 1, /*!< Timer0 Interrupt */ + TIMER1_IRQn = 2, /*!< Timer1 Interrupt */ + TIMER2_IRQn = 3, /*!< Timer2 Interrupt */ + TIMER3_IRQn = 4, /*!< Timer3 Interrupt */ + UART0_IRQn = 5, /*!< UART0 Interrupt */ + UART_IRQn = UART0_IRQn, /*!< Alias for UART0 Interrupt */ + UART1_IRQn = 6, /*!< UART1 Interrupt */ + UART2_IRQn = 7, /*!< UART2 Interrupt */ + UART3_IRQn = 8, /*!< UART3 Interrupt */ + PWM1_IRQn = 9, /*!< PWM1 Interrupt */ + I2C0_IRQn = 10, /*!< I2C0 Interrupt */ + I2C_IRQn = I2C0_IRQn, /*!< Alias for I2C0 Interrupt */ + I2C1_IRQn = 11, /*!< I2C1 Interrupt */ + I2C2_IRQn = 12, /*!< I2C2 Interrupt */ + Reserved0_IRQn = 13, /*!< Reserved */ + SSP0_IRQn = 14, /*!< SSP0 Interrupt */ + SSP_IRQn = SSP0_IRQn, /*!< Alias for SSP0 Interrupt */ + SSP1_IRQn = 15, /*!< SSP1 Interrupt */ + PLL0_IRQn = 16, /*!< PLL0 Lock (Main PLL) Interrupt */ + RTC_IRQn = 17, /*!< Real Time Clock Interrupt */ + EINT0_IRQn = 18, /*!< External Interrupt 0 Interrupt */ + EINT1_IRQn = 19, /*!< External Interrupt 1 Interrupt */ + EINT2_IRQn = 20, /*!< External Interrupt 2 Interrupt */ + EINT3_IRQn = 21, /*!< External Interrupt 3 Interrupt */ + ADC_IRQn = 22, /*!< A/D Converter Interrupt */ + BOD_IRQn = 23, /*!< Brown-Out Detect Interrupt */ + USB_IRQn = 24, /*!< USB Interrupt */ + CAN_IRQn = 25, /*!< CAN Interrupt */ + DMA_IRQn = 26, /*!< General Purpose DMA Interrupt */ + I2S_IRQn = 27, /*!< I2S Interrupt */ + ETHERNET_IRQn = 28, /*!< Ethernet Interrupt */ + SDC_IRQn = 29, /*!< SD/MMC card I/F Interrupt */ + MCPWM_IRQn = 30, /*!< Motor Control PWM Interrupt */ + QEI_IRQn = 31, /*!< Quadrature Encoder Interface Interrupt */ + PLL1_IRQn = 32, /*!< PLL1 Lock (USB PLL) Interrupt */ + USBActivity_IRQn = 33, /*!< USB Activity interrupt */ + CANActivity_IRQn = 34, /*!< CAN Activity interrupt */ + UART4_IRQn = 35, /*!< UART4 Interrupt */ + SSP2_IRQn = 36, /*!< SSP2 Interrupt */ + LCD_IRQn = 37, /*!< LCD Interrupt */ + GPIO_IRQn = 38, /*!< GPIO Interrupt */ + PWM0_IRQn = 39, /*!< PWM0 Interrupt */ + EEPROM_IRQn = 40, /*!< EEPROM Interrupt */ +} LPC40XX_IRQn_Type; + +/** + * @} + */ + +/* + * ========================================================================== + * ----------- Processor and Core Peripheral Section ------------------------ + * ========================================================================== + */ + +/** @defgroup CMSIS_40XX_COMMON CHIP: LPC40xx Cortex CMSIS definitions + * @{ + */ + +#define __CM4_REV 0x0001 /*!< Cortex-M4 Core Revision */ +#define __MPU_PRESENT 1 /*!< MPU present or not */ +#define __NVIC_PRIO_BITS 5 /*!< Number of Bits used for Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ +#ifndef __FPU_PRESENT +#define __FPU_PRESENT 1 /*!< FPU present or not */ +#endif + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CMSIS_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4.h b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4.h new file mode 100644 index 000000000..d65016c71 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4.h @@ -0,0 +1,1772 @@ +/**************************************************************************//** + * @file core_cm4.h + * @brief CMSIS Cortex-M4 Core Peripheral Access Layer Header File + * @version V3.20 + * @date 25. February 2013 + * + * @note + * + ******************************************************************************/ +/* Copyright (c) 2009 - 2013 ARM LIMITED + + 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. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + 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 COPYRIGHT HOLDERS AND 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. + ---------------------------------------------------------------------------*/ + + +#if defined ( __ICCARM__ ) + #pragma system_include /* treat file as system include file for MISRA check */ +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +#ifndef __CORE_CM4_H_GENERIC +#define __CORE_CM4_H_GENERIC + +/** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions + CMSIS violates the following MISRA-C:2004 rules: + + \li Required Rule 8.5, object/function definition in header file.
+ Function definitions in header files are used to allow 'inlining'. + + \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
+ Unions are used for effective representation of core registers. + + \li Advisory Rule 19.7, Function-like macro defined.
+ Function-like macros are used to allow more efficient code. + */ + + +/******************************************************************************* + * CMSIS definitions + ******************************************************************************/ +/** \ingroup Cortex_M4 + @{ + */ + +/* CMSIS CM4 definitions */ +#define __CM4_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ +#define __CM4_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ +#define __CM4_CMSIS_VERSION ((__CM4_CMSIS_VERSION_MAIN << 16) | \ + __CM4_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ + +#define __CORTEX_M (0x04) /*!< Cortex-M Core */ + + +#if defined ( __CC_ARM ) + #define __ASM __asm /*!< asm keyword for ARM Compiler */ + #define __INLINE __inline /*!< inline keyword for ARM Compiler */ + #define __STATIC_INLINE static __inline + +#elif defined ( __ICCARM__ ) + #define __ASM __asm /*!< asm keyword for IAR Compiler */ + #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ + #define __STATIC_INLINE static inline + +#elif defined ( __TMS470__ ) + #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ + #define __STATIC_INLINE static inline + +#elif defined ( __GNUC__ ) + #define __ASM __asm /*!< asm keyword for GNU Compiler */ + #define __INLINE inline /*!< inline keyword for GNU Compiler */ + #define __STATIC_INLINE static inline + +#elif defined ( __TASKING__ ) + #define __ASM __asm /*!< asm keyword for TASKING Compiler */ + #define __INLINE inline /*!< inline keyword for TASKING Compiler */ + #define __STATIC_INLINE static inline + +#endif + +/** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. +*/ +#if defined ( __CC_ARM ) + #if defined __TARGET_FPU_VFP + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __ICCARM__ ) + #if defined __ARMVFP__ + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __TMS470__ ) + #if defined __TI_VFP_SUPPORT__ + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __GNUC__ ) + #if defined (__VFP_FP__) && !defined(__SOFTFP__) + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __TASKING__ ) + #if defined __FPU_VFP__ + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif +#endif + +#include /* standard types definitions */ +#include /* Core Instruction Access */ +#include /* Core Function Access */ +#include /* Compiler specific SIMD Intrinsics */ + +#endif /* __CORE_CM4_H_GENERIC */ + +#ifndef __CMSIS_GENERIC + +#ifndef __CORE_CM4_H_DEPENDANT +#define __CORE_CM4_H_DEPENDANT + +/* check device defines and use defaults */ +#if defined __CHECK_DEVICE_DEFINES + #ifndef __CM4_REV + #define __CM4_REV 0x0000 + #warning "__CM4_REV not defined in device header file; using default!" + #endif + + #ifndef __FPU_PRESENT + #define __FPU_PRESENT 0 + #warning "__FPU_PRESENT not defined in device header file; using default!" + #endif + + #ifndef __MPU_PRESENT + #define __MPU_PRESENT 0 + #warning "__MPU_PRESENT not defined in device header file; using default!" + #endif + + #ifndef __NVIC_PRIO_BITS + #define __NVIC_PRIO_BITS 4 + #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" + #endif + + #ifndef __Vendor_SysTickConfig + #define __Vendor_SysTickConfig 0 + #warning "__Vendor_SysTickConfig not defined in device header file; using default!" + #endif +#endif + +/* IO definitions (access restrictions to peripheral registers) */ +/** + \defgroup CMSIS_glob_defs CMSIS Global Defines + + IO Type Qualifiers are used + \li to specify the access to peripheral variables. + \li for automatic generation of peripheral register debug information. +*/ +#ifdef __cplusplus + #define __I volatile /*!< Defines 'read only' permissions */ +#else + #define __I volatile const /*!< Defines 'read only' permissions */ +#endif +#define __O volatile /*!< Defines 'write only' permissions */ +#define __IO volatile /*!< Defines 'read / write' permissions */ + +/*@} end of group Cortex_M4 */ + + + +/******************************************************************************* + * Register Abstraction + Core Register contain: + - Core Register + - Core NVIC Register + - Core SCB Register + - Core SysTick Register + - Core Debug Register + - Core MPU Register + - Core FPU Register + ******************************************************************************/ +/** \defgroup CMSIS_core_register Defines and Type Definitions + \brief Type definitions and defines for Cortex-M processor based devices. +*/ + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_CORE Status and Control Registers + \brief Core Register type definitions. + @{ + */ + +/** \brief Union type to access the Application Program Status Register (APSR). + */ +typedef union +{ + struct + { +#if (__CORTEX_M != 0x04) + uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ +#else + uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ + uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ + uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ +#endif + uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ + uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ + uint32_t C:1; /*!< bit: 29 Carry condition code flag */ + uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ + uint32_t N:1; /*!< bit: 31 Negative condition code flag */ + } b; /*!< Structure used for bit access */ + uint32_t w; /*!< Type used for word access */ +} APSR_Type; + + +/** \brief Union type to access the Interrupt Program Status Register (IPSR). + */ +typedef union +{ + struct + { + uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ + uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ + } b; /*!< Structure used for bit access */ + uint32_t w; /*!< Type used for word access */ +} IPSR_Type; + + +/** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). + */ +typedef union +{ + struct + { + uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ +#if (__CORTEX_M != 0x04) + uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ +#else + uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ + uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ + uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ +#endif + uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ + uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ + uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ + uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ + uint32_t C:1; /*!< bit: 29 Carry condition code flag */ + uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ + uint32_t N:1; /*!< bit: 31 Negative condition code flag */ + } b; /*!< Structure used for bit access */ + uint32_t w; /*!< Type used for word access */ +} xPSR_Type; + + +/** \brief Union type to access the Control Registers (CONTROL). + */ +typedef union +{ + struct + { + uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ + uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ + uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ + uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ + } b; /*!< Structure used for bit access */ + uint32_t w; /*!< Type used for word access */ +} CONTROL_Type; + +/*@} end of group CMSIS_CORE */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) + \brief Type definitions for the NVIC Registers + @{ + */ + +/** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). + */ +typedef struct +{ + __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ + uint32_t RESERVED0[24]; + __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ + uint32_t RSERVED1[24]; + __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ + uint32_t RESERVED2[24]; + __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ + uint32_t RESERVED3[24]; + __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ + uint32_t RESERVED4[56]; + __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ + uint32_t RESERVED5[644]; + __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ +} NVIC_Type; + +/* Software Triggered Interrupt Register Definitions */ +#define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ +#define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ + +/*@} end of group CMSIS_NVIC */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_SCB System Control Block (SCB) + \brief Type definitions for the System Control Block Registers + @{ + */ + +/** \brief Structure type to access the System Control Block (SCB). + */ +typedef struct +{ + __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ + __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ + __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ + __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ + __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ + __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ + __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ + __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ + __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ + __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ + __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ + __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ + __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ + __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ + __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ + __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ + __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ + __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ + __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ + uint32_t RESERVED0[5]; + __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ +} SCB_Type; + +/* SCB CPUID Register Definitions */ +#define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ +#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ + +#define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ +#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ + +#define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ +#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ + +#define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ +#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ + +#define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ +#define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ + +/* SCB Interrupt Control State Register Definitions */ +#define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ +#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ + +#define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ +#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ + +#define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ +#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ + +#define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ +#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ + +#define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ +#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ + +#define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ +#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ + +#define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ +#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ + +#define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ +#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ + +#define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ +#define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ + +#define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ +#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ + +/* SCB Vector Table Offset Register Definitions */ +#define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ +#define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ + +/* SCB Application Interrupt and Reset Control Register Definitions */ +#define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ +#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ + +#define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ +#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ + +#define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ +#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ + +#define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ +#define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ + +#define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ +#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ + +#define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ +#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ + +#define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ +#define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */ + +/* SCB System Control Register Definitions */ +#define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ +#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ + +#define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ +#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ + +#define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ +#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ + +/* SCB Configuration Control Register Definitions */ +#define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ +#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ + +#define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ +#define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ + +#define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ +#define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ + +#define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ +#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ + +#define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ +#define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ + +#define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ +#define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */ + +/* SCB System Handler Control and State Register Definitions */ +#define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ +#define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ + +#define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ +#define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ + +#define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ +#define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ + +#define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ +#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ + +#define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ +#define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ + +#define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ +#define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ + +#define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ +#define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ + +#define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ +#define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ + +#define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ +#define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ + +#define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ +#define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ + +#define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ +#define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ + +#define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ +#define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ + +#define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ +#define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ + +#define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ +#define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */ + +/* SCB Configurable Fault Status Registers Definitions */ +#define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ +#define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ + +#define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ +#define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ + +#define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ +#define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ + +/* SCB Hard Fault Status Registers Definitions */ +#define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ +#define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ + +#define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ +#define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ + +#define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ +#define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ + +/* SCB Debug Fault Status Register Definitions */ +#define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ +#define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ + +#define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ +#define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ + +#define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ +#define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ + +#define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ +#define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ + +#define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ +#define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */ + +/*@} end of group CMSIS_SCB */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) + \brief Type definitions for the System Control and ID Register not in the SCB + @{ + */ + +/** \brief Structure type to access the System Control and ID Register not in the SCB. + */ +typedef struct +{ + uint32_t RESERVED0[1]; + __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ + __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ +} SCnSCB_Type; + +/* Interrupt Controller Type Register Definitions */ +#define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ +#define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */ + +/* Auxiliary Control Register Definitions */ +#define SCnSCB_ACTLR_DISOOFP_Pos 9 /*!< ACTLR: DISOOFP Position */ +#define SCnSCB_ACTLR_DISOOFP_Msk (1UL << SCnSCB_ACTLR_DISOOFP_Pos) /*!< ACTLR: DISOOFP Mask */ + +#define SCnSCB_ACTLR_DISFPCA_Pos 8 /*!< ACTLR: DISFPCA Position */ +#define SCnSCB_ACTLR_DISFPCA_Msk (1UL << SCnSCB_ACTLR_DISFPCA_Pos) /*!< ACTLR: DISFPCA Mask */ + +#define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ +#define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ + +#define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ +#define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ + +#define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ +#define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */ + +/*@} end of group CMSIS_SCnotSCB */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_SysTick System Tick Timer (SysTick) + \brief Type definitions for the System Timer Registers. + @{ + */ + +/** \brief Structure type to access the System Timer (SysTick). + */ +typedef struct +{ + __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ + __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ + __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ + __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ +} SysTick_Type; + +/* SysTick Control / Status Register Definitions */ +#define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ +#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ + +#define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ +#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ + +#define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ +#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ + +#define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ +#define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ + +/* SysTick Reload Register Definitions */ +#define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ +#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ + +/* SysTick Current Register Definitions */ +#define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ +#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ + +/* SysTick Calibration Register Definitions */ +#define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ +#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ + +#define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ +#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ + +#define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ +#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ + +/*@} end of group CMSIS_SysTick */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) + \brief Type definitions for the Instrumentation Trace Macrocell (ITM) + @{ + */ + +/** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). + */ +typedef struct +{ + __O union + { + __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ + __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ + __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ + } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ + uint32_t RESERVED0[864]; + __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ + uint32_t RESERVED1[15]; + __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ + uint32_t RESERVED2[15]; + __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ + uint32_t RESERVED3[29]; + __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ + __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ + __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ + uint32_t RESERVED4[43]; + __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ + __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ + uint32_t RESERVED5[6]; + __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ + __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ + __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ + __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ + __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ + __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ + __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ + __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ + __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ + __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ + __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ + __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ +} ITM_Type; + +/* ITM Trace Privilege Register Definitions */ +#define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ +#define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */ + +/* ITM Trace Control Register Definitions */ +#define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ +#define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ + +#define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ +#define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ + +#define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ +#define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ + +#define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ +#define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ + +#define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ +#define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ + +#define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ +#define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ + +#define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ +#define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ + +#define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ +#define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ + +#define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ +#define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */ + +/* ITM Integration Write Register Definitions */ +#define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ +#define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */ + +/* ITM Integration Read Register Definitions */ +#define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ +#define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */ + +/* ITM Integration Mode Control Register Definitions */ +#define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ +#define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */ + +/* ITM Lock Status Register Definitions */ +#define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ +#define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ + +#define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ +#define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ + +#define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ +#define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */ + +/*@}*/ /* end of group CMSIS_ITM */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) + \brief Type definitions for the Data Watchpoint and Trace (DWT) + @{ + */ + +/** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). + */ +typedef struct +{ + __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ + __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ + __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ + __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ + __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ + __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ + __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ + __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ + __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ + __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ + __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ + uint32_t RESERVED0[1]; + __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ + __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ + __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ + uint32_t RESERVED1[1]; + __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ + __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ + __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ + uint32_t RESERVED2[1]; + __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ + __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ + __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ +} DWT_Type; + +/* DWT Control Register Definitions */ +#define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ +#define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ + +#define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ +#define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ + +#define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ +#define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ + +#define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ +#define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ + +#define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ +#define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ + +#define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ +#define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ + +#define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ +#define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ + +#define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ +#define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ + +#define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ +#define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ + +#define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ +#define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ + +#define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ +#define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ + +#define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ +#define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ + +#define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ +#define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ + +#define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ +#define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ + +#define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ +#define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ + +#define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ +#define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ + +#define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ +#define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ + +#define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ +#define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */ + +/* DWT CPI Count Register Definitions */ +#define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ +#define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */ + +/* DWT Exception Overhead Count Register Definitions */ +#define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ +#define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */ + +/* DWT Sleep Count Register Definitions */ +#define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ +#define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ + +/* DWT LSU Count Register Definitions */ +#define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ +#define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */ + +/* DWT Folded-instruction Count Register Definitions */ +#define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ +#define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */ + +/* DWT Comparator Mask Register Definitions */ +#define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ +#define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */ + +/* DWT Comparator Function Register Definitions */ +#define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ +#define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ + +#define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ +#define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ + +#define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ +#define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ + +#define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ +#define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ + +#define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ +#define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ + +#define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ +#define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ + +#define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ +#define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ + +#define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ +#define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ + +#define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ +#define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */ + +/*@}*/ /* end of group CMSIS_DWT */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_TPI Trace Port Interface (TPI) + \brief Type definitions for the Trace Port Interface (TPI) + @{ + */ + +/** \brief Structure type to access the Trace Port Interface Register (TPI). + */ +typedef struct +{ + __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ + __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ + uint32_t RESERVED0[2]; + __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ + uint32_t RESERVED1[55]; + __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ + uint32_t RESERVED2[131]; + __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ + __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ + __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ + uint32_t RESERVED3[759]; + __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ + __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ + __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ + uint32_t RESERVED4[1]; + __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ + __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ + __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ + uint32_t RESERVED5[39]; + __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ + __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ + uint32_t RESERVED7[8]; + __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ + __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ +} TPI_Type; + +/* TPI Asynchronous Clock Prescaler Register Definitions */ +#define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ +#define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */ + +/* TPI Selected Pin Protocol Register Definitions */ +#define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ +#define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */ + +/* TPI Formatter and Flush Status Register Definitions */ +#define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ +#define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ + +#define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ +#define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ + +#define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ +#define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ + +#define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ +#define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */ + +/* TPI Formatter and Flush Control Register Definitions */ +#define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ +#define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ + +#define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ +#define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ + +/* TPI TRIGGER Register Definitions */ +#define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ +#define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */ + +/* TPI Integration ETM Data Register Definitions (FIFO0) */ +#define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ +#define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ + +#define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ +#define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ + +#define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ +#define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ + +#define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ +#define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ + +#define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ +#define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ + +#define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ +#define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ + +#define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ +#define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */ + +/* TPI ITATBCTR2 Register Definitions */ +#define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ +#define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */ + +/* TPI Integration ITM Data Register Definitions (FIFO1) */ +#define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ +#define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ + +#define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ +#define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ + +#define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ +#define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ + +#define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ +#define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ + +#define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ +#define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ + +#define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ +#define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ + +#define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ +#define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */ + +/* TPI ITATBCTR0 Register Definitions */ +#define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ +#define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */ + +/* TPI Integration Mode Control Register Definitions */ +#define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ +#define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */ + +/* TPI DEVID Register Definitions */ +#define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ +#define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ + +#define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ +#define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ + +#define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ +#define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ + +#define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ +#define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ + +#define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ +#define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ + +#define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ +#define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */ + +/* TPI DEVTYPE Register Definitions */ +#define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ +#define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */ + +#define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ +#define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ + +/*@}*/ /* end of group CMSIS_TPI */ + + +#if (__MPU_PRESENT == 1) +/** \ingroup CMSIS_core_register + \defgroup CMSIS_MPU Memory Protection Unit (MPU) + \brief Type definitions for the Memory Protection Unit (MPU) + @{ + */ + +/** \brief Structure type to access the Memory Protection Unit (MPU). + */ +typedef struct +{ + __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ + __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ + __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ + __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ + __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ + __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ + __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ + __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ + __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ + __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ + __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ +} MPU_Type; + +/* MPU Type Register */ +#define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ +#define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ + +#define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ +#define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ + +#define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ +#define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ + +/* MPU Control Register */ +#define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ +#define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ + +#define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ +#define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ + +#define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ +#define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ + +/* MPU Region Number Register */ +#define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ +#define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ + +/* MPU Region Base Address Register */ +#define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ +#define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ + +#define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ +#define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ + +#define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ +#define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ + +/* MPU Region Attribute and Size Register */ +#define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ +#define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ + +#define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ +#define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ + +#define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ +#define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ + +#define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ +#define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ + +#define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ +#define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ + +#define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ +#define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ + +#define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ +#define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ + +#define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ +#define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ + +#define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ +#define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ + +#define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ +#define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ + +/*@} end of group CMSIS_MPU */ +#endif + + +#if (__FPU_PRESENT == 1) +/** \ingroup CMSIS_core_register + \defgroup CMSIS_FPU Floating Point Unit (FPU) + \brief Type definitions for the Floating Point Unit (FPU) + @{ + */ + +/** \brief Structure type to access the Floating Point Unit (FPU). + */ +typedef struct +{ + uint32_t RESERVED0[1]; + __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ + __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ + __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ + __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ + __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ +} FPU_Type; + +/* Floating-Point Context Control Register */ +#define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ +#define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ + +#define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ +#define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ + +#define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ +#define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ + +#define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ +#define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ + +#define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ +#define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ + +#define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ +#define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ + +#define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ +#define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ + +#define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ +#define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ + +#define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ +#define FPU_FPCCR_LSPACT_Msk (1UL << FPU_FPCCR_LSPACT_Pos) /*!< FPCCR: Lazy state preservation active bit Mask */ + +/* Floating-Point Context Address Register */ +#define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ +#define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ + +/* Floating-Point Default Status Control Register */ +#define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ +#define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ + +#define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ +#define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ + +#define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ +#define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ + +#define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ +#define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ + +/* Media and FP Feature Register 0 */ +#define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ +#define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ + +#define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ +#define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ + +#define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ +#define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ + +#define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ +#define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ + +#define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ +#define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ + +#define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ +#define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ + +#define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ +#define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ + +#define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ +#define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL << FPU_MVFR0_A_SIMD_registers_Pos) /*!< MVFR0: A_SIMD registers bits Mask */ + +/* Media and FP Feature Register 1 */ +#define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ +#define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ + +#define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ +#define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ + +#define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ +#define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ + +#define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ +#define FPU_MVFR1_FtZ_mode_Msk (0xFUL << FPU_MVFR1_FtZ_mode_Pos) /*!< MVFR1: FtZ mode bits Mask */ + +/*@} end of group CMSIS_FPU */ +#endif + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) + \brief Type definitions for the Core Debug Registers + @{ + */ + +/** \brief Structure type to access the Core Debug Register (CoreDebug). + */ +typedef struct +{ + __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ + __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ + __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ + __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ +} CoreDebug_Type; + +/* Debug Halting Control and Status Register */ +#define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ +#define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ + +#define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ +#define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ + +#define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ +#define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ + +#define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ +#define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ + +#define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ +#define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ + +#define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ +#define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ + +#define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ +#define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ + +#define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ +#define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ + +#define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ +#define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ + +#define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ +#define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ + +#define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ +#define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ + +#define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ +#define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ + +/* Debug Core Register Selector Register */ +#define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ +#define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ + +#define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ +#define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */ + +/* Debug Exception and Monitor Control Register */ +#define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ +#define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ + +#define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ +#define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ + +#define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ +#define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ + +#define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ +#define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ + +#define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ +#define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ + +#define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ +#define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ + +#define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ +#define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ + +#define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ +#define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ + +#define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ +#define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ + +#define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ +#define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ + +#define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ +#define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ + +#define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ +#define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ + +#define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ +#define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ + +/*@} end of group CMSIS_CoreDebug */ + + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_core_base Core Definitions + \brief Definitions for base addresses, unions, and structures. + @{ + */ + +/* Memory mapping of Cortex-M4 Hardware */ +#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ +#define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ +#define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ +#define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ +#define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ +#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ +#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ +#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ + +#define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ +#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ +#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ +#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ +#define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ +#define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ +#define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ +#define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ + +#if (__MPU_PRESENT == 1) + #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ + #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ +#endif + +#if (__FPU_PRESENT == 1) + #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ + #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ +#endif + +/*@} */ + + + +/******************************************************************************* + * Hardware Abstraction Layer + Core Function Interface contains: + - Core NVIC Functions + - Core SysTick Functions + - Core Debug Functions + - Core Register Access Functions + ******************************************************************************/ +/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference +*/ + + + +/* ########################## NVIC functions #################################### */ +/** \ingroup CMSIS_Core_FunctionInterface + \defgroup CMSIS_Core_NVICFunctions NVIC Functions + \brief Functions that manage interrupts and exceptions via the NVIC. + @{ + */ + +/** \brief Set Priority Grouping + + The function sets the priority grouping field using the required unlock sequence. + The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. + Only values from 0..7 are used. + In case of a conflict between priority grouping and available + priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. + + \param [in] PriorityGroup Priority grouping field. + */ +__STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) +{ + uint32_t reg_value; + uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */ + + reg_value = SCB->AIRCR; /* read old register configuration */ + reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */ + reg_value = (reg_value | + ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) | + (PriorityGroupTmp << 8)); /* Insert write key and priorty group */ + SCB->AIRCR = reg_value; +} + + +/** \brief Get Priority Grouping + + The function reads the priority grouping field from the NVIC Interrupt Controller. + + \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). + */ +__STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) +{ + return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */ +} + + +/** \brief Enable External Interrupt + + The function enables a device-specific interrupt in the NVIC interrupt controller. + + \param [in] IRQn External interrupt number. Value cannot be negative. + */ +__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) +{ +/* NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); enable interrupt */ + NVIC->ISER[(uint32_t)((int32_t)IRQn) >> 5] = (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); /* enable interrupt */ +} + + +/** \brief Disable External Interrupt + + The function disables a device-specific interrupt in the NVIC interrupt controller. + + \param [in] IRQn External interrupt number. Value cannot be negative. + */ +__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) +{ + NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ +} + + +/** \brief Get Pending Interrupt + + The function reads the pending register in the NVIC and returns the pending bit + for the specified interrupt. + + \param [in] IRQn Interrupt number. + + \return 0 Interrupt status is not pending. + \return 1 Interrupt status is pending. + */ +__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) +{ + return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ +} + + +/** \brief Set Pending Interrupt + + The function sets the pending bit of an external interrupt. + + \param [in] IRQn Interrupt number. Value cannot be negative. + */ +__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) +{ + NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ +} + + +/** \brief Clear Pending Interrupt + + The function clears the pending bit of an external interrupt. + + \param [in] IRQn External interrupt number. Value cannot be negative. + */ +__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) +{ + NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ +} + + +/** \brief Get Active Interrupt + + The function reads the active register in NVIC and returns the active bit. + + \param [in] IRQn Interrupt number. + + \return 0 Interrupt status is not active. + \return 1 Interrupt status is active. + */ +__STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) +{ + return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ +} + + +/** \brief Set Interrupt Priority + + The function sets the priority of an interrupt. + + \note The priority cannot be set for every core interrupt. + + \param [in] IRQn Interrupt number. + \param [in] priority Priority to set. + */ +__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) +{ + if(IRQn < 0) { + SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */ + else { + NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */ +} + + +/** \brief Get Interrupt Priority + + The function reads the priority of an interrupt. The interrupt + number can be positive to specify an external (device specific) + interrupt, or negative to specify an internal (core) interrupt. + + + \param [in] IRQn Interrupt number. + \return Interrupt Priority. Value is aligned automatically to the implemented + priority bits of the microcontroller. + */ +__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) +{ + + if(IRQn < 0) { + return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */ + else { + return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ +} + + +/** \brief Encode Priority + + The function encodes the priority for an interrupt with the given priority group, + preemptive priority value, and subpriority value. + In case of a conflict between priority grouping and available + priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set. + + \param [in] PriorityGroup Used priority group. + \param [in] PreemptPriority Preemptive priority value (starting from 0). + \param [in] SubPriority Subpriority value (starting from 0). + \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). + */ +__STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) +{ + uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ + uint32_t PreemptPriorityBits; + uint32_t SubPriorityBits; + + PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; + SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; + + return ( + ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) | + ((SubPriority & ((1 << (SubPriorityBits )) - 1))) + ); +} + + +/** \brief Decode Priority + + The function decodes an interrupt priority value with a given priority group to + preemptive priority value and subpriority value. + In case of a conflict between priority grouping and available + priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set. + + \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). + \param [in] PriorityGroup Used priority group. + \param [out] pPreemptPriority Preemptive priority value (starting from 0). + \param [out] pSubPriority Subpriority value (starting from 0). + */ +__STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) +{ + uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ + uint32_t PreemptPriorityBits; + uint32_t SubPriorityBits; + + PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; + SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; + + *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1); + *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1); +} + + +/** \brief System Reset + + The function initiates a system reset request to reset the MCU. + */ +__STATIC_INLINE void NVIC_SystemReset(void) +{ + __DSB(); /* Ensure all outstanding memory accesses included + buffered write are completed before reset */ + SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | + (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | + SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */ + __DSB(); /* Ensure completion of memory access */ + while(1); /* wait until reset */ +} + +/*@} end of CMSIS_Core_NVICFunctions */ + + + +/* ################################## SysTick function ############################################ */ +/** \ingroup CMSIS_Core_FunctionInterface + \defgroup CMSIS_Core_SysTickFunctions SysTick Functions + \brief Functions that configure the System. + @{ + */ + +#if (__Vendor_SysTickConfig == 0) + +/** \brief System Tick Configuration + + The function initializes the System Timer and its interrupt, and starts the System Tick Timer. + Counter is in free running mode to generate periodic interrupts. + + \param [in] ticks Number of ticks between two interrupts. + + \return 0 Function succeeded. + \return 1 Function failed. + + \note When the variable __Vendor_SysTickConfig is set to 1, then the + function SysTick_Config is not included. In this case, the file device.h + must contain a vendor-specific implementation of this function. + + */ +__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) +{ + if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ + + SysTick->LOAD = ticks - 1; /* set reload register */ + NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ + SysTick->VAL = 0; /* Load the SysTick Counter Value */ + SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | + SysTick_CTRL_TICKINT_Msk | + SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ + return (0); /* Function successful */ +} + +#endif + +/*@} end of CMSIS_Core_SysTickFunctions */ + + + +/* ##################################### Debug In/Output function ########################################### */ +/** \ingroup CMSIS_Core_FunctionInterface + \defgroup CMSIS_core_DebugFunctions ITM Functions + \brief Functions that access the ITM debug interface. + @{ + */ + +extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ +#define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ + + +/** \brief ITM Send Character + + The function transmits a character via the ITM channel 0, and + \li Just returns when no debugger is connected that has booked the output. + \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. + + \param [in] ch Character to transmit. + + \returns Character to transmit. + */ +__STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) +{ + if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */ + (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */ + { + while (ITM->PORT[0].u32 == 0); + ITM->PORT[0].u8 = (uint8_t) ch; + } + return (ch); +} + + +/** \brief ITM Receive Character + + The function inputs a character via the external variable \ref ITM_RxBuffer. + + \return Received character. + \return -1 No character pending. + */ +__STATIC_INLINE int32_t ITM_ReceiveChar (void) { + int32_t ch = -1; /* no character available */ + + if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { + ch = ITM_RxBuffer; + ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ + } + + return (ch); +} + + +/** \brief ITM Check Character + + The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. + + \return 0 No character available. + \return 1 Character available. + */ +__STATIC_INLINE int32_t ITM_CheckChar (void) { + + if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { + return (0); /* no character available */ + } else { + return (1); /* character available */ + } +} + +/*@} end of CMSIS_core_DebugFunctions */ + +#endif /* __CORE_CM4_H_DEPENDANT */ + +#endif /* __CMSIS_GENERIC */ + +#ifdef __cplusplus +} +#endif diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4_simd.h b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4_simd.h new file mode 100644 index 000000000..83db95b5f --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cm4_simd.h @@ -0,0 +1,673 @@ +/**************************************************************************//** + * @file core_cm4_simd.h + * @brief CMSIS Cortex-M4 SIMD Header File + * @version V3.20 + * @date 25. February 2013 + * + * @note + * + ******************************************************************************/ +/* Copyright (c) 2009 - 2013 ARM LIMITED + + 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. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + 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 COPYRIGHT HOLDERS AND 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. + ---------------------------------------------------------------------------*/ + + +#ifdef __cplusplus + extern "C" { +#endif + +#ifndef __CORE_CM4_SIMD_H +#define __CORE_CM4_SIMD_H + + +/******************************************************************************* + * Hardware Abstraction Layer + ******************************************************************************/ + + +/* ################### Compiler specific Intrinsics ########################### */ +/** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics + Access to dedicated SIMD instructions + @{ +*/ + +#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ +/* ARM armcc specific functions */ + +/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ +#define __SADD8 __sadd8 +#define __QADD8 __qadd8 +#define __SHADD8 __shadd8 +#define __UADD8 __uadd8 +#define __UQADD8 __uqadd8 +#define __UHADD8 __uhadd8 +#define __SSUB8 __ssub8 +#define __QSUB8 __qsub8 +#define __SHSUB8 __shsub8 +#define __USUB8 __usub8 +#define __UQSUB8 __uqsub8 +#define __UHSUB8 __uhsub8 +#define __SADD16 __sadd16 +#define __QADD16 __qadd16 +#define __SHADD16 __shadd16 +#define __UADD16 __uadd16 +#define __UQADD16 __uqadd16 +#define __UHADD16 __uhadd16 +#define __SSUB16 __ssub16 +#define __QSUB16 __qsub16 +#define __SHSUB16 __shsub16 +#define __USUB16 __usub16 +#define __UQSUB16 __uqsub16 +#define __UHSUB16 __uhsub16 +#define __SASX __sasx +#define __QASX __qasx +#define __SHASX __shasx +#define __UASX __uasx +#define __UQASX __uqasx +#define __UHASX __uhasx +#define __SSAX __ssax +#define __QSAX __qsax +#define __SHSAX __shsax +#define __USAX __usax +#define __UQSAX __uqsax +#define __UHSAX __uhsax +#define __USAD8 __usad8 +#define __USADA8 __usada8 +#define __SSAT16 __ssat16 +#define __USAT16 __usat16 +#define __UXTB16 __uxtb16 +#define __UXTAB16 __uxtab16 +#define __SXTB16 __sxtb16 +#define __SXTAB16 __sxtab16 +#define __SMUAD __smuad +#define __SMUADX __smuadx +#define __SMLAD __smlad +#define __SMLADX __smladx +#define __SMLALD __smlald +#define __SMLALDX __smlaldx +#define __SMUSD __smusd +#define __SMUSDX __smusdx +#define __SMLSD __smlsd +#define __SMLSDX __smlsdx +#define __SMLSLD __smlsld +#define __SMLSLDX __smlsldx +#define __SEL __sel +#define __QADD __qadd +#define __QSUB __qsub + +#define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ + ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) + +#define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ + ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) + +#define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ + ((int64_t)(ARG3) << 32) ) >> 32)) + +/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ + + + +#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ +/* IAR iccarm specific functions */ + +/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ +#include + +/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ + + + +#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ +/* TI CCS specific functions */ + +/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ +#include + +/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ + + + +#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ +/* GNU gcc specific functions */ + +/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) +{ + uint32_t result; + + __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); + return(result); +} + +#define __SSAT16(ARG1,ARG2) \ +({ \ + uint32_t __RES, __ARG1 = (ARG1); \ + __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ + __RES; \ + }) + +#define __USAT16(ARG1,ARG2) \ +({ \ + uint32_t __RES, __ARG1 = (ARG1); \ + __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ + __RES; \ + }) + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) +{ + uint32_t result; + + __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) +{ + uint32_t result; + + __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) +{ + uint32_t result; + + __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) +{ + uint32_t result; + + __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); + return(result); +} + +#define __SMLALD(ARG1,ARG2,ARG3) \ +({ \ + uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ + __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ + (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ + }) + +#define __SMLALDX(ARG1,ARG2,ARG3) \ +({ \ + uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ + __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ + (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ + }) + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) +{ + uint32_t result; + + __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) +{ + uint32_t result; + + __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); + return(result); +} + +#define __SMLSLD(ARG1,ARG2,ARG3) \ +({ \ + uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ + __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ + (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ + }) + +#define __SMLSLDX(ARG1,ARG2,ARG3) \ +({ \ + uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ + __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ + (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ + }) + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) +{ + uint32_t result; + + __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); + return(result); +} + +#define __PKHBT(ARG1,ARG2,ARG3) \ +({ \ + uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ + __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ + __RES; \ + }) + +#define __PKHTB(ARG1,ARG2,ARG3) \ +({ \ + uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ + if (ARG3 == 0) \ + __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ + else \ + __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ + __RES; \ + }) + +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) +{ + int32_t result; + + __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); + return(result); +} + +/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ + + + +#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ +/* TASKING carm specific functions */ + + +/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ +/* not yet supported */ +/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ + + +#endif + +/*@} end of group CMSIS_SIMD_intrinsics */ + + +#endif /* __CORE_CM4_SIMD_H */ + +#ifdef __cplusplus +} +#endif diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/core_cmFunc.h b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cmFunc.h new file mode 100644 index 000000000..0a18fafc3 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cmFunc.h @@ -0,0 +1,636 @@ +/**************************************************************************//** + * @file core_cmFunc.h + * @brief CMSIS Cortex-M Core Function Access Header File + * @version V3.20 + * @date 25. February 2013 + * + * @note + * + ******************************************************************************/ +/* Copyright (c) 2009 - 2013 ARM LIMITED + + 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. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + 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 COPYRIGHT HOLDERS AND 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. + ---------------------------------------------------------------------------*/ + + +#ifndef __CORE_CMFUNC_H +#define __CORE_CMFUNC_H + + +/* ########################### Core Function Access ########################### */ +/** \ingroup CMSIS_Core_FunctionInterface + \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions + @{ + */ + +#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ +/* ARM armcc specific functions */ + +#if (__ARMCC_VERSION < 400677) + #error "Please use ARM Compiler Toolchain V4.0.677 or later!" +#endif + +/* intrinsic void __enable_irq(); */ +/* intrinsic void __disable_irq(); */ + +/** \brief Get Control Register + + This function returns the content of the Control Register. + + \return Control Register value + */ +__STATIC_INLINE uint32_t __get_CONTROL(void) +{ + register uint32_t __regControl __ASM("control"); + return(__regControl); +} + + +/** \brief Set Control Register + + This function writes the given value to the Control Register. + + \param [in] control Control Register value to set + */ +__STATIC_INLINE void __set_CONTROL(uint32_t control) +{ + register uint32_t __regControl __ASM("control"); + __regControl = control; +} + + +/** \brief Get IPSR Register + + This function returns the content of the IPSR Register. + + \return IPSR Register value + */ +__STATIC_INLINE uint32_t __get_IPSR(void) +{ + register uint32_t __regIPSR __ASM("ipsr"); + return(__regIPSR); +} + + +/** \brief Get APSR Register + + This function returns the content of the APSR Register. + + \return APSR Register value + */ +__STATIC_INLINE uint32_t __get_APSR(void) +{ + register uint32_t __regAPSR __ASM("apsr"); + return(__regAPSR); +} + + +/** \brief Get xPSR Register + + This function returns the content of the xPSR Register. + + \return xPSR Register value + */ +__STATIC_INLINE uint32_t __get_xPSR(void) +{ + register uint32_t __regXPSR __ASM("xpsr"); + return(__regXPSR); +} + + +/** \brief Get Process Stack Pointer + + This function returns the current value of the Process Stack Pointer (PSP). + + \return PSP Register value + */ +__STATIC_INLINE uint32_t __get_PSP(void) +{ + register uint32_t __regProcessStackPointer __ASM("psp"); + return(__regProcessStackPointer); +} + + +/** \brief Set Process Stack Pointer + + This function assigns the given value to the Process Stack Pointer (PSP). + + \param [in] topOfProcStack Process Stack Pointer value to set + */ +__STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) +{ + register uint32_t __regProcessStackPointer __ASM("psp"); + __regProcessStackPointer = topOfProcStack; +} + + +/** \brief Get Main Stack Pointer + + This function returns the current value of the Main Stack Pointer (MSP). + + \return MSP Register value + */ +__STATIC_INLINE uint32_t __get_MSP(void) +{ + register uint32_t __regMainStackPointer __ASM("msp"); + return(__regMainStackPointer); +} + + +/** \brief Set Main Stack Pointer + + This function assigns the given value to the Main Stack Pointer (MSP). + + \param [in] topOfMainStack Main Stack Pointer value to set + */ +__STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) +{ + register uint32_t __regMainStackPointer __ASM("msp"); + __regMainStackPointer = topOfMainStack; +} + + +/** \brief Get Priority Mask + + This function returns the current state of the priority mask bit from the Priority Mask Register. + + \return Priority Mask value + */ +__STATIC_INLINE uint32_t __get_PRIMASK(void) +{ + register uint32_t __regPriMask __ASM("primask"); + return(__regPriMask); +} + + +/** \brief Set Priority Mask + + This function assigns the given value to the Priority Mask Register. + + \param [in] priMask Priority Mask + */ +__STATIC_INLINE void __set_PRIMASK(uint32_t priMask) +{ + register uint32_t __regPriMask __ASM("primask"); + __regPriMask = (priMask); +} + + +#if (__CORTEX_M >= 0x03) + +/** \brief Enable FIQ + + This function enables FIQ interrupts by clearing the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +#define __enable_fault_irq __enable_fiq + + +/** \brief Disable FIQ + + This function disables FIQ interrupts by setting the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +#define __disable_fault_irq __disable_fiq + + +/** \brief Get Base Priority + + This function returns the current value of the Base Priority register. + + \return Base Priority register value + */ +__STATIC_INLINE uint32_t __get_BASEPRI(void) +{ + register uint32_t __regBasePri __ASM("basepri"); + return(__regBasePri); +} + + +/** \brief Set Base Priority + + This function assigns the given value to the Base Priority register. + + \param [in] basePri Base Priority value to set + */ +__STATIC_INLINE void __set_BASEPRI(uint32_t basePri) +{ + register uint32_t __regBasePri __ASM("basepri"); + __regBasePri = (basePri & 0xff); +} + + +/** \brief Get Fault Mask + + This function returns the current value of the Fault Mask register. + + \return Fault Mask register value + */ +__STATIC_INLINE uint32_t __get_FAULTMASK(void) +{ + register uint32_t __regFaultMask __ASM("faultmask"); + return(__regFaultMask); +} + + +/** \brief Set Fault Mask + + This function assigns the given value to the Fault Mask register. + + \param [in] faultMask Fault Mask value to set + */ +__STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) +{ + register uint32_t __regFaultMask __ASM("faultmask"); + __regFaultMask = (faultMask & (uint32_t)1); +} + +#endif /* (__CORTEX_M >= 0x03) */ + + +#if (__CORTEX_M == 0x04) + +/** \brief Get FPSCR + + This function returns the current value of the Floating Point Status/Control register. + + \return Floating Point Status/Control register value + */ +__STATIC_INLINE uint32_t __get_FPSCR(void) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + register uint32_t __regfpscr __ASM("fpscr"); + return(__regfpscr); +#else + return(0); +#endif +} + + +/** \brief Set FPSCR + + This function assigns the given value to the Floating Point Status/Control register. + + \param [in] fpscr Floating Point Status/Control value to set + */ +__STATIC_INLINE void __set_FPSCR(uint32_t fpscr) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + register uint32_t __regfpscr __ASM("fpscr"); + __regfpscr = (fpscr); +#endif +} + +#endif /* (__CORTEX_M == 0x04) */ + + +#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ +/* IAR iccarm specific functions */ + +#include + + +#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ +/* TI CCS specific functions */ + +#include + + +#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ +/* GNU gcc specific functions */ + +/** \brief Enable IRQ Interrupts + + This function enables IRQ interrupts by clearing the I-bit in the CPSR. + Can only be executed in Privileged modes. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) +{ + __ASM volatile ("cpsie i" : : : "memory"); +} + + +/** \brief Disable IRQ Interrupts + + This function disables IRQ interrupts by setting the I-bit in the CPSR. + Can only be executed in Privileged modes. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) +{ + __ASM volatile ("cpsid i" : : : "memory"); +} + + +/** \brief Get Control Register + + This function returns the content of the Control Register. + + \return Control Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void) +{ + uint32_t result; + + __ASM volatile ("MRS %0, control" : "=r" (result) ); + return(result); +} + + +/** \brief Set Control Register + + This function writes the given value to the Control Register. + + \param [in] control Control Register value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control) +{ + __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); +} + + +/** \brief Get IPSR Register + + This function returns the content of the IPSR Register. + + \return IPSR Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void) +{ + uint32_t result; + + __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); + return(result); +} + + +/** \brief Get APSR Register + + This function returns the content of the APSR Register. + + \return APSR Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) +{ + uint32_t result; + + __ASM volatile ("MRS %0, apsr" : "=r" (result) ); + return(result); +} + + +/** \brief Get xPSR Register + + This function returns the content of the xPSR Register. + + \return xPSR Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void) +{ + uint32_t result; + + __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); + return(result); +} + + +/** \brief Get Process Stack Pointer + + This function returns the current value of the Process Stack Pointer (PSP). + + \return PSP Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void) +{ + register uint32_t result; + + __ASM volatile ("MRS %0, psp\n" : "=r" (result) ); + return(result); +} + + +/** \brief Set Process Stack Pointer + + This function assigns the given value to the Process Stack Pointer (PSP). + + \param [in] topOfProcStack Process Stack Pointer value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) +{ + __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); +} + + +/** \brief Get Main Stack Pointer + + This function returns the current value of the Main Stack Pointer (MSP). + + \return MSP Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void) +{ + register uint32_t result; + + __ASM volatile ("MRS %0, msp\n" : "=r" (result) ); + return(result); +} + + +/** \brief Set Main Stack Pointer + + This function assigns the given value to the Main Stack Pointer (MSP). + + \param [in] topOfMainStack Main Stack Pointer value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) +{ + __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); +} + + +/** \brief Get Priority Mask + + This function returns the current state of the priority mask bit from the Priority Mask Register. + + \return Priority Mask value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void) +{ + uint32_t result; + + __ASM volatile ("MRS %0, primask" : "=r" (result) ); + return(result); +} + + +/** \brief Set Priority Mask + + This function assigns the given value to the Priority Mask Register. + + \param [in] priMask Priority Mask + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) +{ + __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); +} + + +#if (__CORTEX_M >= 0x03) + +/** \brief Enable FIQ + + This function enables FIQ interrupts by clearing the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void) +{ + __ASM volatile ("cpsie f" : : : "memory"); +} + + +/** \brief Disable FIQ + + This function disables FIQ interrupts by setting the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void) +{ + __ASM volatile ("cpsid f" : : : "memory"); +} + + +/** \brief Get Base Priority + + This function returns the current value of the Base Priority register. + + \return Base Priority register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void) +{ + uint32_t result; + + __ASM volatile ("MRS %0, basepri_max" : "=r" (result) ); + return(result); +} + + +/** \brief Set Base Priority + + This function assigns the given value to the Base Priority register. + + \param [in] basePri Base Priority value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value) +{ + __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory"); +} + + +/** \brief Get Fault Mask + + This function returns the current value of the Fault Mask register. + + \return Fault Mask register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void) +{ + uint32_t result; + + __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); + return(result); +} + + +/** \brief Set Fault Mask + + This function assigns the given value to the Fault Mask register. + + \param [in] faultMask Fault Mask value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) +{ + __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); +} + +#endif /* (__CORTEX_M >= 0x03) */ + + +#if (__CORTEX_M == 0x04) + +/** \brief Get FPSCR + + This function returns the current value of the Floating Point Status/Control register. + + \return Floating Point Status/Control register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + uint32_t result; + + /* Empty asm statement works as a scheduling barrier */ + __ASM volatile (""); + __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); + __ASM volatile (""); + return(result); +#else + return(0); +#endif +} + + +/** \brief Set FPSCR + + This function assigns the given value to the Floating Point Status/Control register. + + \param [in] fpscr Floating Point Status/Control value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + /* Empty asm statement works as a scheduling barrier */ + __ASM volatile (""); + __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc"); + __ASM volatile (""); +#endif +} + +#endif /* (__CORTEX_M == 0x04) */ + + +#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ +/* TASKING carm specific functions */ + +/* + * The CMSIS functions have been implemented as intrinsics in the compiler. + * Please use "carm -?i" to get an up to date list of all instrinsics, + * Including the CMSIS ones. + */ + +#endif + +/*@} end of CMSIS_Core_RegAccFunctions */ + + +#endif /* __CORE_CMFUNC_H */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/core_cmInstr.h b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cmInstr.h new file mode 100644 index 000000000..d213f0eed --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/core_cmInstr.h @@ -0,0 +1,688 @@ +/**************************************************************************//** + * @file core_cmInstr.h + * @brief CMSIS Cortex-M Core Instruction Access Header File + * @version V3.20 + * @date 05. March 2013 + * + * @note + * + ******************************************************************************/ +/* Copyright (c) 2009 - 2013 ARM LIMITED + + 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. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + 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 COPYRIGHT HOLDERS AND 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. + ---------------------------------------------------------------------------*/ + + +#ifndef __CORE_CMINSTR_H +#define __CORE_CMINSTR_H + + +/* ########################## Core Instruction Access ######################### */ +/** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface + Access to dedicated instructions + @{ +*/ + +#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ +/* ARM armcc specific functions */ + +#if (__ARMCC_VERSION < 400677) + #error "Please use ARM Compiler Toolchain V4.0.677 or later!" +#endif + + +/** \brief No Operation + + No Operation does nothing. This instruction can be used for code alignment purposes. + */ +#define __NOP __nop + + +/** \brief Wait For Interrupt + + Wait For Interrupt is a hint instruction that suspends execution + until one of a number of events occurs. + */ +#define __WFI __wfi + + +/** \brief Wait For Event + + Wait For Event is a hint instruction that permits the processor to enter + a low-power state until one of a number of events occurs. + */ +#define __WFE __wfe + + +/** \brief Send Event + + Send Event is a hint instruction. It causes an event to be signaled to the CPU. + */ +#define __SEV __sev + + +/** \brief Instruction Synchronization Barrier + + Instruction Synchronization Barrier flushes the pipeline in the processor, + so that all instructions following the ISB are fetched from cache or + memory, after the instruction has been completed. + */ +#define __ISB() __isb(0xF) + + +/** \brief Data Synchronization Barrier + + This function acts as a special kind of Data Memory Barrier. + It completes when all explicit memory accesses before this instruction complete. + */ +#define __DSB() __dsb(0xF) + + +/** \brief Data Memory Barrier + + This function ensures the apparent order of the explicit memory operations before + and after the instruction, without ensuring their completion. + */ +#define __DMB() __dmb(0xF) + + +/** \brief Reverse byte order (32 bit) + + This function reverses the byte order in integer value. + + \param [in] value Value to reverse + \return Reversed value + */ +#define __REV __rev + + +/** \brief Reverse byte order (16 bit) + + This function reverses the byte order in two unsigned short values. + + \param [in] value Value to reverse + \return Reversed value + */ +#ifndef __NO_EMBEDDED_ASM +__attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value) +{ + rev16 r0, r0 + bx lr +} +#endif + +/** \brief Reverse byte order in signed short value + + This function reverses the byte order in a signed short value with sign extension to integer. + + \param [in] value Value to reverse + \return Reversed value + */ +#ifndef __NO_EMBEDDED_ASM +__attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value) +{ + revsh r0, r0 + bx lr +} +#endif + + +/** \brief Rotate Right in unsigned value (32 bit) + + This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. + + \param [in] value Value to rotate + \param [in] value Number of Bits to rotate + \return Rotated value + */ +#define __ROR __ror + + +/** \brief Breakpoint + + This function causes the processor to enter Debug state. + Debug tools can use this to investigate system state when the instruction at a particular address is reached. + + \param [in] value is ignored by the processor. + If required, a debugger can use it to store additional information about the breakpoint. + */ +#define __BKPT(value) __breakpoint(value) + + +#if (__CORTEX_M >= 0x03) + +/** \brief Reverse bit order of value + + This function reverses the bit order of the given value. + + \param [in] value Value to reverse + \return Reversed value + */ +#define __RBIT __rbit + + +/** \brief LDR Exclusive (8 bit) + + This function performs a exclusive LDR command for 8 bit value. + + \param [in] ptr Pointer to data + \return value of type uint8_t at (*ptr) + */ +#define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr)) + + +/** \brief LDR Exclusive (16 bit) + + This function performs a exclusive LDR command for 16 bit values. + + \param [in] ptr Pointer to data + \return value of type uint16_t at (*ptr) + */ +#define __LDREXH(ptr) ((uint16_t) __ldrex(ptr)) + + +/** \brief LDR Exclusive (32 bit) + + This function performs a exclusive LDR command for 32 bit values. + + \param [in] ptr Pointer to data + \return value of type uint32_t at (*ptr) + */ +#define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr)) + + +/** \brief STR Exclusive (8 bit) + + This function performs a exclusive STR command for 8 bit values. + + \param [in] value Value to store + \param [in] ptr Pointer to location + \return 0 Function succeeded + \return 1 Function failed + */ +#define __STREXB(value, ptr) __strex(value, ptr) + + +/** \brief STR Exclusive (16 bit) + + This function performs a exclusive STR command for 16 bit values. + + \param [in] value Value to store + \param [in] ptr Pointer to location + \return 0 Function succeeded + \return 1 Function failed + */ +#define __STREXH(value, ptr) __strex(value, ptr) + + +/** \brief STR Exclusive (32 bit) + + This function performs a exclusive STR command for 32 bit values. + + \param [in] value Value to store + \param [in] ptr Pointer to location + \return 0 Function succeeded + \return 1 Function failed + */ +#define __STREXW(value, ptr) __strex(value, ptr) + + +/** \brief Remove the exclusive lock + + This function removes the exclusive lock which is created by LDREX. + + */ +#define __CLREX __clrex + + +/** \brief Signed Saturate + + This function saturates a signed value. + + \param [in] value Value to be saturated + \param [in] sat Bit position to saturate to (1..32) + \return Saturated value + */ +#define __SSAT __ssat + + +/** \brief Unsigned Saturate + + This function saturates an unsigned value. + + \param [in] value Value to be saturated + \param [in] sat Bit position to saturate to (0..31) + \return Saturated value + */ +#define __USAT __usat + + +/** \brief Count leading zeros + + This function counts the number of leading zeros of a data value. + + \param [in] value Value to count the leading zeros + \return number of leading zeros in value + */ +#define __CLZ __clz + +#endif /* (__CORTEX_M >= 0x03) */ + + + +#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ +/* IAR iccarm specific functions */ + +#include + + +#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ +/* TI CCS specific functions */ + +#include + + +#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ +/* GNU gcc specific functions */ + +/* Define macros for porting to both thumb1 and thumb2. + * For thumb1, use low register (r0-r7), specified by constrant "l" + * Otherwise, use general registers, specified by constrant "r" */ +#if defined (__thumb__) && !defined (__thumb2__) +#define __CMSIS_GCC_OUT_REG(r) "=l" (r) +#define __CMSIS_GCC_USE_REG(r) "l" (r) +#else +#define __CMSIS_GCC_OUT_REG(r) "=r" (r) +#define __CMSIS_GCC_USE_REG(r) "r" (r) +#endif + +/** \brief No Operation + + No Operation does nothing. This instruction can be used for code alignment purposes. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __NOP(void) +{ + __ASM volatile ("nop"); +} + + +/** \brief Wait For Interrupt + + Wait For Interrupt is a hint instruction that suspends execution + until one of a number of events occurs. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFI(void) +{ + __ASM volatile ("wfi"); +} + + +/** \brief Wait For Event + + Wait For Event is a hint instruction that permits the processor to enter + a low-power state until one of a number of events occurs. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFE(void) +{ + __ASM volatile ("wfe"); +} + + +/** \brief Send Event + + Send Event is a hint instruction. It causes an event to be signaled to the CPU. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __SEV(void) +{ + __ASM volatile ("sev"); +} + + +/** \brief Instruction Synchronization Barrier + + Instruction Synchronization Barrier flushes the pipeline in the processor, + so that all instructions following the ISB are fetched from cache or + memory, after the instruction has been completed. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __ISB(void) +{ + __ASM volatile ("isb"); +} + + +/** \brief Data Synchronization Barrier + + This function acts as a special kind of Data Memory Barrier. + It completes when all explicit memory accesses before this instruction complete. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __DSB(void) +{ + __ASM volatile ("dsb"); +} + + +/** \brief Data Memory Barrier + + This function ensures the apparent order of the explicit memory operations before + and after the instruction, without ensuring their completion. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __DMB(void) +{ + __ASM volatile ("dmb"); +} + + +/** \brief Reverse byte order (32 bit) + + This function reverses the byte order in integer value. + + \param [in] value Value to reverse + \return Reversed value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV(uint32_t value) +{ +#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) + return __builtin_bswap32(value); +#else + uint32_t result; + + __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); + return(result); +#endif +} + + +/** \brief Reverse byte order (16 bit) + + This function reverses the byte order in two unsigned short values. + + \param [in] value Value to reverse + \return Reversed value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV16(uint32_t value) +{ + uint32_t result; + + __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); + return(result); +} + + +/** \brief Reverse byte order in signed short value + + This function reverses the byte order in a signed short value with sign extension to integer. + + \param [in] value Value to reverse + \return Reversed value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE int32_t __REVSH(int32_t value) +{ +#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) + return (short)__builtin_bswap16(value); +#else + uint32_t result; + + __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); + return(result); +#endif +} + + +/** \brief Rotate Right in unsigned value (32 bit) + + This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. + + \param [in] value Value to rotate + \param [in] value Number of Bits to rotate + \return Rotated value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) +{ + return (op1 >> op2) | (op1 << (32 - op2)); +} + + +/** \brief Breakpoint + + This function causes the processor to enter Debug state. + Debug tools can use this to investigate system state when the instruction at a particular address is reached. + + \param [in] value is ignored by the processor. + If required, a debugger can use it to store additional information about the breakpoint. + */ +#define __BKPT(value) __ASM volatile ("bkpt "#value) + + +#if (__CORTEX_M >= 0x03) + +/** \brief Reverse bit order of value + + This function reverses the bit order of the given value. + + \param [in] value Value to reverse + \return Reversed value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value) +{ + uint32_t result; + + __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); + return(result); +} + + +/** \brief LDR Exclusive (8 bit) + + This function performs a exclusive LDR command for 8 bit value. + + \param [in] ptr Pointer to data + \return value of type uint8_t at (*ptr) + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) +{ + uint32_t result; + +#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) + __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); +#else + /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not + accepted by assembler. So has to use following less efficient pattern. + */ + __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); +#endif + return(result); +} + + +/** \brief LDR Exclusive (16 bit) + + This function performs a exclusive LDR command for 16 bit values. + + \param [in] ptr Pointer to data + \return value of type uint16_t at (*ptr) + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) +{ + uint32_t result; + +#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) + __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); +#else + /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not + accepted by assembler. So has to use following less efficient pattern. + */ + __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); +#endif + return(result); +} + + +/** \brief LDR Exclusive (32 bit) + + This function performs a exclusive LDR command for 32 bit values. + + \param [in] ptr Pointer to data + \return value of type uint32_t at (*ptr) + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) +{ + uint32_t result; + + __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); + return(result); +} + + +/** \brief STR Exclusive (8 bit) + + This function performs a exclusive STR command for 8 bit values. + + \param [in] value Value to store + \param [in] ptr Pointer to location + \return 0 Function succeeded + \return 1 Function failed + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) +{ + uint32_t result; + + __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); + return(result); +} + + +/** \brief STR Exclusive (16 bit) + + This function performs a exclusive STR command for 16 bit values. + + \param [in] value Value to store + \param [in] ptr Pointer to location + \return 0 Function succeeded + \return 1 Function failed + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) +{ + uint32_t result; + + __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); + return(result); +} + + +/** \brief STR Exclusive (32 bit) + + This function performs a exclusive STR command for 32 bit values. + + \param [in] value Value to store + \param [in] ptr Pointer to location + \return 0 Function succeeded + \return 1 Function failed + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) +{ + uint32_t result; + + __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); + return(result); +} + + +/** \brief Remove the exclusive lock + + This function removes the exclusive lock which is created by LDREX. + + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __CLREX(void) +{ + __ASM volatile ("clrex" ::: "memory"); +} + + +/** \brief Signed Saturate + + This function saturates a signed value. + + \param [in] value Value to be saturated + \param [in] sat Bit position to saturate to (1..32) + \return Saturated value + */ +#define __SSAT(ARG1,ARG2) \ +({ \ + uint32_t __RES, __ARG1 = (ARG1); \ + __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ + __RES; \ + }) + + +/** \brief Unsigned Saturate + + This function saturates an unsigned value. + + \param [in] value Value to be saturated + \param [in] sat Bit position to saturate to (0..31) + \return Saturated value + */ +#define __USAT(ARG1,ARG2) \ +({ \ + uint32_t __RES, __ARG1 = (ARG1); \ + __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ + __RES; \ + }) + + +/** \brief Count leading zeros + + This function counts the number of leading zeros of a data value. + + \param [in] value Value to count the leading zeros + \return number of leading zeros in value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __CLZ(uint32_t value) +{ + uint32_t result; + + __ASM volatile ("clz %0, %1" : "=r" (result) : "r" (value) ); + return(result); +} + +#endif /* (__CORTEX_M >= 0x03) */ + + + + +#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ +/* TASKING carm specific functions */ + +/* + * The CMSIS functions have been implemented as intrinsics in the compiler. + * Please use "carm -?i" to get an up to date list of all intrinsics, + * Including the CMSIS ones. + */ + +#endif + +/*@}*/ /* end of group CMSIS_Core_InstructionInterface */ + +#endif /* __CORE_CMINSTR_H */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/crc_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/crc_17xx_40xx.h new file mode 100644 index 000000000..b182cdca0 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/crc_17xx_40xx.h @@ -0,0 +1,236 @@ +/* + * @brief LPC17xx/40xx Cyclic Redundancy Check (CRC) Engine driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licenser disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __CRC_17XX_40XX_H_ +#define __CRC_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup CRC_17XX_40XX CHIP: LPC17xx/40xx Cyclic Redundancy Check Engine driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/** + * @brief CRC register block structure + */ +typedef struct { /*!< CRC Structure */ + __IO uint32_t MODE; /*!< CRC Mode Register */ + __IO uint32_t SEED; /*!< CRC SEED Register */ + union { + __I uint32_t SUM; /*!< CRC Checksum Register. */ + __O uint32_t WRDATA32; /*!< CRC Data Register: write size 32-bit*/ + __O uint16_t WRDATA16; /*!< CRC Data Register: write size 16-bit*/ + __O uint8_t WRDATA8; /*!< CRC Data Register: write size 8-bit*/ + }; + +} LPC_CRC_T; + +/* + * @brief CRC MODE register description + */ +#define CRC_MODE_POLY_BITMASK ((0x03)) /** CRC polynomial Bit mask */ +#define CRC_MODE_POLY_CCITT (0x00) /** Select CRC-CCITT polynomial */ +#define CRC_MODE_POLY_CRC16 (0x01) /** Select CRC-16 polynomial */ +#define CRC_MODE_POLY_CRC32 (0x02) /** Select CRC-32 polynomial */ +#define CRC_MODE_WRDATA_BITMASK (0x03 << 2) /** CRC WR_Data Config Bit mask */ +#define CRC_MODE_WRDATA_BIT_RVS (1 << 2) /** Select Bit order reverse for WR_DATA (per byte) */ +#define CRC_MODE_WRDATA_CMPL (1 << 3) /** Select One's complement for WR_DATA */ +#define CRC_MODE_SUM_BITMASK (0x03 << 4) /** CRC Sum Config Bit mask */ +#define CRC_MODE_SUM_BIT_RVS (1 << 4) /** Select Bit order reverse for CRC_SUM */ +#define CRC_MODE_SUM_CMPL (1 << 5) /** Select One's complement for CRC_SUM */ + +#define MODE_CFG_CCITT (0x00) /** Pre-defined mode word for default CCITT setup */ +#define MODE_CFG_CRC16 (0x15) /** Pre-defined mode word for default CRC16 setup */ +#define MODE_CFG_CRC32 (0x36) /** Pre-defined mode word for default CRC32 setup */ + +#define CRC_SEED_CCITT (0x0000FFFF)/** Initial seed value for CCITT mode */ +#define CRC_SEED_CRC16 (0x00000000)/** Initial seed value for CRC16 mode */ +#define CRC_SEED_CRC32 (0xFFFFFFFF)/** Initial seed value for CRC32 mode */ + +/** + * @brief CRC polynomial + */ +typedef enum IP_CRC_001_POLY { + CRC_POLY_CCITT = CRC_MODE_POLY_CCITT, /**< CRC-CCIT polynomial */ + CRC_POLY_CRC16 = CRC_MODE_POLY_CRC16, /**< CRC-16 polynomial */ + CRC_POLY_CRC32 = CRC_MODE_POLY_CRC32, /**< CRC-32 polynomial */ + CRC_POLY_LAST, +} CRC_POLY_T; + +/** + * @brief Initializes the CRC Engine + * @return Nothing + */ +STATIC INLINE void Chip_CRC_Init(void) {} + +/** + * @brief Deinitializes the CRC Engine + * @return Nothing + */ +STATIC INLINE void Chip_CRC_Deinit(void) {} + +/** + * @brief Set the polynomial used for the CRC calculation + * @param poly : The enumerated polynomial to be used + * @param flags : An Or'ed value of flags that setup the mode + * @return Nothing + * @note Flags for setting up the mode word include CRC_MODE_WRDATA_BIT_RVS, + * CRC_MODE_WRDATA_CMPL, CRC_MODE_SUM_BIT_RVS, and CRC_MODE_SUM_CMPL. + */ +STATIC INLINE void Chip_CRC_SetPoly(CRC_POLY_T poly, uint32_t flags) +{ + LPC_CRC->MODE = (uint32_t) poly | flags; +} + +/** + * @brief Engage the CRC engine with defaults based on the polynomial to be used + * @param poly : The enumerated polynomial to be used + * @return Nothing + */ +void Chip_CRC_UseDefaultConfig(CRC_POLY_T poly); + +/** + * @brief Set the CRC Mode bits + * @param mode : Mode value + * @return Nothing + */ +STATIC INLINE void Chip_CRC_SetMode(uint32_t mode) +{ + LPC_CRC->MODE = mode; +} + +/** + * @brief Get the CRC Mode bits + * @return The current value of the CRC Mode bits + */ +STATIC INLINE uint32_t Chip_CRC_GetMode(void) +{ + return LPC_CRC->MODE; +} + +/** + * @brief Set the seed bits used by the CRC_SUM register + * @param seed : Seed value + * @return Nothing + */ +STATIC INLINE void Chip_CRC_SetSeed(uint32_t seed) +{ + LPC_CRC->SEED = seed; +} + +/** + * @brief Get the CRC seed value + * @return Seed value + */ +STATIC INLINE uint32_t Chip_CRC_GetSeed(void) +{ + return LPC_CRC->SEED; +} + +/** + * @brief Convenience function for writing 8-bit data to the CRC engine + * @param data : 8-bit data to write + * @return Nothing + */ +STATIC INLINE void Chip_CRC_Write8(uint8_t data) +{ + LPC_CRC->WRDATA8 = data; +} + +/** + * @brief Convenience function for writing 16-bit data to the CRC engine + * @param data : 16-bit data to write + * @return Nothing + */ +STATIC INLINE void Chip_CRC_Write16(uint16_t data) +{ + LPC_CRC->WRDATA16 = data; +} + +/** + * @brief Convenience function for writing 32-bit data to the CRC engine + * @param data : 32-bit data to write + * @return Nothing + */ +STATIC INLINE void Chip_CRC_Write32(uint32_t data) +{ + LPC_CRC->WRDATA32 = data; +} + +/** + * @brief Gets the CRC Sum based on the Mode and Seed as previously configured + * @return CRC Checksum value + */ +STATIC INLINE uint32_t Chip_CRC_Sum(void) +{ + return LPC_CRC->SUM; +} + +/** + * @brief Convenience function for computing a standard CCITT checksum from an 8-bit data block + * @param data : Pointer to the block of 8-bit data + * @param bytes : The number of bytes pointed to by data + * @return Check sum value + */ +uint32_t Chip_CRC_CRC8(const uint8_t *data, uint32_t bytes); + +/** + * @brief Convenience function for computing a standard CRC16 checksum from 16-bit data block + * @param data : Pointer to the block of 16-bit data + * @param hwords : The number of 16 byte entries pointed to by data + * @return Check sum value + */ +uint32_t Chip_CRC_CRC16(const uint16_t *data, uint32_t hwords); + +/** + * @brief Convenience function for computing a standard CRC32 checksum from 32-bit data block + * @param data : Pointer to the block of 32-bit data + * @param words : The number of 32-bit entries pointed to by data + * @return Check sum value + */ +uint32_t Chip_CRC_CRC32(const uint32_t *data, uint32_t words); + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __CRC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/dac_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/dac_17xx_40xx.h new file mode 100644 index 000000000..1376d754b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/dac_17xx_40xx.h @@ -0,0 +1,166 @@ +/* + * @brief LPC17xx/40xx D/A conversion driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __DAC_17XX_40XX_H_ +#define __DAC_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup DAC_17XX_40XX CHIP: LPC17xx/40xx D/A conversion driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief DAC register block structure + */ +typedef struct { /*!< DAC Structure */ + __IO uint32_t CR; /*!< DAC register. Holds the conversion data. */ + __IO uint32_t CTRL; /*!< DAC control register. */ + __IO uint32_t CNTVAL; /*!< DAC counter value register. */ +} LPC_DAC_T; + +/** After the selected settling time after this field is written with a + new VALUE, the voltage on the AOUT pin (with respect to VSSA) + is VALUE/1024 ? VREF */ +#define DAC_VALUE(n) ((uint32_t) ((n & 0x3FF) << 6)) +/** If this bit = 0: The settling time of the DAC is 1 microsecond max, + * and the maximum current is 700 microAmpere + * If this bit = 1: The settling time of the DAC is 2.5 microsecond + * and the maximum current is 350 microAmpere + */ +#define DAC_BIAS_EN ((uint32_t) (1 << 16)) +/** Value to reload interrupt DMA counter */ +#define DAC_CCNT_VALUE(n) ((uint32_t) (n & 0xffff)) + +/** DCAR double buffering */ +#define DAC_DBLBUF_ENA ((uint32_t) (1 << 1)) +/** DCAR Time out count enable */ +#define DAC_CNT_ENA ((uint32_t) (1 << 2)) +/** DCAR DMA access */ +#define DAC_DMA_ENA ((uint32_t) (1 << 3)) +/** DCAR DACCTRL mask bit */ +#define DAC_DACCTRL_MASK ((uint32_t) (0x0F)) + +/** + * @brief Current option in DAC configuration option + */ +typedef enum IP_DAC_CURRENT_OPT { + DAC_MAX_UPDATE_RATE_1MHz = 0, /*!< Shorter settling times and higher power consumption; + allows for a maximum update rate of 1 MHz */ + DAC_MAX_UPDATE_RATE_400kHz /*!< Longer settling times and lower power consumption; + allows for a maximum update rate of 400 kHz */ +} DAC_CURRENT_OPT_T; + +/** + * @brief Initial DAC configuration + * - Maximum current is 700 uA + * - Value to AOUT is 0 + * @param pDAC : pointer to LPC_DAC_T + * @return Nothing + */ +void Chip_DAC_Init(LPC_DAC_T *pDAC); + +/** + * @brief Shutdown DAC + * @param pDAC : pointer to LPC_DAC_T + * @return Nothing + */ +void Chip_DAC_DeInit(LPC_DAC_T *pDAC); + +/** + * @brief Update value to DAC buffer + * @param pDAC : pointer to LPC_DAC_T + * @param dac_value : value 10 bit to be converted to output + * @return Nothing + */ +void Chip_DAC_UpdateValue(LPC_DAC_T *pDAC, uint32_t dac_value); + +/** + * @brief Set maximum update rate for DAC + * @param pDAC : pointer to LPC_DAC_T + * @param bias : Using Bias value, should be: + * - 0 is 1MHz + * - 1 is 400kHz + * @return Nothing + */ +void Chip_DAC_SetBias(LPC_DAC_T *pDAC, uint32_t bias); + +/** + * @brief Enables the DMA operation and controls DMA timer + * @param pDAC : pointer to LPC_DAC_T + * @param dacFlags : An Or'ed value of the following DAC values: + * - DAC_DBLBUF_ENA :enable/disable DACR double buffering feature + * - DAC_CNT_ENA :enable/disable timer out counter + * - DAC_DMA_ENA :enable/disable DMA access + * @return Nothing + * @note Pass an Or'ed value of the DAC flags to enable those options. + */ +STATIC INLINE void Chip_DAC_ConfigDAConverterControl(LPC_DAC_T *pDAC, uint32_t dacFlags) +{ + uint32_t temp; + + temp = pDAC->CTRL & ~DAC_DACCTRL_MASK; + pDAC->CTRL = temp | dacFlags; +} + +/** + * @brief Set reload value for interrupt/DMA counter + * @param pDAC : pointer to LPC_DAC_T + * @param time_out : time out to reload for interrupt/DMA counter + * @return Nothing + */ +STATIC INLINE void Chip_DAC_SetDMATimeOut(LPC_DAC_T *pDAC, uint32_t time_out) +{ + pDAC->CNTVAL = DAC_CCNT_VALUE(time_out); +} + +/** + * @brief Get status for interrupt/DMA time out + * @param pDAC : pointer to LPC_DAC_T + * @return interrupt/DMA time out status, should be SET or RESET + */ +STATIC INLINE IntStatus Chip_DAC_GetIntStatus(LPC_DAC_T *pDAC) +{ + return (pDAC->CTRL & 0x01) ? SET : RESET; +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __DAC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/eeprom_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/eeprom_17xx_40xx.h new file mode 100644 index 000000000..98bf820dc --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/eeprom_17xx_40xx.h @@ -0,0 +1,320 @@ +/* + * @brief LPC17xx/40xx EEPROM driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __EEPROM_17XX_40XX_H_ +#define __EEPROM_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup EEPROM_17XX_40XX CHIP: LPC17xx/40xx EEPROM driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/** + * @brief EEPROM register block structure + */ +typedef struct { /* EEPROM Structure */ + __IO uint32_t CMD; /*!< EEPROM command register */ + __IO uint32_t ADDR; /*!< EEPROM address register */ + __O uint32_t WDATA; /*!< EEPROM write data register */ + __I uint32_t RDATA; /*!< EEPROM read data register */ + __IO uint32_t WSTATE; /*!< EEPROM wait state register */ + __IO uint32_t CLKDIV; /*!< EEPROM clock divider register */ + __IO uint32_t PWRDWN; /*!< EEPROM power-down register */ + uint32_t RESERVED0[975]; + __O uint32_t INTENCLR; /*!< EEPROM interrupt enable clear */ + __O uint32_t INTENSET; /*!< EEPROM interrupt enable set */ + __I uint32_t INTSTAT; /*!< EEPROM interrupt status */ + __I uint32_t INTEN; /*!< EEPROM interrupt enable */ + __O uint32_t INTSTATCLR; /*!< EEPROM interrupt status clear */ + __O uint32_t INTSTATSET; /*!< EEPROM interrupt status set */ +} LPC_EEPROM_T; + +#define EEPROM_PAGE_SIZE 64 /*!< EEPROM byes per page */ +#define EEPROM_PAGE_NUM 63 /*!< EEPROM pages */ + +/* + * @brief Macro defines for EEPROM command register + */ +#define EEPROM_CMD_8BITS_READ (0) /*!< EEPROM 8-bit read command */ +#define EEPROM_CMD_16BITS_READ (1) /*!< EEPROM 16-bit read command */ +#define EEPROM_CMD_32BITS_READ (2) /*!< EEPROM 32-bit read command */ +#define EEPROM_CMD_8BITS_WRITE (3) /*!< EEPROM 8-bit write command */ +#define EEPROM_CMD_16BITS_WRITE (4) /*!< EEPROM 16-bit write command */ +#define EEPROM_CMD_32BITS_WRITE (5) /*!< EEPROM 32-bit write command */ +#define EEPROM_CMD_ERASE_PRG_PAGE (6) /*!< EEPROM erase/program command */ +#define EEPROM_CMD_RDPREFETCH (1 << 3)/*!< EEPROM read pre-fetch enable */ + +/* + * @brief Macro defines for EEPROM power down register + */ +#define EEPROM_PWRDWN (1 << 0) + +/* + * @brief Macro defines for EEPROM interrupt related registers + */ +#define EEPROM_INT_ENDOFRW (1 << 26) +#define EEPROM_INT_ENDOFPROG (1 << 28) + +/** + * @brief EEPROM Mode type definition + */ +typedef enum IP_EEPROM_RWSIZE { + EEPROM_RWSIZE_8BITS = 1, + EEPROM_RWSIZE_16BITS = 2, + EEPROM_RWSIZE_32BITS = 4 +} EEPROM_RWSIZE_T; + +/** + * @brief Put EEPROM device in power down mode + * @param pEEPROM : The base of EEPROM peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_EnablePowerDown(LPC_EEPROM_T *pEEPROM) +{ + pEEPROM->PWRDWN = EEPROM_PWRDWN; +} + +/** + * @brief Bring EEPROM device out of power down mode + * @param pEEPROM : The base of EEPROM peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_DisablePowerDown(LPC_EEPROM_T *pEEPROM) +{ + pEEPROM->PWRDWN = 0; +} + +/** + * @brief Initializes EEPROM + * @param pEEPROM : The base of EEPROM peripheral on the chip + * @return Nothing + */ +void Chip_EEPROM_Init(LPC_EEPROM_T *pEEPROM); + +/** + * @brief De-initializes EEPROM + * @param pEEPROM : The base of EEPROM peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_DeInit(LPC_EEPROM_T *pEEPROM) +{ + /* Enable EEPROM power down mode */ + Chip_EEPROM_EnablePowerDown(pEEPROM); +} + +/** + * @brief Select an EEPROM command + * @param pEEPROM : pointer to EEPROM peripheral block + * @param cmd : EEPROM command. + * @return Nothing + * @note cmd is or-ed bits value of EEPROM_CMD_[8|16|32]BITS_READ/EEPROM_CMD_[8|16|32]BITS_WRITE + * with EEPROM_CMD_RDPREFETCH flag. + * Read and erase/program operations are started on the EEPROM device as a side-effect of calling this function. + * Write operations are started as a side-effect of writing data to data register. + */ +STATIC INLINE void Chip_EEPROM_SetCmd(LPC_EEPROM_T *pEEPROM, uint32_t cmd) +{ + pEEPROM->CMD = cmd; +} + +/** + * @brief Set EEPROM address + * @param pEEPROM : pointer to EEPROM peripheral block + * @param pageAddr : Page address. + * @param pageOffset : Page address. + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_SetAddr(LPC_EEPROM_T *pEEPROM, uint32_t pageAddr, uint32_t pageOffset) +{ + pEEPROM->ADDR = (pageAddr << 6) | pageOffset; +} + +/** + * @brief Write EEPROM data + * @param pEEPROM : pointer to EEPROM peripheral block + * @param data : EEPROM data. + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_WriteData(LPC_EEPROM_T *pEEPROM, uint32_t data) +{ + pEEPROM->WDATA = data; +} + +/** + * @brief Read EEPROM data + * @param pEEPROM : pointer to EEPROM peripheral block + * @return data + */ +STATIC INLINE uint32_t Chip_EEPROM_ReadData(LPC_EEPROM_T *pEEPROM) +{ + return pEEPROM->RDATA; +} + +/** + * @brief Set EEPROM wait state + * @param pEEPROM : pointer to EEPROM peripheral block + * @param ws : Wait State value. + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_SetWaitState(LPC_EEPROM_T *pEEPROM, uint32_t ws) +{ + pEEPROM->WSTATE = ws; +} + +/** + * @brief Write data to EEPROM at specific address + * @param pEEPROM : The base of EEPROM peripheral on the chip + * @param pageOffset : offset of data in page register(0 - 63) + * @param pageAddress: page address (0-62) + * @param pData : buffer that contain data that will be written to buffer + * @param wsize : Write size:
+ * - EEPROM_RWSIZE_8BITS : 8-bit read/write mode
+ * - EEPROM_RWSIZE_16BITS : 16-bit read/write mode
+ * - EEPROM_RWSIZE_32BITS : 32-bit read/write mode
+ * @param byteNum : number written data (bytes) + * @return SUCCESS on successful write of data, or ERROR + * @note This function actually write data into EEPROM memory and automatically + * write into next page if current page is overflowed + */ +Status Chip_EEPROM_Write(LPC_EEPROM_T *pEEPROM, uint16_t pageOffset, + uint16_t pageAddress, + void *pData, + EEPROM_RWSIZE_T wsize, + uint32_t byteNum); + +/** + * @brief Read data to EEPROM at specific address + * @param pEEPROM : The base of EEPROM peripheral on the chip + * @param pageOffset : offset of data in page register(0 - 63) + * @param pageAddress: page address (0-62) + * @param pData : buffer that contain data read from read data register + * @param rsize : Read size:
+ * - EEPROM_RWSIZE_8BITS : 8-bit read/write mode
+ * - EEPROM_RWSIZE_16BITS : 16-bit read/write mode
+ * - EEPROM_RWSIZE_32BITS : 32-bit read/write mode
+ * @param byteNum : number read data (bytes) + * @return Nothing + */ +void Chip_EEPROM_Read(LPC_EEPROM_T *pEEPROM, uint16_t pageOffset, + uint16_t pageAddress, + void *pData, + EEPROM_RWSIZE_T rsize, + uint32_t byteNum); + +/** + * @brief Erase a page at the specific address + * @param pEEPROM : The base of EEPROM peripheral on the chip + * @param address : EEPROM page address (0-62) + * @return Nothing + */ +void Chip_EEPROM_Erase(LPC_EEPROM_T *pEEPROM, uint16_t address); + +/** + * @brief Enable EEPROM interrupt + * @param pEEPROM : pointer to EEPROM peripheral block + * @param mask : interrupt mask (or-ed bits value of EEPROM_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_EnableInt(LPC_EEPROM_T *pEEPROM, uint32_t mask) +{ + pEEPROM->INTENSET = mask; +} + +/** + * @brief Disable EEPROM interrupt + * @param pEEPROM : pointer to EEPROM peripheral block + * @param mask : interrupt mask (or-ed bits value of EEPROM_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_DisableInt(LPC_EEPROM_T *pEEPROM, uint32_t mask) +{ + pEEPROM->INTENCLR = mask; +} + +/** + * @brief Get the value of the EEPROM interrupt enable register + * @param pEEPROM : pointer to EEPROM peripheral block + * @return Or-ed bits value of EEPROM_INT_* + */ +STATIC INLINE uint32_t Chip_EEPROM_GetIntEnable(LPC_EEPROM_T *pEEPROM) +{ + return pEEPROM->INTEN; +} + +/** + * @brief Get EEPROM interrupt status + * @param pEEPROM : pointer to EEPROM peripheral block + * @return Or-ed bits value of EEPROM_INT_* + */ +STATIC INLINE uint32_t Chip_EEPROM_GetIntStatus(LPC_EEPROM_T *pEEPROM) +{ + return pEEPROM->INTSTAT; +} + +/** + * @brief Set EEPROM interrupt status + * @param pEEPROM : pointer to EEPROM peripheral block + * @param mask : interrupt mask (or-ed bits value of EEPROM_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_SetIntStatus(LPC_EEPROM_T *pEEPROM, uint32_t mask) +{ + pEEPROM->INTSTATSET = mask; +} + +/** + * @brief Clear EEPROM interrupt status + * @param pEEPROM : pointer to EEPROM peripheral block + * @param mask : interrupt mask (or-ed bits value of EEPROM_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_EEPROM_ClearIntStatus(LPC_EEPROM_T *pEEPROM, uint32_t mask) +{ + pEEPROM->INTSTATCLR = mask; +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __EEPROM_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/emc_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/emc_17xx_40xx.h new file mode 100644 index 000000000..6fccf330d --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/emc_17xx_40xx.h @@ -0,0 +1,358 @@ +/* + * @brief LPC17xx/40xx EMC driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __EMC_17XX_40XX_H_ +#define __EMC_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup EMC_17XX_40XX CHIP: LPC17xx/40xx External Memory Controller driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + * The EMC interface clocks must be enabled outside this driver prior to + * calling any function of this driver. + */ + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/** + * @brief External Memory Controller (EMC) register block structure + */ +typedef struct { /*!< EMC Structure */ + __IO uint32_t CONTROL; /*!< Controls operation of the memory controller. */ + __I uint32_t STATUS; /*!< Provides EMC status information. */ + __IO uint32_t CONFIG; /*!< Configures operation of the memory controller. */ + __I uint32_t RESERVED0[5]; + __IO uint32_t DYNAMICCONTROL; /*!< Controls dynamic memory operation. */ + __IO uint32_t DYNAMICREFRESH; /*!< Configures dynamic memory refresh operation. */ + __IO uint32_t DYNAMICREADCONFIG; /*!< Configures the dynamic memory read strategy. */ + __I uint32_t RESERVED1; + __IO uint32_t DYNAMICRP; /*!< Selects the precharge command period. */ + __IO uint32_t DYNAMICRAS; /*!< Selects the active to precharge command period. */ + __IO uint32_t DYNAMICSREX; /*!< Selects the self-refresh exit time. */ + __IO uint32_t DYNAMICAPR; /*!< Selects the last-data-out to active command time. */ + __IO uint32_t DYNAMICDAL; /*!< Selects the data-in to active command time. */ + __IO uint32_t DYNAMICWR; /*!< Selects the write recovery time. */ + __IO uint32_t DYNAMICRC; /*!< Selects the active to active command period. */ + __IO uint32_t DYNAMICRFC; /*!< Selects the auto-refresh period. */ + __IO uint32_t DYNAMICXSR; /*!< Selects the exit self-refresh to active command time. */ + __IO uint32_t DYNAMICRRD; /*!< Selects the active bank A to active bank B latency. */ + __IO uint32_t DYNAMICMRD; /*!< Selects the load mode register to active command time. */ + __I uint32_t RESERVED2[9]; + __IO uint32_t STATICEXTENDEDWAIT; /*!< Selects time for long static memory read and write transfers. */ + __I uint32_t RESERVED3[31]; + __IO uint32_t DYNAMICCONFIG0; /*!< Selects the configuration information for dynamic memory chip select n. */ + __IO uint32_t DYNAMICRASCAS0; /*!< Selects the RAS and CAS latencies for dynamic memory chip select n. */ + __I uint32_t RESERVED4[6]; + __IO uint32_t DYNAMICCONFIG1; /*!< Selects the configuration information for dynamic memory chip select n. */ + __IO uint32_t DYNAMICRASCAS1; /*!< Selects the RAS and CAS latencies for dynamic memory chip select n. */ + __I uint32_t RESERVED5[6]; + __IO uint32_t DYNAMICCONFIG2; /*!< Selects the configuration information for dynamic memory chip select n. */ + __IO uint32_t DYNAMICRASCAS2; /*!< Selects the RAS and CAS latencies for dynamic memory chip select n. */ + __I uint32_t RESERVED6[6]; + __IO uint32_t DYNAMICCONFIG3; /*!< Selects the configuration information for dynamic memory chip select n. */ + __IO uint32_t DYNAMICRASCAS3; /*!< Selects the RAS and CAS latencies for dynamic memory chip select n. */ + __I uint32_t RESERVED7[38]; + __IO uint32_t STATICCONFIG0; /*!< Selects the memory configuration for static chip select n. */ + __IO uint32_t STATICWAITWEN0; /*!< Selects the delay from chip select n to write enable. */ + __IO uint32_t STATICWAITOEN0; /*!< Selects the delay from chip select n or address change, whichever is later, to output enable. */ + __IO uint32_t STATICWAITRD0; /*!< Selects the delay from chip select n to a read access. */ + __IO uint32_t STATICWAITPAG0; /*!< Selects the delay for asynchronous page mode sequential accesses for chip select n. */ + __IO uint32_t STATICWAITWR0; /*!< Selects the delay from chip select n to a write access. */ + __IO uint32_t STATICWAITTURN0; /*!< Selects bus turnaround cycles */ + __I uint32_t RESERVED8; + __IO uint32_t STATICCONFIG1; /*!< Selects the memory configuration for static chip select n. */ + __IO uint32_t STATICWAITWEN1; /*!< Selects the delay from chip select n to write enable. */ + __IO uint32_t STATICWAITOEN1; /*!< Selects the delay from chip select n or address change, whichever is later, to output enable. */ + __IO uint32_t STATICWAITRD1; /*!< Selects the delay from chip select n to a read access. */ + __IO uint32_t STATICWAITPAG1; /*!< Selects the delay for asynchronous page mode sequential accesses for chip select n. */ + __IO uint32_t STATICWAITWR1; /*!< Selects the delay from chip select n to a write access. */ + __IO uint32_t STATICWAITTURN1; /*!< Selects bus turnaround cycles */ + __I uint32_t RESERVED9; + __IO uint32_t STATICCONFIG2; /*!< Selects the memory configuration for static chip select n. */ + __IO uint32_t STATICWAITWEN2; /*!< Selects the delay from chip select n to write enable. */ + __IO uint32_t STATICWAITOEN2; /*!< Selects the delay from chip select n or address change, whichever is later, to output enable. */ + __IO uint32_t STATICWAITRD2; /*!< Selects the delay from chip select n to a read access. */ + __IO uint32_t STATICWAITPAG2; /*!< Selects the delay for asynchronous page mode sequential accesses for chip select n. */ + __IO uint32_t STATICWAITWR2; /*!< Selects the delay from chip select n to a write access. */ + __IO uint32_t STATICWAITTURN2; /*!< Selects bus turnaround cycles */ + __I uint32_t RESERVED10; + __IO uint32_t STATICCONFIG3; /*!< Selects the memory configuration for static chip select n. */ + __IO uint32_t STATICWAITWEN3; /*!< Selects the delay from chip select n to write enable. */ + __IO uint32_t STATICWAITOEN3; /*!< Selects the delay from chip select n or address change, whichever is later, to output enable. */ + __IO uint32_t STATICWAITRD3; /*!< Selects the delay from chip select n to a read access. */ + __IO uint32_t STATICWAITPAG3; /*!< Selects the delay for asynchronous page mode sequential accesses for chip select n. */ + __IO uint32_t STATICWAITWR3; /*!< Selects the delay from chip select n to a write access. */ + __IO uint32_t STATICWAITTURN3; /*!< Selects bus turnaround cycles */ +} LPC_EMC_T; + +/** + * Dynamic Chip Select Address + */ +#define EMC_ADDRESS_DYCS0 (0xA0000000) +#define EMC_ADDRESS_DYCS1 (0xB0000000) +#define EMC_ADDRESS_DYCS2 (0xC0000000) +#define EMC_ADDRESS_DYCS3 (0xD0000000) + +/** + * Static Chip Select Address + */ +#define EMC_ADDRESS_CS0 (0x80000000) +#define EMC_ADDRESS_CS1 (0x90000000) +#define EMC_ADDRESS_CS2 (0x98000000) +#define EMC_ADDRESS_CS3 (0x9C000000) + +/** + * @brief EMC register support bitfields and mask + */ +/* Reserve for extending support to ARM9 or nextgen LPC */ +#define EMC_SUPPORT_ONLY_PL172 /*!< Reserve for extending support to ARM9 or nextgen LPC */ + +#define EMC_CONFIG_ENDIAN_LITTLE (0) /*!< Value for EMC to operate in Little Endian Mode */ +#define EMC_CONFIG_ENDIAN_BIG (1) /*!< Value for EMC to operate in Big Endian Mode */ + +#define EMC_CONFIG_BUFFER_ENABLE (1 << 19) /*!< EMC Buffer enable bit in EMC Dynamic Configuration register */ +#define EMC_CONFIG_WRITE_PROTECT (1 << 20) /*!< EMC Write protect bit in EMC Dynamic Configuration register */ + +/* Dynamic Memory Configuration Register Bit Definitions */ +#define EMC_DYN_CONFIG_MD_BIT (3) /*!< Memory device bit in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_MD_SDRAM (0 << EMC_DYN_CONFIG_MD_BIT) /*!< Select device as SDRAM in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_MD_LPSDRAM (1 << EMC_DYN_CONFIG_MD_BIT) /*!< Select device as LPSDRAM in EMC Dynamic Configuration register */ + +#define EMC_DYN_CONFIG_LPSDRAM_BIT (12) /*!< LPSDRAM bit in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_LPSDRAM (1 << EMC_DYN_CONFIG_LPSDRAM_BIT) /*!< LPSDRAM value in EMC Dynamic Configuration register */ + +#define EMC_DYN_CONFIG_DEV_SIZE_BIT (9) /*!< Device Size starting bit in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_SIZE_16Mb (0x00 << EMC_DYN_CONFIG_DEV_SIZE_BIT) /*!< 16Mb Device Size value in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_SIZE_64Mb (0x01 << EMC_DYN_CONFIG_DEV_SIZE_BIT) /*!< 64Mb Device Size value in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_SIZE_128Mb (0x02 << EMC_DYN_CONFIG_DEV_SIZE_BIT) /*!< 128Mb Device Size value in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_SIZE_256Mb (0x03 << EMC_DYN_CONFIG_DEV_SIZE_BIT) /*!< 256Mb Device Size value in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_SIZE_512Mb (0x04 << EMC_DYN_CONFIG_DEV_SIZE_BIT) /*!< 512Mb Device Size value in EMC Dynamic Configuration register */ + +#define EMC_DYN_CONFIG_DEV_BUS_BIT (7) /*!< Device bus width starting bit in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_BUS_8 (0x00 << EMC_DYN_CONFIG_DEV_BUS_BIT) /*!< Device 8-bit bus width value in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_BUS_16 (0x01 << EMC_DYN_CONFIG_DEV_BUS_BIT) /*!< Device 16-bit bus width value in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DEV_BUS_32 (0x02 << EMC_DYN_CONFIG_DEV_BUS_BIT) /*!< Device 32-bit bus width value in EMC Dynamic Configuration register */ + +#define EMC_DYN_CONFIG_DATA_BUS_WIDTH_BIT (14) /*!< Device data bus width starting bit in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DATA_BUS_16 (0x00 << EMC_DYN_CONFIG_DATA_BUS_WIDTH_BIT) /*!< Device 16-bit data bus width value in EMC Dynamic Configuration register */ +#define EMC_DYN_CONFIG_DATA_BUS_32 (0x01 << EMC_DYN_CONFIG_DATA_BUS_WIDTH_BIT) /*!< Device 32-bit bus width value in EMC Dynamic Configuration register */ + +/*!< Memory configuration values in EMC Dynamic Configuration Register */ +#define EMC_DYN_CONFIG_2Mx8_2BANKS_11ROWS_9COLS ((0x0 << 9) | (0x0 << 7)) /*!< Value for Memory configuration - 2Mx8 2 Banks 11 Rows 9 Columns */ +#define EMC_DYN_CONFIG_1Mx16_2BANKS_11ROWS_8COLS ((0x0 << 9) | (0x1 << 7)) /*!< Value for Memory configuration - 1Mx16 2 Banks 11 Rows 8 Columns */ +#define EMC_DYN_CONFIG_8Mx8_4BANKS_12ROWS_9COLS ((0x1 << 9) | (0x0 << 7)) /*!< Value for Memory configuration - 8Mx8 4 Banks 12 Rows 9 Columns */ +#define EMC_DYN_CONFIG_4Mx16_4BANKS_12ROWS_8COLS ((0x1 << 9) | (0x1 << 7)) /*!< Value for Memory configuration - 4Mx16 4 Banks 12 Rows 8 Columns */ +#define EMC_DYN_CONFIG_2Mx32_4BANKS_11ROWS_8COLS ((0x1 << 9) | (0x2 << 7)) /*!< Value for Memory configuration - 2Mx32 4 Banks 11 Rows 8 Columns */ +#define EMC_DYN_CONFIG_16Mx8_4BANKS_12ROWS_10COLS ((0x2 << 9) | (0x0 << 7)) /*!< Value for Memory configuration - 16Mx8 4 Banks 12 Rows 10 Columns */ +#define EMC_DYN_CONFIG_8Mx16_4BANKS_12ROWS_9COLS ((0x2 << 9) | (0x1 << 7)) /*!< Value for Memory configuration - 8Mx16 4 Banks 12 Rows 9 Columns */ +#define EMC_DYN_CONFIG_4Mx32_4BANKS_12ROWS_8COLS ((0x2 << 9) | (0x2 << 7)) /*!< Value for Memory configuration - 4Mx32 4 Banks 12 Rows 8 Columns */ +#define EMC_DYN_CONFIG_32Mx8_4BANKS_13ROWS_10COLS ((0x3 << 9) | (0x0 << 7)) /*!< Value for Memory configuration - 32Mx8 4 Banks 13 Rows 10 Columns */ +#define EMC_DYN_CONFIG_16Mx16_4BANKS_13ROWS_9COLS ((0x3 << 9) | (0x1 << 7)) /*!< Value for Memory configuration - 16Mx16 4 Banks 13 Rows 8 Columns */ +#define EMC_DYN_CONFIG_8Mx32_4BANKS_13ROWS_8COLS ((0x3 << 9) | (0x2 << 7)) /*!< Value for Memory configuration - 8Mx32 4 Banks 13 Rows 8 Columns */ +#define EMC_DYN_CONFIG_64Mx8_4BANKS_13ROWS_11COLS ((0x4 << 9) | (0x0 << 7)) /*!< Value for Memory configuration - 64Mx8 4 Banks 13 Rows 11 Columns */ +#define EMC_DYN_CONFIG_32Mx16_4BANKS_13ROWS_10COLS ((0x4 << 9) | (0x1 << 7)) /*!< Value for Memory configuration - 32Mx16 4 Banks 13 Rows 10 Columns */ + +/*!< Dynamic Memory Mode Register Bit Definition */ +#define EMC_DYN_MODE_BURST_LEN_BIT (0) /*!< Starting bit No. of Burst Length in Dynamic Memory Mode Register */ +#define EMC_DYN_MODE_BURST_LEN_1 (0) /*!< Value to set Burst Length to 1 in Dynamic Memory Mode Register */ +#define EMC_DYN_MODE_BURST_LEN_2 (1) /*!< Value to set Burst Length to 2 in Dynamic Memory Mode Register */ +#define EMC_DYN_MODE_BURST_LEN_4 (2) /*!< Value to set Burst Length to 4 in Dynamic Memory Mode Register */ +#define EMC_DYN_MODE_BURST_LEN_8 (3) /*!< Value to set Burst Length to 8 in Dynamic Memory Mode Register */ +#define EMC_DYN_MODE_BURST_LEN_FULL (7) /*!< Value to set Burst Length to Full in Dynamic Memory Mode Register */ + +#define EMC_DYN_MODE_BURST_TYPE_BIT (3) /*!< Burst Type bit in Dynamic Memory Mode Register */ +#define EMC_DYN_MODE_BURST_TYPE_SEQUENTIAL (0 << EMC_DYN_MODE_BURST_TYPE_BIT) /*!< Burst Type Sequential in Dynamic Memory Mode Register */ +#define EMC_DYN_MODE_BURST_TYPE_INTERLEAVE (1 << EMC_DYN_MODE_BURST_TYPE_BIT) /*!< Burst Type Interleaved in Dynamic Memory Mode Register */ + +/*!< CAS Latency in Dynamic Mode Register */ +#define EMC_DYN_MODE_CAS_BIT (4) /*!< CAS latency starting bit in Dynamic Memory Mode register */ +#define EMC_DYN_MODE_CAS_1 (1 << EMC_DYN_MODE_CAS_BIT) /*!< value for CAS latency of 1 cycle */ +#define EMC_DYN_MODE_CAS_2 (2 << EMC_DYN_MODE_CAS_BIT) /*!< value for CAS latency of 2 cycle */ +#define EMC_DYN_MODE_CAS_3 (3 << EMC_DYN_MODE_CAS_BIT) /*!< value for CAS latency of 3 cycle */ + +/*!< Operation Mode in Dynamic Mode register */ +#define EMC_DYN_MODE_OPMODE_BIT (7) /*!< Dynamic Mode Operation bit */ +#define EMC_DYN_MODE_OPMODE_STANDARD (0 << EMC_DYN_MODE_OPMODE_BIT) /*!< Value for Dynamic standard operation Mode */ + +/*!< Write Burst Mode in Dynamic Mode register */ +#define EMC_DYN_MODE_WBMODE_BIT (9) /*!< Write Burst Mode bit */ +#define EMC_DYN_MODE_WBMODE_PROGRAMMED (0 << EMC_DYN_MODE_WBMODE_BIT) /*!< Write Burst Mode programmed */ +#define EMC_DYN_MODE_WBMODE_SINGLE_LOC (1 << EMC_DYN_MODE_WBMODE_BIT) /*!< Write Burst Mode Single LOC */ + +/*!< Dynamic Memory Control Register Bit Definitions */ +#define EMC_DYN_CONTROL_ENABLE (0x03) /*!< Control Enable value */ + +/*!< Static Memory Configuration Register Bit Definitions */ +#define EMC_STATIC_CONFIG_MEM_WIDTH_8 (0) /*!< Static Memory Configuration - 8-bit width */ +#define EMC_STATIC_CONFIG_MEM_WIDTH_16 (1) /*!< Static Memory Configuration - 16-bit width */ +#define EMC_STATIC_CONFIG_MEM_WIDTH_32 (2) /*!< Static Memory Configuration - 32-bit width */ + +#define EMC_STATIC_CONFIG_PAGE_MODE_BIT (3) /*!< Page Mode bit No */ +#define EMC_STATIC_CONFIG_PAGE_MODE_ENABLE (1 << EMC_STATIC_CONFIG_PAGE_MODE_BIT) /*!< Value to enable Page Mode */ + +#define EMC_STATIC_CONFIG_CS_POL_BIT (6) /*!< Chip Select bit No */ +#define EMC_STATIC_CONFIG_CS_POL_ACTIVE_HIGH (1 << EMC_STATIC_CONFIG_CS_POL_BIT) /*!< Chip Select polarity - Active High */ +#define EMC_STATIC_CONFIG_CS_POL_ACTIVE_LOW (0 << EMC_STATIC_CONFIG_CS_POL_BIT) /*!< Chip Select polarity - Active Low */ + +#define EMC_STATIC_CONFIG_BLS_BIT (7) /*!< BLS Configuration bit No */ +#define EMC_STATIC_CONFIG_BLS_HIGH (1 << EMC_STATIC_CONFIG_BLS_BIT) /*!< BLS High Configuration value */ +#define EMC_STATIC_CONFIG_BLS_LOW (0 << EMC_STATIC_CONFIG_BLS_BIT) /*!< BLS Low Configuration value */ + +#define EMC_STATIC_CONFIG_EW_BIT (8) /*!< Ext Wait bit No */ +#define EMC_STATIC_CONFIG_EW_ENABLE (1 << EMC_STATIC_CONFIG_EW_BIT) /*!< Ext Wait Enabled value */ +#define EMC_STATIC_CONFIG_EW_DISABLE (0 << EMC_STATIC_CONFIG_EW_BIT) /*!< Ext Wait Diabled value */ + +/*!< Q24.8 Fixed Point Helper */ +#define Q24_8_FP(x) ((x) * 256) +#define EMC_NANOSECOND(x) Q24_8_FP(x) +#define EMC_CLOCK(x) Q24_8_FP(-(x)) + +/** + * @brief EMC Dynamic Device Configuration structure used for IP drivers + */ +typedef struct { + uint32_t BaseAddr; /*!< Base Address */ + uint8_t RAS; /*!< RAS value */ + uint32_t ModeRegister; /*!< Mode Register value */ + uint32_t DynConfig; /*!< Dynamic Configuration value */ +} IP_EMC_DYN_DEVICE_CONFIG_T; + +/** + * @brief EMC Dynamic Configure Struct + */ +typedef struct { + int32_t RefreshPeriod; /*!< Refresh period */ + uint32_t ReadConfig; /*!< Clock*/ + int32_t tRP; /*!< Precharge Command Period */ + int32_t tRAS; /*!< Active to Precharge Command Period */ + int32_t tSREX; /*!< Self Refresh Exit Time */ + int32_t tAPR; /*!< Last Data Out to Active Time */ + int32_t tDAL; /*!< Data In to Active Command Time */ + int32_t tWR; /*!< Write Recovery Time */ + int32_t tRC; /*!< Active to Active Command Period */ + int32_t tRFC; /*!< Auto-refresh Period */ + int32_t tXSR; /*!< Exit Selt Refresh */ + int32_t tRRD; /*!< Active Bank A to Active Bank B Time */ + int32_t tMRD; /*!< Load Mode register command to Active Command */ + IP_EMC_DYN_DEVICE_CONFIG_T DevConfig[4]; /*!< Device Configuration array */ +} IP_EMC_DYN_CONFIG_T; + +/** + * @brief EMC Static Configure Structure + */ +typedef struct { + uint8_t ChipSelect; /*!< Chip select */ + uint32_t Config; /*!< Configuration value */ + int32_t WaitWen; /*!< Write Enable Wait */ + int32_t WaitOen; /*!< Output Enable Wait */ + int32_t WaitRd; /*!< Read Wait */ + int32_t WaitPage; /*!< Page Access Wait */ + int32_t WaitWr; /*!< Write Wait */ + int32_t WaitTurn; /*!< Turn around wait */ +} IP_EMC_STATIC_CONFIG_T; + +/** + * @brief Dyanmic memory setup + * @param Dynamic_Config : Pointer to dynamic memory setup data + * @return None + */ +void Chip_EMC_Dynamic_Init(IP_EMC_DYN_CONFIG_T *Dynamic_Config); + +/** + * @brief Static memory setup + * @param Static_Config : Pointer to static memory setup data + * @return None + */ +void Chip_EMC_Static_Init(IP_EMC_STATIC_CONFIG_T *Static_Config); + +/** + * @brief Enable Dynamic Memory Controller + * @param Enable : 1 = Enable Dynamic Memory Controller, 0 = Disable + * @return None + */ +void Chip_EMC_Dynamic_Enable(uint8_t Enable); + +/** + * @brief Mirror CS1 to CS0 and DYCS0 + * @param Enable : 1 = Mirror, 0 = Normal Memory Map + * @return None + */ +void Chip_EMC_Mirror(uint8_t Enable); + +/** + * @brief Enable EMC + * @param Enable : 1 = Enable, 0 = Disable + * @return None + */ +void Chip_EMC_Enable(uint8_t Enable); + +/** + * @brief Set EMC LowPower Mode + * @param Enable : 1 = Enable, 0 = Disable + * @return None + * @note This function should only be called when the memory + * controller is not busy (bit 0 of the status register is not set). + */ +void Chip_EMC_LowPowerMode(uint8_t Enable); + +/** + * @brief Initialize EMC + * @param Enable : 1 = Enable, 0 = Disable + * @param ClockRatio : clock out ratio, 0 = 1:1, 1 = 1:2 + * @param EndianMode : Endian Mode, 0 = Little, 1 = Big + * @return None + */ +void Chip_EMC_Init(uint32_t Enable, uint32_t ClockRatio, uint32_t EndianMode); + +/** + * @brief Set Static Memory Extended Wait in Clock + * @param Wait16Clks : Number of '16 clock' delay cycles + * @return None + */ +STATIC INLINE void Chip_EMC_SetStaticExtendedWait(uint32_t Wait16Clks) +{ + LPC_EMC->STATICEXTENDEDWAIT = Wait16Clks; +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __EMC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/enet_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/enet_17xx_40xx.h new file mode 100644 index 000000000..3bdb1f5b8 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/enet_17xx_40xx.h @@ -0,0 +1,914 @@ +/* + * @brief LPC17xx/40xx Ethernet driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __ENET_17XX_40XX_H_ +#define __ENET_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup ENET_17XX_40XX CHIP: LPC17xx/40xx Ethernet driver (2) + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief Ethernet MAC register block structure + */ +typedef struct { + __IO uint32_t MAC1; /*!< MAC Configuration register 1 */ + __IO uint32_t MAC2; /*!< MAC Configuration register 2 */ + __IO uint32_t IPGT; /*!< Back-to-Back Inter-Packet-Gap register */ + __IO uint32_t IPGR; /*!< Non Back-to-Back Inter-Packet-Gap register */ + __IO uint32_t CLRT; /*!< Collision window / Retry register */ + __IO uint32_t MAXF; /*!< Maximum Frame register */ + __IO uint32_t SUPP; /*!< PHY Support register */ + __IO uint32_t TEST; /*!< Test register */ + __IO uint32_t MCFG; /*!< MII Mgmt Configuration register */ + __IO uint32_t MCMD; /*!< MII Mgmt Command register */ + __IO uint32_t MADR; /*!< MII Mgmt Address register */ + __O uint32_t MWTD; /*!< MII Mgmt Write Data register */ + __I uint32_t MRDD; /*!< MII Mgmt Read Data register */ + __I uint32_t MIND; /*!< MII Mgmt Indicators register */ + uint32_t RESERVED0[2]; + __IO uint32_t SA[3]; /*!< Station Address registers */ +} ENET_MAC_T; + +/** + * @brief Ethernet Transfer register Block Structure + */ +typedef struct { + __IO uint32_t DESCRIPTOR; /*!< Descriptor base address register */ + __IO uint32_t STATUS; /*!< Status base address register */ + __IO uint32_t DESCRIPTORNUMBER; /*!< Number of descriptors register */ + __IO uint32_t PRODUCEINDEX; /*!< Produce index register */ + __IO uint32_t CONSUMEINDEX; /*!< Consume index register */ +} ENET_TRANSFER_INFO_T; + +/** + * @brief Ethernet Control register block structure + */ +typedef struct { + __IO uint32_t COMMAND; /*!< Command register */ + __I uint32_t STATUS; /*!< Status register */ + ENET_TRANSFER_INFO_T RX; /*!< Receive block registers */ + ENET_TRANSFER_INFO_T TX; /*!< Transmit block registers */ + uint32_t RESERVED0[10]; + __I uint32_t TSV0; /*!< Transmit status vector 0 register */ + __I uint32_t TSV1; /*!< Transmit status vector 1 register */ + __I uint32_t RSV; /*!< Receive status vector register */ + uint32_t RESERVED1[3]; + __IO uint32_t FLOWCONTROLCOUNTER; /*!< Flow control counter register */ + __I uint32_t FLOWCONTROLSTATUS; /*!< Flow control status register */ +} ENET_CONTROL_T; + +/** + * @brief Ethernet Receive Filter register block structure + */ +typedef struct { + __IO uint32_t CONTROL; /*!< Receive filter control register */ + __I uint32_t WOLSTATUS; /*!< Receive filter WoL status register */ + __O uint32_t WOLCLEAR; /*!< Receive filter WoL clear register */ + uint32_t RESERVED; + __IO uint32_t HashFilterL; /*!< Hash filter table LSBs register */ + __IO uint32_t HashFilterH; /*!< Hash filter table MSBs register */ +} ENET_RXFILTER_T; + +/** + * @brief Ethernet Module Control register block structure + */ +typedef struct { + __I uint32_t INTSTATUS; /*!< Interrupt status register */ + __IO uint32_t INTENABLE; /*!< Interrupt enable register */ + __O uint32_t INTCLEAR; /*!< Interrupt clear register */ + __O uint32_t INTSET; /*!< Interrupt set register */ + uint32_t RESERVED; + __IO uint32_t POWERDOWN; /*!< Power-down register */ +} ENET_MODULE_CTRL_T; + +/** + * @brief Ethernet register block structure + */ +typedef struct { + ENET_MAC_T MAC; /*!< MAC registers */ + uint32_t RESERVED1[45]; + ENET_CONTROL_T CONTROL; /*!< Control registers */ + uint32_t RESERVED4[34]; + ENET_RXFILTER_T RXFILTER; /*!< RxFilter registers */ + uint32_t RESERVED6[882]; + ENET_MODULE_CTRL_T MODULE_CONTROL; /*!< Module Control registers */ +} LPC_ENET_T; + +/* + * @brief MAC Configuration Register 1 bit definitions + */ +#define ENET_MAC1_MASK 0xcf1f /*!< MAC1 register mask */ +#define ENET_MAC1_RXENABLE 0x00000001 /*!< Receive Enable */ +#define ENET_MAC1_PARF 0x00000002 /*!< Pass All Receive Frames */ +#define ENET_MAC1_RXFLOWCTRL 0x00000004 /*!< RX Flow Control */ +#define ENET_MAC1_TXFLOWCTRL 0x00000008 /*!< TX Flow Control */ +#define ENET_MAC1_LOOPBACK 0x00000010 /*!< Loop Back Mode */ +#define ENET_MAC1_RESETTX 0x00000100 /*!< Reset TX Logic */ +#define ENET_MAC1_RESETMCSTX 0x00000200 /*!< Reset MAC TX Control Sublayer */ +#define ENET_MAC1_RESETRX 0x00000400 /*!< Reset RX Logic */ +#define ENET_MAC1_RESETMCSRX 0x00000800 /*!< Reset MAC RX Control Sublayer */ +#define ENET_MAC1_SIMRESET 0x00004000 /*!< Simulation Reset */ +#define ENET_MAC1_SOFTRESET 0x00008000 /*!< Soft Reset MAC */ + +/* + * @brief MAC Configuration Register 2 bit definitions + */ +#define ENET_MAC2_MASK 0x73ff /*!< MAC2 register mask */ +#define ENET_MAC2_FULLDUPLEX 0x00000001 /*!< Full-Duplex Mode */ +#define ENET_MAC2_FLC 0x00000002 /*!< Frame Length Checking */ +#define ENET_MAC2_HFEN 0x00000004 /*!< Huge Frame Enable */ +#define ENET_MAC2_DELAYEDCRC 0x00000008 /*!< Delayed CRC Mode */ +#define ENET_MAC2_CRCEN 0x00000010 /*!< Append CRC to every Frame */ +#define ENET_MAC2_PADCRCEN 0x00000020 /*!< Pad all Short Frames */ +#define ENET_MAC2_VLANPADEN 0x00000040 /*!< VLAN Pad Enable */ +#define ENET_MAC2_AUTODETPADEN 0x00000080 /*!< Auto Detect Pad Enable */ +#define ENET_MAC2_PPENF 0x00000100 /*!< Pure Preamble Enforcement */ +#define ENET_MAC2_LPENF 0x00000200 /*!< Long Preamble Enforcement */ +#define ENET_MAC2_NOBACKOFF 0x00001000 /*!< No Backoff Algorithm */ +#define ENET_MAC2_BP_NOBACKOFF 0x00002000 /*!< Backoff Presurre / No Backoff */ +#define ENET_MAC2_EXCESSDEFER 0x00004000 /*!< Excess Defer */ + +/* + * @brief Back-to-Back Inter-Packet-Gap Register bit definitions + */ +/** Programmable field representing the nibble time offset of the minimum possible period + * between the end of any transmitted packet to the beginning of the next */ +#define ENET_IPGT_BTOBINTEGAP(n) ((n) & 0x7F) + +/** Recommended value for Full Duplex of Programmable field representing the nibble time + * offset of the minimum possible period between the end of any transmitted packet to the + * beginning of the next */ +#define ENET_IPGT_FULLDUPLEX (ENET_IPGT_BTOBINTEGAP(0x15)) + +/** Recommended value for Half Duplex of Programmable field representing the nibble time + * offset of the minimum possible period between the end of any transmitted packet to the + * beginning of the next */ +#define ENET_IPGT_HALFDUPLEX (ENET_IPGT_BTOBINTEGAP(0x12)) + +/* + * @brief Non Back-to-Back Inter-Packet-Gap Register bit definitions + */ + +/** Programmable field representing the Non-Back-to-Back Inter-Packet-Gap */ +#define ENET_IPGR_NBTOBINTEGAP2(n) ((n) & 0x7F) + +/** Recommended value for Programmable field representing the Non-Back-to-Back Inter-Packet-Gap Part 1 */ +#define ENET_IPGR_P2_DEF (ENET_IPGR_NBTOBINTEGAP2(0x12)) + +/** Programmable field representing the optional carrierSense window referenced in + * IEEE 802.3/4.2.3.2.1 'Carrier Deference' */ +#define ENET_IPGR_NBTOBINTEGAP1(n) (((n) & 0x7F) << 8) + +/** Recommended value for Programmable field representing the Non-Back-to-Back Inter-Packet-Gap Part 2 */ +#define ENET_IPGR_P1_DEF ENET_IPGR_NBTOBINTEGAP1(0x0C) + +/* + * @brief Collision Window/Retry Register bit definitions + */ +/** Programmable field specifying the number of retransmission attempts following a collision before + * aborting the packet due to excessive collisions */ +#define ENET_CLRT_RETRANSMAX(n) ((n) & 0x0F) + +/** Programmable field representing the slot time or collision window during which collisions occur + * in properly configured networks */ +#define ENET_CLRT_COLLWIN(n) (((n) & 0x3F) << 8) + +/** Default value for Collision Window / Retry register */ +#define ENET_CLRT_DEF ((ENET_CLRT_RETRANSMAX(0x0F)) | (ENET_CLRT_COLLWIN(0x37))) + +/* + * @brief Maximum Frame Register bit definitions + */ +/** Represents a maximum receive frame of 1536 octets */ +#define ENET_MAXF_MAXFLEN(n) ((n) & 0xFFFF) +#define ENET_MAXF_MAXFLEN_DEF (0x600) + +/* PHY Support Register */ +#define ENET_SUPP_100Mbps_SPEED 0x00000100 /*!< Reduced MII Logic Current Speed */ + +/* + * @brief Test Register bit definitions + */ +#define ENET_TEST_SCPQ 0x00000001 /*!< Shortcut Pause Quanta */ +#define ENET_TEST_TESTPAUSE 0x00000002 /*!< Test Pause */ +#define ENET_TEST_TESTBP 0x00000004 /*!< Test Back Pressure */ + +/* + * @brief MII Management Configuration Register bit definitions + */ +#define ENET_MCFG_SCANINC 0x00000001 /*!< Scan Increment PHY Address */ +#define ENET_MCFG_SUPPPREAMBLE 0x00000002 /*!< Suppress Preamble */ +#define ENET_MCFG_CLOCKSEL(n) (((n) & 0x0F) << 2) /*!< Clock Select Field */ +#define ENET_MCFG_RES_MII 0x00008000 /*!< Reset MII Management Hardware */ +#define ENET_MCFG_RESETMIIMGMT 2500000UL /*!< MII Clock max */ + +/* + * @brief MII Management Command Register bit definitions + */ +#define ENET_MCMD_READ 0x00000001 /*!< MII Read */ +#define ENET_MCMD_SCAN 0x00000002 /*!< MII Scan continuously */ +#define ENET_MII_WR_TOUT 0x00050000 /*!< MII Write timeout count */ +#define ENET_MII_RD_TOUT 0x00050000 /*!< MII Read timeout count */ + +/* + * @brief MII Management Address Register bit definitions + */ +#define ENET_MADR_REGADDR(n) ((n) & 0x1F) /*!< MII Register Address field */ +#define ENET_MADR_PHYADDR(n) (((n) & 0x1F) << 8) /*!< PHY Address Field */ + +/* + * @brief MII Management Write Data Register bit definitions + */ +#define ENET_MWTD_DATA(n) ((n) & 0xFFFF) /*!< Data field for MMI Management Write Data register */ + +/** + * @brief MII Management Read Data Register bit definitions + */ +#define ENET_MRDD_DATA(n) ((n) & 0xFFFF) /*!< Data field for MMI Management Read Data register */ + +/* + * @brief MII Management Indicators Register bit definitions + */ +#define ENET_MIND_BUSY 0x00000001 /*!< MII is Busy */ +#define ENET_MIND_SCANNING 0x00000002 /*!< MII Scanning in Progress */ +#define ENET_MIND_NOTVALID 0x00000004 /*!< MII Read Data not valid */ +#define ENET_MIND_MIILINKFAIL 0x00000008 /*!< MII Link Failed */ + +/* + * @brief Command Register bit definitions + */ +#define ENET_COMMAND_RXENABLE 0x00000001 /*!< Enable Receive */ +#define ENET_COMMAND_TXENABLE 0x00000002 /*!< Enable Transmit */ +#define ENET_COMMAND_REGRESET 0x00000008 /*!< Reset Host Registers */ +#define ENET_COMMAND_TXRESET 0x00000010 /*!< Reset Transmit Datapath */ +#define ENET_COMMAND_RXRESET 0x00000020 /*!< Reset Receive Datapath */ +#define ENET_COMMAND_PASSRUNTFRAME 0x00000040 /*!< Pass Runt Frames */ +#define ENET_COMMAND_PASSRXFILTER 0x00000080 /*!< Pass RX Filter */ +#define ENET_COMMAND_TXFLOWCONTROL 0x00000100 /*!< TX Flow Control */ +#define ENET_COMMAND_RMII 0x00000200 /*!< Reduced MII Interface */ +#define ENET_COMMAND_FULLDUPLEX 0x00000400 /*!< Full Duplex */ + +/* + * @brief Status Register bit definitions + */ +#define ENET_STATUS_RXSTATUS 0x00000001 /*!< Receive Channel Active Status */ +#define ENET_STATUS_TXSTATUS 0x00000002 /*!< Transmit Channel Active Status */ + +/* + * @brief Transmit Status Vector 0 Register bit definitions + */ +#define ENET_TSV0_CRCERR 0x00000001 /*!< CRC error */ +#define ENET_TSV0_LCE 0x00000002 /*!< Length Check Error */ +#define ENET_TSV0_LOR 0x00000004 /*!< Length Out of Range */ +#define ENET_TSV0_DONE 0x00000008 /*!< Tramsmission Completed */ +#define ENET_TSV0_MULTICAST 0x00000010 /*!< Multicast Destination */ +#define ENET_TSV0_BROADCAST 0x00000020 /*!< Broadcast Destination */ +#define ENET_TSV0_PACKETDEFER 0x00000040 /*!< Packet Deferred */ +#define ENET_TSV0_EXDF 0x00000080 /*!< Excessive Packet Deferral */ +#define ENET_TSV0_EXCOL 0x00000100 /*!< Excessive Collision */ +#define ENET_TSV0_LCOL 0x00000200 /*!< Late Collision Occured */ +#define ENET_TSV0_GIANT 0x00000400 /*!< Giant Frame */ +#define ENET_TSV0_UNDERRUN 0x00000800 /*!< Buffer Underrun */ +#define ENET_TSV0_TOTALBYTES 0x0FFFF000 /*!< Total Bytes Transferred */ +#define ENET_TSV0_CONTROLFRAME 0x10000000 /*!< Control Frame */ +#define ENET_TSV0_PAUSE 0x20000000 /*!< Pause Frame */ +#define ENET_TSV0_BACKPRESSURE 0x40000000 /*!< Backpressure Method Applied */ +#define ENET_TSV0_VLAN 0x80000000 /*!< VLAN Frame */ + +/* + * @brief Transmit Status Vector 0 Register bit definitions + */ +#define ENET_TSV1_TBC 0x0000FFFF /*!< Transmit Byte Count */ +#define ENET_TSV1_TCC 0x000F0000 /*!< Transmit Collision Count */ + +/* + * @brief Receive Status Vector Register bit definitions + */ +#define ENET_RSV_RBC 0x0000FFFF /*!< Receive Byte Count */ +#define ENET_RSV_PPI 0x00010000 /*!< Packet Previously Ignored */ +#define ENET_RSV_RXDVSEEN 0x00020000 /*!< RXDV Event Previously Seen */ +#define ENET_RSV_CESEEN 0x00040000 /*!< Carrier Event Previously Seen */ +#define ENET_RSV_RCV 0x00080000 /*!< Receive Code Violation */ +#define ENET_RSV_CRCERR 0x00100000 /*!< CRC Error */ +#define ENET_RSV_LCERR 0x00200000 /*!< Length Check Error */ +#define ENET_RSV_LOR 0x00400000 /*!< Length Out of Range */ +#define ENET_RSV_ROK 0x00800000 /*!< Frame Received OK */ +#define ENET_RSV_MULTICAST 0x01000000 /*!< Multicast Frame */ +#define ENET_RSV_BROADCAST 0x02000000 /*!< Broadcast Frame */ +#define ENET_RSV_DRIBBLENIBBLE 0x04000000 /*!< Dribble Nibble */ +#define ENET_RSV_CONTROLFRAME 0x08000000 /*!< Control Frame */ +#define ENET_RSV_PAUSE 0x10000000 /*!< Pause Frame */ +#define ENET_RSV_UO 0x20000000 /*!< Unsupported Opcode */ +#define ENET_RSV_VLAN 0x40000000 /*!< VLAN Frame */ + +/* + * @brief Flow Control Counter Register bit definitions + */ +#define ENET_FLOWCONTROLCOUNTER_MC(n) ((n) & 0xFFFF) /*!< Mirror Counter */ +#define ENET_FLOWCONTROLCOUNTER_PT(n) (((n) & 0xFFFF) << 16) /*!< Pause Timer */ + +/* + * @brief Flow Control Status Register bit definitions + */ +#define ENET_FLOWCONTROLSTATUS_MCC(n) ((n) & 0xFFFF) /*!< Mirror Counter Current */ + +/* + * @brief Receive Filter Control Register bit definitions + */ +#define ENET_RXFILTERCTRL_AUE 0x00000001 /*!< Accept Unicast Frames Enable */ +#define ENET_RXFILTERCTRL_ABE 0x00000002 /*!< Accept Broadcast Frames Enable */ +#define ENET_RXFILTERCTRL_AME 0x00000004 /*!< Accept Multicast Frames Enable */ +#define ENET_RXFILTERCTRL_AUHE 0x00000008 /*!< Accept Unicast Hash Filter Frames */ +#define ENET_RXFILTERCTRL_AMHE 0x00000010 /*!< Accept Multicast Hash Filter Fram */ +#define ENET_RXFILTERCTRL_APE 0x00000020 /*!< Accept Perfect Match Enable */ +#define ENET_RXFILTERCTRL_MPEW 0x00001000 /*!< Magic Packet Filter WoL Enable */ +#define ENET_RXFILTERCTRL_RFEW 0x00002000 /*!< Perfect Filter WoL Enable */ + +/* + * @brief Receive Filter WoL Status/Clear Register bit definitions + */ +#define ENET_RXFILTERWOLSTATUS_AUW 0x00000001 /*!< Unicast Frame caused WoL */ +#define ENET_RXFILTERWOLSTATUS_ABW 0x00000002 /*!< Broadcast Frame caused WoL */ +#define ENET_RXFILTERWOLSTATUS_AMW 0x00000004 /*!< Multicast Frame caused WoL */ +#define ENET_RXFILTERWOLSTATUS_AUHW 0x00000008 /*!< Unicast Hash Filter Frame WoL */ +#define ENET_RXFILTERWOLSTATUS_AMHW 0x00000010 /*!< Multicast Hash Filter Frame WoL */ +#define ENET_RXFILTERWOLSTATUS_APW 0x00000020 /*!< Perfect Filter WoL */ +#define ENET_RXFILTERWOLSTATUS_RFW 0x00000080 /*!< RX Filter caused WoL */ +#define ENET_RXFILTERWOLSTATUS_MPW 0x00000100 /*!< Magic Packet Filter caused WoL */ +#define ENET_RXFILTERWOLSTATUS_BITMASK 0x01BF /*!< Receive Filter WoL Status/Clear bitmasl value */ + +/* + * @brief Interrupt Status/Enable/Clear/Set Register bit definitions + */ +#define ENET_INT_RXOVERRUN 0x00000001 /*!< Overrun Error in RX Queue */ +#define ENET_INT_RXERROR 0x00000002 /*!< Receive Error */ +#define ENET_INT_RXFINISHED 0x00000004 /*!< RX Finished Process Descriptors */ +#define ENET_INT_RXDONE 0x00000008 /*!< Receive Done */ +#define ENET_INT_TXUNDERRUN 0x00000010 /*!< Transmit Underrun */ +#define ENET_INT_TXERROR 0x00000020 /*!< Transmit Error */ +#define ENET_INT_TXFINISHED 0x00000040 /*!< TX Finished Process Descriptors */ +#define ENET_INT_TXDONE 0x00000080 /*!< Transmit Done */ +#define ENET_INT_SOFT 0x00001000 /*!< Software Triggered Interrupt */ +#define ENET_INT_WAKEUP 0x00002000 /*!< Wakeup Event Interrupt */ + +/* + * @brief Power Down Register bit definitions + */ +#define ENET_POWERDOWN_PD 0x80000000 /*!< Power Down MAC */ + +/** + * @brief RX Descriptor structure + */ +typedef struct { + uint32_t Packet; /*!< Base address of the data buffer for storing receive data */ + uint32_t Control; /*!< Control information */ +} ENET_RXDESC_T; + +/** + * @brief RX Descriptor Control structure type definition + */ +#define ENET_RCTRL_SIZE(n) (((n) - 1) & 0x7FF) /*!< Buffer size field */ +#define ENET_RCTRL_INT 0x80000000 /*!< Generate RxDone Interrupt */ + +/** + * @brief RX Status structure + */ +typedef struct { + uint32_t StatusInfo; /*!< Receive status return flags.*/ + uint32_t StatusHashCRC; /*!< The concatenation of the destination address hash CRC and the source + address hash CRC */ +} ENET_RXSTAT_T; + +/* + * @brief RX Status Hash CRC Word definition + */ +#define ENET_RHASH_SA 0x000001FF /*!< Hash CRC for Source Address */ +#define ENET_RHASH_DA 0x001FF000 /*!< Hash CRC for Destination Address */ + +/* RX Status Information Word */ +#define ENET_RINFO_SIZE(n) (((n) & 0x7FF) + 1) /*!< Data size in bytes */ +#define ENET_RINFO_CTRL_FRAME 0x00040000 /*!< Control Frame */ +#define ENET_RINFO_VLAN 0x00080000 /*!< VLAN Frame */ +#define ENET_RINFO_FAIL_FILT 0x00100000 /*!< RX Filter Failed */ +#define ENET_RINFO_MCAST 0x00200000 /*!< Multicast Frame */ +#define ENET_RINFO_BCAST 0x00400000 /*!< Broadcast Frame */ +#define ENET_RINFO_CRC_ERR 0x00800000 /*!< CRC Error in Frame */ +#define ENET_RINFO_SYM_ERR 0x01000000 /*!< Symbol Error from PHY */ +#define ENET_RINFO_LEN_ERR 0x02000000 /*!< Length Error */ +#define ENET_RINFO_RANGE_ERR 0x04000000 /*!< Range Error (exceeded max. size) */ +#define ENET_RINFO_ALIGN_ERR 0x08000000 /*!< Alignment Error */ +#define ENET_RINFO_OVERRUN 0x10000000 /*!< Receive overrun */ +#define ENET_RINFO_NO_DESCR 0x20000000 /*!< No new Descriptor available */ +#define ENET_RINFO_LAST_FLAG 0x40000000 /*!< Last Fragment in Frame */ +#define ENET_RINFO_ERR 0x80000000 /*!< Error Occured (OR of all errors) */ +/** RX Error status mask */ +#define ENET_RINFO_ERR_MASK (ENET_RINFO_FAIL_FILT | ENET_RINFO_CRC_ERR | ENET_RINFO_SYM_ERR | \ + ENET_RINFO_LEN_ERR | ENET_RINFO_ALIGN_ERR | ENET_RINFO_OVERRUN) + +/** + * @brief TX Descriptor structure + */ +typedef struct { + uint32_t Packet; /*!< Base address of the data buffer containing transmit data */ + uint32_t Control; /*!< Control information */ +} ENET_TXDESC_T; + +/* + * @brief TX Descriptor Control structure type definition + */ +#define ENET_TCTRL_SIZE(n) (((n) - 1) & 0x7FF) /*!< Size of data buffer in bytes */ +#define ENET_TCTRL_OVERRIDE 0x04000000 /*!< Override Default MAC Registers */ +#define ENET_TCTRL_HUGE 0x08000000 /*!< Enable Huge Frame */ +#define ENET_TCTRL_PAD 0x10000000 /*!< Pad short Frames to 64 bytes */ +#define ENET_TCTRL_CRC 0x20000000 /*!< Append a hardware CRC to Frame */ +#define ENET_TCTRL_LAST 0x40000000 /*!< Last Descriptor for TX Frame */ +#define ENET_TCTRL_INT 0x80000000 /*!< Generate TxDone Interrupt */ + +/** + * @brief TX Status structure + */ +typedef struct { + uint32_t StatusInfo; /*!< Receive status return flags.*/ +} ENET_TXSTAT_T; + +/* TX Status Information Word */ +#define ENET_TINFO_COL_CNT 0x01E00000 /*!< Collision Count */ +#define ENET_TINFO_DEFER 0x02000000 /*!< Packet Deferred (not an error) */ +#define ENET_TINFO_EXCESS_DEF 0x04000000 /*!< Excessive Deferral */ +#define ENET_TINFO_EXCESS_COL 0x08000000 /*!< Excessive Collision */ +#define ENET_TINFO_LATE_COL 0x10000000 /*!< Late Collision Occured */ +#define ENET_TINFO_UNDERRUN 0x20000000 /*!< Transmit Underrun */ +#define ENET_TINFO_NO_DESCR 0x40000000 /*!< No new Descriptor available */ +#define ENET_TINFO_ERR 0x80000000 /*!< Error Occured (OR of all errors) */ + +/** + * @brief Maximum size of an ethernet buffer + */ +#define ENET_ETH_MAX_FLEN (1536) + +/** + * @brief ENET Buffer status definition + */ +typedef enum { + ENET_BUFF_EMPTY, /* buffer is empty */ + ENET_BUFF_PARTIAL_FULL, /* buffer contains some packets */ + ENET_BUFF_FULL, /* buffer is full */ +} ENET_BUFF_STATUS_T; + +/** + * @brief Resets the ethernet interface + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + * @note Resets the ethernet interface. This should be called prior to + * Chip_ENET_Init with a small delay after this call. + */ +STATIC INLINE void Chip_ENET_Reset(LPC_ENET_T *pENET) +{ + /* This should be called prior to IP_ENET_Init. The MAC controller may + not be ready for a call to init right away so a small delay should + occur after this call. */ + pENET->MAC.MAC1 = ENET_MAC1_RESETTX | ENET_MAC1_RESETMCSTX | ENET_MAC1_RESETRX | + ENET_MAC1_RESETMCSRX | ENET_MAC1_SIMRESET | ENET_MAC1_SOFTRESET; + pENET->CONTROL.COMMAND = ENET_COMMAND_REGRESET | ENET_COMMAND_TXRESET | ENET_COMMAND_RXRESET | + ENET_COMMAND_PASSRUNTFRAME; +} + +/** + * @brief Sets the address of the interface + * @param pENET : The base of ENET peripheral on the chip + * @param macAddr : Pointer to the 6 bytes used for the MAC address + * @return Nothing + */ +STATIC INLINE void Chip_ENET_SetADDR(LPC_ENET_T *pENET, const uint8_t *macAddr) +{ + /* Save MAC address */ + pENET->MAC.SA[0] = ((uint32_t) macAddr[5] << 8) | ((uint32_t) macAddr[4]); + pENET->MAC.SA[1] = ((uint32_t) macAddr[3] << 8) | ((uint32_t) macAddr[2]); + pENET->MAC.SA[2] = ((uint32_t) macAddr[1] << 8) | ((uint32_t) macAddr[0]); +} + +/** + * @brief Sets up the PHY link clock divider and PHY address + * @param pENET : The base of ENET peripheral on the chip + * @param div : Divider index, not a divider value, see user manual + * @param addr : PHY address, used with MII read and write + * @return Nothing + * @note The MII clock divider rate is divided from the peripheral clock returned + * from the Chip_Clock_GetSystemClockRate() function. Use Chip_ENET_FindMIIDiv() + * with a desired clock rate to find the correct divider index value. + */ +void Chip_ENET_SetupMII(LPC_ENET_T *pENET, uint32_t div, uint8_t addr); + +/** + * @brief Starts a PHY write via the MII + * @param pENET : The base of ENET peripheral on the chip + * @param reg : PHY register to write + * @param data : Data to write to PHY register + * @return Nothing + * @note Start a PHY write operation. Does not block, requires calling + * IP_ENET_IsMIIBusy to determine when write is complete. + */ +void Chip_ENET_StartMIIWrite(LPC_ENET_T *pENET, uint8_t reg, uint16_t data); + +/** + * @brief Starts a PHY read via the MII + * @param pENET : The base of ENET peripheral on the chip + * @param reg : PHY register to read + * @return Nothing + * @note Start a PHY read operation. Does not block, requires calling + * IP_ENET_IsMIIBusy to determine when read is complete and calling + * IP_ENET_ReadMIIData to get the data. + */ +void Chip_ENET_StartMIIRead(LPC_ENET_T *pENET, uint8_t reg); + +/** + * @brief Returns MII link (PHY) busy status + * @param pENET : The base of ENET peripheral on the chip + * @return Returns true if busy, otherwise false + */ +STATIC INLINE bool Chip_ENET_IsMIIBusy(LPC_ENET_T *pENET) +{ + return (pENET->MAC.MIND & ENET_MIND_BUSY) ? true : false; +} + +/** + * @brief Returns the value read from the PHY + * @param pENET : The base of ENET peripheral on the chip + * @return Read value from PHY + */ +uint16_t Chip_ENET_ReadMIIData(LPC_ENET_T *pENET); + +/** + * @brief Enables ethernet transmit + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_TXEnable(LPC_ENET_T *pENET) +{ + /* Descriptor list head pointers must be setup prior to enable */ + pENET->CONTROL.COMMAND |= ENET_COMMAND_TXENABLE; +} + +/** + * @brief Disables ethernet transmit + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_TXDisable(LPC_ENET_T *pENET) +{ + pENET->CONTROL.COMMAND &= ~ENET_COMMAND_TXENABLE; +} + +/** + * @brief Enables ethernet packet reception + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_RXEnable(LPC_ENET_T *pENET) +{ + /* Descriptor list head pointers must be setup prior to enable */ + pENET->CONTROL.COMMAND |= ENET_COMMAND_RXENABLE; + pENET->MAC.MAC1 |= ENET_MAC1_RXENABLE; +} + +/** + * @brief Disables ethernet packet reception + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_RXDisable(LPC_ENET_T *pENET) +{ + pENET->CONTROL.COMMAND &= ~ENET_COMMAND_RXENABLE; + pENET->MAC.MAC1 &= ~ENET_MAC1_RXENABLE; +} + +/** + * @brief Reset Tx Logic + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_ResetTXLogic(LPC_ENET_T *pENET) +{ + pENET->MAC.MAC1 |= ENET_MAC1_RESETTX; +} + +/** + * @brief Reset Rx Logic + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_ResetRXLogic(LPC_ENET_T *pENET) +{ + pENET->MAC.MAC1 |= ENET_MAC1_RESETRX; +} + +/** + * @brief Enable Rx Filter + * @param pENET : The base of ENET peripheral on the chip + * @param mask : Filter mask (Or-ed bit values of ENET_RXFILTERCTRL_*) + * @return Nothing + */ +STATIC INLINE void Chip_ENET_EnableRXFilter(LPC_ENET_T *pENET, uint32_t mask) +{ + pENET->CONTROL.COMMAND &= ~ENET_COMMAND_PASSRXFILTER; + pENET->RXFILTER.CONTROL |= mask; +} + +/** + * @brief Disable Rx Filter + * @param pENET : The base of ENET peripheral on the chip + * @param mask : Filter mask (Or-ed bit values of ENET_RXFILTERCTRL_*) + * @return Nothing + */ +STATIC INLINE void Chip_ENET_DisableRXFilter(LPC_ENET_T *pENET, uint32_t mask) +{ + pENET->RXFILTER.CONTROL &= ~mask; +} + +/** + * @brief Sets full duplex operation for the interface + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +void Chip_ENET_SetFullDuplex(LPC_ENET_T *pENET); + +/** + * @brief Sets half duplex operation for the interface + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +void Chip_ENET_SetHalfDuplex(LPC_ENET_T *pENET); + +/** + * @brief Selects 100Mbps for the current speed + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_Set100Mbps(LPC_ENET_T *pENET) +{ + pENET->MAC.SUPP = ENET_SUPP_100Mbps_SPEED; +} + +/** + * @brief Selects 10Mbps for the current speed + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_ENET_Set10Mbps(LPC_ENET_T *pENET) +{ + pENET->MAC.SUPP = 0; +} + +/** + * @brief Configures the initial ethernet transmit descriptors + * @param pENET : The base of ENET peripheral on the chip + * @param pDescs : Pointer to TX descriptor list + * @param pStatus : Pointer to TX status list + * @param descNum : the number of desciptors + * @return Nothing + */ +void Chip_ENET_InitTxDescriptors(LPC_ENET_T *pENET, ENET_TXDESC_T *pDescs, + ENET_TXSTAT_T *pStatus, + uint32_t descNum); + +/** + * @brief Configures the initial ethernet receive descriptors + * @param pENET : The base of ENET peripheral on the chip + * @param pDescs : Pointer to TX descriptor list + * @param pStatus : Pointer to TX status list + * @param descNum : the number of desciptors + * @return Nothing + */ +void Chip_ENET_InitRxDescriptors(LPC_ENET_T *pENET, ENET_RXDESC_T *pDescs, + ENET_RXSTAT_T *pStatus, + uint32_t descNum); + +/** + * @brief Get the current Tx Produce Descriptor Index + * @param pENET : The base of ENET peripheral on the chip + * @return Tx Produce Index + */ +STATIC INLINE uint16_t Chip_ENET_GetTXProduceIndex(LPC_ENET_T *pENET) +{ + return pENET->CONTROL.TX.PRODUCEINDEX; +} + +/** + * @brief Get the current Tx Consume Descriptor Index + * @param pENET : The base of ENET peripheral on the chip + * @return Tx Consume Index + */ +STATIC INLINE uint16_t Chip_ENET_GetTXConsumeIndex(LPC_ENET_T *pENET) +{ + return pENET->CONTROL.TX.CONSUMEINDEX; +} + +/** + * @brief Get the current Rx Produce Descriptor Index + * @param pENET : The base of ENET peripheral on the chip + * @return Rx Produce Index + */ +STATIC INLINE uint16_t Chip_ENET_GetRXProduceIndex(LPC_ENET_T *pENET) +{ + return pENET->CONTROL.RX.PRODUCEINDEX; +} + +/** + * @brief Get the current Rx Consume Descriptor Index + * @param pENET : The base of ENET peripheral on the chip + * @return Rx Consume Index + */ +STATIC INLINE uint16_t Chip_ENET_GetRXConsumeIndex(LPC_ENET_T *pENET) +{ + return pENET->CONTROL.RX.CONSUMEINDEX; +} + +/** + * @brief Get the buffer status with the current Produce Index and Consume Index + * @param pENET : The base of ENET peripheral on the chip + * @param produceIndex : Produce Index + * @param consumeIndex : Consume Index + * @param buffSize : Buffer size + * @return Status (One of status value: ENET_BUFF_EMPTY/ENET_BUFF_FULL/ENET_BUFF_PARTIAL_FULL) + */ +ENET_BUFF_STATUS_T Chip_ENET_GetBufferStatus(LPC_ENET_T *pENET, uint16_t produceIndex, + uint16_t consumeIndex, + uint16_t buffSize); + +/** + * @brief Get the number of descriptors filled + * @param pENET : The base of ENET peripheral on the chip + * @param produceIndex : Produce Index + * @param consumeIndex : Consume Index + * @param buffSize : Buffer size + * @return the number of descriptors + */ +uint32_t Chip_ENET_GetFillDescNum(LPC_ENET_T *pENET, uint16_t produceIndex, uint16_t consumeIndex, uint16_t buffSize); + +/** + * @brief Get the number of free descriptors + * @param pENET : The base of ENET peripheral on the chip + * @param produceIndex : Produce Index + * @param consumeIndex : Consume Index + * @param buffSize : Buffer size + * @return the number of descriptors + */ +STATIC INLINE uint32_t Chip_ENET_GetFreeDescNum(LPC_ENET_T *pENET, + uint16_t produceIndex, + uint16_t consumeIndex, + uint16_t buffSize) +{ + return buffSize - 1 - Chip_ENET_GetFillDescNum(pENET, produceIndex, consumeIndex, buffSize); +} + +/** + * @brief Check if Tx buffer is full + * @param pENET : The base of ENET peripheral on the chip + * @return true/false + */ +STATIC INLINE bool Chip_ENET_IsTxFull(LPC_ENET_T *pENET) +{ + return ((pENET->CONTROL.TX.CONSUMEINDEX == (pENET->CONTROL.TX.PRODUCEINDEX + 1)) || + ((pENET->CONTROL.TX.CONSUMEINDEX == 0) && + (pENET->CONTROL.TX.PRODUCEINDEX == pENET->CONTROL.TX.DESCRIPTORNUMBER))) ? true : false; +} + +/** + * @brief Check if Rx buffer is empty + * @param pENET : The base of ENET peripheral on the chip + * @return true/false + */ +STATIC INLINE bool Chip_ENET_IsRxEmpty(LPC_ENET_T *pENET) +{ + uint32_t tem = pENET->CONTROL.RX.PRODUCEINDEX; + return (pENET->CONTROL.RX.CONSUMEINDEX != tem) ? false : true; +} + +/** + * @brief Increase the current Tx Produce Descriptor Index + * @param pENET : The base of ENET peripheral on the chip + * @return The new index value + */ +uint16_t Chip_ENET_IncTXProduceIndex(LPC_ENET_T *pENET); + +/** + * @brief Increase the current Rx Consume Descriptor Index + * @param pENET : The base of ENET peripheral on the chip + * @return The new index value + */ +uint16_t Chip_ENET_IncRXConsumeIndex(LPC_ENET_T *pENET); + +/** + * @brief Enable ENET interrupts + * @param pENET : The base of ENET peripheral on the chip + * @param mask : Interrupt mask (Or-ed bit values of ENET_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_ENET_EnableInt(LPC_ENET_T *pENET, uint32_t mask) +{ + pENET->MODULE_CONTROL.INTENABLE |= mask; +} + +/** + * @brief Disable ENET interrupts + * @param pENET : The base of ENET peripheral on the chip + * @param mask : Interrupt mask (Or-ed bit values of ENET_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_ENET_DisableInt(LPC_ENET_T *pENET, uint32_t mask) +{ + pENET->MODULE_CONTROL.INTENABLE &= ~mask; +} + +/** + * @brief Get the interrupt status + * @param pENET : The base of ENET peripheral on the chip + * @return interrupt status (Or-ed bit values of ENET_INT_*) + */ +STATIC INLINE uint32_t Chip_ENET_GetIntStatus(LPC_ENET_T *pENET) +{ + return pENET->MODULE_CONTROL.INTSTATUS; +} + +/** + * @brief Clear the interrupt status + * @param pENET : The base of ENET peripheral on the chip + * @param mask : Interrupt mask (Or-ed bit values of ENET_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_ENET_ClearIntStatus(LPC_ENET_T *pENET, uint32_t mask) +{ + pENET->MODULE_CONTROL.INTCLEAR = mask; +} + +/** + * @brief Initialize ethernet interface + * @param pENET : The base of ENET peripheral on the chip + * @param useRMII : true to setup interface for RMII, false for MII + * @return Nothing + * @note Performs basic initialization of the ethernet interface in a default + * state. This is enough to place the interface in a usable state, but + * may require more setup outside this function. + */ +void Chip_ENET_Init(LPC_ENET_T *pENET, bool useRMII); + +/** + * @brief De-initialize the ethernet interface + * @param pENET : The base of ENET peripheral on the chip + * @return Nothing + */ +void Chip_ENET_DeInit(LPC_ENET_T *pENET); + +/** + * @brief Find the divider index for a desired MII clock rate + * @param pENET : The base of ENET peripheral on the chip + * @param clockRate : Clock rate to get divider index for + * @return MII divider index to get the closest clock rate for clockRate + * @note Use this function to get a divider index for the Chip_ENET_SetupMII() + * function determined from the desired MII clock rate. + */ +uint32_t Chip_ENET_FindMIIDiv(LPC_ENET_T *pENET, uint32_t clockRate); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __ENET_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/error.h b/hw/mcu/nxp/lpc_chip_40xx/inc/error.h new file mode 100644 index 000000000..ee6c62b86 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/error.h @@ -0,0 +1,184 @@ +/* + * @brief Error code returned by Boot ROM drivers/library functions + * @ingroup Common + * + * This file contains unified error codes to be used across driver, + * middleware, applications, hal and demo software. + * + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __LPC_ERROR_H__ +#define __LPC_ERROR_H__ + +/** Error code returned by Boot ROM drivers/library functions + * + * Error codes are a 32-bit value with : + * - The 16 MSB contains the peripheral code number + * - The 16 LSB contains an error code number associated to that peripheral + * + */ +typedef enum { + /**\b 0x00000000*/ LPC_OK = 0, /**< enum value returned on Success */ + /**\b 0xFFFFFFFF*/ ERR_FAILED = -1, /**< enum value returned on general failure */ + /**\b 0xFFFFFFFE*/ ERR_TIME_OUT = -2, /**< enum value returned on general timeout */ + /**\b 0xFFFFFFFD*/ ERR_BUSY = -3, /**< enum value returned when resource is busy */ + + /* ISP related errors */ + ERR_ISP_BASE = 0x00000000, + /*0x00000001*/ ERR_ISP_INVALID_COMMAND = ERR_ISP_BASE + 1, + /*0x00000002*/ ERR_ISP_SRC_ADDR_ERROR, /* Source address not on word boundary */ + /*0x00000003*/ ERR_ISP_DST_ADDR_ERROR, /* Destination address not on word or 256 byte boundary */ + /*0x00000004*/ ERR_ISP_SRC_ADDR_NOT_MAPPED, + /*0x00000005*/ ERR_ISP_DST_ADDR_NOT_MAPPED, + /*0x00000006*/ ERR_ISP_COUNT_ERROR, /* Byte count is not multiple of 4 or is not a permitted value */ + /*0x00000007*/ ERR_ISP_INVALID_SECTOR, + /*0x00000008*/ ERR_ISP_SECTOR_NOT_BLANK, + /*0x00000009*/ ERR_ISP_SECTOR_NOT_PREPARED_FOR_WRITE_OPERATION, + /*0x0000000A*/ ERR_ISP_COMPARE_ERROR, + /*0x0000000B*/ ERR_ISP_BUSY,/* Flash programming hardware interface is busy */ + /*0x0000000C*/ ERR_ISP_PARAM_ERROR, /* Insufficient number of parameters */ + /*0x0000000D*/ ERR_ISP_ADDR_ERROR, /* Address not on word boundary */ + /*0x0000000E*/ ERR_ISP_ADDR_NOT_MAPPED, + /*0x0000000F*/ ERR_ISP_CMD_LOCKED, /* Command is locked */ + /*0x00000010*/ ERR_ISP_INVALID_CODE,/* Unlock code is invalid */ + /*0x00000011*/ ERR_ISP_INVALID_BAUD_RATE, + /*0x00000012*/ ERR_ISP_INVALID_STOP_BIT, + /*0x00000013*/ ERR_ISP_CODE_READ_PROTECTION_ENABLED, + + /* ROM API related errors */ + ERR_API_BASE = 0x00010000, + /**\b 0x00010001*/ ERR_API_INVALID_PARAMS = ERR_API_BASE + 1, /**< Invalid parameters*/ + /**\b 0x00010002*/ ERR_API_INVALID_PARAM1, /**< PARAM1 is invalid */ + /**\b 0x00010003*/ ERR_API_INVALID_PARAM2, /**< PARAM2 is invalid */ + /**\b 0x00010004*/ ERR_API_INVALID_PARAM3, /**< PARAM3 is invalid */ + /**\b 0x00010005*/ ERR_API_MOD_INIT,/**< API is called before module init */ + + /* SPIFI API related errors */ + ERR_SPIFI_BASE = 0x00020000, + /*0x00020001*/ ERR_SPIFI_DEVICE_ERROR = ERR_SPIFI_BASE + 1, + /*0x00020002*/ ERR_SPIFI_INTERNAL_ERROR, + /*0x00020003*/ ERR_SPIFI_TIMEOUT, + /*0x00020004*/ ERR_SPIFI_OPERAND_ERROR, + /*0x00020005*/ ERR_SPIFI_STATUS_PROBLEM, + /*0x00020006*/ ERR_SPIFI_UNKNOWN_EXT, + /*0x00020007*/ ERR_SPIFI_UNKNOWN_ID, + /*0x00020008*/ ERR_SPIFI_UNKNOWN_TYPE, + /*0x00020009*/ ERR_SPIFI_UNKNOWN_MFG, + + /* Security API related errors */ + ERR_SEC_BASE = 0x00030000, + /*0x00030001*/ ERR_SEC_AES_WRONG_CMD = ERR_SEC_BASE + 1, + /*0x00030002*/ ERR_SEC_AES_NOT_SUPPORTED, + /*0x00030003*/ ERR_SEC_AES_KEY_ALREADY_PROGRAMMED, + + /* USB device stack related errors */ + ERR_USBD_BASE = 0x00040000, + /**\b 0x00040001*/ ERR_USBD_INVALID_REQ = ERR_USBD_BASE + 1,/**< invalid request */ + /**\b 0x00040002*/ ERR_USBD_UNHANDLED, /**< Callback did not process the event */ + /**\b 0x00040003*/ ERR_USBD_STALL, /**< Stall the endpoint on which the call back is called */ + /**\b 0x00040004*/ ERR_USBD_SEND_ZLP, /**< Send ZLP packet on the endpoint on which the call back is called */ + /**\b 0x00040005*/ ERR_USBD_SEND_DATA, /**< Send data packet on the endpoint on which the call back is called */ + /**\b 0x00040006*/ ERR_USBD_BAD_DESC, /**< Bad descriptor*/ + /**\b 0x00040007*/ ERR_USBD_BAD_CFG_DESC, /**< Bad config descriptor*/ + /**\b 0x00040008*/ ERR_USBD_BAD_INTF_DESC, /**< Bad interface descriptor*/ + /**\b 0x00040009*/ ERR_USBD_BAD_EP_DESC,/**< Bad endpoint descriptor*/ + /**\b 0x0004000a*/ ERR_USBD_BAD_MEM_BUF,/**< Bad alignment of buffer passed. */ + /**\b 0x0004000b*/ ERR_USBD_TOO_MANY_CLASS_HDLR,/**< Too many class handlers. */ + + /* CGU related errors */ + ERR_CGU_BASE = 0x00050000, + /*0x00050001*/ ERR_CGU_NOT_IMPL = ERR_CGU_BASE + 1, + /*0x00050002*/ ERR_CGU_INVALID_PARAM, + /*0x00050003*/ ERR_CGU_INVALID_SLICE, + /*0x00050004*/ ERR_CGU_OUTPUT_GEN, + /*0x00050005*/ ERR_CGU_DIV_SRC, + /*0x00050006*/ ERR_CGU_DIV_VAL, + /*0x00050007*/ ERR_CGU_SRC, + + /* I2C related errors */ + ERR_I2C_BASE = 0x00060000, + /*0x00060001*/ ERR_I2C_NAK = ERR_I2C_BASE + 1, + /*0x00060002*/ ERR_I2C_BUFFER_OVERFLOW, + /*0x00060003*/ ERR_I2C_BYTE_COUNT_ERR, + /*0x00060004*/ ERR_I2C_LOSS_OF_ARBRITRATION, + /*0x00060005*/ ERR_I2C_SLAVE_NOT_ADDRESSED, + /*0x00060006*/ ERR_I2C_LOSS_OF_ARBRITRATION_NAK_BIT, + /*0x00060007*/ ERR_I2C_GENERAL_FAILURE, + /*0x00060008*/ ERR_I2C_REGS_SET_TO_DEFAULT, + /*0x00060009*/ ERR_I2C_TIMEOUT, + /*0x0006000A*/ ERR_I2C_BUFFER_UNDERFLOW, + + /* UART related errors */ + ERR_UART_BASE = 0x00080000, + /**\b 0x00080001*/ ERR_UART_RXD_BUSY = ERR_UART_BASE + 1, /*!< Receive is busy */ + /**\b 0x00080002*/ ERR_UART_TXD_BUSY, /*!< Transmit is busy */ + /**\b 0x00080003*/ ERR_UART_OVERRUN_FRAME_PARITY_NOISE, /*!< Overrun, Frame, Parity , Receive Noise error */ + /**\b 0x00080004*/ ERR_UART_UNDERRUN, /*!< Underrun */ + /**\b 0x00080005*/ ERR_UART_PARAM, /*!< Parameter error */ + + ERR_DMA_BASE = 0x000D0000, + /*0x000D0001*/ ERR_DMA_ERROR_INT = ERR_DMA_BASE + 1, + /*0x000D0002*/ ERR_DMA_CHANNEL_NUMBER, + /*0x000D0003*/ ERR_DMA_CHANNEL_DISABLED, + /*0x000D0004*/ ERR_DMA_BUSY, + /*0x000D0005*/ ERR_DMA_NOT_ALIGNMENT, + /*0x000D0006*/ ERR_DMA_PING_PONG_EN, + /*0x000D0007*/ ERR_DMA_CHANNEL_VALID_PENDING, + + /* SPI related errors */ + ERR_SPI_BASE = 0x000E0000, + /*0x000E0001*/ ERR_SPI_RXOVERRUN=ERR_SPI_BASE+1, + /*0x000E0002*/ ERR_SPI_TXUNDERRUN, + /*0x000E0003*/ ERR_SPI_SELNASSERT, + /*0x000E0004*/ ERR_SPI_SELNDEASSERT, + /*0x000E0005*/ ERR_SPI_CLKSTALL, + /*0x000E0006*/ ERR_SPI_PARAM, + /*0x000E0007*/ ERR_SPI_INVALID_LENGTH, + + /* ADC related errors */ + ERR_ADC_BASE = 0x000F0000, + /*0x000F0001*/ ERR_ADC_OVERRUN = ERR_ADC_BASE + 1, + /*0x000F0002*/ ERR_ADC_INVALID_CHANNEL, + /*0x000F0003*/ ERR_ADC_INVALID_SEQUENCE, + /*0x000F0004*/ ERR_ADC_INVALID_SETUP, + /*0x000F0005*/ ERR_ADC_PARAM, + /*0x000F0006*/ ERR_ADC_INVALID_LENGTH, + /*0x000F0007*/ ERR_ADC_NO_POWER +} ErrorCode_t; + +#ifndef offsetof +#define offsetof(s, m) (int) &(((s *) 0)->m) +#endif + +#define COMPILE_TIME_ASSERT(pred) switch (0) { \ + case 0: \ + case pred:; } + +#endif /* __LPC_ERROR_H__ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/fmc_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/fmc_17xx_40xx.h new file mode 100644 index 000000000..83979408b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/fmc_17xx_40xx.h @@ -0,0 +1,133 @@ +/* + * @brief LPC17xx/40xx FLASH Memory Controller (FMC) driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __FMC_17XX_40XX_H_ +#define __FMC_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup FMC_17XX_40XX CHIP: LPC17xx/40xx FLASH Memory Controller driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief FLASH Memory Controller Unit register block structure + */ +typedef struct { /*!< FMC Structure */ + __I uint32_t RESERVED1[8]; + __IO uint32_t FMSSTART; + __IO uint32_t FMSSTOP; + __I uint32_t RESERVED3; + __I uint32_t FMSW[4]; + __I uint32_t RESERVED4[1001]; + __I uint32_t FMSTAT; + __I uint32_t RESERVED5; + __O uint32_t FMSTATCLR; +} LPC_FMC_T; + +/* Flash signature start and busy status bit */ +#define FMC_FLASHSIG_BUSY (1UL << 17) + +/* Flash signature clear status bit */ +#define FMC_FLASHSIG_STAT (1 << 2) + +/** + * @brief Start computation of a signature for a FLASH memory range + * @param start : Starting FLASH address for computation, must be aligned on 16 byte boundary + * @param stop : Ending FLASH address for computation, must be aligned on 16 byte boundary + * @return Nothing + * @note Only bits 20..4 are used for the FLASH signature computation. + * Use the Chip_FMC_IsSignatureBusy() function to determine when the + * signature computation operation is complete and use the + * Chip_FMC_GetSignature() function to get the computed signature. + */ +STATIC INLINE void Chip_FMC_ComputeSignature(uint32_t start, uint32_t stop) +{ + LPC_FMC->FMSSTART = (start >> 4); + LPC_FMC->FMSTATCLR = FMC_FLASHSIG_STAT; + LPC_FMC->FMSSTOP = (stop >> 4) | FMC_FLASHSIG_BUSY; +} + +/** + * @brief Start computation of a signature for a FLASH memory address and block count + * @param start : Starting FLASH address for computation, must be aligned on 16 byte boundary + * @param blocks : Number of 16 byte blocks used for computation + * @return Nothing + * @note Only bits 20..4 are used for the FLASH signature computation. + * Use the Chip_FMC_IsSignatureBusy() function to determine when the + * signature computation operation is complete and the + * Chip_FMC_GetSignature() function to get the computed signature. + */ +STATIC INLINE void Chip_FMC_ComputeSignatureBlocks(uint32_t start, uint32_t blocks) +{ + Chip_FMC_ComputeSignature(start, (start + (blocks * 16))); +} + +/** + * @brief Clear signature generation completion flag + * @return Nothing + */ +STATIC INLINE void Chip_FMC_ClearSignatureBusy(void) +{ + LPC_FMC->FMSTATCLR = FMC_FLASHSIG_STAT; +} + +/** + * @brief Check for signature generation completion + * @return true if the signature computation is running, false if finished + */ +STATIC INLINE bool Chip_FMC_IsSignatureBusy(void) +{ + return (bool) ((LPC_FMC->FMSTAT & FMC_FLASHSIG_STAT) == 0); +} + +/** + * @brief Returns the generated FLASH signature value + * @param index : Signature index to get - use 0 to FMSW0, 1 to FMSW1, etc. + * @return the generated FLASH signature value + */ +STATIC INLINE uint32_t Chip_FMC_GetSignature(int index) +{ + return LPC_FMC->FMSW[index]; +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __FMC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/fpu_init.h b/hw/mcu/nxp/lpc_chip_40xx/inc/fpu_init.h new file mode 100644 index 000000000..86e71c898 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/fpu_init.h @@ -0,0 +1,52 @@ +/* + * @brief FPU init code + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __FPU_INIT_H_ +#define __FPU_INIT_H_ + +/** + * @defgroup CHIP_FPU_CMX CHIP: FPU initialization + * @ingroup CHIP_Common + * Cortex FPU initialization + * @{ + */ + +/** + * @brief Early initialization of the FPU + * @return Nothing + */ +void fpuInit(void); + +/** + * @} + */ + +#endif /* __FPU_INIT_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/gpdma_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/gpdma_17xx_40xx.h new file mode 100644 index 000000000..8eea13402 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/gpdma_17xx_40xx.h @@ -0,0 +1,450 @@ +/* + * @brief LPC17xx/40xx General Purpose DMA driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __GPDMA_17XX_40XX_H_ +#define __GPDMA_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup GPDMA_17XX_40XX CHIP: LPC17xx/40xx General Purpose DMA driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief Number of channels on GPDMA + */ +#define GPDMA_NUMBER_CHANNELS 8 + +/** + * @brief GPDMA Channel register block structure + */ +typedef struct { + __IO uint32_t SRCADDR; /*!< DMA Channel Source Address Register */ + __IO uint32_t DESTADDR; /*!< DMA Channel Destination Address Register */ + __IO uint32_t LLI; /*!< DMA Channel Linked List Item Register */ + __IO uint32_t CONTROL; /*!< DMA Channel Control Register */ + __IO uint32_t CONFIG; /*!< DMA Channel Configuration Register */ + __I uint32_t RESERVED1[3]; +} GPDMA_CH_T; + +/** + * @brief GPDMA register block + */ +typedef struct { /*!< GPDMA Structure */ + __I uint32_t INTSTAT; /*!< DMA Interrupt Status Register */ + __I uint32_t INTTCSTAT; /*!< DMA Interrupt Terminal Count Request Status Register */ + __O uint32_t INTTCCLEAR; /*!< DMA Interrupt Terminal Count Request Clear Register */ + __I uint32_t INTERRSTAT; /*!< DMA Interrupt Error Status Register */ + __O uint32_t INTERRCLR; /*!< DMA Interrupt Error Clear Register */ + __I uint32_t RAWINTTCSTAT; /*!< DMA Raw Interrupt Terminal Count Status Register */ + __I uint32_t RAWINTERRSTAT; /*!< DMA Raw Error Interrupt Status Register */ + __I uint32_t ENBLDCHNS; /*!< DMA Enabled Channel Register */ + __IO uint32_t SOFTBREQ; /*!< DMA Software Burst Request Register */ + __IO uint32_t SOFTSREQ; /*!< DMA Software Single Request Register */ + __IO uint32_t SOFTLBREQ; /*!< DMA Software Last Burst Request Register */ + __IO uint32_t SOFTLSREQ; /*!< DMA Software Last Single Request Register */ + __IO uint32_t CONFIG; /*!< DMA Configuration Register */ + __IO uint32_t SYNC; /*!< DMA Synchronization Register */ + __I uint32_t RESERVED0[50]; + GPDMA_CH_T CH[GPDMA_NUMBER_CHANNELS]; +} LPC_GPDMA_T; + +/** + * @brief Macro defines for DMA channel control registers + */ +#define GPDMA_DMACCxControl_TransferSize(n) (((n & 0xFFF) << 0)) /*!< Transfer size*/ +#define GPDMA_DMACCxControl_SBSize(n) (((n & 0x07) << 12)) /*!< Source burst size*/ +#define GPDMA_DMACCxControl_DBSize(n) (((n & 0x07) << 15)) /*!< Destination burst size*/ +#define GPDMA_DMACCxControl_SWidth(n) (((n & 0x07) << 18)) /*!< Source transfer width*/ +#define GPDMA_DMACCxControl_DWidth(n) (((n & 0x07) << 21)) /*!< Destination transfer width*/ +#define GPDMA_DMACCxControl_SI ((1UL << 26)) /*!< Source increment*/ +#define GPDMA_DMACCxControl_DI ((1UL << 27)) /*!< Destination increment*/ +#define GPDMA_DMACCxControl_SrcTransUseAHBMaster1 0 +#define GPDMA_DMACCxControl_DestTransUseAHBMaster1 0 +#define GPDMA_DMACCxControl_Prot1 ((1UL << 28)) /*!< Indicates that the access is in user mode or privileged mode*/ +#define GPDMA_DMACCxControl_Prot2 ((1UL << 29)) /*!< Indicates that the access is bufferable or not bufferable*/ +#define GPDMA_DMACCxControl_Prot3 ((1UL << 30)) /*!< Indicates that the access is cacheable or not cacheable*/ +#define GPDMA_DMACCxControl_I ((1UL << 31)) /*!< Terminal count interrupt enable bit */ + +/** + * @brief Macro defines for DMA Configuration register + */ +#define GPDMA_DMACConfig_E ((0x01)) /*!< DMA Controller enable*/ +#define GPDMA_DMACConfig_M ((0x02)) /*!< AHB Master endianness configuration*/ +#define GPDMA_DMACConfig_BITMASK ((0x03)) + +/** + * @brief Macro defines for DMA Channel Configuration registers + */ +#define GPDMA_DMACCxConfig_E ((1UL << 0)) /*!< DMA control enable*/ +#define GPDMA_DMACCxConfig_SrcPeripheral(n) (((n & 0x1F) << 1)) /*!< Source peripheral*/ +#define GPDMA_DMACCxConfig_DestPeripheral(n) (((n & 0x1F) << 6)) /*!< Destination peripheral*/ +#define GPDMA_DMACCxConfig_TransferType(n) (((n & 0x7) << 11)) /*!< This value indicates the type of transfer*/ +#define GPDMA_DMACCxConfig_IE ((1UL << 14)) /*!< Interrupt error mask*/ +#define GPDMA_DMACCxConfig_ITC ((1UL << 15)) /*!< Terminal count interrupt mask*/ +#define GPDMA_DMACCxConfig_L ((1UL << 16)) /*!< Lock*/ +#define GPDMA_DMACCxConfig_A ((1UL << 17)) /*!< Active*/ +#define GPDMA_DMACCxConfig_H ((1UL << 18)) /*!< Halt*/ + +/** + * @brief GPDMA Interrupt Clear Status + */ +typedef enum { + GPDMA_STATCLR_INTTC, /*!< GPDMA Interrupt Terminal Count Request Clear */ + GPDMA_STATCLR_INTERR /*!< GPDMA Interrupt Error Clear */ +} GPDMA_STATECLEAR_T; + +/** + * @brief GPDMA Type of Interrupt Status + */ +typedef enum { + GPDMA_STAT_INT, /*!< GPDMA Interrupt Status */ + GPDMA_STAT_INTTC, /*!< GPDMA Interrupt Terminal Count Request Status */ + GPDMA_STAT_INTERR, /*!< GPDMA Interrupt Error Status */ + GPDMA_STAT_RAWINTTC, /*!< GPDMA Raw Interrupt Terminal Count Status */ + GPDMA_STAT_RAWINTERR, /*!< GPDMA Raw Error Interrupt Status */ + GPDMA_STAT_ENABLED_CH /*!< GPDMA Enabled Channel Status */ +} GPDMA_STATUS_T; + +/** + * @brief GPDMA Type of DMA controller + */ +typedef enum { + GPDMA_TRANSFERTYPE_M2M_CONTROLLER_DMA = ((0UL)), /*!< Memory to memory - DMA control */ + GPDMA_TRANSFERTYPE_M2P_CONTROLLER_DMA = ((1UL)), /*!< Memory to peripheral - DMA control */ + GPDMA_TRANSFERTYPE_P2M_CONTROLLER_DMA = ((2UL)), /*!< Peripheral to memory - DMA control */ + GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DMA = ((3UL)), /*!< Source peripheral to destination peripheral - DMA control */ + GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DestPERIPHERAL = ((4UL)), /*!< Source peripheral to destination peripheral - destination peripheral control */ + GPDMA_TRANSFERTYPE_M2P_CONTROLLER_PERIPHERAL = ((5UL)), /*!< Memory to peripheral - peripheral control */ + GPDMA_TRANSFERTYPE_P2M_CONTROLLER_PERIPHERAL = ((6UL)), /*!< Peripheral to memory - peripheral control */ + GPDMA_TRANSFERTYPE_P2P_CONTROLLER_SrcPERIPHERAL = ((7UL)) /*!< Source peripheral to destination peripheral - source peripheral control */ +} GPDMA_FLOW_CONTROL_T; + +/** + * @brief GPDMA structure using for DMA configuration + */ +typedef struct { + uint32_t ChannelNum; /*!< DMA channel number, should be in + * range from 0 to 7. + * Note: DMA channel 0 has the highest priority + * and DMA channel 7 the lowest priority. + */ + uint32_t TransferSize; /*!< Length/Size of transfer */ + uint32_t TransferWidth; /*!< Transfer width - used for TransferType is GPDMA_TRANSFERTYPE_M2M only */ + uint32_t SrcAddr; /*!< Physical Source Address, used in case TransferType is chosen as + * GPDMA_TRANSFERTYPE_M2M or GPDMA_TRANSFERTYPE_M2P */ + uint32_t DstAddr; /*!< Physical Destination Address, used in case TransferType is chosen as + * GPDMA_TRANSFERTYPE_M2M or GPDMA_TRANSFERTYPE_P2M */ + uint32_t TransferType; /*!< Transfer Type, should be one of the following: + * - GPDMA_TRANSFERTYPE_M2M: Memory to memory - DMA control + * - GPDMA_TRANSFERTYPE_M2P: Memory to peripheral - DMA control + * - GPDMA_TRANSFERTYPE_P2M: Peripheral to memory - DMA control + * - GPDMA_TRANSFERTYPE_P2P: Source peripheral to destination peripheral - DMA control + */ +} GPDMA_CH_CFG_T; + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) +/** + * @brief GPDMA request connections + */ +#define GPDMA_CONN_MEMORY ((0UL)) /*!< Memory */ +#define GPDMA_CONN_SDC ((1UL)) /*!< SD card */ +#define GPDMA_CONN_SSP0_Tx ((2UL)) /*!< SSP0 Tx */ +#define GPDMA_CONN_SSP0_Rx ((3UL)) /*!< SSP0 Rx */ +#define GPDMA_CONN_SSP1_Tx ((4UL)) /*!< SSP1 Tx */ +#define GPDMA_CONN_SSP1_Rx ((5UL)) /*!< SSP1 Rx */ +#define GPDMA_CONN_SSP2_Tx ((6UL)) /*!< SSP2 Tx */ +#define GPDMA_CONN_SSP2_Rx ((7UL)) /*!< SSP2 Rx */ +#define GPDMA_CONN_ADC ((8UL)) /*!< ADC */ +#define GPDMA_CONN_DAC ((9UL)) /*!< DAC */ +#define GPDMA_CONN_UART0_Tx ((10UL)) /*!< UART0 Tx */ +#define GPDMA_CONN_UART0_Rx ((11UL)) /*!< UART0 Rx */ +#define GPDMA_CONN_UART1_Tx ((12UL)) /*!< UART1 Tx */ +#define GPDMA_CONN_UART1_Rx ((13UL)) /*!< UART1 Rx */ +#define GPDMA_CONN_UART2_Tx ((14UL)) /*!< UART2 Tx */ +#define GPDMA_CONN_UART2_Rx ((15UL)) /*!< UART2 Rx */ +#define GPDMA_CONN_MAT0_0 ((16UL)) /*!< MAT0.0 */ +#define GPDMA_CONN_MAT0_1 ((17UL)) /*!< MAT0.1 */ +#define GPDMA_CONN_MAT1_0 ((18UL)) /*!< MAT1.0 */ +#define GPDMA_CONN_MAT1_1 ((19UL)) /*!< MAT1.1 */ +#define GPDMA_CONN_MAT2_0 ((20UL)) /*!< MAT2.0 */ +#define GPDMA_CONN_MAT2_1 ((21UL)) /*!< MAT2.1 */ +#define GPDMA_CONN_I2S_Channel_0 ((22UL)) /*!< I2S channel 0 */ +#define GPDMA_CONN_I2S_Channel_1 ((23UL)) /*!< I2S channel 1 */ +#define GPDMA_CONN_UART3_Tx ((26UL)) /*!< UART3 Tx */ +#define GPDMA_CONN_UART3_Rx ((27UL)) /*!< UART3 Rx */ +#define GPDMA_CONN_UART4_Tx ((28UL)) /*!< UART3 Tx */ +#define GPDMA_CONN_UART4_Rx ((29UL)) /*!< UART3 Rx */ +#define GPDMA_CONN_MAT3_0 ((30UL)) /*!< MAT3.0 */ +#define GPDMA_CONN_MAT3_1 ((31UL)) /*!< MAT3.1 */ + +#elif defined(CHIP_LPC175X_6X) +/** + * @brief GPDMA request connections + */ +#define GPDMA_CONN_SSP0_Tx ((0UL)) /**< SSP0 Tx */ +#define GPDMA_CONN_SSP0_Rx ((1UL)) /**< SSP0 Rx */ +#define GPDMA_CONN_SSP1_Tx ((2UL)) /**< SSP1 Tx */ +#define GPDMA_CONN_SSP1_Rx ((3UL)) /**< SSP1 Rx */ +#define GPDMA_CONN_ADC ((4UL)) /**< ADC */ +#define GPDMA_CONN_I2S_Channel_0 ((5UL)) /**< I2S channel 0 */ +#define GPDMA_CONN_I2S_Channel_1 ((6UL)) /**< I2S channel 1 */ +#define GPDMA_CONN_DAC ((7UL)) /**< DAC */ +#define GPDMA_CONN_UART0_Tx ((8UL)) /**< UART0 Tx */ +#define GPDMA_CONN_UART0_Rx ((9UL)) /**< UART0 Rx */ +#define GPDMA_CONN_UART1_Tx ((10UL)) /**< UART1 Tx */ +#define GPDMA_CONN_UART1_Rx ((11UL)) /**< UART1 Rx */ +#define GPDMA_CONN_UART2_Tx ((12UL)) /**< UART2 Tx */ +#define GPDMA_CONN_UART2_Rx ((13UL)) /**< UART2 Rx */ +#define GPDMA_CONN_UART3_Tx ((14UL)) /**< UART3 Tx */ +#define GPDMA_CONN_UART3_Rx ((15UL)) /**< UART3 Rx */ +#define GPDMA_CONN_MAT0_0 ((16UL)) /**< MAT0.0 */ +#define GPDMA_CONN_MAT0_1 ((17UL)) /**< MAT0.1 */ +#define GPDMA_CONN_MAT1_0 ((18UL)) /**< MAT1.0 */ +#define GPDMA_CONN_MAT1_1 ((19UL)) /**< MAT1.1 */ +#define GPDMA_CONN_MAT2_0 ((20UL)) /**< MAT2.0 */ +#define GPDMA_CONN_MAT2_1 ((21UL)) /**< MAT2.1 */ +#define GPDMA_CONN_MAT3_0 ((22UL)) /**< MAT3.0 */ +#define GPDMA_CONN_MAT3_1 ((23UL)) /**< MAT3.1 */ +#define GPDMA_CONN_MEMORY ((24UL)) +#endif + +/** + * @brief GPDMA Burst size in Source and Destination definitions + */ +#define GPDMA_BSIZE_1 ((0UL)) /*!< Burst size = 1 */ +#define GPDMA_BSIZE_4 ((1UL)) /*!< Burst size = 4 */ +#define GPDMA_BSIZE_8 ((2UL)) /*!< Burst size = 8 */ +#define GPDMA_BSIZE_16 ((3UL)) /*!< Burst size = 16 */ +#define GPDMA_BSIZE_32 ((4UL)) /*!< Burst size = 32 */ +#define GPDMA_BSIZE_64 ((5UL)) /*!< Burst size = 64 */ +#define GPDMA_BSIZE_128 ((6UL)) /*!< Burst size = 128 */ +#define GPDMA_BSIZE_256 ((7UL)) /*!< Burst size = 256 */ + +/** + * @brief Width in Source transfer width and Destination transfer width definitions + */ +#define GPDMA_WIDTH_BYTE ((0UL)) /*!< Width = 1 byte */ +#define GPDMA_WIDTH_HALFWORD ((1UL)) /*!< Width = 2 bytes */ +#define GPDMA_WIDTH_WORD ((2UL)) /*!< Width = 4 bytes */ + +/** + * @brief Flow control definitions + */ +#define DMA_CONTROLLER 0 /*!< Flow control is DMA controller*/ +#define SRC_PER_CONTROLLER 1 /*!< Flow control is Source peripheral controller*/ +#define DST_PER_CONTROLLER 2 /*!< Flow control is Destination peripheral controller*/ + +/** + * @brief DMA channel handle structure + */ +typedef struct { + FunctionalState ChannelStatus; /*!< DMA channel status */ +} DMA_ChannelHandle_t; + +/** + * @brief Transfer Descriptor structure typedef + */ +typedef struct DMA_TransferDescriptor { + uint32_t src; /*!< Source address */ + uint32_t dst; /*!< Destination address */ + uint32_t lli; /*!< Pointer to next descriptor structure */ + uint32_t ctrl; /*!< Control word that has transfer size, type etc. */ +} DMA_TransferDescriptor_t; + +/** + * @brief Initialize the GPDMA + * @param pGPDMA : The base of GPDMA on the chip + * @return Nothing + */ +void Chip_GPDMA_Init(LPC_GPDMA_T *pGPDMA); + +/** + * @brief Shutdown the GPDMA + * @param pGPDMA : The base of GPDMA on the chip + * @return Nothing + */ +void Chip_GPDMA_DeInit(LPC_GPDMA_T *pGPDMA); + +/** + * @brief Initialize channel configuration strucutre + * @param pGPDMA : The base of GPDMA on the chip + * @param GPDMACfg : Pointer to configuration structure to be initialized + * @param ChannelNum : Channel used for transfer *must be obtained using Chip_GPDMA_GetFreeChannel()* + * @param src : Address of Memory or one of GPDMA_CONN_MEMORY + * PeripheralConnection_ID , which is the source + * @param dst : Address of Memory or one of GPDMA_CONN_MEMORY + * PeripheralConnection_ID, which is the destination + * @param Size : The number of DMA transfers + * @param TransferType : Select the transfer controller and the type of transfer. (See, #GPDMA_FLOW_CONTROL_T) + * @return ERROR on error, SUCCESS on success + */ +int Chip_GPDMA_InitChannelCfg(LPC_GPDMA_T *pGPDMA, + GPDMA_CH_CFG_T *GPDMACfg, + uint8_t ChannelNum, + uint32_t src, + uint32_t dst, + uint32_t Size, + GPDMA_FLOW_CONTROL_T TransferType); + +/** + * @brief Enable or Disable the GPDMA Channel + * @param pGPDMA : The base of GPDMA on the chip + * @param channelNum : The GPDMA channel : 0 - 7 + * @param NewState : ENABLE to enable GPDMA or DISABLE to disable GPDMA + * @return Nothing + */ +void Chip_GPDMA_ChannelCmd(LPC_GPDMA_T *pGPDMA, uint8_t channelNum, FunctionalState NewState); + +/** + * @brief Stop a stream DMA transfer + * @param pGPDMA : The base of GPDMA on the chip + * @param ChannelNum : Channel Number to be closed + * @return Nothing + */ +void Chip_GPDMA_Stop(LPC_GPDMA_T *pGPDMA, uint8_t ChannelNum); + +/** + * @brief The GPDMA stream interrupt status checking + * @param pGPDMA : The base of GPDMA on the chip + * @param ChannelNum : Channel Number to be checked on interruption + * @return Status: + * - SUCCESS : DMA transfer success + * - ERROR : DMA transfer failed + */ +Status Chip_GPDMA_Interrupt(LPC_GPDMA_T *pGPDMA, uint8_t ChannelNum); + +/** + * @brief Read the status from different registers according to the type + * @param pGPDMA : The base of GPDMA on the chip + * @param type : Status mode, should be: + * - GPDMA_STAT_INT : GPDMA Interrupt Status + * - GPDMA_STAT_INTTC : GPDMA Interrupt Terminal Count Request Status + * - GPDMA_STAT_INTERR : GPDMA Interrupt Error Status + * - GPDMA_STAT_RAWINTTC : GPDMA Raw Interrupt Terminal Count Status + * - GPDMA_STAT_RAWINTERR : GPDMA Raw Error Interrupt Status + * - GPDMA_STAT_ENABLED_CH : GPDMA Enabled Channel Status + * @param channel : The GPDMA channel : 0 - 7 + * @return SET is interrupt is pending or RESET if not pending + */ +IntStatus Chip_GPDMA_IntGetStatus(LPC_GPDMA_T *pGPDMA, GPDMA_STATUS_T type, uint8_t channel); + +/** + * @brief Clear the Interrupt Flag from different registers according to the type + * @param pGPDMA : The base of GPDMA on the chip + * @param type : Flag mode, should be: + * - GPDMA_STATCLR_INTTC : GPDMA Interrupt Terminal Count Request + * - GPDMA_STATCLR_INTERR : GPDMA Interrupt Error + * @param channel : The GPDMA channel : 0 - 7 + * @return Nothing + */ +void Chip_GPDMA_ClearIntPending(LPC_GPDMA_T *pGPDMA, GPDMA_STATECLEAR_T type, uint8_t channel); + +/** + * @brief Get a free GPDMA channel for one DMA connection + * @param pGPDMA : The base of GPDMA on the chip + * @param PeripheralConnection_ID : Some chip fix each peripheral DMA connection on a specified channel ( have not used in 17xx/40xx ) + * @return The channel number which is selected + */ +uint8_t Chip_GPDMA_GetFreeChannel(LPC_GPDMA_T *pGPDMA, + uint32_t PeripheralConnection_ID); + +/** + * @brief Do a DMA transfer M2M, M2P,P2M or P2P + * @param pGPDMA : The base of GPDMA on the chip + * @param ChannelNum : Channel used for transfer + * @param src : Address of Memory or PeripheralConnection_ID which is the source + * @param dst : Address of Memory or PeripheralConnection_ID which is the destination + * @param TransferType: Select the transfer controller and the type of transfer. Should be: + * - GPDMA_TRANSFERTYPE_M2M_CONTROLLER_DMA + * - GPDMA_TRANSFERTYPE_M2P_CONTROLLER_DMA + * - GPDMA_TRANSFERTYPE_P2M_CONTROLLER_DMA + * - GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DMA + * - GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DestPERIPHERAL + * - GPDMA_TRANSFERTYPE_M2P_CONTROLLER_PERIPHERAL + * - GPDMA_TRANSFERTYPE_P2M_CONTROLLER_PERIPHERAL + * - GPDMA_TRANSFERTYPE_P2P_CONTROLLER_SrcPERIPHERAL + * @param Size : The number of DMA transfers + * @return ERROR on error, SUCCESS on success + */ +Status Chip_GPDMA_Transfer(LPC_GPDMA_T *pGPDMA, + uint8_t ChannelNum, + uint32_t src, + uint32_t dst, + GPDMA_FLOW_CONTROL_T TransferType, + uint32_t Size); + +/** + * @brief Do a DMA transfer using linked list of descriptors + * @param pGPDMA : The base of GPDMA on the chip + * @param ChannelNum : Channel used for transfer *must be obtained using Chip_GPDMA_GetFreeChannel()* + * @param DMADescriptor : First node in the linked list of descriptors + * @param TransferType : Select the transfer controller and the type of transfer. (See, #GPDMA_FLOW_CONTROL_T) + * @return ERROR on error, SUCCESS on success + */ +Status Chip_GPDMA_SGTransfer(LPC_GPDMA_T *pGPDMA, + uint8_t ChannelNum, + const DMA_TransferDescriptor_t *DMADescriptor, + GPDMA_FLOW_CONTROL_T TransferType); + +/** + * @brief Prepare a single DMA descriptor + * @param pGPDMA : The base of GPDMA on the chip + * @param DMADescriptor : DMA Descriptor to be initialized + * @param src : Address of Memory or one of GPDMA_CONN_MEMORY + * PeripheralConnection_ID, which is the source + * @param dst : Address of Memory or one of GPDMA_CONN_MEMORY + * PeripheralConnection_ID, which is the destination + * @param Size : The number of DMA transfers + * @param TransferType : Select the transfer controller and the type of transfer. (See, #GPDMA_FLOW_CONTROL_T) + * @param NextDescriptor : Pointer to next descriptor (0 if no more descriptors available) + * @return ERROR on error, SUCCESS on success + */ +Status Chip_GPDMA_PrepareDescriptor(LPC_GPDMA_T *pGPDMA, + DMA_TransferDescriptor_t *DMADescriptor, + uint32_t src, + uint32_t dst, + uint32_t Size, + GPDMA_FLOW_CONTROL_T TransferType, + const DMA_TransferDescriptor_t *NextDescriptor); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __GPDMA_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/gpio_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/gpio_17xx_40xx.h new file mode 100644 index 000000000..3ea66737b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/gpio_17xx_40xx.h @@ -0,0 +1,491 @@ +/* + * @brief LPC17xx/40xx GPIO driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __GPIO_17XX_40XX_H_ +#define __GPIO_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup GPIO_17XX_40XX CHIP: LPC17xx/40xx GPIO driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#define GPIO_PORT_BITS 32 + +/** + * @brief GPIO port (GPIO_PORT) for LPC175x_6x, LPC177x_8x and LPC407x_8x + */ + +typedef struct { /* GPIO_PORT Structure */ + __IO uint32_t DIR; /*!< Offset 0x0000: GPIO Port Direction control register */ + uint32_t RESERVED0[3]; + __IO uint32_t MASK; /*!< Offset 0x0010: GPIO Mask register */ + __IO uint32_t PIN; /*!< Offset 0x0014: Pin value register using FIOMASK */ + __IO uint32_t SET; /*!< Offset 0x0018: Output Set register using FIOMASK */ + __O uint32_t CLR; /*!< Offset 0x001C: Output Clear register using FIOMASK */ +} LPC_GPIO_T; + +/** + * @brief Initialize GPIO block + * @param pGPIO : The base of GPIO peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_Init(LPC_GPIO_T *pGPIO) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_GPIO); +} + +/** + * @brief De-Initialize GPIO block + * @param pGPIO : The base of GPIO peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_DeInit(LPC_GPIO_T *pGPIO) +{ + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_GPIO); +} + +/** + * @brief Set a GPIO pin state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pin : GPIO pin to set + * @param setting : true for high, false for low + * @return Nothing + * @note This function replaces Chip_GPIO_WritePortBit() + */ +STATIC INLINE void Chip_GPIO_SetPinState(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin, bool setting) +{ + if (setting) { /* Set Port */ + pGPIO[port].SET |= 1UL << pin; + } + else { /* Clear Port */ + pGPIO[port].CLR |= 1UL << pin; + } +} + +/** + * @brief Set a GPIO port/bit state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO port to set + * @param pin : GPIO pin to set + * @param setting : true for high, false for low + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_WritePortBit(LPC_GPIO_T *pGPIO, uint32_t port, uint8_t pin, bool setting) +{ + Chip_GPIO_SetPinState(pGPIO, port, pin, setting); +} + +/** + * @brief Get a GPIO pin state via the GPIO byte register + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pin : GPIO pin to get state for + * @return true if the GPIO is high, false if low + * @note This function replaces Chip_GPIO_ReadPortBit() + */ +STATIC INLINE bool Chip_GPIO_GetPinState(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin) +{ + return (bool) ((pGPIO[port].PIN >> pin) & 1); +} + +/** + * @brief Read a GPIO state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO port to read + * @param pin : GPIO pin to read + * @return true of the GPIO is high, false if low + * @note It is recommended to use the Chip_GPIO_GetPinState() function instead. + */ +STATIC INLINE bool Chip_GPIO_ReadPortBit(LPC_GPIO_T *pGPIO, uint32_t port, uint8_t pin) +{ + return Chip_GPIO_GetPinState(pGPIO, port, pin); +} + +/** + * @brief Set GPIO direction for a single GPIO pin to an output + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where a pin is located + * @param pin : GPIO pin to set direction on as output + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_SetPinDIROutput(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin) +{ + pGPIO[port].DIR |= 1UL << pin; +} + +/** + * @brief Set GPIO direction for a single GPIO pin to an input + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pin : GPIO pin to set direction on as input + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_SetPinDIRInput(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin) +{ + pGPIO[port].DIR &= ~(1UL << pin); +} + +/** + * @brief Set GPIO direction for a single GPIO pin + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pin : GPIO pin to set direction for + * @param output : true for output, false for input + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_SetPinDIR(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin, bool output) +{ + if (output) { + Chip_GPIO_SetPinDIROutput(pGPIO, port, pin); + } + else { + Chip_GPIO_SetPinDIRInput(pGPIO, port, pin); + } +} + +/** + * @brief Set a GPIO direction + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO port to set + * @param bit : GPIO bit to set + * @param setting : true for output, false for input + * @return Nothing + * @note It is recommended to use the Chip_GPIO_SetPinDIROutput(), + * Chip_GPIO_SetPinDIRInput() or Chip_GPIO_SetPinDIR() functions instead + * of this function. + */ +STATIC INLINE void Chip_GPIO_WriteDirBit(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t bit, bool setting) +{ + Chip_GPIO_SetPinDIR(pGPIO, port, bit, setting); +} + +/** + * @brief Get GPIO direction for a single GPIO pin + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pin : GPIO pin to get direction for + * @return true if the GPIO is an output, false if input + */ +STATIC INLINE bool Chip_GPIO_GetPinDIR(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin) +{ + return (bool) (((pGPIO[port].DIR) >> pin) & 1); +} + +/** + * @brief Read a GPIO direction (out or in) + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO port to read + * @param bit : GPIO bit to read + * @return true of the GPIO is an output, false if input + * @note It is recommended to use the Chip_GPIO_GetPinDIR() function instead. + */ +STATIC INLINE bool Chip_GPIO_ReadDirBit(LPC_GPIO_T *pGPIO, uint32_t port, uint8_t bit) +{ + return Chip_GPIO_GetPinDIR(pGPIO, port, bit); +} + +/** + * @brief Set Direction for a GPIO port + * @param pGPIO : The base of GPIO peripheral on the chip + * @param portNum : port Number + * @param bitValue : GPIO bit to set + * @param out : Direction value, 0 = input, !0 = output + * @return None + * @note Bits set to '0' are not altered. It is recommended to use the + * Chip_GPIO_SetPortDIR() function instead. + */ +STATIC INLINE void Chip_GPIO_SetDir(LPC_GPIO_T *pGPIO, uint8_t portNum, uint32_t bitValue, uint8_t out) +{ + Chip_GPIO_SetPinDIR(pGPIO, portNum, bitValue, out); +} + +/** + * @brief Set GPIO direction for a all selected GPIO pins to an output + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pinMask : GPIO pin mask to set direction on as output (bits 0..b for pins 0..n) + * @return Nothing + * @note Sets multiple GPIO pins to the output direction, each bit's position that is + * high sets the corresponding pin number for that bit to an output. + */ +STATIC INLINE void Chip_GPIO_SetPortDIROutput(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t pinMask) +{ + pGPIO[port].DIR |= pinMask; +} + +/** + * @brief Set GPIO direction for a all selected GPIO pins to an input + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pinMask : GPIO pin mask to set direction on as input (bits 0..b for pins 0..n) + * @return Nothing + * @note Sets multiple GPIO pins to the input direction, each bit's position that is + * high sets the corresponding pin number for that bit to an input. + */ +STATIC INLINE void Chip_GPIO_SetPortDIRInput(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t pinMask) +{ + pGPIO[port].DIR &= ~pinMask; +} + +/** + * @brief Set GPIO direction for a all selected GPIO pins to an input or output + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pinMask : GPIO pin mask to set direction on (bits 0..b for pins 0..n) + * @param outSet : Direction value, false = set as inputs, true = set as outputs + * @return Nothing + * @note Sets multiple GPIO pins to the input direction, each bit's position that is + * high sets the corresponding pin number for that bit to an input. + */ +STATIC INLINE void Chip_GPIO_SetPortDIR(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t pinMask, bool outSet) +{ + if (outSet) { + Chip_GPIO_SetPortDIROutput(pGPIO, port, pinMask); + } + else { + Chip_GPIO_SetPortDIRInput(pGPIO, port, pinMask); + } +} + +/** + * @brief Get GPIO direction for a all GPIO pins + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @return a bitfield containing the input and output states for each pin + * @note For pins 0..n, a high state in a bit corresponds to an output state for the + * same pin, while a low state corresponds to an input state. + */ +STATIC INLINE uint32_t Chip_GPIO_GetPortDIR(LPC_GPIO_T *pGPIO, uint8_t port) +{ + return pGPIO[port].DIR; +} + +/** + * @brief Set GPIO port mask value for GPIO masked read and write + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : port Number + * @param mask : Mask value for read and write (only low bits are enabled) + * @return Nothing + * @note Controls which bits are set or unset when using the masked + * GPIO read and write functions. A low state indicates the pin is settable + * and readable via the masked write and read functions. + */ +STATIC INLINE void Chip_GPIO_SetPortMask(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t mask) +{ + pGPIO[port].MASK = mask; +} + +/** + * @brief Get GPIO port mask value used for GPIO masked read and write + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : port Number + * @return Returns value set with the Chip_GPIO_SetPortMask() function. + * @note A high bit in the return value indicates that that GPIO pin for the + * port cannot be set using the masked write function. + */ +STATIC INLINE uint32_t Chip_GPIO_GetPortMask(LPC_GPIO_T *pGPIO, uint8_t port) +{ + return pGPIO[port].MASK; +} + +/** + * @brief Set all GPIO pin states, but mask via the MASK register + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param value : Value to set all GPIO pin states (0..n) to + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_SetMaskedPortValue(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t value) +{ + pGPIO[port].PIN = value; +} + +/** + * @brief Get all GPIO pin states but mask via the MASK register + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @return Current (masked) state of all GPIO pins + */ +STATIC INLINE uint32_t Chip_GPIO_GetMaskedPortValue(LPC_GPIO_T *pGPIO, uint8_t port) +{ + return pGPIO[port].PIN; +} + +/** + * @brief Set all GPIO raw pin states (does not bypass masking on this chip!) + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param value : Value to set all GPIO pin states (0..n) to + * @return Nothing + */ +STATIC INLINE void Chip_GPIO_SetPortValue(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t value) +{ + Chip_GPIO_SetMaskedPortValue(pGPIO, port, value); +} + +/** + * @brief Get all GPIO raw pin states (does not bypass masking on this chip!) + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @return Current (raw) state of all GPIO pins + */ +STATIC INLINE uint32_t Chip_GPIO_GetPortValue(LPC_GPIO_T *pGPIO, uint8_t port) +{ + return Chip_GPIO_GetMaskedPortValue(pGPIO, port); +} + +/** + * @brief Set selected GPIO output pins to the high state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pins : pins (0..n) to set high + * @return None + * @note Any bit set as a '0' will not have it's state changed. This only + * applies to ports configured as an output. + */ +STATIC INLINE void Chip_GPIO_SetPortOutHigh(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t pins) +{ + pGPIO[port].SET = pins; +} + +/** + * @brief Set a GPIO port/bit to the high state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param portNum : port number + * @param bitValue : bit(s) in the port to set high + * @return None + * @note Any bit set as a '0' will not have it's state changed. This only + * applies to ports configured as an output. It is recommended to use the + * Chip_GPIO_SetPortOutHigh() function instead. + */ +STATIC INLINE void Chip_GPIO_SetValue(LPC_GPIO_T *pGPIO, uint8_t portNum, uint32_t bitValue) +{ + Chip_GPIO_SetPortOutHigh(pGPIO,portNum,bitValue); +} + +/** + * @brief Set an individual GPIO output pin to the high state + * @param pGPIO : The base of GPIO peripheral on the chip' + * @param port : GPIO Port number where pin is located + * @param pin : pin number (0..n) to set high + * @return None + * @note Any bit set as a '0' will not have it's state changed. This only + * applies to ports configured as an output. + */ +STATIC INLINE void Chip_GPIO_SetPinOutHigh(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin) +{ + pGPIO[port].SET = (1 << pin); +} + +/** + * @brief Set selected GPIO output pins to the low state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pins : pins (0..n) to set low + * @return None + * @note Any bit set as a '0' will not have it's state changed. This only + * applies to ports configured as an output. + */ +STATIC INLINE void Chip_GPIO_SetPortOutLow(LPC_GPIO_T *pGPIO, uint8_t port, uint32_t pins) +{ + pGPIO[port].CLR = pins; +} + +/** + * @brief Set a GPIO port/bit to the low state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param portNum : port number + * @param bitValue : bit(s) in the port to set low + * @return None + * @note Any bit set as a '0' will not have it's state changed. This only + * applies to ports configured as an output. + */ +STATIC INLINE void Chip_GPIO_ClearValue(LPC_GPIO_T *pGPIO, uint8_t portNum, uint32_t bitValue) +{ + Chip_GPIO_SetPortOutLow(pGPIO, portNum, bitValue); +} + +/** + * @brief Set an individual GPIO output pin to the low state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where pin is located + * @param pin : pin number (0..n) to set low + * @return None + * @note Any bit set as a '0' will not have it's state changed. This only + * applies to ports configured as an output. + */ +STATIC INLINE void Chip_GPIO_SetPinOutLow(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin) +{ + pGPIO[port].CLR = (1 << pin); +} + +/** + * @brief Toggle an individual GPIO output pin to the opposite state + * @param pGPIO : The base of GPIO peripheral on the chip + * @param port : GPIO Port number where @a pin is located + * @param pin : pin number (0..n) to toggle + * @return None + * @note Any bit set as a '0' will not have it's state changed. This only + * applies to ports configured as an output. + */ +STATIC INLINE void Chip_GPIO_SetPinToggle(LPC_GPIO_T *pGPIO, uint8_t port, uint8_t pin) +{ + bool setting = !Chip_GPIO_GetPinState(pGPIO, port, pin); + Chip_GPIO_SetPinState(pGPIO, port, pin, setting); +} + +/** + * @brief Read current bit states for the selected port + * @param pGPIO : The base of GPIO peripheral on the chip + * @param portNum : port number to read + * @return Current value of GPIO port + * @note The current states of the bits for the port are read, regardless of + * whether the GPIO port bits are input or output. + */ +STATIC INLINE uint32_t Chip_GPIO_ReadValue(LPC_GPIO_T *pGPIO, uint8_t portNum) +{ + return pGPIO[portNum].PIN; +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __GPIO_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/gpioint_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/gpioint_17xx_40xx.h new file mode 100644 index 000000000..4f74323c4 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/gpioint_17xx_40xx.h @@ -0,0 +1,227 @@ +/* + * @brief LPC17xx/40xx GPIO driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __GPIOINT_17XX_40XX_H_ +#define __GPIOINT_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup GPIOINT_17XX_40XX CHIP: LPC17xx/40xx GPIO Interrupt driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief GPIO Interupt registers for Portn + */ +typedef struct { + __I uint32_t STATR; /*!< GPIO Interrupt Status Register for Rising edge */ + __I uint32_t STATF; /*!< GPIO Interrupt Status Register for Falling edge */ + __O uint32_t CLR; /*!< GPIO Interrupt Clear Register */ + __IO uint32_t ENR; /*!< GPIO Interrupt Enable Register 0 for Rising edge */ + __IO uint32_t ENF; /*!< GPIO Interrupt Enable Register 0 for Falling edge */ +} GPIOINT_PORT_T; + +/** + * @brief GPIO Interrupt register block structure + */ +typedef struct { + __I uint32_t STATUS; /*!< GPIO overall Interrupt Status Register */ + GPIOINT_PORT_T IO0; /*!< GPIO Interrupt Registers for Port 0 */ + uint32_t RESERVED0[3]; + GPIOINT_PORT_T IO2; /*!< GPIO Interrupt Registers for Port 2 */ +} LPC_GPIOINT_T; + +/** + * @brief GPIO interrupt capable ports + */ +typedef enum { + GPIOINT_PORT0, /*!< GPIO PORT 0 */ + GPIOINT_PORT2 = 2 /*!< GPIO PORT 2 */ +}LPC_GPIOINT_PORT_T; + +/** + * @brief Initialize GPIO interrupt block + * @param pGPIOINT : The base address of GPIO interrupt block + * @return Nothing + * @note This function enables the clock to IOCON, GPIO and GPIOINT + * peripheral blocks. + */ +STATIC INLINE void Chip_GPIOINT_Init(LPC_GPIOINT_T *pGPIOINT) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_GPIO); +} + +/** + * @brief De-Initialize GPIO Interrupt block + * @param pGPIOINT : The base of GPIO interrupt peripheral on the chip + * @return Nothing + * @note This function disables the clock to IOCON, GPIO and GPIOINT + * peripheral blocks This function should not be called + * if IOCON or GPIO needs to be used after calling this function. + */ +STATIC INLINE void Chip_GPIOINT_DeInit(LPC_GPIOINT_T *pGPIOINT) +{ + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_GPIO); +} + +/** + * @brief Enable interrupts on falling edge of given @a pins + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @param pins : Pins set to 1 will have falling edge interrupt enabled, + * Pins set to 0 will have falling edge interrupt disabled + * @return Nothing + */ +STATIC INLINE void Chip_GPIOINT_SetIntFalling(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port, uint32_t pins) +{ + if (port == GPIOINT_PORT0) { + pGPIOINT->IO0.ENF = pins; + } else { + pGPIOINT->IO2.ENF = pins; + } +} + +/** + * @brief Enable interrupts on rising edge of given @a pins + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @param pins : Pins set to 1 will have rising edge interrupt enabled, + * Pins set to 0 will have rising edge interrupt disabled + * @return Nothing + */ +STATIC INLINE void Chip_GPIOINT_SetIntRising(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port, uint32_t pins) +{ + if (port == GPIOINT_PORT0) { + pGPIOINT->IO0.ENR = pins; + } else { + pGPIOINT->IO2.ENR = pins; + } +} + +/** + * @brief Get the pins that has falling edge interrupt enabled + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @return Pins that are configured for Falling edge interrupt enabled + */ +STATIC INLINE uint32_t Chip_GPIOINT_GetIntFalling(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port) +{ + if (port == GPIOINT_PORT0) { + return pGPIOINT->IO0.ENF; + } else { + return pGPIOINT->IO2.ENF; + } +} + +/** + * @brief Get pins that has rising edge interrupt enabled + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @return Pins that are configured for rising edge interrupt enabled + */ +STATIC INLINE uint32_t Chip_GPIOINT_GetIntRising(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port) +{ + if (port == GPIOINT_PORT0) { + return pGPIOINT->IO0.ENR; + } else { + return pGPIOINT->IO2.ENR; + } +} + +/** + * @brief Get status of the pins for falling edge + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @return Pins that has detected falling edge + */ +STATIC INLINE uint32_t Chip_GPIOINT_GetStatusFalling(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port) +{ + if (port == GPIOINT_PORT0) { + return pGPIOINT->IO0.STATF; + } else { + return pGPIOINT->IO2.STATF; + } +} + +/** + * @brief Get status of the pins for rising edge + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @return Pins that has detected rising edge + */ +STATIC INLINE uint32_t Chip_GPIOINT_GetStatusRising(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port) +{ + if (port == GPIOINT_PORT0) { + return pGPIOINT->IO0.STATR; + } else { + return pGPIOINT->IO2.STATR; + } +} + +/** + * @brief Clear the falling and rising edge interrupt for given @a pins + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @param pins : Pins to clear the interrupts for + * @return Nothing + */ +STATIC INLINE void Chip_GPIOINT_ClearIntStatus(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port, uint32_t pins) +{ + if (port == GPIOINT_PORT0) { + pGPIOINT->IO0.CLR = pins; + } else { + pGPIOINT->IO2.CLR = pins; + } +} + +/** + * @brief Checks if an interrupt is pending on a given port + * @param pGPIOINT : The base address of GPIO interrupt block + * @param port : GPIOINT port (GPIOINT_PORT0 or GPIOINT_PORT2) + * @return true if any pin in given port has a pending interrupt + */ +STATIC INLINE bool Chip_GPIOINT_IsIntPending(LPC_GPIOINT_T *pGPIOINT, LPC_GPIOINT_PORT_T port) +{ + return ((pGPIOINT->STATUS & (1 << (int)port)) != 0); +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __GPIOINT_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/i2c_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/i2c_17xx_40xx.h new file mode 100644 index 000000000..451fb027f --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/i2c_17xx_40xx.h @@ -0,0 +1,541 @@ +/* + * @brief LPC17xx/40xx I2C driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __I2C_17XX_40XX_H_ +#define __I2C_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup I2C_17XX_40XX CHIP: LPC17xx/40xx I2C driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief I2C register block structure + */ +typedef struct { /* I2C0 Structure */ + __IO uint32_t CONSET; /*!< I2C Control Set Register. When a one is written to a bit of this register, the corresponding bit in the I2C control register is set. Writing a zero has no effect on the corresponding bit in the I2C control register. */ + __I uint32_t STAT; /*!< I2C Status Register. During I2C operation, this register provides detailed status codes that allow software to determine the next action needed. */ + __IO uint32_t DAT; /*!< I2C Data Register. During master or slave transmit mode, data to be transmitted is written to this register. During master or slave receive mode, data that has been received may be read from this register. */ + __IO uint32_t ADR0; /*!< I2C Slave Address Register 0. Contains the 7-bit slave address for operation of the I2C interface in slave mode, and is not used in master mode. The least significant bit determines whether a slave responds to the General Call address. */ + __IO uint32_t SCLH; /*!< SCH Duty Cycle Register High Half Word. Determines the high time of the I2C clock. */ + __IO uint32_t SCLL; /*!< SCL Duty Cycle Register Low Half Word. Determines the low time of the I2C clock. SCLL and SCLH together determine the clock frequency generated by an I2C master and certain times used in slave mode. */ + __O uint32_t CONCLR; /*!< I2C Control Clear Register. When a one is written to a bit of this register, the corresponding bit in the I2C control register is cleared. Writing a zero has no effect on the corresponding bit in the I2C control register. */ + __IO uint32_t MMCTRL; /*!< Monitor mode control register. */ + __IO uint32_t ADR1; /*!< I2C Slave Address Register. Contains the 7-bit slave address for operation of the I2C interface in slave mode, and is not used in master mode. The least significant bit determines whether a slave responds to the General Call address. */ + __IO uint32_t ADR2; /*!< I2C Slave Address Register. Contains the 7-bit slave address for operation of the I2C interface in slave mode, and is not used in master mode. The least significant bit determines whether a slave responds to the General Call address. */ + __IO uint32_t ADR3; /*!< I2C Slave Address Register. Contains the 7-bit slave address for operation of the I2C interface in slave mode, and is not used in master mode. The least significant bit determines whether a slave responds to the General Call address. */ + __I uint32_t DATA_BUFFER; /*!< Data buffer register. The contents of the 8 MSBs of the DAT shift register will be transferred to the DATA_BUFFER automatically after every nine bits (8 bits of data plus ACK or NACK) has been received on the bus. */ + __IO uint32_t MASK[4]; /*!< I2C Slave address mask register */ +} LPC_I2C_T; + +/** + * @brief Return values for SLAVE handler + * @note + * Chip drivers will usally be designed to match their events with this value + */ +#define RET_SLAVE_TX 6 /**< Return value, when 1 byte TX'd successfully */ +#define RET_SLAVE_RX 5 /**< Return value, when 1 byte RX'd successfully */ +#define RET_SLAVE_IDLE 2 /**< Return value, when slave enter idle mode */ +#define RET_SLAVE_BUSY 0 /**< Return value, when slave is busy */ + +/** + * @brief I2C state handle return values + */ +#define I2C_STA_STO_RECV 0x20 + +/* + * @brief I2C Control Set register description + */ +#define I2C_I2CONSET_AA ((0x04))/*!< Assert acknowledge flag */ +#define I2C_I2CONSET_SI ((0x08))/*!< I2C interrupt flag */ +#define I2C_I2CONSET_STO ((0x10))/*!< STOP flag */ +#define I2C_I2CONSET_STA ((0x20))/*!< START flag */ +#define I2C_I2CONSET_I2EN ((0x40))/*!< I2C interface enable */ + +/* + * @brief I2C Control Clear register description + */ +#define I2C_I2CONCLR_AAC ((1 << 2)) /*!< Assert acknowledge Clear bit */ +#define I2C_I2CONCLR_SIC ((1 << 3)) /*!< I2C interrupt Clear bit */ +#define I2C_I2CONCLR_STOC ((1 << 4)) /*!< I2C STOP Clear bit */ +#define I2C_I2CONCLR_STAC ((1 << 5)) /*!< START flag Clear bit */ +#define I2C_I2CONCLR_I2ENC ((1 << 6)) /*!< I2C interface Disable bit */ + +/* + * @brief I2C Common Control register description + */ +#define I2C_CON_AA (1UL << 2) /*!< Assert acknowledge bit */ +#define I2C_CON_SI (1UL << 3) /*!< I2C interrupt bit */ +#define I2C_CON_STO (1UL << 4) /*!< I2C STOP bit */ +#define I2C_CON_STA (1UL << 5) /*!< START flag bit */ +#define I2C_CON_I2EN (1UL << 6) /*!< I2C interface bit */ + +/* + * @brief I2C Status Code definition (I2C Status register) + */ +#define I2C_STAT_CODE_BITMASK ((0xF8))/*!< Return Code mask in I2C status register */ +#define I2C_STAT_CODE_ERROR ((0xFF))/*!< Return Code error mask in I2C status register */ + +/* + * @brief I2C return status code definitions + */ +#define I2C_I2STAT_NO_INF ((0xF8))/*!< No relevant information */ +#define I2C_I2STAT_BUS_ERROR ((0x00))/*!< Bus Error */ + +/* + * @brief I2C Master transmit mode + */ +#define I2C_I2STAT_M_TX_START ((0x08))/*!< A start condition has been transmitted */ +#define I2C_I2STAT_M_TX_RESTART ((0x10))/*!< A repeat start condition has been transmitted */ +#define I2C_I2STAT_M_TX_SLAW_ACK ((0x18))/*!< SLA+W has been transmitted, ACK has been received */ +#define I2C_I2STAT_M_TX_SLAW_NACK ((0x20))/*!< SLA+W has been transmitted, NACK has been received */ +#define I2C_I2STAT_M_TX_DAT_ACK ((0x28))/*!< Data has been transmitted, ACK has been received */ +#define I2C_I2STAT_M_TX_DAT_NACK ((0x30))/*!< Data has been transmitted, NACK has been received */ +#define I2C_I2STAT_M_TX_ARB_LOST ((0x38))/*!< Arbitration lost in SLA+R/W or Data bytes */ + +/* + * @brief I2C Master receive mode + */ +#define I2C_I2STAT_M_RX_START ((0x08))/*!< A start condition has been transmitted */ +#define I2C_I2STAT_M_RX_RESTART ((0x10))/*!< A repeat start condition has been transmitted */ +#define I2C_I2STAT_M_RX_ARB_LOST ((0x38))/*!< Arbitration lost */ +#define I2C_I2STAT_M_RX_SLAR_ACK ((0x40))/*!< SLA+R has been transmitted, ACK has been received */ +#define I2C_I2STAT_M_RX_SLAR_NACK ((0x48))/*!< SLA+R has been transmitted, NACK has been received */ +#define I2C_I2STAT_M_RX_DAT_ACK ((0x50))/*!< Data has been received, ACK has been returned */ +#define I2C_I2STAT_M_RX_DAT_NACK ((0x58))/*!< Data has been received, NACK has been returned */ + +/* + * @brief I2C Slave receive mode + */ +#define I2C_I2STAT_S_RX_SLAW_ACK ((0x60))/*!< Own slave address has been received, ACK has been returned */ +#define I2C_I2STAT_S_RX_ARB_LOST_M_SLA ((0x68))/*!< Arbitration lost in SLA+R/W as master */ +// #define I2C_I2STAT_S_RX_SLAW_ACK ((0x68)) /*!< Own SLA+W has been received, ACK returned */ +#define I2C_I2STAT_S_RX_GENCALL_ACK ((0x70))/*!< General call address has been received, ACK has been returned */ +#define I2C_I2STAT_S_RX_ARB_LOST_M_GENCALL ((0x78))/*!< Arbitration lost in SLA+R/W (GENERAL CALL) as master */ +// #define I2C_I2STAT_S_RX_GENCALL_ACK ((0x78)) /*!< General call address has been received, ACK has been returned */ +#define I2C_I2STAT_S_RX_PRE_SLA_DAT_ACK ((0x80))/*!< Previously addressed with own SLA; Data has been received, ACK has been returned */ +#define I2C_I2STAT_S_RX_PRE_SLA_DAT_NACK ((0x88))/*!< Previously addressed with own SLA;Data has been received and NOT ACK has been returned */ +#define I2C_I2STAT_S_RX_PRE_GENCALL_DAT_ACK ((0x90))/*!< Previously addressed with General Call; Data has been received and ACK has been returned */ +#define I2C_I2STAT_S_RX_PRE_GENCALL_DAT_NACK ((0x98))/*!< Previously addressed with General Call; Data has been received and NOT ACK has been returned */ +#define I2C_I2STAT_S_RX_STA_STO_SLVREC_SLVTRX ((0xA0))/*!< A STOP condition or repeated START condition has been received while still addressed as SLV/REC (Slave Receive) or + SLV/TRX (Slave Transmit) */ + +/* + * @brief I2C Slave transmit mode + */ +#define I2C_I2STAT_S_TX_SLAR_ACK ((0xA8))/*!< Own SLA+R has been received, ACK has been returned */ +#define I2C_I2STAT_S_TX_ARB_LOST_M_SLA ((0xB0))/*!< Arbitration lost in SLA+R/W as master */ +// #define I2C_I2STAT_S_TX_SLAR_ACK ((0xB0)) /*!< Own SLA+R has been received, ACK has been returned */ +#define I2C_I2STAT_S_TX_DAT_ACK ((0xB8))/*!< Data has been transmitted, ACK has been received */ +#define I2C_I2STAT_S_TX_DAT_NACK ((0xC0))/*!< Data has been transmitted, NACK has been received */ +#define I2C_I2STAT_S_TX_LAST_DAT_ACK ((0xC8))/*!< Last data byte in I2DAT has been transmitted (AA = 0); ACK has been received */ +#define I2C_SLAVE_TIME_OUT 0x10000000UL/*!< Time out in case of using I2C slave mode */ + +/* + * @brief I2C Data register definition + */ +#define I2C_I2DAT_BITMASK ((0xFF))/*!< Mask for I2DAT register */ +#define I2C_I2DAT_IDLE_CHAR (0xFF) /*!< Idle data value will be send out in slave mode in case of the actual expecting data requested from the master is greater than + its sending data length that can be supported */ + +/* + * @brief I2C Monitor mode control register description + */ +#define I2C_I2MMCTRL_MM_ENA ((1 << 0)) /**< Monitor mode enable */ +#define I2C_I2MMCTRL_ENA_SCL ((1 << 1)) /**< SCL output enable */ +#define I2C_I2MMCTRL_MATCH_ALL ((1 << 2)) /**< Select interrupt register match */ +#define I2C_I2MMCTRL_BITMASK ((0x07)) /**< Mask for I2MMCTRL register */ + +/* + * @brief I2C Data buffer register description + */ +#define I2DATA_BUFFER_BITMASK ((0xFF))/*!< I2C Data buffer register bit mask */ + +/* + * @brief I2C Slave Address registers definition + */ +#define I2C_I2ADR_GC ((1 << 0)) /*!< General Call enable bit */ +#define I2C_I2ADR_BITMASK ((0xFF))/*!< I2C Slave Address registers bit mask */ + +/* + * @brief I2C Mask Register definition + */ +#define I2C_I2MASK_MASK(n) ((n & 0xFE))/*!< I2C Mask Register mask field */ + +/* + * @brief I2C SCL HIGH duty cycle Register definition + */ +#define I2C_I2SCLH_BITMASK ((0xFFFF)) /*!< I2C SCL HIGH duty cycle Register bit mask */ + +/* + * @brief I2C SCL LOW duty cycle Register definition + */ +#define I2C_I2SCLL_BITMASK ((0xFFFF)) /*!< I2C SCL LOW duty cycle Register bit mask */ + +/* + * @brief I2C status values + */ +#define I2C_SETUP_STATUS_ARBF (1 << 8) /**< Arbitration false */ +#define I2C_SETUP_STATUS_NOACKF (1 << 9) /**< No ACK returned */ +#define I2C_SETUP_STATUS_DONE (1 << 10) /**< Status DONE */ + +/* + * @brief I2C state handle return values + */ +#define I2C_OK 0x00 +#define I2C_BYTE_SENT 0x01 +#define I2C_BYTE_RECV 0x02 +#define I2C_LAST_BYTE_RECV 0x04 +#define I2C_SEND_END 0x08 +#define I2C_RECV_END 0x10 +#define I2C_STA_STO_RECV 0x20 + +#define I2C_ERR (0x10000000) +#define I2C_NAK_RECV (0x10000000 | 0x01) + +#define I2C_CheckError(ErrorCode) (ErrorCode & 0x10000000) + +/* + * @brief I2C monitor control configuration defines + */ +#define I2C_MONITOR_CFG_SCL_OUTPUT I2C_I2MMCTRL_ENA_SCL /**< SCL output enable */ +#define I2C_MONITOR_CFG_MATCHALL I2C_I2MMCTRL_MATCH_ALL /**< Select interrupt register match */ + +/** + * @brief I2C Slave Identifiers + */ +typedef enum { + I2C_SLAVE_GENERAL, /**< Slave ID for general calls */ + I2C_SLAVE_0, /**< Slave ID fo Slave Address 0 */ + I2C_SLAVE_1, /**< Slave ID fo Slave Address 1 */ + I2C_SLAVE_2, /**< Slave ID fo Slave Address 2 */ + I2C_SLAVE_3, /**< Slave ID fo Slave Address 3 */ + I2C_SLAVE_NUM_INTERFACE /**< Number of slave interfaces */ +} I2C_SLAVE_ID; + +/** + * @brief I2C transfer status + */ +typedef enum { + I2C_STATUS_DONE, /**< Transfer done successfully */ + I2C_STATUS_NAK, /**< NAK received during transfer */ + I2C_STATUS_ARBLOST, /**< Aribitration lost during transfer */ + I2C_STATUS_BUSERR, /**< Bus error in I2C transfer */ + I2C_STATUS_BUSY, /**< I2C is busy doing transfer */ +} I2C_STATUS_T; + +/** + * @brief Master transfer data structure definitions + */ +typedef struct { + uint8_t slaveAddr; /**< 7-bit I2C Slave address */ + const uint8_t *txBuff; /**< Pointer to array of bytes to be transmitted */ + int txSz; /**< Number of bytes in transmit array, + if 0 only receive transfer will be carried on */ + uint8_t *rxBuff; /**< Pointer memory where bytes received from I2C be stored */ + int rxSz; /**< Number of bytes to received, + if 0 only transmission we be carried on */ + I2C_STATUS_T status; /**< Status of the current I2C transfer */ +} I2C_XFER_T; + +/** + * @brief I2C interface IDs + * @note + * All Chip functions will take this as the first parameter, + * I2C_NUM_INTERFACE must never be used for calling any Chip + * functions, it is only used to find the number of interfaces + * available in the Chip. + */ +typedef enum I2C_ID { + I2C0, /**< ID I2C0 */ + I2C1, /**< ID I2C1 */ + I2C2, /**< ID I2C2 */ + I2C_NUM_INTERFACE /**< Number of I2C interfaces in the chip */ +} I2C_ID_T; + +/** + * @brief I2C master events + */ +typedef enum { + I2C_EVENT_WAIT = 1, /**< I2C Wait event */ + I2C_EVENT_DONE, /**< Done event that wakes up Wait event */ + I2C_EVENT_LOCK, /**< Re-entrency lock event for I2C transfer */ + I2C_EVENT_UNLOCK, /**< Re-entrency unlock event for I2C transfer */ + I2C_EVENT_SLAVE_RX, /**< Slave receive event */ + I2C_EVENT_SLAVE_TX, /**< Slave transmit event */ +} I2C_EVENT_T; + +/** + * @brief Event handler function type + */ +typedef void (*I2C_EVENTHANDLER_T)(I2C_ID_T, I2C_EVENT_T); + +/** + * @brief Initializes the LPC_I2C peripheral with specified parameter. + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return Nothing + */ +void Chip_I2C_Init(I2C_ID_T id); + +/** + * @brief De-initializes the I2C peripheral registers to their default reset values + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return Nothing + */ +void Chip_I2C_DeInit(I2C_ID_T id); + +/** + * @brief Set up clock rate for LPC_I2C peripheral. + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @param clockrate : Target clock rate value to initialized I2C peripheral (Hz) + * @return Nothing + * @note + * Parameter @a clockrate for I2C0 should be from 1000 up to 1000000 + * (1 KHz to 1 MHz), as I2C0 support Fast Mode Plus. If the @a clockrate + * is more than 400 KHz (Fast Plus Mode) Board_I2C_EnableFastPlus() + * must be called prior to calling this function. + */ +void Chip_I2C_SetClockRate(I2C_ID_T id, uint32_t clockrate); + +/** + * @brief Get current clock rate for LPC_I2C peripheral. + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return The current I2C peripheral clock rate + */ +uint32_t Chip_I2C_GetClockRate(I2C_ID_T id); + +/** + * @brief Transmit and Receive data in master mode + * @param id : I2C peripheral selected (I2C0, I2C1 etc) + * @param xfer : Pointer to a I2C_XFER_T structure see notes below + * @return + * Any of #I2C_STATUS_T values, xfer->txSz will have number of bytes + * not sent due to error, xfer->rxSz will have the number of bytes yet + * to be received. + * @note + * The parameter @a xfer should have its member @a slaveAddr initialized + * to the 7-Bit slave address to which the master will do the xfer, Bit0 + * to bit6 should have the address and Bit8 is ignored. During the transfer + * no code (like event handler) must change the content of the memory + * pointed to by @a xfer. The member of @a xfer, @a txBuff and @a txSz be + * initialized to the memory from which the I2C must pick the data to be + * transfered to slave and the number of bytes to send respectively, similarly + * @a rxBuff and @a rxSz must have pointer to memroy where data received + * from slave be stored and the number of data to get from slave respectilvely. + */ +int Chip_I2C_MasterTransfer(I2C_ID_T id, I2C_XFER_T *xfer); + +/** + * @brief Transmit data to I2C slave using I2C Master mode + * @param id : I2C peripheral ID (I2C0, I2C1 .. etc) + * @param slaveAddr : Slave address to which the data be written + * @param buff : Pointer to buffer having the array of data + * @param len : Number of bytes to be transfered from @a buff + * @return Number of bytes successfully transfered + */ +int Chip_I2C_MasterSend(I2C_ID_T id, uint8_t slaveAddr, const uint8_t *buff, uint8_t len); + +/** + * @brief Transfer a command to slave and receive data from slave after a repeated start + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @param slaveAddr : Slave address of the I2C device + * @param cmd : Command (Address/Register) to be written + * @param buff : Pointer to memory that will hold the data received + * @param len : Number of bytes to receive + * @return Number of bytes successfully received + */ +int Chip_I2C_MasterCmdRead(I2C_ID_T id, uint8_t slaveAddr, uint8_t cmd, uint8_t *buff, int len); + +/** + * @brief Get pointer to current function handling the events + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return Pointer to function handing events of I2C + */ +I2C_EVENTHANDLER_T Chip_I2C_GetMasterEventHandler(I2C_ID_T id); + +/** + * @brief Set function that must handle I2C events + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @param event : Pointer to function that will handle the event (Should not be NULL) + * @return 1 when successful, 0 when a transfer is on going with its own event handler + */ +int Chip_I2C_SetMasterEventHandler(I2C_ID_T id, I2C_EVENTHANDLER_T event); + +/** + * @brief Set function that must handle I2C events + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @param slaveAddr : Slave address from which data be read + * @param buff : Pointer to memory where data read be stored + * @param len : Number of bytes to read from slave + * @return Number of bytes read successfully + */ +int Chip_I2C_MasterRead(I2C_ID_T id, uint8_t slaveAddr, uint8_t *buff, int len); + +/** + * @brief Default event handler for polling operation + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @param event : Event ID of the event that called the function + * @return Nothing + */ +void Chip_I2C_EventHandlerPolling(I2C_ID_T id, I2C_EVENT_T event); + +/** + * @brief Default event handler for interrupt base operation + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @param event : Event ID of the event that called the function + * @return Nothing + */ +void Chip_I2C_EventHandler(I2C_ID_T id, I2C_EVENT_T event); + +/** + * @brief I2C Master transfer state change handler + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return Nothing + * @note Usually called from the appropriate Interrupt handler + */ +void Chip_I2C_MasterStateHandler(I2C_ID_T id); + +/** + * @brief Disable I2C peripheral's operation + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return Nothing + */ +void Chip_I2C_Disable(I2C_ID_T id); + +/** + * @brief Checks if master xfer in progress + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return 1 if master xfer in progress 0 otherwise + * @note + * This API is generally used in interrupt handler + * of the application to decide whether to call + * master state handler or to call slave state handler + */ +int Chip_I2C_IsMasterActive(I2C_ID_T id); + +/** + * @brief Setup a slave I2C device + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @param sid : I2C Slave peripheral ID (I2C_SLAVE_0, I2C_SLAVE_1 etc) + * @param xfer : Pointer to transfer structure (see note below for more info) + * @param event : Event handler for slave transfers + * @param addrMask : Address mask to use along with slave address (see notes below for more info) + * @return Nothing + * @note + * Parameter @a xfer should point to a valid I2C_XFER_T structure object + * and must have @a slaveAddr initialized with 7bit Slave address (From Bit1 to Bit7), + * Bit0 when set enables general call handling, @a slaveAddr along with @a addrMask will + * be used to match the slave address. @a rxBuff and @a txBuff must point to valid buffers + * where slave can receive or send the data from, size of which will be provided by + * @a rxSz and @a txSz respectively. Function pointed to by @a event will be called + * for the following events #I2C_EVENT_SLAVE_RX (One byte of data received successfully + * from the master and stored inside memory pointed by xfer->rxBuff, incremented + * the pointer and decremented the @a xfer->rxSz), #I2C_EVENT_SLAVE_TX (One byte of + * data from xfer->txBuff was sent to master successfully, incremented the pointer + * and decremented xfer->txSz), #I2C_EVENT_DONE (Master is done doing its transfers + * with the slave).
+ *
Bit-0 of the parameter @a addrMask is reserved and should always be 0. Any bit (BIT1 + * to BIT7) set in @a addrMask will make the corresponding bit in *xfer->slaveAddr* as + * don't care. Thit is, if *xfer->slaveAddr* is (0x10 << 1) and @a addrMask is (0x03 << 1) then + * 0x10, 0x11, 0x12, 0x13 will all be considered as valid slave addresses for the registered + * slave. Upon receving any event *xfer->slaveAddr* (BIT1 to BIT7) will hold the actual + * address which was received from master.
+ *
General Call Handling
+ * Slave can receive data from master using general call address (0x00). General call + * handling must be setup as given below + * - Call Chip_I2C_SlaveSetup() with argument @a sid as I2C_SLAVE_GENERAL + * - xfer->slaveAddr ignored, argument @a addrMask ignored + * - function provided by @a event will registered to be called when slave received data using addr 0x00 + * - xfer->rxBuff and xfer->rxSz should be valid in argument @a xfer + * - To handle General Call only (No other slaves are configured) + * - Call Chip_I2C_SlaveSetup() with sid as I2C_SLAVE_X (X=0,1,2,3) + * - setup @a xfer with slaveAddr member set to 0, @a event is ignored hence can be NULL + * - provide @a addrMask (typically 0, if not you better be knowing what you are doing) + * - To handler General Call when other slave is active + * - Call Chip_I2C_SlaveSetup() with sid as I2C_SLAVE_X (X=0,1,2,3) + * - setup @a xfer with slaveAddr member set to 7-Bit Slave address [from Bit1 to 7] + * - Set Bit0 of @a xfer->slaveAddr as 1 + * - Provide appropriate @a addrMask + * - Argument @a event must point to function, that handles events from actual slaveAddress and not the GC + * @warning + * If the slave has only one byte in its txBuff, once that byte is transfered to master the event handler + * will be called for event #I2C_EVENT_DONE. If the master attempts to read more bytes in the same transfer + * then the slave hardware will send 0xFF to master till the end of transfer, event handler will not be + * called to notify this. For more info see section below
+ *
Last data handling in slave
+ * If the user wants to implement a slave which will read a byte from a specific location over and over + * again whenever master reads the slave. If the user initializes the xfer->txBuff as the location to read + * the byte from and xfer->txSz as 1, then say, if master reads one byte; slave will send the byte read from + * xfer->txBuff and will call the event handler with #I2C_EVENT_DONE. If the master attempts to read another + * byte instead of sending the byte read from xfer->txBuff the slave hardware will send 0xFF and no event will + * occur. To handle this issue, slave should set xfer->txSz to 2, in which case when master reads the byte + * event handler will be called with #I2C_EVENT_SLAVE_TX, in which the slave implementation can reset the buffer + * and size back to original location (i.e, xfer->txBuff--, xfer->txSz++), if the master reads another byte + * in the same transfer, byte read from xfer->txBuff will be sent and #I2C_EVENT_SLAVE_TX will be called again, and + * the process repeats. + */ +void Chip_I2C_SlaveSetup(I2C_ID_T id, + I2C_SLAVE_ID sid, + I2C_XFER_T *xfer, + I2C_EVENTHANDLER_T event, + uint8_t addrMask); + +/** + * @brief I2C Slave event handler + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return Nothing + */ +void Chip_I2C_SlaveStateHandler(I2C_ID_T id); + +/** + * @brief I2C peripheral state change checking + * @param id : I2C peripheral ID (I2C0, I2C1 ... etc) + * @return 1 if I2C peripheral @a id has changed its state, + * 0 if there is no state change + * @note + * This function must be used by the application when + * the polling has to be done based on state change. + */ +int Chip_I2C_IsStateChanged(I2C_ID_T id); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __I2C_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/i2s_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/i2s_17xx_40xx.h new file mode 100644 index 000000000..7fe254a27 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/i2s_17xx_40xx.h @@ -0,0 +1,534 @@ +/* + * @brief LPC17xx/40xx I2S driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __I2S_17XX_40XX_H_ +#define __I2S_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup I2S_17XX_40XX CHIP: LPC17xx/40xx I2S driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief I2S DMA request channel define + */ +typedef enum { + I2S_DMA_REQUEST_CHANNEL_1, /*!< DMA request channel 1 */ + I2S_DMA_REQUEST_CHANNEL_2, /*!< DMA request channel 2 */ + I2S_DMA_REQUEST_CHANNEL_NUM,/*!< The number of DMA request channels */ +} I2S_DMA_CHANNEL_T; + +/** + * @brief I2S register block structure + */ +typedef struct { /*!< I2S Structure */ + __IO uint32_t DAO; /*!< I2S Digital Audio Output Register. Contains control bits for the I2S transmit channel */ + __IO uint32_t DAI; /*!< I2S Digital Audio Input Register. Contains control bits for the I2S receive channel */ + __O uint32_t TXFIFO; /*!< I2S Transmit FIFO. Access register for the 8 x 32-bit transmitter FIFO */ + __I uint32_t RXFIFO; /*!< I2S Receive FIFO. Access register for the 8 x 32-bit receiver FIFO */ + __I uint32_t STATE; /*!< I2S Status Feedback Register. Contains status information about the I2S interface */ + __IO uint32_t DMA[I2S_DMA_REQUEST_CHANNEL_NUM]; /*!< I2S DMA Configuration Registers. Contains control information for DMA request channels */ + __IO uint32_t IRQ; /*!< I2S Interrupt Request Control Register. Contains bits that control how the I2S interrupt request is generated */ + __IO uint32_t TXRATE; /*!< I2S Transmit MCLK divider. This register determines the I2S TX MCLK rate by specifying the value to divide PCLK by in order to produce MCLK */ + __IO uint32_t RXRATE; /*!< I2S Receive MCLK divider. This register determines the I2S RX MCLK rate by specifying the value to divide PCLK by in order to produce MCLK */ + __IO uint32_t TXBITRATE; /*!< I2S Transmit bit rate divider. This register determines the I2S transmit bit rate by specifying the value to divide TX_MCLK by in order to produce the transmit bit clock */ + __IO uint32_t RXBITRATE; /*!< I2S Receive bit rate divider. This register determines the I2S receive bit rate by specifying the value to divide RX_MCLK by in order to produce the receive bit clock */ + __IO uint32_t TXMODE; /*!< I2S Transmit mode control */ + __IO uint32_t RXMODE; /*!< I2S Receive mode control */ +} LPC_I2S_T; + +/* + * @brief I2S configuration parameter defines + */ +/* I2S Wordwidth bit */ +#define I2S_WORDWIDTH_8 (0UL << 0) /*!< 8 bit Word */ +#define I2S_WORDWIDTH_16 (1UL << 0) /*!< 16 bit word */ +#define I2S_WORDWIDTH_32 (3UL << 0) /*!< 32 bit word */ + +/* I2S Channel bit */ +#define I2S_STEREO (0UL << 2) /*!< Stereo audio */ +#define I2S_MONO (1UL << 2) /*!< Mono audio */ + +/* I2S Master/Slave mode bit */ +#define I2S_MASTER_MODE (0UL << 5) /*!< I2S in master mode */ +#define I2S_SLAVE_MODE (1UL << 5) /*!< I2S in slave mode */ + +/* I2S Stop bit */ +#define I2S_STOP_ENABLE (0UL << 3) /*!< I2S stop enable mask */ +#define I2S_STOP_DISABLE (1UL << 3) /*!< I2S stop disable mask */ + +/* I2S Reset bit */ +#define I2S_RESET_ENABLE (1UL << 4) /*!< I2S reset enable mask */ +#define I2S_RESET_DISABLE (0UL << 4) /*!< I2S reset disable mask */ + +/* I2S Mute bit */ +#define I2S_MUTE_ENABLE (1UL << 15) /*!< I2S mute enable mask */ +#define I2S_MUTE_DISABLE (0UL << 15) /*!< I2S mute disbale mask */ + +/* + * @brief Macro defines for DAO-Digital Audio Output register + */ +/* I2S wordwide - the number of bytes in data*/ +#define I2S_DAO_WORDWIDTH_8 ((uint32_t) (0)) /*!< DAO 8 bit */ +#define I2S_DAO_WORDWIDTH_16 ((uint32_t) (1)) /*!< DAO 16 bit */ +#define I2S_DAO_WORDWIDTH_32 ((uint32_t) (3)) /*!< DAO 32 bit */ +#define I2S_DAO_WORDWIDTH_MASK ((uint32_t) (3)) + +/* I2S control mono or stereo format */ +#define I2S_DAO_MONO ((uint32_t) (1 << 2)) /*!< DAO mono audio mask */ + +/* I2S control stop mode */ +#define I2S_DAO_STOP ((uint32_t) (1 << 3)) /*!< DAO stop mask */ + +/* I2S control reset mode */ +#define I2S_DAO_RESET ((uint32_t) (1 << 4)) /*!< DAO reset mask */ + +/* I2S control master/slave mode */ +#define I2S_DAO_SLAVE ((uint32_t) (1 << 5)) /*!< DAO slave mode mask */ + +/* I2S word select half period minus one */ +#define I2S_DAO_WS_HALFPERIOD(n) ((uint32_t) (((n) & 0x1FF) << 6)) /*!< DAO Word select set macro */ +#define I2S_DAO_WS_HALFPERIOD_MASK ((uint32_t) ((0x1FF) << 6)) /*!< DAO Word select mask */ + +/* I2S control mute mode */ +#define I2S_DAO_MUTE ((uint32_t) (1 << 15)) /*!< DAO mute mask */ + +/* + * @brief Macro defines for DAI-Digital Audio Input register + */ +/* I2S wordwide - the number of bytes in data*/ +#define I2S_DAI_WORDWIDTH_8 ((uint32_t) (0)) /*!< DAI 8 bit */ +#define I2S_DAI_WORDWIDTH_16 ((uint32_t) (1)) /*!< DAI 16 bit */ +#define I2S_DAI_WORDWIDTH_32 ((uint32_t) (3)) /*!< DAI 32 bit */ +#define I2S_DAI_WORDWIDTH_MASK ((uint32_t) (3)) /*!< DAI word wide mask */ + +/* I2S control mono or stereo format */ +#define I2S_DAI_MONO ((uint32_t) (1 << 2)) /*!< DAI mono mode mask */ + +/* I2S control stop mode */ +#define I2S_DAI_STOP ((uint32_t) (1 << 3)) /*!< DAI stop bit mask */ + +/* I2S control reset mode */ +#define I2S_DAI_RESET ((uint32_t) (1 << 4)) /*!< DAI reset bit mask */ + +/* I2S control master/slave mode */ +#define I2S_DAI_SLAVE ((uint32_t) (1 << 5)) /*!< DAI slave mode mask */ + +/* I2S word select half period minus one (9 bits)*/ +#define I2S_DAI_WS_HALFPERIOD(n) ((uint32_t) (((n) & 0x1FF) << 6)) /*!< DAI Word select set macro */ +#define I2S_DAI_WS_HALFPERIOD_MASK ((uint32_t) ((0x1FF) << 6)) /*!< DAI Word select mask */ + +/* + * @brief Macro defines for STAT register (Status Feedback register) + */ +#define I2S_STATE_IRQ ((uint32_t) (1))/*!< I2S Status Receive or Transmit Interrupt */ +#define I2S_STATE_DMA1 ((uint32_t) (1 << 1)) /*!< I2S Status Receive or Transmit DMA1 */ +#define I2S_STATE_DMA2 ((uint32_t) (1 << 2)) /*!< I2S Status Receive or Transmit DMA2 */ +#define I2S_STATE_RX_LEVEL(n) ((uint32_t) ((n & 1F) << 8))/*!< I2S Status Current level of the Receive FIFO (5 bits)*/ +#define I2S_STATE_TX_LEVEL(n) ((uint32_t) ((n & 1F) << 16)) /*!< I2S Status Current level of the Transmit FIFO (5 bits)*/ + +/* + * @brief Macro defines for DMA1 register (DMA1 Configuration register) + */ +#define I2S_DMA1_RX_ENABLE ((uint32_t) (1))/*!< I2S control DMA1 for I2S receive */ +#define I2S_DMA1_TX_ENABLE ((uint32_t) (1 << 1)) /*!< I2S control DMA1 for I2S transmit */ +#define I2S_DMA1_RX_DEPTH(n) ((uint32_t) ((n & 0x1F) << 8)) /*!< I2S set FIFO level that trigger a receive DMA request on DMA1 */ +#define I2S_DMA1_TX_DEPTH(n) ((uint32_t) ((n & 0x1F) << 16)) /*!< I2S set FIFO level that trigger a transmit DMA request on DMA1 */ + +/* + * @brief Macro defines for DMA2 register (DMA2 Configuration register) + */ +#define I2S_DMA2_RX_ENABLE ((uint32_t) (1))/*!< I2S control DMA2 for I2S receive */ +#define I2S_DMA2_TX_ENABLE ((uint32_t) (1 << 1)) /*!< I2S control DMA1 for I2S transmit */ +#define I2S_DMA2_RX_DEPTH(n) ((uint32_t) ((n & 0x1F) << 8)) /*!< I2S set FIFO level that trigger a receive DMA request on DMA1 */ +#define I2S_DMA2_TX_DEPTH(n) ((uint32_t) ((n & 0x1F) << 16)) /*!< I2S set FIFO level that trigger a transmit DMA request on DMA1 */ + +/* + * @brief Macro defines for IRQ register (Interrupt Request Control register) + */ + +#define I2S_IRQ_RX_ENABLE ((uint32_t) (1))/*!< I2S control I2S receive interrupt */ +#define I2S_IRQ_TX_ENABLE ((uint32_t) (1 << 1)) /*!< I2S control I2S transmit interrupt */ +#define I2S_IRQ_RX_DEPTH(n) ((uint32_t) ((n & 0x0F) << 8)) /*!< I2S set the FIFO level on which to create an irq request */ +#define I2S_IRQ_RX_DEPTH_MASK ((uint32_t) ((0x0F) << 8)) +#define I2S_IRQ_TX_DEPTH(n) ((uint32_t) ((n & 0x0F) << 16)) /*!< I2S set the FIFO level on which to create an irq request */ +#define I2S_IRQ_TX_DEPTH_MASK ((uint32_t) ((0x0F) << 16)) + +/* + * @brief Macro defines for TXRATE/RXRATE register (Transmit/Receive Clock Rate register) + */ +#define I2S_TXRATE_Y_DIVIDER(n) ((uint32_t) (n & 0xFF)) /*!< I2S Transmit MCLK rate denominator */ +#define I2S_TXRATE_X_DIVIDER(n) ((uint32_t) ((n & 0xFF) << 8)) /*!< I2S Transmit MCLK rate denominator */ +#define I2S_RXRATE_Y_DIVIDER(n) ((uint32_t) (n & 0xFF)) /*!< I2S Receive MCLK rate denominator */ +#define I2S_RXRATE_X_DIVIDER(n) ((uint32_t) ((n & 0xFF) << 8)) /*!< I2S Receive MCLK rate denominator */ + +/* + * @brief Macro defines for TXBITRATE & RXBITRATE register (Transmit/Receive Bit Rate register) + */ +#define I2S_TXBITRATE(n) ((uint32_t) (n & 0x3F)) +#define I2S_RXBITRATE(n) ((uint32_t) (n & 0x3F)) + +/* + * @brief Macro defines for TXMODE/RXMODE register (Transmit/Receive Mode Control register) + */ +#define I2S_TXMODE_CLKSEL(n) ((uint32_t) (n & 0x03)) /*!< I2S Transmit select clock source (2 bits)*/ +#define I2S_TXMODE_4PIN_ENABLE ((uint32_t) (1 << 2)) /*!< I2S Transmit control 4-pin mode */ +#define I2S_TXMODE_MCENA ((uint32_t) (1 << 3)) /*!< I2S Transmit control the TX_MCLK output */ +#define I2S_RXMODE_CLKSEL(n) ((uint32_t) (n & 0x03)) /*!< I2S Receive select clock source */ +#define I2S_RXMODE_4PIN_ENABLE ((uint32_t) (1 << 2)) /*!< I2S Receive control 4-pin mode */ +#define I2S_RXMODE_MCENA ((uint32_t) (1 << 3)) /*!< I2S Receive control the TX_MCLK output */ + +/** + * @brief I2S Audio Format Structure + */ +typedef struct { + uint32_t SampleRate; /*!< Sample Rate */ + uint8_t ChannelNumber; /*!< Channel Number - 1 is mono, 2 is stereo */ + uint8_t WordWidth; /*!< Word Width - 8, 16 or 32 bits */ +} I2S_AUDIO_FORMAT_T; + +/** + * @brief Initialize for I2S + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + */ +void Chip_I2S_Init(LPC_I2S_T *pI2S); + +/** + * @brief Shutdown I2S + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + * @note Reset all relative registers (DMA, transmit/receive control, interrupt) to default value + */ +void Chip_I2S_DeInit(LPC_I2S_T *pI2S); + +/** + * @brief Send a 32-bit data to TXFIFO for transmition + * @param pI2S : The base of I2S peripheral on the chip + * @param data : Data to be transmited + * @return Nothing + * @note The function writes to TXFIFO without checking any condition. + */ +STATIC INLINE void Chip_I2S_Send(LPC_I2S_T *pI2S, uint32_t data) +{ + pI2S->TXFIFO = data; +} + +/** + * @brief Get received data from RXFIFO + * @param pI2S : The base of I2S peripheral on the chip + * @return Data received in RXFIFO + * @note The function reads from RXFIFO without checking any condition. + */ +STATIC INLINE uint32_t Chip_I2S_Receive(LPC_I2S_T *pI2S) +{ + return pI2S->RXFIFO; +} + +/** + * @brief Start transmit data + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_I2S_TxStart(LPC_I2S_T *pI2S) +{ + pI2S->DAO &= ~(I2S_DAO_RESET | I2S_DAO_STOP | I2S_DAO_MUTE); +} + +/** + * @brief Start receive data + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_I2S_RxStart(LPC_I2S_T *pI2S) +{ + pI2S->DAI &= ~(I2S_DAI_RESET | I2S_DAI_STOP); +} + +/** + * @brief Disables accesses on FIFOs, places the transmit channel in mute mode + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_I2S_TxPause(LPC_I2S_T *pI2S) +{ + pI2S->DAO |= I2S_DAO_STOP; +} + +/** + * @brief Disables accesses on FIFOs, places the transmit channel in mute mode + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_I2S_RxPause(LPC_I2S_T *pI2S) +{ + pI2S->DAI |= I2S_DAI_STOP; +} + +/** + * @brief Mute the Transmit channel + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + * @note The data output from I2S transmit channel is always zeroes + */ +STATIC INLINE void Chip_I2S_EnableMute(LPC_I2S_T *pI2S) +{ + pI2S->DAO |= I2S_DAO_MUTE; +} + +/** + * @brief Un-Mute the I2S channel + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_I2S_DisableMute(LPC_I2S_T *pI2S) +{ + pI2S->DAO &= ~I2S_DAO_MUTE; +} + +/** + * @brief Stop I2S asynchronously + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + * @note Pause, resets the transmit channel and FIFO asynchronously + */ +STATIC INLINE void Chip_I2S_TxStop(LPC_I2S_T *pI2S) +{ + pI2S->DAO &= ~I2S_DAO_MUTE; + pI2S->DAO |= I2S_DAO_STOP | I2S_DAO_RESET; +} + +/** + * @brief Stop I2S asynchronously + * @param pI2S : The base of I2S peripheral on the chip + * @return Nothing + * @note Pause, resets the transmit channel and FIFO asynchronously + */ +STATIC INLINE void Chip_I2S_RxStop(LPC_I2S_T *pI2S) +{ + pI2S->DAI |= I2S_DAI_STOP | I2S_DAI_RESET; +} + +/** + * @brief Set the I2S transmit mode + * @param pI2S : The base of I2S peripheral on the chip + * @param clksel : Clock source selection for the receive bit clock divider + * @param fpin : Receive 4-pin mode selection + * @param mcena : Enable for the RX_MCLK output + * @return Nothing + * @note In addition to master and slave modes, which are independently configurable for + * the transmitter and the receiver, several different clock sources are possible, + * including variations that share the clock and/or WS between the transmitter and + * receiver. It also allows using I2S with fewer pins, typically four. + */ +STATIC INLINE void Chip_I2S_TxModeConfig(LPC_I2S_T *pI2S, + uint32_t clksel, + uint32_t fpin, + uint32_t mcena) +{ + pI2S->TXMODE = clksel | fpin | mcena; +} + +/** + * @brief Set the I2S receive mode + * @param pI2S : The base of I2S peripheral on the chip + * @param clksel : Clock source selection for the receive bit clock divider + * @param fpin : Receive 4-pin mode selection + * @param mcena : Enable for the RX_MCLK output + * @return Nothing + * @note In addition to master and slave modes, which are independently configurable for + * the transmitter and the receiver, several different clock sources are possible, + * including variations that share the clock and/or WS between the transmitter and + * receiver. It also allows using I2S with fewer pins, typically four. + */ +STATIC INLINE void Chip_I2S_RxModeConfig(LPC_I2S_T *pI2S, + uint32_t clksel, + uint32_t fpin, + uint32_t mcena) +{ + pI2S->RXMODE = clksel | fpin | mcena; +} + +/** + * @brief Get the current level of the Transmit FIFO + * @param pI2S : The base of I2S peripheral on the chip + * @return Current level of the Transmit FIFO + */ +STATIC INLINE uint8_t Chip_I2S_GetTxLevel(LPC_I2S_T *pI2S) +{ + return (pI2S->STATE >> 16) & 0xF; +} + +/** + * @brief Get the current level of the Receive FIFO + * @param pI2S : The base of I2S peripheral on the chip + * @return Current level of the Receive FIFO + */ +STATIC INLINE uint8_t Chip_I2S_GetRxLevel(LPC_I2S_T *pI2S) +{ + return (pI2S->STATE >> 8) & 0xF; +} + +/** + * @brief Set the clock frequency for I2S interface + * @param pI2S : The base of I2S peripheral on the chip + * @param div : Clock divider. This value plus one is used to divide MCLK to produce the clock frequency for I2S interface + * @return Nothing + * @note The value depends on the audio sample rate desired and the data size and format(stereo/mono) used. + * For example, a 48 kHz sample rate for 16-bit stereo data requires a bit rate of 48 000 x 16 x 2 = 1.536 MHz. So the mclk_divider should be MCLK/1.536 MHz + */ +STATIC INLINE void Chip_I2S_SetTxBitRate(LPC_I2S_T *pI2S, uint32_t div) +{ + pI2S->TXBITRATE = div; +} + +/** + * @brief Set the clock frequency for I2S interface + * @param pI2S : The base of I2S peripheral on the chip + * @param div : Clock divider. This value plus one is used to divide MCLK to produce the clock frequency for I2S interface + * @return Nothing + * @note The value depends on the audio sample rate desired and the data size and format(stereo/mono) used. + * For example, a 48 kHz sample rate for 16-bit stereo data requires a bit rate of 48 000 x 16 x 2 = 1.536 MHz. So the mclk_divider should be MCLK/1.536 MHz + */ +STATIC INLINE void Chip_I2S_SetRxBitRate(LPC_I2S_T *pI2S, uint32_t div) +{ + pI2S->RXBITRATE = div; +} + +/** + * @brief Set the MCLK rate by using a fractional rate generator, dividing down the frequency of PCLK + * @param pI2S : The base of I2S peripheral on the chip + * @param xDiv : I2S transmit MCLK rate numerator + * @param yDiv : I2S transmit MCLK rate denominator + * @return Nothing + * @note Values of the numerator (X) and the denominator (Y) must be chosen to + * produce a frequency twice that desired for the transmitter MCLK, which + * must be an integer multiple of the transmitter bit clock rate. + * The equation for the fractional rate generator is: + * MCLK = PCLK * (X/Y) /2 + * Note: If the value of X or Y is 0, then no clock is generated. Also, the value of Y must be + * greater than or equal to X. + */ +STATIC INLINE void Chip_I2S_SetTxXYDivider(LPC_I2S_T *pI2S, uint8_t xDiv, uint8_t yDiv) +{ + pI2S->TXRATE = yDiv | (xDiv << 8); +} + +/** + * @brief Set the MCLK rate by using a fractional rate generator, dividing down the frequency of PCLK + * @param pI2S : The base of I2S peripheral on the chip + * @param xDiv : I2S transmit MCLK rate numerator + * @param yDiv : I2S transmit MCLK rate denominator + * @return Nothing + * @note Values of the numerator (X) and the denominator (Y) must be chosen to + * produce a frequency twice that desired for the transmitter MCLK, which + * must be an integer multiple of the transmitter bit clock rate. + * The equation for the fractional rate generator is: + * MCLK = PCLK * (X/Y) /2 + * Note: If the value of X or Y is 0, then no clock is generated. Also, the value of Y must be + * greater than or equal to X. + */ +STATIC INLINE void Chip_I2S_SetRxXYDivider(LPC_I2S_T *pI2S, uint8_t xDiv, uint8_t yDiv) +{ + pI2S->RXRATE = yDiv | (xDiv << 8); +} + +/** + * @brief Configure I2S for Audio Format input + * @param pI2S : The base I2S peripheral on the chip + * @param format : Audio Format + * @return SUCCESS or ERROR + */ +Status Chip_I2S_TxConfig(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format); + +/** + * @brief Configure I2S for Audio Format input + * @param pI2S : The base I2S peripheral on the chip + * @param format : Audio Format + * @return SUCCESS or ERROR + */ +Status Chip_I2S_RxConfig(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format); + +/** + * @brief Enable/Disable Interrupt with a specific FIFO depth + * @param pI2S : The base I2S peripheral on the chip + * @param newState : ENABLE or DISABLE interrupt + * @param depth : FIFO level creating an irq request + * @return Nothing + */ +void Chip_I2S_Int_TxCmd(LPC_I2S_T *pI2S, FunctionalState newState, uint8_t depth); + +/** + * @brief Enable/Disable Interrupt with a specific FIFO depth + * @param pI2S : The base I2S peripheral on the chip + * @param newState : ENABLE or DISABLE interrupt + * @param depth : FIFO level creating an irq request + * @return Nothing + */ +void Chip_I2S_Int_RxCmd(LPC_I2S_T *pI2S, FunctionalState newState, uint8_t depth); + +/** + * @brief Enable/Disable DMA with a specific FIFO depth + * @param pI2S : The base I2S peripheral on the chip + * @param dmaNum : Should be + * - I2S_DMA_REQUEST_CHANNEL_1 : Using DMA1 + * - I2S_DMA_REQUEST_CHANNEL_2 : Using DMA2 + * @param newState : ENABLE or DISABLE interrupt + * @param depth : FIFO level creating an irq request + * @return Nothing + */ +void Chip_I2S_DMA_TxCmd(LPC_I2S_T *pI2S, I2S_DMA_CHANNEL_T dmaNum, FunctionalState newState, uint8_t depth); + +/** + * @brief Enable/Disable DMA with a specific FIFO depth + * @param pI2S : The base I2S peripheral on the chip + * @param dmaNum : Should be + * - I2S_DMA_REQUEST_CHANNEL_1 : Using DMA1 + * - I2S_DMA_REQUEST_CHANNEL_2 : Using DMA2 + * @param newState : ENABLE or DISABLE interrupt + * @param depth : FIFO level creating an irq request + * @return Nothing + */ +void Chip_I2S_DMA_RxCmd(LPC_I2S_T *pI2S, I2S_DMA_CHANNEL_T dmaNum, FunctionalState newState, uint8_t depth); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __I2S_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/iap.h b/hw/mcu/nxp/lpc_chip_40xx/inc/iap.h new file mode 100644 index 000000000..a90e87c9b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/iap.h @@ -0,0 +1,184 @@ +/* + * @brief Common IAP support functions + * + * @note + * Copyright(C) NXP Semiconductors, 2013 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licenser disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __IAP_H_ +#define __IAP_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup COMMON_IAP CHIP: Common Chip ISP/IAP commands and return codes + * @ingroup CHIP_Common + * @{ + */ + +/* IAP command definitions */ +#define IAP_PREWRRITE_CMD 50 /*!< Prepare sector for write operation command */ +#define IAP_WRISECTOR_CMD 51 /*!< Write Sector command */ +#define IAP_ERSSECTOR_CMD 52 /*!< Erase Sector command */ +#define IAP_BLANK_CHECK_SECTOR_CMD 53 /*!< Blank check sector */ +#define IAP_REPID_CMD 54 /*!< Read PartID command */ +#define IAP_READ_BOOT_CODE_CMD 55 /*!< Read Boot code version */ +#define IAP_COMPARE_CMD 56 /*!< Compare two RAM address locations */ +#define IAP_REINVOKE_ISP_CMD 57 /*!< Reinvoke ISP */ +#define IAP_READ_UID_CMD 58 /*!< Read UID */ +#define IAP_ERASE_PAGE_CMD 59 /*!< Erase page */ +#define IAP_EEPROM_WRITE 61 /*!< EEPROM Write command */ +#define IAP_EEPROM_READ 62 /*!< EEPROM READ command */ + +/* IAP response definitions */ +#define IAP_CMD_SUCCESS 0 /*!< Command is executed successfully */ +#define IAP_INVALID_COMMAND 1 /*!< Invalid command */ +#define IAP_SRC_ADDR_ERROR 2 /*!< Source address is not on word boundary */ +#define IAP_DST_ADDR_ERROR 3 /*!< Destination address is not on a correct boundary */ +#define IAP_SRC_ADDR_NOT_MAPPED 4 /*!< Source address is not mapped in the memory map */ +#define IAP_DST_ADDR_NOT_MAPPED 5 /*!< Destination address is not mapped in the memory map */ +#define IAP_COUNT_ERROR 6 /*!< Byte count is not multiple of 4 or is not a permitted value */ +#define IAP_INVALID_SECTOR 7 /*!< Sector number is invalid or end sector number is greater than start sector number */ +#define IAP_SECTOR_NOT_BLANK 8 /*!< Sector is not blank */ +#define IAP_SECTOR_NOT_PREPARED 9 /*!< Command to prepare sector for write operation was not executed */ +#define IAP_COMPARE_ERROR 10 /*!< Source and destination data not equal */ +#define IAP_BUSY 11 /*!< Flash programming hardware interface is busy */ +#define IAP_PARAM_ERROR 12 /*!< nsufficient number of parameters or invalid parameter */ +#define IAP_ADDR_ERROR 13 /*!< Address is not on word boundary */ +#define IAP_ADDR_NOT_MAPPED 14 /*!< Address is not mapped in the memory map */ +#define IAP_CMD_LOCKED 15 /*!< Command is locked */ +#define IAP_INVALID_CODE 16 /*!< Unlock code is invalid */ +#define IAP_INVALID_BAUD_RATE 17 /*!< Invalid baud rate setting */ +#define IAP_INVALID_STOP_BIT 18 /*!< Invalid stop bit setting */ +#define IAP_CRP_ENABLED 19 /*!< Code read protection enabled */ + +/* IAP_ENTRY API function type */ +typedef void (*IAP_ENTRY_T)(unsigned int[5], unsigned int[4]); + +/** + * @brief Prepare sector for write operation + * @param strSector : Start sector number + * @param endSector : End sector number + * @return Status code to indicate the command is executed successfully or not + * @note This command must be executed before executing "Copy RAM to flash" + * or "Erase Sector" command. + * The end sector must be greater than or equal to start sector number + */ +uint8_t Chip_IAP_PreSectorForReadWrite(uint32_t strSector, uint32_t endSector); + +/** + * @brief Copy RAM to flash + * @param dstAdd : Destination flash address where data bytes are to be written + * @param srcAdd : Source flash address where data bytes are to be read + * @param byteswrt : Number of bytes to be written + * @return Status code to indicate the command is executed successfully or not + * @note The addresses should be a 256 byte boundary and the number of bytes + * should be 256 | 512 | 1024 | 4096 + */ +uint8_t Chip_IAP_CopyRamToFlash(uint32_t dstAdd, uint32_t *srcAdd, uint32_t byteswrt); + +/** + * @brief Erase sector + * @param strSector : Start sector number + * @param endSector : End sector number + * @return Status code to indicate the command is executed successfully or not + * @note The end sector must be greater than or equal to start sector number + */ +uint8_t Chip_IAP_EraseSector(uint32_t strSector, uint32_t endSector); + +/** + * @brief Blank check a sector or multiples sector of on-chip flash memory + * @param strSector : Start sector number + * @param endSector : End sector number + * @return Offset of the first non blank word location if the status code is SECTOR_NOT_BLANK + * @note The end sector must be greater than or equal to start sector number + */ +// FIXME - There are two return value (result[0] & result[1] +// Result0:Offset of the first non blank word location if the Status Code is +// SECTOR_NOT_BLANK. +// Result1:Contents of non blank word location. +uint8_t Chip_IAP_BlankCheckSector(uint32_t strSector, uint32_t endSector); + +/** + * @brief Read part identification number + * @return Part identification number + */ +uint32_t Chip_IAP_ReadPID(void); + +/** + * @brief Read boot code version number + * @return Boot code version number + */ +uint8_t Chip_IAP_ReadBootCode(void); + +/** + * @brief Compare the memory contents at two locations + * @param dstAdd : Destination of the RAM address of data bytes to be compared + * @param srcAdd : Source of the RAM address of data bytes to be compared + * @param bytescmp : Number of bytes to be compared + * @return Offset of the first mismatch of the status code is COMPARE_ERROR + * @note The addresses should be a word boundary and number of bytes should be + * a multiply of 4 + */ +uint8_t Chip_IAP_Compare(uint32_t dstAdd, uint32_t srcAdd, uint32_t bytescmp); + +/** + * @brief IAP reinvoke ISP to invoke the bootloader in ISP mode + * @return none + */ +uint8_t Chip_IAP_ReinvokeISP(void); + +/** + * @brief Read the unique ID + * @return Status code to indicate the command is executed successfully or not + */ +uint32_t Chip_IAP_ReadUID(void); + +/** + * @brief Erase a page or multiple papers of on-chip flash memory + * @param strPage : Start page number + * @param endPage : End page number + * @return Status code to indicate the command is executed successfully or not + * @note The page number must be greater than or equal to start page number + */ +// FIXME - There are four return value +// Result0:The first 32-bit word (at the lowest address) +// Result1:The second 32-bit word. +// Result2:The third 32-bit word. +// Result3:The fourth 32-bit word. +uint8_t Chip_IAP_ErasePage(uint32_t strPage, uint32_t endPage); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __IAP_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/iocon_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/iocon_17xx_40xx.h new file mode 100644 index 000000000..8d5f055be --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/iocon_17xx_40xx.h @@ -0,0 +1,274 @@ +/* + * @brief LPC17xx/40xx IOCON registers and control functions + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __IOCON_17XX_40XX_H_ +#define __IOCON_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup IOCON_17XX_40XX CHIP: LPC17xx/40xx I/O configuration driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief Array of IOCON pin definitions passed to Chip_IOCON_SetPinMuxing() must be in this format + */ +typedef struct { + uint32_t pingrp:3; /* Pin group */ + uint32_t pinnum:5; /* Pin number */ + uint32_t modefunc:24; /* Function and mode. */ +} PINMUX_GRP_T; + +/** + * @brief IOCON register block + */ +typedef struct { +#if defined(CHIP_LPC175X_6X) + __IO uint32_t PINSEL[11]; + uint32_t RESERVED0[5]; + __IO uint32_t PINMODE[10]; + __IO uint32_t PINMODE_OD[5]; + __IO uint32_t I2CPADCFG; +#else + __IO uint32_t p[5][32]; +#endif +} LPC_IOCON_T; + +/** + * IOCON function and mode selection definitions + * See the User Manual for specific modes and functions supoprted by the + * various LPC11xx devices. Functionality can vary per device. + */ +#define IOCON_FUNC0 0x0 /*!< Selects pin function 0 */ +#define IOCON_FUNC1 0x1 /*!< Selects pin function 1 */ +#define IOCON_FUNC2 0x2 /*!< Selects pin function 2 */ +#define IOCON_FUNC3 0x3 /*!< Selects pin function 3 */ +#if defined(CHIP_LPC175X_6X) +#define IOCON_MODE_INACT (0x2 << 2) /*!< No addition pin function */ +#define IOCON_MODE_PULLDOWN (0x3 << 2) /*!< Selects pull-down function */ +#define IOCON_MODE_PULLUP (0x0 << 2) /*!< Selects pull-up function */ +#define IOCON_MODE_REPEATER (0x1 << 2) /*!< Selects pin repeater function */ +#else +#define IOCON_FUNC4 0x4 /*!< Selects pin function 4 */ +#define IOCON_FUNC5 0x5 /*!< Selects pin function 5 */ +#define IOCON_FUNC6 0x6 /*!< Selects pin function 6 */ +#define IOCON_FUNC7 0x7 /*!< Selects pin function 7 */ +#define IOCON_MODE_INACT (0x0 << 3) /*!< No addition pin function */ +#define IOCON_MODE_PULLDOWN (0x1 << 3) /*!< Selects pull-down function */ +#define IOCON_MODE_PULLUP (0x2 << 3) /*!< Selects pull-up function */ +#define IOCON_MODE_REPEATER (0x3 << 3) /*!< Selects pin repeater function */ +#define IOCON_HYS_EN (0x1 << 5) /*!< Enables hysteresis */ +#define IOCON_INV_EN (0x1 << 6) /*!< Enables invert function on input */ +#define IOCON_ADMODE_EN (0x0 << 7) /*!< Enables analog input function (analog pins only) */ +#define IOCON_DIGMODE_EN (0x1 << 7) /*!< Enables digital function (analog pins only) */ +#define IOCON_FILT_DIS (0x1 << 8) /*!< Disables noise pulses filtering (10nS glitch filter) */ +#define IOCON_HS_DIS (0x1 << 8) /*!< I2C glitch filter and slew rate disabled */ +#define IOCON_HIDRIVE_EN (0x1 << 9) /*!< Sink current is 20 mA */ +#define IOCON_FASTSLEW_EN (0x1 << 9) /*!< Enables fast slew */ +#define IOCON_OPENDRAIN_EN (0x1 << 10) /*!< Enables open-drain function */ +#define IOCON_DAC_EN (0x1 << 16) /*!< Enables DAC function */ +#endif + +/** + * IOCON function and mode selection definitions (old) + * For backwards compatibility. + */ +#define FUNC0 0x0 /** Function 0 */ +#define FUNC1 0x1 /** Function 1 */ +#define FUNC2 0x2 /** Function 2 */ +#define FUNC3 0x3 /** Function 3 */ +#if defined(CHIP_LPC175X_6X) +#define MD_PLN (0x2) +#define MD_PDN (0x3) +#define MD_PUP (0x0) +#define MD_BUK (0x1) + +#else +#define MD_PLN (0x0 << 3) +#define MD_PDN (0x1 << 3) +#define MD_PUP (0x2 << 3) +#define MD_BUK (0x3 << 3) +#define MD_HYS_ENA (0x1 << 5) /*!< Macro to enable hysteresis- use with Chip_IOCON_PinMux */ +#define MD_HYS_DIS (0x0 << 5) /*!< Macro to disable hysteresis- use with Chip_IOCON_PinMux */ +#define MD_IINV_ENA (0x1 << 6) /*!< Macro to enable input inversion- use with Chip_IOCON_PinMux */ +#define MD_IINV_DIS (0x0 << 6) /*!< Macro to disable input inversion- use with Chip_IOCON_PinMux */ +#define MD_OD_ENA (0x1 << 10) /*!< Macro to enable simulated open drain mode- use with Chip_IOCON_PinMux */ +#define MD_OD_DIS (0x0 << 10) /*!< Macro to disable simulated open drain mode- use with Chip_IOCON_PinMux */ +#define MD_HS_ENA (0x0 << 8) /*!< Macro to enable I2C 50ns glitch filter and slew rate control- use with Chip_IOCON_PinMux */ +#define MD_HS_DIS (0x1 << 8) /*!< Macro to disable I2C 50ns glitch filter and slew rate control- use with Chip_IOCON_PinMux */ +#define MD_ANA_ENA (0x0 << 7) /*!< Macro to enable analog mode (ADC)- use with Chip_IOCON_PinMux */ +#define MD_ANA_DIS (0x1 << 7) /*!< Macro to disable analog mode (ADC)- use with Chip_IOCON_PinMux */ +#define MD_FILT_ENA (0x0 << 8) /*!< Macro to enable input filter- use with Chip_IOCON_PinMux */ +#define MD_FILT_DIS (0x1 << 8) /*!< Macro to disable input filter- use with Chip_IOCON_PinMux */ +#define MD_DAC_ENA (0x1 << 16) /*!< Macro to enable DAC- use with Chip_IOCON_PinMux */ +#define MD_DAC_DIS (0x0 << 16) /*!< Macro to disable DAC- use with Chip_IOCON_PinMux */ +#define MD_STD_SLEW_RATE (0x0 << 9) /*!< Macro to enable standard mode, slew rate control is enabled - use with Chip_IOCON_PinMux */ +#define MD_FAST_SLEW_RATE (0x1 << 9) /*!< Macro to enable fast mode, slew rate control is disabled - use with Chip_IOCON_PinMux */ +#define MD_HD_ENA (0x1 << 9) /*!< Macro to enable high drive output- use with Chip_IOCON_PinMux */ +#define MD_HD_DIS (0x0 << 9) /*!< Macro to disable high drive output- use with Chip_IOCON_PinMux */ +#define FUNC4 0x4 /** Function 4 */ +#define FUNC5 0x5 /** Function 5 */ +#define FUNC6 0x6 /** Function 6 */ +#define FUNC7 0x7 /** Function 7 */ +#endif /* defined(CHIP_LPC175X_6X)*/ + +/** + * @brief Initialize the IOCON peripheral + * @param pIOCON : The base of IOCON peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_IOCON_Init(LPC_IOCON_T *pIOCON) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_GPIO); +} + +#if defined(CHIP_LPC175X_6X) +/* PINSEL and PINMODE register index calculation.*/ +#define IOCON_REG_INDEX(port, pin) (2 * port + (pin / 16)) +/* Bit position calculation in PINSEL and PINMODE register.*/ +#define IOCON_BIT_INDEX(pin) ((pin % 16) * 2) + +/** + * @brief Sets I/O Control pin mux + * @param pIOCON : The base of IOCON peripheral on the chip + * @param port : GPIO port to mux + * @param pin : GPIO pin to mux + * @param modefunc : OR'ed values or type IOCON_* + * @return Nothing + */ +void Chip_IOCON_PinMuxSet(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t modefunc); + +/** + * @brief Setup pin modes and function + * @param pIOCON : The base of IOCON peripheral on the chip + * @param port : port number + * @param pin : gpio pin number + * @param mode : OR'ed values or type IOCON_* + * @param func : Pin function, value of type IOCON_FUNC0 to IOCON_FUNC3 + * @return Nothing + */ +void Chip_IOCON_PinMux(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t mode, uint8_t func); + +/** + * @brief Enable open drain mode + * @param pIOCON : The base of IOCON peripheral on the chip + * @param port : port number + * @param pin : gpio pin number + * @return Nothing + */ +STATIC INLINE void Chip_IOCON_EnableOD(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin) +{ + pIOCON->PINMODE_OD[port] |= (0x01UL << pin); +} + +/** + * @brief Disable open drain mode + * @param pIOCON : The base of IOCON peripheral on the chip + * @param port : port number + * @param pin : gpio pin number + * @return Nothing + */ +STATIC INLINE void Chip_IOCON_DisableOD(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin) +{ + pIOCON->PINMODE_OD[port] &= ~(0x01UL << pin); +} + +/** + * @brief I2C pin configuration definitions + */ +typedef enum { + I2CPADCFG_STD_MODE = 0x00, /*!< Standard I2C mode */ + I2CPADCFG_FAST_MODE = I2CPADCFG_STD_MODE, /*!< Fast mode */ + I2CPADCFG_FAST_MODE_PLUS = 0x05, /*!< Fast mode plus */ + I2CPADCFG_NON_I2C = 0x0A, /*!< For non-I2C use*/ +} IOCON_I2CPINS_CONFIG; + +/** + * @brief Configure I2C pad pins (P0.27 and P0.28) + * @param pIOCON : The base of IOCON peripheral on the chip + * @param cfg : pin configurations + * @return Nothing + */ +STATIC INLINE void Chip_IOCON_SetI2CPad(LPC_IOCON_T *pIOCON, IOCON_I2CPINS_CONFIG cfg) +{ + pIOCON->I2CPADCFG = cfg; +} + +#else +/** + * @brief Sets I/O Control pin mux + * @param pIOCON : The base of IOCON peripheral on the chip + * @param port : GPIO port to mux + * @param pin : GPIO pin to mux + * @param modefunc : OR'ed values or type IOCON_* + * @return Nothing + */ +STATIC INLINE void Chip_IOCON_PinMuxSet(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t modefunc) +{ + pIOCON->p[port][pin] = modefunc; +} + +/** + * @brief Setup pin modes and function + * @param pIOCON : The base of IOCON peripheral on the chip + * @param port : port number + * @param pin : gpio pin number + * @param mode : OR'ed values or type IOCON_* + * @param func : Pin function, value of type IOCON_FUNC0 to IOCON_FUNC7 + * @return Nothing + */ +STATIC INLINE void Chip_IOCON_PinMux(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t mode, uint8_t func) +{ + Chip_IOCON_PinMuxSet(pIOCON, port, pin, (mode | func)); +} +#endif /* defined(CHIP_LPC175X_6X) */ + +/** + * @brief Set all I/O Control pin muxing + * @param pIOCON : The base of IOCON peripheral on the chip + * @param pinArray : Pointer to array of pin mux selections + * @param arrayLength : Number of entries in pinArray + * @return Nothing + */ +void Chip_IOCON_SetPinMuxing(LPC_IOCON_T *pIOCON, const PINMUX_GRP_T* pinArray, uint32_t arrayLength); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __IOCON_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/lcd_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/lcd_17xx_40xx.h new file mode 100644 index 000000000..c6a1628cd --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/lcd_17xx_40xx.h @@ -0,0 +1,387 @@ +/* + * @brief LPC17xx/40xx LCD driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __LCD_17XX_40XX_H_ +#define __LCD_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup LCD_17XX_40XX CHIP: LPC17xx/40xx LCD driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/** + * @brief LCD Controller register block structure + */ +typedef struct { /*!< LCD Structure */ + __IO uint32_t TIMH; /*!< Horizontal Timing Control register */ + __IO uint32_t TIMV; /*!< Vertical Timing Control register */ + __IO uint32_t POL; /*!< Clock and Signal Polarity Control register */ + __IO uint32_t LE; /*!< Line End Control register */ + __IO uint32_t UPBASE; /*!< Upper Panel Frame Base Address register */ + __IO uint32_t LPBASE; /*!< Lower Panel Frame Base Address register */ + __IO uint32_t CTRL; /*!< LCD Control register */ + __IO uint32_t INTMSK; /*!< Interrupt Mask register */ + __I uint32_t INTRAW; /*!< Raw Interrupt Status register */ + __I uint32_t INTSTAT; /*!< Masked Interrupt Status register */ + __O uint32_t INTCLR; /*!< Interrupt Clear register */ + __I uint32_t UPCURR; /*!< Upper Panel Current Address Value register */ + __I uint32_t LPCURR; /*!< Lower Panel Current Address Value register */ + __I uint32_t RESERVED0[115]; + __IO uint16_t PAL[256]; /*!< 256x16-bit Color Palette registers */ + __I uint32_t RESERVED1[256]; + __IO uint32_t CRSR_IMG[256];/*!< Cursor Image registers */ + __IO uint32_t CRSR_CTRL; /*!< Cursor Control register */ + __IO uint32_t CRSR_CFG; /*!< Cursor Configuration register */ + __IO uint32_t CRSR_PAL0; /*!< Cursor Palette register 0 */ + __IO uint32_t CRSR_PAL1; /*!< Cursor Palette register 1 */ + __IO uint32_t CRSR_XY; /*!< Cursor XY Position register */ + __IO uint32_t CRSR_CLIP; /*!< Cursor Clip Position register */ + __I uint32_t RESERVED2[2]; + __IO uint32_t CRSR_INTMSK; /*!< Cursor Interrupt Mask register */ + __O uint32_t CRSR_INTCLR; /*!< Cursor Interrupt Clear register */ + __I uint32_t CRSR_INTRAW; /*!< Cursor Raw Interrupt Status register */ + __I uint32_t CRSR_INTSTAT;/*!< Cursor Masked Interrupt Status register */ +} LPC_LCD_T; + +/** + * @brief LCD Palette entry format + */ +typedef struct { + uint32_t Rl : 5; + uint32_t Gl : 5; + uint32_t Bl : 5; + uint32_t Il : 1; + uint32_t Ru : 5; + uint32_t Gu : 5; + uint32_t Bu : 5; + uint32_t Iu : 1; +} LCD_PALETTE_ENTRY_T; + +/** + * @brief LCD Panel type + */ +typedef enum { + LCD_TFT = 0x02, /*!< standard TFT */ + LCD_MONO_4 = 0x01, /*!< 4-bit STN mono */ + LCD_MONO_8 = 0x05, /*!< 8-bit STN mono */ + LCD_CSTN = 0x00 /*!< color STN */ +} LCD_PANEL_OPT_T; + +/** + * @brief LCD Color Format + */ +typedef enum { + LCD_COLOR_FORMAT_RGB = 0, + LCD_COLOR_FORMAT_BGR +} LCD_COLOR_FORMAT_OPT_T; + +/** LCD Interrupt control mask register bits */ +#define LCD_INTMSK_FUFIM 0x2 /*!< FIFO underflow interrupt enable */ +#define LCD_INTMSK_LNBUIM 0x4 /*!< LCD next base address update interrupt enable */ +#define LCD_INTMSK_VCOMPIM 0x8 /*!< Vertical compare interrupt enable */ +#define LCD_INTMSK_BERIM 0x10 /*!< AHB master error interrupt enable */ + +#define CLCDC_LCDCTRL_ENABLE _BIT(0) /*!< LCD control enable bit */ +#define CLCDC_LCDCTRL_PWR _BIT(11) /*!< LCD control power enable bit */ + +/** + * @brief A structure for LCD Configuration + */ +typedef struct { + uint8_t HBP; /*!< Horizontal back porch in clocks */ + uint8_t HFP; /*!< Horizontal front porch in clocks */ + uint8_t HSW; /*!< HSYNC pulse width in clocks */ + uint16_t PPL; /*!< Pixels per line */ + uint8_t VBP; /*!< Vertical back porch in clocks */ + uint8_t VFP; /*!< Vertical front porch in clocks */ + uint8_t VSW; /*!< VSYNC pulse width in clocks */ + uint16_t LPP; /*!< Lines per panel */ + uint8_t IOE; /*!< Invert output enable, 1 = invert */ + uint8_t IPC; /*!< Invert panel clock, 1 = invert */ + uint8_t IHS; /*!< Invert HSYNC, 1 = invert */ + uint8_t IVS; /*!< Invert VSYNC, 1 = invert */ + uint8_t ACB; /*!< AC bias frequency in clocks (not used) */ + uint8_t BPP; /*!< Maximum bits per pixel the display supports */ + LCD_PANEL_OPT_T LCD; /*!< LCD panel type */ + LCD_COLOR_FORMAT_OPT_T color_format; /*!CTRL |= CLCDC_LCDCTRL_PWR; + for (i = 0; i < 1000000; i++) {} + pLCD->CTRL |= CLCDC_LCDCTRL_ENABLE; +} + +/** + * @brief Power-off the LCD Panel (power pin) + * @param pLCD : The base of LCD peripheral on the chip + * @return None + */ +STATIC INLINE void Chip_LCD_PowerOff(LPC_LCD_T *pLCD) +{ + volatile int i; + pLCD->CTRL &= ~CLCDC_LCDCTRL_PWR; + for (i = 0; i < 1000000; i++) {} + pLCD->CTRL &= ~CLCDC_LCDCTRL_ENABLE; +} + +/** + * @brief Enable/Disable the LCD Controller + * @param pLCD : The base of LCD peripheral on the chip + * @return None + */ +STATIC INLINE void Chip_LCD_Enable(LPC_LCD_T *pLCD) +{ + pLCD->CTRL |= CLCDC_LCDCTRL_ENABLE; +} + +/** + * @brief Enable/Disable the LCD Controller + * @param pLCD : The base of LCD peripheral on the chip + * @return None + */ +STATIC INLINE void Chip_LCD_Disable(LPC_LCD_T *pLCD) +{ + pLCD->CTRL &= ~CLCDC_LCDCTRL_ENABLE; +} + +/** + * @brief Set LCD Upper Panel Frame Buffer for Single Panel or Upper Panel Frame + * Buffer for Dual Panel + * @param pLCD : The base of LCD peripheral on the chip + * @param buffer : address of buffer + * @return None + */ +STATIC INLINE void Chip_LCD_SetUPFrameBuffer(LPC_LCD_T *pLCD, void *buffer) +{ + pLCD->UPBASE = (uint32_t) buffer; +} + +/** + * @brief Set LCD Lower Panel Frame Buffer for Dual Panel + * @param pLCD : The base of LCD peripheral on the chip + * @param buffer : address of buffer + * @return None + */ +STATIC INLINE void Chip_LCD_SetLPFrameBuffer(LPC_LCD_T *pLCD, void *buffer) +{ + pLCD->LPBASE = (uint32_t) buffer; +} + +/** + * @brief Configure Cursor + * @param pLCD : The base of LCD peripheral on the chip + * @param cursor_size : specify size of cursor + * - LCD_CURSOR_32x32 :cursor size is 32x32 pixels + * - LCD_CURSOR_64x64 :cursor size is 64x64 pixels + * @param sync : cursor sync mode + * - TRUE :cursor sync to the frame sync pulse + * - FALSE :cursor async mode + * @return None + */ +void Chip_LCD_Cursor_Config(LPC_LCD_T *pLCD, LCD_CURSOR_SIZE_OPT_T cursor_size, bool sync); + +/** + * @brief Enable Cursor + * @param pLCD : The base of LCD peripheral on the chip + * @param cursor_num : specify number of cursor is going to be written + * this param must < 4 + * @return None + */ +STATIC INLINE void Chip_LCD_Cursor_Enable(LPC_LCD_T *pLCD, uint8_t cursor_num) +{ + pLCD->CRSR_CTRL = (cursor_num << 4) | 1; +} + +/** + * @brief Disable Cursor + * @param pLCD : The base of LCD peripheral on the chip + * @param cursor_num : specify number of cursor is going to be written + * this param must < 4 + * @return None + */ +STATIC INLINE void Chip_LCD_Cursor_Disable(LPC_LCD_T *pLCD, uint8_t cursor_num) +{ + pLCD->CRSR_CTRL = (cursor_num << 4); +} + +/** + * @brief Load Cursor Palette + * @param pLCD : The base of LCD peripheral on the chip + * @param palette_color : cursor palette 0 value + * @return None + */ +STATIC INLINE void Chip_LCD_Cursor_LoadPalette0(LPC_LCD_T *pLCD, uint32_t palette_color) +{ + /* 7:0 - Red + 15:8 - Green + 23:16 - Blue + 31:24 - Not used*/ + pLCD->CRSR_PAL0 = (uint32_t) palette_color; +} + +/** + * @brief Load Cursor Palette + * @param pLCD : The base of LCD peripheral on the chip + * @param palette_color : cursor palette 1 value + * @return None + */ +STATIC INLINE void Chip_LCD_Cursor_LoadPalette1(LPC_LCD_T *pLCD, uint32_t palette_color) +{ + /* 7:0 - Red + 15:8 - Green + 23:16 - Blue + 31:24 - Not used*/ + pLCD->CRSR_PAL1 = (uint32_t) palette_color; +} + +/** + * @brief Set Cursor Position + * @param pLCD : The base of LCD peripheral on the chip + * @param x : horizontal position + * @param y : vertical position + * @return None + */ +STATIC INLINE void Chip_LCD_Cursor_SetPos(LPC_LCD_T *pLCD, uint16_t x, uint16_t y) +{ + pLCD->CRSR_XY = (x & 0x3FF) | ((y & 0x3FF) << 16); +} + +/** + * @brief Set Cursor Clipping Position + * @param pLCD : The base of LCD peripheral on the chip + * @param x : horizontal position, should be in range: 0..63 + * @param y : vertical position, should be in range: 0..63 + * @return None + */ +STATIC INLINE void Chip_LCD_Cursor_SetClip(LPC_LCD_T *pLCD, uint16_t x, uint16_t y) +{ + pLCD->CRSR_CLIP = (x & 0x3F) | ((y & 0x3F) << 8); +} + +/** + * @brief Enable Controller Interrupt + * @param pLCD : The base of LCD peripheral on the chip + * @param ints : OR'ed interrupt bits to enable + * @return None + */ +STATIC INLINE void Chip_LCD_EnableInts(LPC_LCD_T *pLCD, uint32_t ints) +{ + pLCD->INTMSK = ints; +} + +/** + * @brief Disable Controller Interrupt + * @param pLCD : The base of LCD peripheral on the chip + * @param ints : OR'ed interrupt bits to disable + * @return None + */ +STATIC INLINE void Chip_LCD_DisableInts(LPC_LCD_T *pLCD, uint32_t ints) +{ + pLCD->INTMSK = pLCD->INTMSK & ~(ints); +} + +/** + * @brief Clear Controller Interrupt + * @param pLCD : The base of LCD peripheral on the chip + * @param ints : OR'ed interrupt bits to clear + * @return None + */ +STATIC INLINE void Chip_LCD_ClearInts(LPC_LCD_T *pLCD, uint32_t ints) +{ + pLCD->INTCLR = pLCD->INTMSK & (ints); +} + +/** + * @brief Write Cursor Image into Internal Cursor Image Buffer + * @param pLCD : The base of LCD peripheral on the chip + * @param cursor_num : Cursor index + * @param Image : Pointer to image data + * @return None + */ +void Chip_LCD_Cursor_WriteImage(LPC_LCD_T *pLCD, uint8_t cursor_num, void *Image); + +/** + * @brief Load LCD Palette + * @param pLCD : The base of LCD peripheral on the chip + * @param palette : Address of palette table to load + * @return None + */ +void Chip_LCD_LoadPalette(LPC_LCD_T *pLCD, void *palette); + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ + +#ifdef __cplusplus +} +#endif + +/** + * @} + */ + +#endif /* __LCD_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/lpc_types.h b/hw/mcu/nxp/lpc_chip_40xx/inc/lpc_types.h new file mode 100644 index 000000000..14c7b6050 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/lpc_types.h @@ -0,0 +1,216 @@ +/* + * @brief Common types used in LPC functions + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __LPC_TYPES_H_ +#define __LPC_TYPES_H_ + +#include +#include + +/** @defgroup LPC_Types CHIP: LPC Common Types + * @ingroup CHIP_Common + * @{ + */ + +/** @defgroup LPC_Types_Public_Types LPC Public Types + * @{ + */ + +/** + * @brief Boolean Type definition + */ +typedef enum {FALSE = 0, TRUE = !FALSE} Bool; + +/** + * @brief Boolean Type definition + */ +#if !defined(__cplusplus) +// typedef enum {false = 0, true = !false} bool; +#endif + +/** + * @brief Flag Status and Interrupt Flag Status type definition + */ +typedef enum {RESET = 0, SET = !RESET} FlagStatus, IntStatus, SetState; +#define PARAM_SETSTATE(State) ((State == RESET) || (State == SET)) + +/** + * @brief Functional State Definition + */ +typedef enum {DISABLE = 0, ENABLE = !DISABLE} FunctionalState; +#define PARAM_FUNCTIONALSTATE(State) ((State == DISABLE) || (State == ENABLE)) + +/** + * @ Status type definition + */ +typedef enum {ERROR = 0, SUCCESS = !ERROR} Status; + +/** + * Read/Write transfer type mode (Block or non-block) + */ +typedef enum { + NONE_BLOCKING = 0, /**< None Blocking type */ + BLOCKING, /**< Blocking type */ +} TRANSFER_BLOCK_T; + +/** Pointer to Function returning Void (any number of parameters) */ +typedef void (*PFV)(); + +/** Pointer to Function returning int32_t (any number of parameters) */ +typedef int32_t (*PFI)(); + +/** + * @} + */ + +/** @defgroup LPC_Types_Public_Macros LPC Public Macros + * @{ + */ + +/* _BIT(n) sets the bit at position "n" + * _BIT(n) is intended to be used in "OR" and "AND" expressions: + * e.g., "(_BIT(3) | _BIT(7))". + */ +#undef _BIT +/* Set bit macro */ +#define _BIT(n) (1 << (n)) + +/* _SBF(f,v) sets the bit field starting at position "f" to value "v". + * _SBF(f,v) is intended to be used in "OR" and "AND" expressions: + * e.g., "((_SBF(5,7) | _SBF(12,0xF)) & 0xFFFF)" + */ +#undef _SBF +/* Set bit field macro */ +#define _SBF(f, v) ((v) << (f)) + +/* _BITMASK constructs a symbol with 'field_width' least significant + * bits set. + * e.g., _BITMASK(5) constructs '0x1F', _BITMASK(16) == 0xFFFF + * The symbol is intended to be used to limit the bit field width + * thusly: + * = (any_expression) & _BITMASK(x), where 0 < x <= 32. + * If "any_expression" results in a value that is larger than can be + * contained in 'x' bits, the bits above 'x - 1' are masked off. When + * used with the _SBF example above, the example would be written: + * a_reg = ((_SBF(5,7) | _SBF(12,0xF)) & _BITMASK(16)) + * This ensures that the value written to a_reg is no wider than + * 16 bits, and makes the code easier to read and understand. + */ +#undef _BITMASK +/* Bitmask creation macro */ +#define _BITMASK(field_width) ( _BIT(field_width) - 1) + +/* NULL pointer */ +#ifndef NULL +#define NULL ((void *) 0) +#endif + +/* Number of elements in an array */ +#define NELEMENTS(array) (sizeof(array) / sizeof(array[0])) + +/* Static data/function define */ +#define STATIC static +/* External data/function define */ +#define EXTERN extern + +#if !defined(MAX) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif +#if !defined(MIN) +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +/** + * @} + */ + +/* Old Type Definition compatibility */ +/** @addtogroup LPC_Types_Public_Types + * @{ + */ + +/** LPC type for character type */ +typedef char CHAR; + +/** LPC type for 8 bit unsigned value */ +typedef uint8_t UNS_8; + +/** LPC type for 8 bit signed value */ +typedef int8_t INT_8; + +/** LPC type for 16 bit unsigned value */ +typedef uint16_t UNS_16; + +/** LPC type for 16 bit signed value */ +typedef int16_t INT_16; + +/** LPC type for 32 bit unsigned value */ +typedef uint32_t UNS_32; + +/** LPC type for 32 bit signed value */ +typedef int32_t INT_32; + +/** LPC type for 64 bit signed value */ +typedef int64_t INT_64; + +/** LPC type for 64 bit unsigned value */ +typedef uint64_t UNS_64; + +#ifdef __CODE_RED +#define BOOL_32 bool +#define BOOL_16 bool +#define BOOL_8 bool +#else +/** 32 bit boolean type */ +typedef bool BOOL_32; + +/** 16 bit boolean type */ +typedef bool BOOL_16; + +/** 8 bit boolean type */ +typedef bool BOOL_8; +#endif + +#ifdef __CC_ARM +#define INLINE __inline +#else +#define INLINE inline +#endif + +/** + * @} + */ + +/** + * @} + */ + +#endif /* __LPC_TYPES_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/mcpwm_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/mcpwm_17xx_40xx.h new file mode 100644 index 000000000..a0a8b37d5 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/mcpwm_17xx_40xx.h @@ -0,0 +1,80 @@ +/* + * @brief LPC17xx/40xx Motor Control PWM driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __MCPWM_17XX_40XX_H_ +#define __MCPWM_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup MCPWM_17XX_40XX CHIP: LPC17xx/40xx Motor Control PWM driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief Motor Control PWM register block structure + */ +typedef struct { /*!< MCPWM Structure */ + __I uint32_t CON; /*!< PWM Control read address */ + __O uint32_t CON_SET; /*!< PWM Control set address */ + __O uint32_t CON_CLR; /*!< PWM Control clear address */ + __I uint32_t CAPCON; /*!< Capture Control read address */ + __O uint32_t CAPCON_SET; /*!< Capture Control set address */ + __O uint32_t CAPCON_CLR; /*!< Event Control clear address */ + __IO uint32_t TC[3]; /*!< Timer Counter register */ + __IO uint32_t LIM[3]; /*!< Limit register */ + __IO uint32_t MAT[3]; /*!< Match register */ + __IO uint32_t DT; /*!< Dead time register */ + __IO uint32_t CCP; /*!< Communication Pattern register */ + __I uint32_t CAP[3]; /*!< Capture register */ + __I uint32_t INTEN; /*!< Interrupt Enable read address */ + __O uint32_t INTEN_SET; /*!< Interrupt Enable set address */ + __O uint32_t INTEN_CLR; /*!< Interrupt Enable clear address */ + __I uint32_t CNTCON; /*!< Count Control read address */ + __O uint32_t CNTCON_SET; /*!< Count Control set address */ + __O uint32_t CNTCON_CLR; /*!< Count Control clear address */ + __I uint32_t INTF; /*!< Interrupt flags read address */ + __O uint32_t INTF_SET; /*!< Interrupt flags set address */ + __O uint32_t INTF_CLR; /*!< Interrupt flags clear address */ + __O uint32_t CAP_CLR; /*!< Capture clear address */ +} LPC_MCPWM_T; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __MCPWM_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/pmu_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/pmu_17xx_40xx.h new file mode 100644 index 000000000..7255df228 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/pmu_17xx_40xx.h @@ -0,0 +1,135 @@ +/* + * @brief LPC17xx_40xx PMU chip driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __PMU_17XX_40XX_H_ +#define __PMU_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup PMU_17XX_40XX CHIP: LPC17xx_40xx PMU driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief LPC17xx_40xx Power Management Unit register block structure + */ +typedef struct { + __IO uint32_t PCON; /*!< Offset: 0x000 Power control Register (R/W) */ +} LPC_PMU_T; + +/** + * @brief LPC17xx_40xx low power mode type definitions + */ +typedef enum CHIP_PMU_MCUPOWER { + PMU_MCU_SLEEP = 0, /*!< Sleep mode */ + PMU_MCU_DEEP_SLEEP, /*!< Deep Sleep mode */ + PMU_MCU_POWER_DOWN, /*!< Power down mode */ + PMU_MCU_DEEP_PWRDOWN /*!< Deep power down mode */ +} CHIP_PMU_MCUPOWER_T; + +/** + * PMU PCON register bit fields & masks + */ +#define PMU_PCON_PM0_FLAG (1 << 0) +#define PMU_PCON_PM1_FLAG (1 << 1) +#define PMU_PCON_BODRPM_FLAG (1 << 2) +#define PMU_PCON_BOGD_FLAG (1 << 3) +#define PMU_PCON_BORD_FLAG (1 << 4) +#define PMU_PCON_SMFLAG (1 << 8) /*!< Sleep mode flag */ +#define PMU_PCON_DSFLAG (1 << 9) /*!< Deep Sleep mode flag */ +#define PMU_PCON_PDFLAG (1 << 10) /*!< Power-down flag */ +#define PMU_PCON_DPDFLAG (1 << 11) /*!< Deep power-down flag */ + +/** + * @brief Enter MCU Sleep mode + * @param pPMU : Pointer to PMU register block + * @return None + * @note The sleep mode affects the ARM Cortex-M0+ core only. Peripherals + * and memories are active. + */ +void Chip_PMU_SleepState(LPC_PMU_T *pPMU); + +/** + * @brief Enter MCU Deep Sleep mode + * @param pPMU : Pointer to PMU register block + * @return None + * @note In Deep-sleep mode, the peripherals receive no internal clocks. + * The flash is in stand-by mode. The SRAM memory and all peripheral registers + * as well as the processor maintain their internal states. The WWDT, WKT, + * and BOD can remain active to wake up the system on an interrupt. + */ +void Chip_PMU_DeepSleepState(LPC_PMU_T *pPMU); + +/** + * @brief Enter MCU Power down mode + * @param pPMU : Pointer to PMU register block + * @return None + * @note In Power-down mode, the peripherals receive no internal clocks. + * The internal SRAM memory and all peripheral registers as well as the + * processor maintain their internal states. The flash memory is powered + * down. The WWDT, WKT, and BOD can remain active to wake up the system + * on an interrupt. + */ +void Chip_PMU_PowerDownState(LPC_PMU_T *pPMU); + +/** + * @brief Enter MCU Deep Power down mode + * @param pPMU : Pointer to PMU register block + * @return None + * @note For maximal power savings, the entire system is shut down + * except for the general purpose registers in the PMU and the self + * wake-up timer. Only the general purpose registers in the PMU maintain + * their internal states. The part can wake up on a pulse on the WAKEUP + * pin or when the self wake-up timer times out. On wake-up, the part + * reboots. + */ +void Chip_PMU_DeepPowerDownState(LPC_PMU_T *pPMU); + +/** + * @brief Place the MCU in a low power state + * @param pPMU : Pointer to PMU register block + * @param SleepMode : Sleep mode + * @return None + */ +void Chip_PMU_Sleep(LPC_PMU_T *pPMU, CHIP_PMU_MCUPOWER_T SleepMode); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __PMU_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/qei_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/qei_17xx_40xx.h new file mode 100644 index 000000000..ae2bb9352 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/qei_17xx_40xx.h @@ -0,0 +1,86 @@ +/* + * @brief LPC17xx/40xx Quadrature Encoder Interface driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __QEI_17XX_40XX_H_ +#define __QEI_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup QEI_17XX_40XX CHIP: LPc17xx/40xx Quadrature Encoder Interface driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief Quadrature Encoder Interface register block structure + */ +typedef struct { /*!< QEI Structure */ + __O uint32_t CON; /*!< Control register */ + __I uint32_t STAT; /*!< Encoder status register */ + __IO uint32_t CONF; /*!< Configuration register */ + __I uint32_t POS; /*!< Position register */ + __IO uint32_t MAXPOS; /*!< Maximum position register */ + __IO uint32_t CMPOS0; /*!< position compare register 0 */ + __IO uint32_t CMPOS1; /*!< position compare register 1 */ + __IO uint32_t CMPOS2; /*!< position compare register 2 */ + __I uint32_t INXCNT; /*!< Index count register */ + __IO uint32_t INXCMP0; /*!< Index compare register 0 */ + __IO uint32_t LOAD; /*!< Velocity timer reload register */ + __I uint32_t TIME; /*!< Velocity timer register */ + __I uint32_t VEL; /*!< Velocity counter register */ + __I uint32_t CAP; /*!< Velocity capture register */ + __IO uint32_t VELCOMP; /*!< Velocity compare register */ + __IO uint32_t FILTERPHA; /*!< Digital filter register on input phase A (QEI_A) */ + __IO uint32_t FILTERPHB; /*!< Digital filter register on input phase B (QEI_B) */ + __IO uint32_t FILTERINX; /*!< Digital filter register on input index (QEI_IDX) */ + __IO uint32_t WINDOW; /*!< Index acceptance window register */ + __IO uint32_t INXCMP1; /*!< Index compare register 1 */ + __IO uint32_t INXCMP2; /*!< Index compare register 2 */ + __I uint32_t RESERVED0[993]; + __O uint32_t IEC; /*!< Interrupt enable clear register */ + __O uint32_t IES; /*!< Interrupt enable set register */ + __I uint32_t INTSTAT; /*!< Interrupt status register */ + __I uint32_t IE; /*!< Interrupt enable register */ + __O uint32_t CLR; /*!< Interrupt status clear register */ + __O uint32_t SET; /*!< Interrupt status set register */ +} LPC_QEI_T; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __QEI_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/ring_buffer.h b/hw/mcu/nxp/lpc_chip_40xx/inc/ring_buffer.h new file mode 100644 index 000000000..8c205fd3a --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/ring_buffer.h @@ -0,0 +1,188 @@ +/* + * @brief Common ring buffer support functions + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __RING_BUFFER_H_ +#define __RING_BUFFER_H_ + +#include "lpc_types.h" + +/** @defgroup Ring_Buffer CHIP: Simple ring buffer implementation + * @ingroup CHIP_Common + * @{ + */ + +/** + * @brief Ring buffer structure + */ +typedef struct { + void *data; + int count; + int itemSz; + uint32_t head; + uint32_t tail; +} RINGBUFF_T; + +/** + * @def RB_VHEAD(rb) + * volatile typecasted head index + */ +#define RB_VHEAD(rb) (*(volatile uint32_t *) &(rb)->head) + +/** + * @def RB_VTAIL(rb) + * volatile typecasted tail index + */ +#define RB_VTAIL(rb) (*(volatile uint32_t *) &(rb)->tail) + +/** + * @brief Initialize ring buffer + * @param RingBuff : Pointer to ring buffer to initialize + * @param buffer : Pointer to buffer to associate with RingBuff + * @param itemSize : Size of each buffer item size + * @param count : Size of ring buffer + * @note Memory pointed by @a buffer must have correct alignment of + * @a itemSize, and @a count must be a power of 2 and must at + * least be 2 or greater. + * @return Nothing + */ +int RingBuffer_Init(RINGBUFF_T *RingBuff, void *buffer, int itemSize, int count); + +/** + * @brief Resets the ring buffer to empty + * @param RingBuff : Pointer to ring buffer + * @return Nothing + */ +STATIC INLINE void RingBuffer_Flush(RINGBUFF_T *RingBuff) +{ + RingBuff->head = RingBuff->tail = 0; +} + +/** + * @brief Return size the ring buffer + * @param RingBuff : Pointer to ring buffer + * @return Size of the ring buffer in bytes + */ +STATIC INLINE int RingBuffer_GetSize(RINGBUFF_T *RingBuff) +{ + return RingBuff->count; +} + +/** + * @brief Return number of items in the ring buffer + * @param RingBuff : Pointer to ring buffer + * @return Number of items in the ring buffer + */ +STATIC INLINE int RingBuffer_GetCount(RINGBUFF_T *RingBuff) +{ + return RB_VHEAD(RingBuff) - RB_VTAIL(RingBuff); +} + +/** + * @brief Return number of free items in the ring buffer + * @param RingBuff : Pointer to ring buffer + * @return Number of free items in the ring buffer + */ +STATIC INLINE int RingBuffer_GetFree(RINGBUFF_T *RingBuff) +{ + return RingBuff->count - RingBuffer_GetCount(RingBuff); +} + +/** + * @brief Return number of items in the ring buffer + * @param RingBuff : Pointer to ring buffer + * @return 1 if the ring buffer is full, otherwise 0 + */ +STATIC INLINE int RingBuffer_IsFull(RINGBUFF_T *RingBuff) +{ + return (RingBuffer_GetCount(RingBuff) >= RingBuff->count); +} + +/** + * @brief Return empty status of ring buffer + * @param RingBuff : Pointer to ring buffer + * @return 1 if the ring buffer is empty, otherwise 0 + */ +STATIC INLINE int RingBuffer_IsEmpty(RINGBUFF_T *RingBuff) +{ + return RB_VHEAD(RingBuff) == RB_VTAIL(RingBuff); +} + +/** + * @brief Insert a single item into ring buffer + * @param RingBuff : Pointer to ring buffer + * @param data : pointer to item + * @return 1 when successfully inserted, + * 0 on error (Buffer not initialized using + * RingBuffer_Init() or attempted to insert + * when buffer is full) + */ +int RingBuffer_Insert(RINGBUFF_T *RingBuff, const void *data); + +/** + * @brief Insert an array of items into ring buffer + * @param RingBuff : Pointer to ring buffer + * @param data : Pointer to first element of the item array + * @param num : Number of items in the array + * @return number of items successfully inserted, + * 0 on error (Buffer not initialized using + * RingBuffer_Init() or attempted to insert + * when buffer is full) + */ +int RingBuffer_InsertMult(RINGBUFF_T *RingBuff, const void *data, int num); + +/** + * @brief Pop an item from the ring buffer + * @param RingBuff : Pointer to ring buffer + * @param data : Pointer to memory where popped item be stored + * @return 1 when item popped successfuly onto @a data, + * 0 When error (Buffer not initialized using + * RingBuffer_Init() or attempted to pop item when + * the buffer is empty) + */ +int RingBuffer_Pop(RINGBUFF_T *RingBuff, void *data); + +/** + * @brief Pop an array of items from the ring buffer + * @param RingBuff : Pointer to ring buffer + * @param data : Pointer to memory where popped items be stored + * @param num : Max number of items array @a data can hold + * @return Number of items popped onto @a data, + * 0 on error (Buffer not initialized using RingBuffer_Init() + * or attempted to pop when the buffer is empty) + */ +int RingBuffer_PopMult(RINGBUFF_T *RingBuff, void *data, int num); + + +/** + * @} + */ + +#endif /* __RING_BUFFER_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/ritimer_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/ritimer_17xx_40xx.h new file mode 100644 index 000000000..2aa2b4fe1 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/ritimer_17xx_40xx.h @@ -0,0 +1,199 @@ +/* + * @brief LPC17xx/40xx RITimer driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __RITIMER_17XX_40XX_H_ +#define __RITIMER_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup RIT_17XX_40XX CHIP: LPC17xx/40xx Repetitive Interrupt Timer driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC175X_6X) + +/** + * @brief Repetitive Interrupt Timer register block structure + */ +typedef struct { /*!< RITIMER Structure */ + __IO uint32_t COMPVAL; /*!< Compare register */ + __IO uint32_t MASK; /*!< Mask register. This register holds the 32-bit mask value. A 1 written to any bit will force a compare on the corresponding bit of the counter and compare register. */ + __IO uint32_t CTRL; /*!< Control register. */ + __IO uint32_t COUNTER; /*!< 32-bit counter */ +#if defined(CHIP_LPC1347) + __IO uint32_t COMPVAL_H; /*!< Compare upper register */ + __IO uint32_t MASK_H; /*!< Mask upper register */ + __I uint32_t RESERVED0[1]; + __IO uint32_t COUNTER_H; /*!< Counter upper register */ +#endif +} LPC_RITIMER_T; + +/* + * @brief RITIMER register support bitfields and mask + */ + +/* + * RIT control register + */ +/** Set by H/W when the counter value equals the masked compare value */ +#define RIT_CTRL_INT ((uint32_t) (1)) +/** Set timer enable clear to 0 when the counter value equals the masked compare value */ +#define RIT_CTRL_ENCLR ((uint32_t) _BIT(1)) +/** Set timer enable on debug */ +#define RIT_CTRL_ENBR ((uint32_t) _BIT(2)) +/** Set timer enable */ +#define RIT_CTRL_TEN ((uint32_t) _BIT(3)) + +/** + * @brief Initialize the RIT + * @param pRITimer : RITimer peripheral selected + * @return None + */ +void Chip_RIT_Init(LPC_RITIMER_T *pRITimer); + +/** + * @brief Shutdown the RIT + * @param pRITimer : RITimer peripheral selected + * @return None + */ +void Chip_RIT_DeInit(LPC_RITIMER_T *pRITimer); + +/** + * @brief Enable Timer + * @param pRITimer : RITimer peripheral selected + * @return None + */ +STATIC INLINE void Chip_RIT_Enable(LPC_RITIMER_T *pRITimer) +{ + pRITimer->CTRL |= RIT_CTRL_TEN; +} + +/** + * @brief Disable Timer + * @param pRITimer : RITimer peripheral selected + * @return None + */ +STATIC INLINE void Chip_RIT_Disable(LPC_RITIMER_T *pRITimer) +{ + pRITimer->CTRL &= ~RIT_CTRL_TEN; +} + +/** + * @brief Enable timer debug + * @param pRITimer : RITimer peripheral selected + * @return None + */ +STATIC INLINE void Chip_RIT_TimerDebugEnable(LPC_RITIMER_T *pRITimer) +{ + pRITimer->CTRL |= RIT_CTRL_ENBR; +} + +/** + * @brief Disable timer debug + * @param pRITimer : RITimer peripheral selected + * @return None + */ +STATIC INLINE void Chip_RIT_TimerDebugDisable(LPC_RITIMER_T *pRITimer) +{ + pRITimer->CTRL &= ~RIT_CTRL_ENBR; +} + +/** + * @brief Check whether interrupt flag is set or not + * @param pRITimer : RITimer peripheral selected + * @return Current interrupt status, either ET or UNSET + */ +IntStatus Chip_RIT_GetIntStatus(LPC_RITIMER_T *pRITimer); + +/** + * @brief Set a tick value for the interrupt to time out + * @param pRITimer : RITimer peripheral selected + * @param val : value (in ticks) of the interrupt to be set + * @return None + */ +STATIC INLINE void Chip_RIT_SetCOMPVAL(LPC_RITIMER_T *pRITimer, uint32_t val) +{ + pRITimer->COMPVAL = val; +} + +/** + * @brief Enables or clears the RIT or interrupt + * @param pRITimer : RITimer peripheral selected + * @param val : RIT to be set, one or more RIT_CTRL_* values + * @return None + */ +STATIC INLINE void Chip_RIT_EnableCTRL(LPC_RITIMER_T *pRITimer, uint32_t val) +{ + pRITimer->CTRL |= val; +} + +/** + * @brief Clears the RIT interrupt + * @param pRITimer : RITimer peripheral selected + * @return None + */ +STATIC INLINE void Chip_RIT_ClearInt(LPC_RITIMER_T *pRITimer) +{ + pRITimer->CTRL |= RIT_CTRL_INT; +} + +/** + * @brief Returns the current RIT Counter value + * @param pRITimer : RITimer peripheral selected + * @return the current timer counter value + */ +STATIC INLINE uint32_t Chip_RIT_GetCounter(LPC_RITIMER_T *pRITimer) +{ + return pRITimer->COUNTER; +} + +/** + * @brief Set timer interval value + * @param pRITimer : RITimer peripheral selected + * @param time_interval : timer interval value (ms) + * @return None + */ +void Chip_RIT_SetTimerInterval(LPC_RITIMER_T *pRITimer, uint32_t time_interval); + +#endif /* defined(CHIP_LPC175X_6X) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __RITIMER_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/romapi_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/romapi_17xx_40xx.h new file mode 100644 index 000000000..95cbd1441 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/romapi_17xx_40xx.h @@ -0,0 +1,91 @@ +/* + * @brief LPC17xx/40xx ROM API declarations and functions + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __ROMAPI_17XX40XX_H_ +#define __ROMAPI_17XX40XX_H_ + +#include "iap.h" +#include "error.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup ROMAPI_407X_8X CHIP: LPC17XX/40XX ROM API declarations and functions + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if !defined(CHIP_LPC175X_6X) +/** + * @brief LPC17XX/40XX High level ROM API structure + */ +typedef struct { + const uint32_t usbdApiBase; /*!< USBD API function table base address */ + const uint32_t reserved0; /*!< Reserved */ + const uint32_t reserved1; /*!< Reserved */ + const uint32_t reserved2; /*!< Reserved */ + const uint32_t reserved3; /*!< Reserved */ + const uint32_t reserved4; /*!< Reserved */ + const uint32_t reserved5; /*!< Reserved */ + const uint32_t reserved6; /*!< Reserved */ + const uint32_t reserved7; /*!< Reserved */ + const uint32_t reserved8; /*!< Reserved */ + const uint32_t reserved9; /*!< Reserved */ + const uint32_t reserved10; /*!< Reserved */ +} LPC_ROM_API_T; + +/* Pointer to ROM API function address */ +#define LPC_ROM_API_BASE_LOC 0x1FFF1FF8 +#define LPC_ROM_API (*(LPC_ROM_API_T * *) LPC_ROM_API_BASE_LOC) + +#endif /* !defined(CHIP_LPC175X_6X) */ + +/* Pointer to ROM IAP entry functions */ +#define IAP_ENTRY_LOCATION 0X1FFF1FF1 + +/** + * @brief LPC17XX/40XX IAP_ENTRY API function type + */ +static INLINE void iap_entry(unsigned int cmd_param[5], unsigned int status_result[4]) +{ + ((IAP_ENTRY_T) IAP_ENTRY_LOCATION)(cmd_param, status_result); +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __ROMAPI_17XX40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/rtc_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/rtc_17xx_40xx.h new file mode 100644 index 000000000..4d437f227 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/rtc_17xx_40xx.h @@ -0,0 +1,646 @@ +/* + * @brief LPC17xx/40xx RTC driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __RTC_17XX_40XX_H_ +#define __RTC_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup RTC_17XX_40XX CHIP: LPC17xx/40xx Real Time Clock driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) +#define RTC_EV_SUPPORT 1 /* Event Monitor/Recorder support */ +#endif + +/** + * @brief RTC time type option + */ +typedef enum { + RTC_TIMETYPE_SECOND, /*!< Second */ + RTC_TIMETYPE_MINUTE, /*!< Month */ + RTC_TIMETYPE_HOUR, /*!< Hour */ + RTC_TIMETYPE_DAYOFMONTH, /*!< Day of month */ + RTC_TIMETYPE_DAYOFWEEK, /*!< Day of week */ + RTC_TIMETYPE_DAYOFYEAR, /*!< Day of year */ + RTC_TIMETYPE_MONTH, /*!< Month */ + RTC_TIMETYPE_YEAR, /*!< Year */ + RTC_TIMETYPE_LAST +} RTC_TIMEINDEX_T; + +#if RTC_EV_SUPPORT +/** + * @brief Event Channel Identifier definitions + */ +typedef enum { + RTC_EV_CHANNEL_1 = 0, + RTC_EV_CHANNEL_2, + RTC_EV_CHANNEL_3, + RTC_EV_CHANNEL_NUM, +} RTC_EV_CHANNEL_T; +#endif /*RTC_EV_SUPPORT*/ + +/** + * @brief Real Time Clock register block structure + */ +typedef struct { /*!< RTC Structure */ + __IO uint32_t ILR; /*!< Interrupt Location Register */ + __I uint32_t RESERVED0; + __IO uint32_t CCR; /*!< Clock Control Register */ + __IO uint32_t CIIR; /*!< Counter Increment Interrupt Register */ + __IO uint32_t AMR; /*!< Alarm Mask Register */ + __I uint32_t CTIME[3]; /*!< Consolidated Time Register 0,1,2 */ + __IO uint32_t TIME[RTC_TIMETYPE_LAST]; /*!< Timer field registers */ + __IO uint32_t CALIBRATION; /*!< Calibration Value Register */ + __IO uint32_t GPREG[5]; /*!< General Purpose Storage Registers */ + __IO uint32_t RTC_AUXEN; /*!< RTC Auxiliary Enable register */ + __IO uint32_t RTC_AUX; /*!< RTC Auxiliary control register*/ + __IO uint32_t ALRM[RTC_TIMETYPE_LAST]; /*!< Alarm field registers */ +#if RTC_EV_SUPPORT + __IO uint32_t ERSTATUS; /*!< Event Monitor/Recorder Status register*/ + __IO uint32_t ERCONTROL; /*!< Event Monitor/Recorder Control register*/ + __I uint32_t ERCOUNTERS; /*!< Event Monitor/Recorder Counters register*/ + __I uint32_t RESERVED2; + __I uint32_t ERFIRSTSTAMP[RTC_EV_CHANNEL_NUM]; /*!> (8 * ch)) & 0x07)) + +/* + * @brief Event Monitor/Recorder TimeStamp register + */ +#define RTC_ER_TIMESTAMP_SEC(n) ((uint32_t) (n & 0x3F)) +#define RTC_ER_TIMESTAMP_MIN(n) ((uint32_t) ((n >> 6) & 0x3F)) +#define RTC_ER_TIMESTAMP_HOUR(n) ((uint32_t) ((n >> 12) & 0x1F)) +#define RTC_ER_TIMESTAMP_DOY(n) ((uint32_t) ((n >> 17) & 0x1FF)) + +/** + * @brief Event Monitor/Recorder Mode definition + */ +typedef enum IP_RTC_EV_MODE { + RTC_EV_MODE_DISABLE = 0, /*!< Event Monitor/Recoder is disabled */ + RTC_EV_MODE_ENABLE_16HZ = 1, /*!< Event Monitor/Recoder is enabled and use 16Hz sample clock for event input */ + RTC_EV_MODE_ENABLE_64HZ = 2, /*!< Event Monitor/Recoder is enabled and use 64Hz sample clock for event input */ + RTC_EV_MODE_ENABLE_1KHZ = 3, /*!< Event Monitor/Recoder is enabled and use 1kHz sample clock for event input */ + RTC_EV_MODE_LAST, +} RTC_EV_MODE_T; + +/** + * @brief Event Monitor/Recorder Timestamp structure + */ +typedef struct { + uint8_t sec; /*!< Second */ + uint8_t min; /*!< Minute */ + uint8_t hour; /*!< Hour */ + uint16_t dayofyear; /*!< Day of year */ +} RTC_EV_TIMESTAMP_T; + +#endif /*RTC_EV_SUPPORT*/ + +/** + * @brief RTC enumeration + */ + +/** @brief RTC interrupt source */ +typedef enum { + RTC_INT_COUNTER_INCREASE = RTC_IRL_RTCCIF, /*!< Counter Increment Interrupt */ + RTC_INT_ALARM = RTC_IRL_RTCALF /*!< The alarm interrupt */ +} RTC_INT_OPT_T; + +typedef struct { + uint32_t time[RTC_TIMETYPE_LAST]; +} RTC_TIME_T; + +/** + * @brief Reset clock tick counter in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @return None + */ +void Chip_RTC_ResetClockTickCounter(LPC_RTC_T *pRTC); + +/** + * @brief Start/Stop RTC peripheral + * @param pRTC : RTC peripheral selected + * @param NewState : New State of this function, should be: + * - ENABLE :The time counters are enabled + * - DISABLE :The time counters are disabled + * @return None + */ +void Chip_RTC_Enable(LPC_RTC_T *pRTC, FunctionalState NewState); + +/** + * @brief Enable/Disable Counter increment interrupt for a time type in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param cntrMask : Or'ed bit values for time types (RTC_AMR_CIIR_IM*) + * @param NewState : ENABLE or DISABLE + * @return None + */ +void Chip_RTC_CntIncrIntConfig(LPC_RTC_T *pRTC, uint32_t cntrMask, FunctionalState NewState); + +/** + * @brief Enable/Disable Alarm interrupt for a time type in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param alarmMask : Or'ed bit values for ALARM types (RTC_AMR_CIIR_IM*) + * @param NewState : ENABLE or DISABLE + * @return None + */ +void Chip_RTC_AlarmIntConfig(LPC_RTC_T *pRTC, uint32_t alarmMask, FunctionalState NewState); + +/** + * @brief Set current time value for a time type in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param Timetype : time field index type to set + * @param TimeValue : Value to palce in time field + * @return None + */ +STATIC INLINE void Chip_RTC_SetTime(LPC_RTC_T *pRTC, RTC_TIMEINDEX_T Timetype, uint32_t TimeValue) +{ + pRTC->TIME[Timetype] = TimeValue; +} + +/** + * @brief Get current time value for a type time type + * @param pRTC : RTC peripheral selected + * @param Timetype : Time field index type to get + * @return Value of time field according to specified time type + */ +STATIC INLINE uint32_t Chip_RTC_GetTime(LPC_RTC_T *pRTC, RTC_TIMEINDEX_T Timetype) +{ + return pRTC->TIME[Timetype]; +} + +/** + * @brief Set full time in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param pFullTime : Pointer to full time data + * @return None + */ +void Chip_RTC_SetFullTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime); + +/** + * @brief Get full time from the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param pFullTime : Pointer to full time record to fill + * @return None + */ +void Chip_RTC_GetFullTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime); + +/** + * @brief Set alarm time value for a time type + * @param pRTC : RTC peripheral selected + * @param Timetype : Time index field to set + * @param ALValue : Alarm time value to set + * @return None + */ +STATIC INLINE void Chip_RTC_SetAlarmTime(LPC_RTC_T *pRTC, RTC_TIMEINDEX_T Timetype, uint32_t ALValue) +{ + pRTC->ALRM[Timetype] = ALValue; +} + +/** + * @brief Get alarm time value for a time type + * @param pRTC : RTC peripheral selected + * @param Timetype : Time index field to get + * @return Value of Alarm time according to specified time type + */ +STATIC INLINE uint32_t Chip_RTC_GetAlarmTime(LPC_RTC_T *pRTC, RTC_TIMEINDEX_T Timetype) +{ + return pRTC->ALRM[Timetype]; +} + +/** + * @brief Set full alarm time in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param pFullTime : Pointer to full time record to set alarm + * @return None + */ +void Chip_RTC_SetFullAlarmTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime); + +/** + * @brief Get full alarm time in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param pFullTime : Pointer to full time record to fill + * @return None + */ +void Chip_RTC_GetFullAlarmTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime); + +/** + * @brief Write value to General purpose registers + * @param pRegFile : RegFile peripheral selected + * @param index : General purpose register index + * @param value : Value to write + * @return None + * @note These General purpose registers can be used to store important + * information when the main power supply is off. The value in these + * registers is not affected by chip reset. These registers are + * powered in the RTC power domain. + */ +STATIC INLINE void Chip_REGFILE_Write(LPC_REGFILE_T *pRegFile, uint8_t index, uint32_t value) +{ + pRegFile->REGFILE[index] = value; +} + +/** + * @brief Read value from General purpose registers + * @param pRegFile : RegFile peripheral selected + * @param index : General purpose register index + * @return Read Value + * @note These General purpose registers can be used to store important + * information when the main power supply is off. The value in these + * registers is not affected by chip reset. These registers are + * powered in the RTC power domain. + */ +STATIC INLINE uint32_t Chip_REGFILE_Read(LPC_REGFILE_T *pRegFile, uint8_t index) +{ + return pRegFile->REGFILE[index]; +} + +/** + * @brief Enable/Disable calibration counter in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param NewState : New State of this function, should be: + * - ENABLE :The calibration counter is enabled and counting + * - DISABLE :The calibration counter is disabled and reset to zero + * @return None + */ +void Chip_RTC_CalibCounterCmd(LPC_RTC_T *pRTC, FunctionalState NewState); + +/** + * @brief Configures Calibration in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param CalibValue : Calibration value, should be in range from 0 to 131,072 + * @param CalibDir : Calibration Direction, should be: + * - RTC_CALIB_DIR_FORWARD :Forward calibration + * - RTC_CALIB_DIR_BACKWARD :Backward calibration + * @return None + */ +STATIC INLINE void Chip_RTC_CalibConfig(LPC_RTC_T *pRTC, uint32_t CalibValue, uint8_t CalibDir) +{ + pRTC->CALIBRATION = ((CalibValue - 1) & RTC_CALIBRATION_CALVAL_MASK) + | ((CalibDir == RTC_CALIB_DIR_BACKWARD) ? RTC_CALIBRATION_LIBDIR : 0); +} + +/** + * @brief Clear specified Location interrupt pending in the RTC peripheral + * @param pRTC : RTC peripheral selected + * @param IntType : Interrupt location type, should be: + * - RTC_INT_COUNTER_INCREASE :Clear Counter Increment Interrupt pending. + * - RTC_INT_ALARM :Clear alarm interrupt pending + * @return None + */ +STATIC INLINE void Chip_RTC_ClearIntPending(LPC_RTC_T *pRTC, uint32_t IntType) +{ + pRTC->ILR = IntType; +} + +/** + * @brief Check whether if specified location interrupt in the RTC peripheral is set or not + * @param pRTC : RTC peripheral selected + * @param IntType : Interrupt location type, should be: + * - RTC_INT_COUNTER_INCREASE: Counter Increment Interrupt block generated an interrupt. + * - RTC_INT_ALARM: Alarm generated an interrupt. + * @return New state of specified Location interrupt in RTC peripheral, SET OR RESET + */ +STATIC INLINE IntStatus Chip_RTC_GetIntPending(LPC_RTC_T *pRTC, uint32_t IntType) +{ + return (pRTC->ILR & IntType) ? SET : RESET; +} + +#if RTC_EV_SUPPORT + +/** + * @brief Configure a specific event channel + * @param pRTC : RTC peripheral selected + * @param ch : Channel number + * @param flag : Configuration flag + * @return None + * @note flag is or-ed bit value of RTC_ERCTRL_INTWAKE_EN,RTC_ERCTRL_GPCLEAR_EN, + * RTC_ERCTRL_POL_POSITIVE and RTC_ERCTRL_INPUT_EN. + */ +STATIC INLINE void Chip_RTC_EV_Config(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch, uint32_t flag) +{ + uint32_t temp; + + temp = pRTC->ERCONTROL & (~(RTC_ERCTRL_CHANNEL_CONFIG_BITMASK(ch))) & RTC_ERCTRL_BITMASK; + pRTC->ERCONTROL = temp | (RTC_ERCTRL_CHANNEL_CONFIG(ch, flag) & RTC_ERCTRL_BITMASK); +} + +/** + * @brief Enable/Disable and select clock frequency for Event Monitor/Recorder + * @param pRTC : RTC peripheral selected + * @param mode : selected mode + * @return None + */ +STATIC INLINE void Chip_RTC_EV_SetMode(LPC_RTC_T *pRTC, RTC_EV_MODE_T mode) +{ + uint32_t temp; + + temp = pRTC->ERCONTROL & (~RTC_ERCTRL_MODE_MASK) & RTC_ERCTRL_BITMASK; + pRTC->ERCONTROL = temp | RTC_ERCTRL_MODE(mode); +} + +/** + * @brief Get Event Monitor/Recorder Status + * @param pRTC : RTC peripheral selected + * @return Or-ed bit value of RTC_ERSTATUS_GPCLEARED and RTC_ERSTATUS_WAKEUP + */ +STATIC INLINE uint8_t Chip_RTC_EV_GetStatus(LPC_RTC_T *pRTC) +{ + return pRTC->ERSTATUS & (RTC_ERSTATUS_GPCLEARED | RTC_ERSTATUS_WAKEUP); +} + +/** + * @brief Clear Event Monitor/Recorder Status + * @param pRTC : RTC peripheral selected + * @param flag : Or-ed bit value of RTC_ERSTATUS_GPCLEARED and RTC_ERSTATUS_WAKEUP + * @return Nothing + */ +STATIC INLINE void Chip_RTC_EV_ClearStatus(LPC_RTC_T *pRTC, uint32_t flag) +{ + pRTC->ERSTATUS = flag & (RTC_ERSTATUS_GPCLEARED | RTC_ERSTATUS_WAKEUP); +} + +/** + * @brief Get status of a specific event channel + * @param pRTC : RTC peripheral selected + * @param ch : Channel number + * @return SET (At least 1 event occurred on the channel), RESET: no event occured. + */ +STATIC INLINE FlagStatus Chip_RTC_EV_GetChannelStatus(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch) +{ + return (pRTC->ERSTATUS & RTC_ERSTATUS_CHANNEL_EV(ch)) ? SET : RESET; +} + +/** + * @brief Clear status of a specific event channel + * @param pRTC : RTC peripheral selected + * @param ch : Channel number + * @return Nothing. + */ +STATIC INLINE void Chip_RTC_EV_ClearChannelStatus(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch) +{ + pRTC->ERSTATUS = RTC_ERSTATUS_CHANNEL_EV(ch); +} + +/** + * @brief Get counter value of a specific event channel + * @param pRTC : RTC peripheral selected + * @param ch : Channel number + * @return counter value + */ +STATIC INLINE uint8_t Chip_RTC_EV_GetCounter(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch) +{ + return RTC_ER_COUNTER(ch, pRTC->ERCOUNTERS); +} + +/** + * @brief Get first time stamp of a specific event channel + * @param pRTC : RTC peripheral selected + * @param ch : Channel number + * @param pTimeStamp : pointer to Timestamp buffer + * @return Nothing. + */ +void Chip_RTC_EV_GetFirstTimeStamp(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch, RTC_EV_TIMESTAMP_T *pTimeStamp); + +/** + * @brief Get last time stamp of a specific event channel + * @param pRTC : RTC peripheral selected + * @param ch : Channel number + * @param pTimeStamp : pointer to Timestamp buffer + * @return Nothing. + */ +void Chip_RTC_EV_GetLastTimeStamp(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch, RTC_EV_TIMESTAMP_T *pTimeStamp); + +#endif /*RTC_EV_SUPPORT*/ + +/** + * @brief Initialize the RTC peripheral + * @param pRTC : RTC peripheral selected + * @return None + */ +void Chip_RTC_Init(LPC_RTC_T *pRTC); + +/** + * @brief De-initialize the RTC peripheral + * @param pRTC : RTC peripheral selected + * @return None + */ +void Chip_RTC_DeInit(LPC_RTC_T *pRTC); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __RTC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/sdc_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/sdc_17xx_40xx.h new file mode 100644 index 000000000..9fb0d5181 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/sdc_17xx_40xx.h @@ -0,0 +1,583 @@ +/* + * @brief LPC17xx/40xx SD Card Interface driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __SDC_17XX_40XX_H_ +#define __SDC_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup SDC_17XX_40XX CHIP: LPC17xx/40xx SD Card Interafce driver + * @ingroup CHIP_17XX_40XX_Drivers + * SD/MMC card Interface + * @{ + */ + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/** + * @brief SD/MMC card Interface (SDC) register block structure + */ +typedef struct { + __IO uint32_t POWER; /*!< Power Control register */ + __IO uint32_t CLOCK; /*!< Clock control regsiter */ + __IO uint32_t ARGUMENT; /*!< Command argument register */ + __IO uint32_t COMMAND; /*!< Command register */ + __I uint32_t RESPCMD; /*!< Command response register */ + __I uint32_t RESPONSE[4]; /*!< Response registers */ + __IO uint32_t DATATIMER; /*!< Data timer register */ + __IO uint32_t DATALENGTH; /*!< Data length register */ + __IO uint32_t DATACTRL; /*!< Data control register */ + __I uint32_t DATACNT; /*!< Data count register */ + __I uint32_t STATUS; /*!< Status register */ + __O uint32_t CLEAR; /*!< Clear register */ + __IO uint32_t MASK0; /*!< Mask 0 register */ + uint32_t RESERVED0[2]; + __I uint32_t FIFOCNT; /*!< FIFO count register */ + uint32_t RESERVED1[13]; + __IO uint32_t FIFO[16]; /*!< FIFO registers */ +} LPC_SDC_T; + +/** + * @brief SDC Power Control Register bit definitions + */ +/** SDC Power Control Register Bitmask */ +#define SDC_PWR_BITMASK ((uint32_t) 0xC3) +/** SDC Power Control Bit Mask */ +#define SDC_PWR_CTRL_BITMASK (((uint32_t) 0x03) << 0) +/** SDC Power Control */ +#define SDC_PWR_CTRL(n) (((uint32_t) (n & 0x03)) << 0) +/** SD_CMD Output Control */ +#define SDC_PWR_OPENDRAIN (((uint32_t) 1) << 6) +/** Rod Control */ +#define SDC_PWR_ROD (((uint32_t) 1) << 7) + +/** + * @brief SDC Clock Control Register bit definitions + */ +/** SDC Clock Control Register Bitmask */ +#define SDC_CLOCK_BITMASK ((uint32_t) 0xFFF) +/** SDC Clock Divider Bitmask */ +#define SDC_CLOCK_CLKDIV_BITMASK (((uint32_t) 0xFF ) << 0) +/** Set SDC Clock Divide value */ +#define SDC_CLOCK_CLKDIV(n) (((uint32_t) (n & 0x0FF)) << 0) + +/** + * @brief SDC Command Register bit definitions + */ +/** SDC Command Register Bitmask */ +#define SDC_COMMAND_BITMASK ((uint32_t) 0x7FF) +/** SDC Command Index Bitmask */ +#define SDC_COMMAND_INDEX_BITMASK ((uint32_t) 0x3F) +/** Set SDC Command Index */ +#define SDC_COMMAND_INDEX(n) ((uint32_t) n & 0x3F) +/** No response is expected */ +#define SDC_COMMAND_NO_RSP (((uint32_t) 0 ) << 6) +/** Short response is expected */ +#define SDC_COMMAND_SHORT_RSP (((uint32_t) 1 ) << 6) +/** Long response is expected */ +#define SDC_COMMAND_LONG_RSP (((uint32_t) 3 ) << 6) +/** Response bit mask */ +#define SDC_COMMAND_RSP_BITMASK (((uint32_t) 3 ) << 6) +/** Mark that command timer is disabled and CPSM waits for interrupt request */ +#define SDC_COMMAND_INTERRUPT (((uint32_t) 1 ) << 8) +/** Mark that CPSM waits for CmdPend before starting sending a command*/ +#define SDC_COMMAND_PENDING (((uint32_t) 1 ) << 9) +/** Enable CPSM */ +#define SDC_COMMAND_ENABLE (((uint32_t) 1 ) << 10) + +/** + * @brief SDC Command Response Register bit definitions + */ +/** SDC Command Response value */ +#define SDC_RESPCOMMAND_VAL(n) ((uint32_t) n & 0x3F) + +/** + * @brief SDC Data Length Register bit definitions + */ +/** SDC Data Length set */ +#define SDC_DATALENGTH_LEN(n) ((uint32_t) n & 0xFFFF) + +/** + * @brief SDC Data Control Register bit definitions + */ +/** SDC Data Control Register Bitmask */ +#define SDC_DATACTRL_BITMASK ((uint32_t) 0xFF) +/** Enable Data Transfer */ +#define SDC_DATACTRL_ENABLE (((uint32_t) 1 ) << 0) +/** Mark that Data is transfer from card to controller */ +#define SDC_DATACTRL_DIR_FROMCARD (((uint32_t) 1 ) << 1) +/** Mark that Data is transfer from controller to card */ +#define SDC_DATACTRL_DIR_TOCARD ((uint32_t) 0) +/** Mark that the transfer mode is Stream Data Transfer */ +#define SDC_DATACTRL_XFER_MODE_STREAM (((uint32_t) 1 ) << 2) +/** Mark that the transfer mode is Block Data Transfer */ +#define SDC_DATACTRL_XFER_MODE_BLOCK ((uint32_t) 0) +/** Enable DMA */ +#define SDC_DATACTRL_DMA_ENABLE (((uint32_t) 1 ) << 3) +/** Set Data Block size */ +#define SDC_DATACTRL_BLOCKSIZE(n) (((uint32_t) (n & 0x0F) ) << 4) +/** Get Data Block size value */ +#define SDC_DATACTRL_BLOCKSIZE_VAL(n) (((uint32_t) 1) << n) + +/** + * @brief SDC Data Counter Register bit definitions + */ +#define SDC_DATACNT_VAL(n) ((uint32_t) n & 0xFFFF) + +/** + * @brief SDC Status Register bit definitions + */ +/** Command Response received (CRC check failed) */ +#define SDC_STATUS_CMDCRCFAIL (((uint32_t) 1 ) << 0) +/** Data block sent/received (CRC check failed). */ +#define SDC_STATUS_DATACRCFAIL (((uint32_t) 1 ) << 1) +/** Command response timeout.. */ +#define SDC_STATUS_CMDTIMEOUT (((uint32_t) 1 ) << 2) +/** Data timeout. */ +#define SDC_STATUS_DATATIMEOUT (((uint32_t) 1 ) << 3) +/** Transmit FIFO underrun error. */ +#define SDC_STATUS_TXUNDERRUN (((uint32_t) 1 ) << 4) +/** Receive FIFO overrun error. */ +#define SDC_STATUS_RXOVERRUN (((uint32_t) 1 ) << 5) +/** Command response received (CRC check passed). */ +#define SDC_STATUS_CMDRESPEND (((uint32_t) 1 ) << 6) +/** Command sent (no response required).*/ +#define SDC_STATUS_CMDSENT (((uint32_t) 1 ) << 7) +/** Data end (data counter is zero).*/ +#define SDC_STATUS_DATAEND (((uint32_t) 1 ) << 8) +/** Start bit not detected on all data signals in wide bus mode..*/ +#define SDC_STATUS_STARTBITERR (((uint32_t) 1 ) << 9) +/** Data block sent/received (CRC check passed).*/ +#define SDC_STATUS_DATABLOCKEND (((uint32_t) 1 ) << 10) +/** Command transfer in progress.*/ +#define SDC_STATUS_CMDACTIVE (((uint32_t) 1 ) << 11) +/** Data transmit in progress.*/ +#define SDC_STATUS_TXACTIVE (((uint32_t) 1 ) << 12) +/** Data receive in progress.*/ +#define SDC_STATUS_RXACTIVE (((uint32_t) 1 ) << 13) +/** Transmit FIFO half empty.*/ +#define SDC_STATUS_TXFIFOHALFEMPTY (((uint32_t) 1 ) << 14) +/** Receive FIFO half full.*/ +#define SDC_STATUS_RXFIFOHALFFULL (((uint32_t) 1 ) << 15) +/** Transmit FIFO full.*/ +#define SDC_STATUS_TXFIFOFULL (((uint32_t) 1 ) << 16) +/** Receive FIFO full.*/ +#define SDC_STATUS_RXFIFOFULL (((uint32_t) 1 ) << 17) +/** Transmit FIFO empty.*/ +#define SDC_STATUS_TXFIFOEMPTY (((uint32_t) 1 ) << 18) +/** Receive FIFO empty.*/ +#define SDC_STATUS_RXFIFOEMPTY (((uint32_t) 1 ) << 19) +/** Data available in transmit FIFO.*/ +#define SDC_STATUS_TXDATAAVLBL (((uint32_t) 1 ) << 20) +/** Data available in receive FIFO.*/ +#define SDC_STATUS_RXDATAAVLBL (((uint32_t) 1 ) << 21) +/** Command Error Status */ +#define SDC_STATUS_CMDERR (SDC_STATUS_CMDCRCFAIL | SDC_STATUS_CMDTIMEOUT | SDC_STATUS_STARTBITERR) +/** Data Error Status */ +#define SDC_STATUS_DATAERR (SDC_STATUS_DATACRCFAIL | SDC_STATUS_DATATIMEOUT | SDC_STATUS_TXUNDERRUN \ + | SDC_STATUS_RXOVERRUN | SDC_STATUS_STARTBITERR) +/** FIFO Status*/ +#define SDC_STATUS_FIFO (SDC_STATUS_TXFIFOHALFEMPTY | SDC_STATUS_RXFIFOHALFFULL \ + | SDC_STATUS_TXFIFOFULL | SDC_STATUS_RXFIFOFULL \ + | SDC_STATUS_TXFIFOEMPTY | SDC_STATUS_RXFIFOEMPTY \ + | SDC_STATUS_DATABLOCKEND) + +/** Data Transfer Status*/ +#define SDC_STATUS_DATA (SDC_STATUS_DATAEND ) + +/** + * @brief SDC Clear Register bit definitions + */ +/** Clear all status flag*/ +#define SDC_CLEAR_ALL ((uint32_t) 0x7FF) +/** Clears CmdCrcFail flag.*/ +#define SDC_CLEAR_CMDCRCFAIL (((uint32_t) 1 ) << 0) +/** Clears DataCrcFail flag. */ +#define SDC_CLEAR_DATACRCFAIL (((uint32_t) 1 ) << 1) +/** Clears CmdTimeOut flag. */ +#define SDC_CLEAR_CMDTIMEOUT (((uint32_t) 1 ) << 2) +/** Clears DataTimeOut flag. */ +#define SDC_CLEAR_DATATIMEOUT (((uint32_t) 1 ) << 3) +/** Clears TxUnderrun flag. */ +#define SDC_CLEAR_TXUNDERRUN (((uint32_t) 1 ) << 4) +/**Clears RxOverrun flag. */ +#define SDC_CLEAR_RXOVERRUN (((uint32_t) 1 ) << 5) +/** Clears CmdRespEnd flag. */ +#define SDC_CLEAR_CMDRESPEND (((uint32_t) 1 ) << 6) +/** Clears CmdSent flag.*/ +#define SDC_CLEAR_CMDSENT (((uint32_t) 1 ) << 7) +/**Clears DataEnd flag.*/ +#define SDC_CLEAR_DATAEND (((uint32_t) 1 ) << 8) +/** Clears StartBitErr flag.*/ +#define SDC_CLEAR_STARTBITERR (((uint32_t) 1 ) << 9) +/** Clears DataBlockEnd flag.*/ +#define SDC_CLEAR_DATABLOCKEND (((uint32_t) 1 ) << 10) + +/** + * @brief SDC Interrupt Mask Register bit definitions + */ +/** Mask CmdCrcFail flag.*/ +#define SDC_MASK0_CMDCRCFAIL (((uint32_t) 1 ) << 0) +/** Mask DataCrcFail flag. */ +#define SDC_MASK0_DATACRCFAIL (((uint32_t) 1 ) << 1) +/** Mask CmdTimeOut flag. */ +#define SDC_MASK0_CMDTIMEOUT (((uint32_t) 1 ) << 2) +/** Mask DataTimeOut flag. */ +#define SDC_MASK0_DATATIMEOUT (((uint32_t) 1 ) << 3) +/** Mask TxUnderrun flag. */ +#define SDC_MASK0_TXUNDERRUN (((uint32_t) 1 ) << 4) +/** Mask RxOverrun flag. */ +#define SDC_MASK0_RXOVERRUN (((uint32_t) 1 ) << 5) +/** Mask CmdRespEnd flag. */ +#define SDC_MASK0_CMDRESPEND (((uint32_t) 1 ) << 6) +/** Mask CmdSent flag.*/ +#define SDC_MASK0_CMDSENT (((uint32_t) 1 ) << 7) +/** Mask DataEnd flag.*/ +#define SDC_MASK0_DATAEND (((uint32_t) 1 ) << 8) +/** Mask StartBitErr flag.*/ +#define SDC_MASK0_STARTBITERR (((uint32_t) 1 ) << 9) +/** Mask DataBlockEnd flag.*/ +#define SDC_MASK0_DATABLOCKEND (((uint32_t) 1 ) << 10) +/** Mask CmdActive flag.*/ +#define SDC_MASK0_CMDACTIVE (((uint32_t) 1 ) << 11) +/** Mask TxActive flag.*/ +#define SDC_MASK0_TXACTIVE (((uint32_t) 1 ) << 12) +/** Mask RxActive flag.*/ +#define SDC_MASK0_RXACTIVE (((uint32_t) 1 ) << 13) +/** Mask TxFifoHalfEmpty flag.*/ +#define SDC_MASK0_TXFIFOHALFEMPTY (((uint32_t) 1 ) << 14) +/** Mask RxFifoHalfFull flag.*/ +#define SDC_MASK0_RXFIFOHALFFULL (((uint32_t) 1 ) << 15) +/** Mask TxFifoFull flag.*/ +#define SDC_MASK0_TXFIFOFULL (((uint32_t) 1 ) << 16) +/** Mask RxFifoFull flag.*/ +#define SDC_MASK0_RXFIFOFULL (((uint32_t) 1 ) << 17) +/** Mask TxFifoEmpty flag.*/ +#define SDC_MASK0_TXFIFOEMPTY (((uint32_t) 1 ) << 18) +/** Mask RxFifoEmpty flag.*/ +#define SDC_MASK0_RXFIFOEMPTY (((uint32_t) 1 ) << 19) +/** Mask TxDataAvlbl flag.*/ +#define SDC_MASK0_TXDATAAVLBL (((uint32_t) 1 ) << 20) +/** Mask RxDataAvlbl flag.*/ +#define SDC_MASK0_RXDATAAVLBL (((uint32_t) 1 ) << 21) +/** CMD error interrupt mask */ +#define SDC_MASK0_CMDERR (SDC_MASK0_CMDCRCFAIL | SDC_MASK0_CMDTIMEOUT | SDC_MASK0_STARTBITERR) +/** Data Transmit Error interrupt mask */ +#define SDC_MASK0_TXDATAERR (SDC_MASK0_DATACRCFAIL | SDC_MASK0_DATATIMEOUT | SDC_MASK0_TXUNDERRUN | \ + SDC_MASK0_STARTBITERR) + +/** Data Receive Error interrupt mask */ +#define SDC_MASK0_RXDATAERR (SDC_MASK0_DATACRCFAIL | SDC_MASK0_DATATIMEOUT | SDC_MASK0_RXOVERRUN | \ + SDC_MASK0_STARTBITERR) +/** TX FIFO interrupt mask*/ +#define SDC_MASK0_TXFIFO (SDC_MASK0_TXFIFOHALFEMPTY | SDC_MASK0_DATABLOCKEND ) +/** RX FIFO interrupt mask*/ +#define SDC_MASK0_RXFIFO (SDC_MASK0_RXFIFOHALFFULL | SDC_MASK0_DATABLOCKEND ) + +/** Data Transfer interrupt mask*/ +#define SDC_MASK0_DATA (SDC_MASK0_DATAEND | SDC_MASK0_DATABLOCKEND ) + +/** + * @brief SDC FIFO Counter Register bit definitions + */ +#define SDC_FIFOCNT_VAL(n) ((uint32_t) n & 0x7FFF) + +/* The number of bytes used to store card status*/ +#define SDC_CARDSTATUS_BYTENUM ((uint32_t) 4) + +/** + * @brief SDC Card bus clock rate definitions + */ +/* Card bus clock in Card Identification Mode */ +#define SDC_IDENT_CLOCK_RATE (400000) /* 400KHz */ +/* Card bus clock in Data Transfer Mode */ +#define SDC_TRAN_CLOCK_RATE (20000000) /* 20MHz */ + +/** + * @brief SDC Power Control Options + */ +typedef enum SDC_PWR_CTRL { + SDC_POWER_OFF = 0, /*!< Power-off */ + SDC_POWER_UP = 2, /*!< Power-up */ + SDC_POWER_ON = 3, /*!< Power-on */ +} SDC_PWR_CTRL_T; + +/** + * @brief SDC Clock Control Options + */ +typedef enum SDC_CLOCK_CTRL { + SDC_CLOCK_ENABLE = 8, /*!< Enable SD Card Bus Clock */ + SDC_CLOCK_POWER_SAVE = 9, /*!< Disable SD_CLK output when bus is idle */ + SDC_CLOCK_DIVIDER_BYPASS = 10, /*!< Enable bypass of clock divide logic */ + SDC_CLOCK_WIDEBUS_MODE = 11, /*!< Enable wide bus mode (SD_DAT[3:0] is used instead of SD_DAT[0]) */ +} SDC_CLOCK_CTRL_T; + +/** + * @brief SDC Response type + */ +typedef enum SDC_RESPONSE { + SDC_NO_RESPONSE = SDC_COMMAND_NO_RSP, /*!< No response */ + SDC_SHORT_RESPONSE = SDC_COMMAND_SHORT_RSP, /*!< Short response */ + SDC_LONG_RESPONSE = SDC_COMMAND_LONG_RSP, /*!< Long response */ +} SDC_RESPONSE_T; + +/** + * @brief SDC Data Transfer Direction definitions + */ +typedef enum SDC_TRANSFER_DIR { + SDC_TRANSFER_DIR_FROMCARD = SDC_DATACTRL_DIR_FROMCARD, /*!< Transfer from card */ + SDC_TRANSFER_DIR_TOCARD = SDC_DATACTRL_DIR_TOCARD, /*!< Transfer to card */ +} SDC_TRANSFER_DIR_T; + +/** + * @brief SDC Data Transfer Mode definitions + */ +typedef enum SDC_TRANSFER_MODE { + SDC_TRANSFER_MODE_STREAM = SDC_DATACTRL_XFER_MODE_STREAM, /*!< Stream transfer mode */ + SDC_TRANSFER_MODE_BLOCK = SDC_DATACTRL_XFER_MODE_BLOCK, /*!< Block transfer mode */ +} SDC_TRANSFER_MODE_T; + +/** + * @brief SDC Data Block size definitions (in bytes) + */ +typedef enum SDC_BLOCK_SIZE { + SDC_BLOCK_SIZE_1 = 0, /*!< Block size - 1 byte */ + SDC_BLOCK_SIZE_2, /*!< Block size - 2 bytes */ + SDC_BLOCK_SIZE_4, /*!< Block size - 4 bytes */ + SDC_BLOCK_SIZE_8, /*!< Block size - 8 bytes */ + SDC_BLOCK_SIZE_16, /*!< Block size - 16 bytes */ + SDC_BLOCK_SIZE_32, /*!< Block size - 32 bytes */ + SDC_BLOCK_SIZE_64, /*!< Block size - 64 bytes */ + SDC_BLOCK_SIZE_128, /*!< Block size - 128 bytes */ + SDC_BLOCK_SIZE_256, /*!< Block size - 256 bytes */ + SDC_BLOCK_SIZE_512, /*!< Block size - 512 bytes */ + SDC_BLOCK_SIZE_1024, /*!< Block size - 1024 bytes */ + SDC_BLOCK_SIZE_2048, /*!< Block size - 2048 bytes */ +} SDC_BLOCK_SIZE_T; + +/** + * @brief SDC Return code definitions + */ +typedef enum CHIP_SDC_RET_CODE { + SDC_RET_OK = 0, + SDC_RET_CMD_FAILED = -1, + SDC_RET_BAD_PARAMETERS = -2, + SDC_RET_BUS_NOT_IDLE = -3, + SDC_RET_TIMEOUT = -4, + SDC_RET_ERR_STATE = -5, + SDC_RET_NOT_READY = -6, + SDC_RET_FAILED = -7, +} CHIP_SDC_RET_CODE_T; + +/** + * @brief SDC Command Response structure + */ +typedef struct { + uint8_t CmdIndex; /*!< Command Index of the command response received */ + uint32_t Data[SDC_CARDSTATUS_BYTENUM]; /* Card Status which can be stored in 1 or 4 bytes */ +} SDC_RESP_T; + +/** + * @brief SDC Data Transfer Setup structure + */ +typedef struct { + uint16_t BlockNum; /*!< The number of block which will be transfered */ + SDC_BLOCK_SIZE_T BlockSize; /*!< Data Block Length */ + SDC_TRANSFER_DIR_T Dir; /*!< Direction */ + SDC_TRANSFER_MODE_T Mode; /*!< Mode */ + bool DMAUsed; /*!< true: DMA used */ + uint32_t Timeout; /*!< Data Transfer timeout periods (in Card Bus Clock)*/ +} SDC_DATA_TRANSFER_T; + +/** + * @brief Set the power state of SDC peripheral + * @param pSDC : Pointer to SDC register block + * @param pwrMode : Power mode + * @param flag : Output control flag + * @return Nothing + * @note When the external power supply is switched on, the software first enters the power-up + * state, and waits until the supply output is stable before moving to the power-on state. + * During the power-up state, SD_PWR is set HIGH. The card bus outlets are disabled + * during both states. + * flag is or-ed bit value of SDC_PWR_OPENDRAIN and SDC_PWR_ROD + */ +void Chip_SDC_PowerControl(LPC_SDC_T *pSDC, SDC_PWR_CTRL_T pwrMode, uint32_t flag); + +/** + * @brief Set clock divider value for SDC peripheral + * @param pSDC : Pointer to SDC register block + * @param div : clock divider + * @return Nothing + * @note While the SD card interface is in identification mode, the SD_CLK frequency must be less + * than 400 kHz. The clock frequency can be changed to the maximum card bus frequency + * when relative card addresses are assigned to all cards. + * SD_CLK frequency = MCLK / [2x(ClkDiv+1)]. + */ +void Chip_SDC_SetClockDiv(LPC_SDC_T *pSDC, uint8_t div); + +/** + * @brief Set or Reset clock control of SDC peripheral + * @param pSDC : Pointer to SDC register block + * @param ctrlType : Clock Control type + * @param NewState : New State to set + * @return Nothing + */ +void Chip_SDC_ClockControl(LPC_SDC_T *pSDC, SDC_CLOCK_CTRL_T ctrlType, + FunctionalState NewState); + +/** + * @brief Set the clock frequency for SDC peripheral + * @param pSDC : Pointer to SDC peripheral base address + * @param freq : Expected clock frequency + * @return None + */ +void Chip_SDC_SetClock(LPC_SDC_T *pSDC, uint32_t freq); + +/** + * @brief Set SDC Command Information + * @param pSDC : Pointer to SDC register block + * @param Cmd : Command value + * @param Arg : Argument for the command + * @return Nothing + */ +void Chip_SDC_SetCommand(LPC_SDC_T *pSDC, uint32_t Cmd, uint32_t Arg); + +/** + * @brief Reset SDC Command Information + * @param pSDC : Pointer to SDC register block + * @return Nothing + */ +void Chip_SDC_ResetCommand(LPC_SDC_T *pSDC); + +/** + * @brief Get SDC Response + * @param pSDC : Pointer to SDC register block + * @param pResp : Pointer to buffer storing response data + * @return Nothing + */ +void Chip_SDC_GetResp(LPC_SDC_T *pSDC, SDC_RESP_T *pResp); + +/** + * @brief Set SDC Data Timeout Period + * @param pSDC : Pointer to SDC register block + * @param timeout : Data timeout value in card bus clock periods + * @return Nothing + */ +STATIC INLINE void Chip_SDC_SetDataTimer(LPC_SDC_T *pSDC, uint32_t timeout) +{ + pSDC->DATATIMER = timeout; +} + +/** + * @brief Set SDC Data Transfer Information + * @param pSDC : Pointer to SDC register block + * @param pTransfer : Pointer to Data Transfer structure + * @return Nothing + */ +void Chip_SDC_SetDataTransfer(LPC_SDC_T *pSDC, SDC_DATA_TRANSFER_T *pTransfer); + +/** + * @brief Write Data to FIFO + * @param pSDC : Pointer to SDC register block + * @param pSrc : Pointer to data buffer + * @param bFirstHalf : true (write to the first half of FIFO) false (write to the second half of FIFO) + * @return Nothing + */ +void Chip_SDC_WriteFIFO(LPC_SDC_T *pSDC, uint32_t *pSrc, bool bFirstHalf); + +/** + * @brief Write Data to FIFO + * @param pSDC : Pointer to SDC register block + * @param pDst : The buffer hold the data read + * @param bFirstHalf : true (read the first half of FIFO) false (read the second half of FIFO) + * @return Nothing + */ +void Chip_SDC_ReadFIFO(LPC_SDC_T *pSDC, uint32_t *pDst, bool bFirstHalf); + +/** + * @brief Get status of SDC Peripheral + * @param pSDC : Pointer to SDC register block + * @return Status (Or-ed bit value of SDC_STATUS_*) + */ +STATIC INLINE uint32_t Chip_SDC_GetStatus(LPC_SDC_T *pSDC) +{ + return pSDC->STATUS; +} + +/** + * @brief Clear status of SDC Peripheral + * @param pSDC : Pointer to SDC register block + * @param flag : Status flag(s) to be cleared (Or-ed bit value of SDC_CLEAR_*) + * @return None + */ +STATIC INLINE void Chip_SDC_ClearStatus(LPC_SDC_T *pSDC, uint32_t flag) +{ + pSDC->CLEAR = flag; +} + +/** + * @brief Set interrupt mask for SDC Peripheral + * @param pSDC : Pointer to SDC register block + * @param mask : Interrupt mask (Or-ed bit value of SDC_MASK0_*) + * @return None + */ +STATIC INLINE void Chip_SDC_SetIntMask(LPC_SDC_T *pSDC, uint32_t mask) +{ + pSDC->MASK0 = mask; +} + +/** + * @brief Initialize the SDC card controller + * @param pSDC : Pointer to SDC register block + * @return None + */ +void Chip_SDC_Init(LPC_SDC_T *pSDC); + +/** + * @brief Deinitialise SDC peripheral + * @param pSDC : Pointer to SDC peripheral base address + * @return None + */ +void Chip_SDC_DeInit(LPC_SDC_T *pSDC); + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __SDC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc.h b/hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc.h new file mode 100644 index 000000000..878246787 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc.h @@ -0,0 +1,450 @@ +/* + * @brief Common definitions used in SD/MMC cards + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __SDMMC_H +#define __SDMMC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup CHIP_SDMMC_Definitions CHIP: Common SD/MMC definitions + * @ingroup CHIP_Common + * @{ + */ + +/** + * @brief OCR Register definitions + */ +/** Support voltage range 2.0-2.1 (this bit is reserved in SDC)*/ +#define SDC_OCR_20_21 (((uint32_t) 1) << 8) +/** Support voltage range 2.1-2.2 (this bit is reserved in SDC)*/ +#define SDC_OCR_21_22 (((uint32_t) 1) << 9) +/** Support voltage range 2.2-2.3 (this bit is reserved in SDC)*/ +#define SDC_OCR_22_23 (((uint32_t) 1) << 10) +/** Support voltage range 2.3-2.4 (this bit is reserved in SDC)*/ +#define SDC_OCR_23_24 (((uint32_t) 1) << 11) +/** Support voltage range 2.4-2.5 (this bit is reserved in SDC)*/ +#define SDC_OCR_24_25 (((uint32_t) 1) << 12) +/** Support voltage range 2.5-2.6 (this bit is reserved in SDC)*/ +#define SDC_OCR_25_26 (((uint32_t) 1) << 13) +/** Support voltage range 2.6-2.7 (this bit is reserved in SDC)*/ +#define SDC_OCR_26_27 (((uint32_t) 1) << 14) +/** Support voltage range 2.7-2.8 */ +#define SDC_OCR_27_28 (((uint32_t) 1) << 15) +/** Support voltage range 2.8-2.9*/ +#define SDC_OCR_28_29 (((uint32_t) 1) << 16) +/** Support voltage range 2.9-3.0 */ +#define SDC_OCR_29_30 (((uint32_t) 1) << 17) +/** Support voltage range 3.0-3.1 */ +#define SDC_OCR_30_31 (((uint32_t) 1) << 18) +/** Support voltage range 3.1-3.2 */ +#define SDC_OCR_31_32 (((uint32_t) 1) << 19) +/** Support voltage range 3.2-3.3 */ +#define SDC_OCR_32_33 (((uint32_t) 1) << 20) +/** Support voltage range 3.3-3.4 */ +#define SDC_OCR_33_34 (((uint32_t) 1) << 21) +/** Support voltage range 3.4-3.5 */ +#define SDC_OCR_34_35 (((uint32_t) 1) << 22) +/** Support voltage range 3.5-3.6 */ +#define SDC_OCR_35_36 (((uint32_t) 1) << 23) +/** Support voltage range 2.7-3.6 */ +#define SDC_OCR_27_36 ((uint32_t) 0x00FF8000) +/** Card Capacity Status (CCS). (this bit is reserved in MMC) */ +#define SDC_OCR_HC_CCS (((uint32_t) 1) << 30) +/** Card power up status bit */ +#define SDC_OCR_IDLE (((uint32_t) 1) << 31) +#define SDC_OCR_BUSY (((uint32_t) 0) << 31) + +/* SD/MMC commands - this matrix shows the command, response types, and + supported card type for that command. + Command Number Resp SD MMC + ----------------------- ------ ----- --- --- + Reset (go idle) CMD0 NA x x + Send op condition CMD1 R3 x + All send CID CMD2 R2 x x + Send relative address CMD3 R1 x + Send relative address CMD3 R6 x + Program DSR CMD4 NA x + Select/deselect card CMD7 R1b x + Select/deselect card CMD7 R1 x + Send CSD CMD9 R2 x x + Send CID CMD10 R2 x x + Read data until stop CMD11 R1 x x + Stop transmission CMD12 R1/b x x + Send status CMD13 R1 x x + Go inactive state CMD15 NA x x + Set block length CMD16 R1 x x + Read single block CMD17 R1 x x + Read multiple blocks CMD18 R1 x x + Write data until stop CMD20 R1 x + Setblock count CMD23 R1 x + Write single block CMD24 R1 x x + Write multiple blocks CMD25 R1 x x + Program CID CMD26 R1 x + Program CSD CMD27 R1 x x + Set write protection CMD28 R1b x x + Clear write protection CMD29 R1b x x + Send write protection CMD30 R1 x x + Erase block start CMD32 R1 x + Erase block end CMD33 R1 x + Erase block start CMD35 R1 x + Erase block end CMD36 R1 x + Erase blocks CMD38 R1b x + Fast IO CMD39 R4 x + Go IRQ state CMD40 R5 x + Lock/unlock CMD42 R1b x + Application command CMD55 R1 x + General command CMD56 R1b x + + *** SD card application commands - these must be preceded with *** + *** MMC CMD55 application specific command first *** + Set bus width ACMD6 R1 x + Send SD status ACMD13 R1 x + Send number WR blocks ACMD22 R1 x + Set WR block erase cnt ACMD23 R1 x + Send op condition ACMD41 R3 x + Set clear card detect ACMD42 R1 x + Send CSR ACMD51 R1 x */ + +/** + * @brief SD/MMC application specific commands for SD cards only - these + * must be preceded by the SDMMC CMD55 to work correctly + */ +typedef enum { + SD_SET_BUS_WIDTH, /*!< Set the SD bus width */ + SD_SEND_STATUS, /*!< Send the SD card status */ + SD_SEND_WR_BLOCKS, /*!< Send the number of written clocks */ + SD_SET_ERASE_COUNT, /*!< Set the number of blocks to pre-erase */ + SD_SENDOP_COND, /*!< Send the OCR register (init) */ + SD_CLEAR_CARD_DET, /*!< Set or clear the 50K detect pullup */ + SD_SEND_SCR, /*!< Send the SD configuration register */ + SD_INVALID_APP_CMD /*!< Invalid SD application command */ +} SD_APP_CMD_T; + +/** + * @brief Possible SDMMC response types + */ +typedef enum { + SDMMC_RESPONSE_R1, /*!< Typical status */ + SDMMC_RESPONSE_R1B, /*!< Typical status with busy */ + SDMMC_RESPONSE_R2, /*!< CID/CSD registers (CMD2 and CMD10) */ + SDMMC_RESPONSE_R3, /*!< OCR register (CMD1, ACMD41) */ + SDMMC_RESPONSE_R4, /*!< Fast IO response word */ + SDMMC_RESPONSE_R5, /*!< Go IRQ state response word */ + SDMMC_RESPONSE_R6, /*!< Published RCA response */ + SDMMC_RESPONSE_NONE /*!< No response expected */ +} SDMMC_RESPONSE_T; + +/** + * @brief Possible SDMMC card state types + */ +typedef enum { + SDMMC_IDLE_ST = 0, /*!< Idle state */ + SDMMC_READY_ST, /*!< Ready state */ + SDMMC_IDENT_ST, /*!< Identification State */ + SDMMC_STBY_ST, /*!< standby state */ + SDMMC_TRAN_ST, /*!< transfer state */ + SDMMC_DATA_ST, /*!< Sending-data State */ + SDMMC_RCV_ST, /*!< Receive-data State */ + SDMMC_PRG_ST, /*!< Programming State */ + SDMMC_DIS_ST /*!< Disconnect State */ +} SDMMC_STATE_T; + +/* Function prototype for event setup function */ +typedef void (*SDMMC_EVSETUP_FUNC_T)(void *); + +/* Function prototype for wait for event function */ +typedef uint32_t (*SDMMC_EVWAIT_FUNC_T)(void); + +/* Function prototype for milliSecond delay function */ +typedef void (*SDMMC_MSDELAY_FUNC_T)(uint32_t); + +/** + * @brief SD/MMC Card specific setup data structure + */ +typedef struct { + uint32_t response[4]; /*!< Most recent response */ + uint32_t cid[4]; /*!< CID of acquired card */ + uint32_t csd[4]; /*!< CSD of acquired card */ + uint32_t ext_csd[512 / 4]; /*!< Ext CSD */ + uint32_t card_type; /*!< Card Type */ + uint16_t rca; /*!< Relative address assigned to card */ + uint32_t speed; /*!< Speed */ + uint32_t block_len; /*!< Card sector size */ + uint32_t device_size; /*!< Device Size */ + uint32_t blocknr; /*!< Block Number */ + uint32_t clk_rate; /*! Clock rate */ + SDMMC_EVSETUP_FUNC_T evsetup_cb; /*!< Function to setup event information */ + SDMMC_EVWAIT_FUNC_T waitfunc_cb; /*!< Function to wait for event */ + SDMMC_MSDELAY_FUNC_T msdelay_func; /*!< Function to sleep in ms */ +} SDMMC_CARD_T; + +/** + * @brief SD/MMC commands, arguments and responses + * Standard SD/MMC commands (3.1) type argument response + */ +/* class 1 */ +#define MMC_GO_IDLE_STATE 0 /* bc */ +#define MMC_SEND_OP_COND 1 /* bcr [31:0] OCR R3 */ +#define MMC_ALL_SEND_CID 2 /* bcr R2 */ +#define MMC_SET_RELATIVE_ADDR 3 /* ac [31:16] RCA R1 */ +#define MMC_SET_DSR 4 /* bc [31:16] RCA */ +#define MMC_SELECT_CARD 7 /* ac [31:16] RCA R1 */ +#define MMC_SEND_EXT_CSD 8 /* bc R1 */ +#define MMC_SEND_CSD 9 /* ac [31:16] RCA R2 */ +#define MMC_SEND_CID 10 /* ac [31:16] RCA R2 */ +#define MMC_STOP_TRANSMISSION 12 /* ac R1b */ +#define MMC_SEND_STATUS 13 /* ac [31:16] RCA R1 */ +#define MMC_GO_INACTIVE_STATE 15 /* ac [31:16] RCA */ + +/* class 2 */ +#define MMC_SET_BLOCKLEN 16 /* ac [31:0] block len R1 */ +#define MMC_READ_SINGLE_BLOCK 17 /* adtc [31:0] data addr R1 */ +#define MMC_READ_MULTIPLE_BLOCK 18 /* adtc [31:0] data addr R1 */ + +/* class 3 */ +#define MMC_WRITE_DAT_UNTIL_STOP 20 /* adtc [31:0] data addr R1 */ + +/* class 4 */ +#define MMC_SET_BLOCK_COUNT 23 /* adtc [31:0] data addr R1 */ +#define MMC_WRITE_BLOCK 24 /* adtc [31:0] data addr R1 */ +#define MMC_WRITE_MULTIPLE_BLOCK 25 /* adtc R1 */ +#define MMC_PROGRAM_CID 26 /* adtc R1 */ +#define MMC_PROGRAM_CSD 27 /* adtc R1 */ + +/* class 6 */ +#define MMC_SET_WRITE_PROT 28 /* ac [31:0] data addr R1b */ +#define MMC_CLR_WRITE_PROT 29 /* ac [31:0] data addr R1b */ +#define MMC_SEND_WRITE_PROT 30 /* adtc [31:0] wpdata addr R1 */ + +/* class 5 */ +#define MMC_ERASE_GROUP_START 35 /* ac [31:0] data addr R1 */ +#define MMC_ERASE_GROUP_END 36 /* ac [31:0] data addr R1 */ +#define MMC_ERASE 37 /* ac R1b */ +#define SD_ERASE_WR_BLK_START 32 /* ac [31:0] data addr R1 */ +#define SD_ERASE_WR_BLK_END 33 /* ac [31:0] data addr R1 */ +#define SD_ERASE 38 /* ac R1b */ + +/* class 9 */ +#define MMC_FAST_IO 39 /* ac R4 */ +#define MMC_GO_IRQ_STATE 40 /* bcr R5 */ + +/* class 7 */ +#define MMC_LOCK_UNLOCK 42 /* adtc R1b */ + +/* class 8 */ +#define MMC_APP_CMD 55 /* ac [31:16] RCA R1 */ +#define MMC_GEN_CMD 56 /* adtc [0] RD/WR R1b */ + +/* SD commands type argument response */ +/* class 8 */ +/* This is basically the same command as for MMC with some quirks. */ +#define SD_SEND_RELATIVE_ADDR 3 /* ac R6 */ +#define SD_CMD8 8 /* bcr [31:0] OCR R3 */ + +/* Application commands */ +#define SD_APP_SET_BUS_WIDTH 6 /* ac [1:0] bus width R1 */ +#define SD_APP_OP_COND 41 /* bcr [31:0] OCR R1 (R4) */ +#define SD_APP_SEND_SCR 51 /* adtc R1 */ + +/** + * @brief MMC status in R1
+ * Type
+ * e : error bit
+ * s : status bit
+ * r : detected and set for the actual command response
+ * x : detected and set during command execution. the host must poll + * the card by sending status command in order to read these bits. + * Clear condition
+ * a : according to the card state
+ * b : always related to the previous command. Reception of + * a valid command will clear it (with a delay of one command)
+ * c : clear by read
+ */ + +#define R1_OUT_OF_RANGE (1UL << 31) /* er, c */ +#define R1_ADDRESS_ERROR (1 << 30) /* erx, c */ +#define R1_BLOCK_LEN_ERROR (1 << 29) /* er, c */ +#define R1_ERASE_SEQ_ERROR (1 << 28) /* er, c */ +#define R1_ERASE_PARAM (1 << 27) /* ex, c */ +#define R1_WP_VIOLATION (1 << 26) /* erx, c */ +#define R1_CARD_IS_LOCKED (1 << 25) /* sx, a */ +#define R1_LOCK_UNLOCK_FAILED (1 << 24) /* erx, c */ +#define R1_COM_CRC_ERROR (1 << 23) /* er, b */ +#define R1_ILLEGAL_COMMAND (1 << 22) /* er, b */ +#define R1_CARD_ECC_FAILED (1 << 21) /* ex, c */ +#define R1_CC_ERROR (1 << 20) /* erx, c */ +#define R1_ERROR (1 << 19) /* erx, c */ +#define R1_UNDERRUN (1 << 18) /* ex, c */ +#define R1_OVERRUN (1 << 17) /* ex, c */ +#define R1_CID_CSD_OVERWRITE (1 << 16) /* erx, c, CID/CSD overwrite */ +#define R1_WP_ERASE_SKIP (1 << 15) /* sx, c */ +#define R1_CARD_ECC_DISABLED (1 << 14) /* sx, a */ +#define R1_ERASE_RESET (1 << 13) /* sr, c */ +#define R1_STATUS(x) (x & 0xFFFFE000) +#define R1_CURRENT_STATE(x) ((x & 0x00001E00) >> 9) /* sx, b (4 bits) */ +#define R1_READY_FOR_DATA (1 << 8) /* sx, a */ +#define R1_APP_CMD (1 << 5) /* sr, c */ + +/** + * @brief SD/MMC card OCR register bits + */ +#define OCR_ALL_READY (1UL << 31) /* Card Power up status bit */ +#define OCR_HC_CCS (1 << 30) /* High capacity card */ +#define OCR_VOLTAGE_RANGE_MSK (0x00FF8000) + +#define SD_SEND_IF_ARG 0x000001AA +#define SD_SEND_IF_ECHO_MSK 0x000000FF +#define SD_SEND_IF_RESP 0x000000AA + +/** + * @brief R3 response definitions + */ +#define CMDRESP_R3_OCR_VAL(n) (((uint32_t) n) & 0xFFFFFF) +#define CMDRESP_R3_S18A (((uint32_t) 1 ) << 24) +#define CMDRESP_R3_HC_CCS (((uint32_t) 1 ) << 30) +#define CMDRESP_R3_INIT_COMPLETE (((uint32_t) 1 ) << 31) + +/** + * @brief R6 response definitions + */ +#define CMDRESP_R6_RCA_VAL(n) (((uint32_t) (n >> 16)) & 0xFFFF) +#define CMDRESP_R6_CARD_STATUS(n) (((uint32_t) (n & 0x1FFF)) | \ + ((n & (1 << 13)) ? (1 << 19) : 0) | \ + ((n & (1 << 14)) ? (1 << 22) : 0) | \ + ((n & (1 << 15)) ? (1 << 23) : 0)) + +/** + * @brief R7 response definitions + */ +/** Echo-back of check-pattern */ +#define CMDRESP_R7_CHECK_PATTERN(n) (((uint32_t) n ) & 0xFF) +/** Voltage accepted */ +#define CMDRESP_R7_VOLTAGE_ACCEPTED (((uint32_t) 1 ) << 8) + +/** + * @brief CMD3 command definitions + */ +/** Card Address */ +#define CMD3_RCA(n) (((uint32_t) (n & 0xFFFF) ) << 16) + +/** + * @brief CMD7 command definitions + */ +/** Card Address */ +#define CMD7_RCA(n) (((uint32_t) (n & 0xFFFF) ) << 16) + +/** + * @brief CMD8 command definitions + */ +/** Check pattern */ +#define CMD8_CHECKPATTERN(n) (((uint32_t) (n & 0xFF) ) << 0) +/** Recommended pattern */ +#define CMD8_DEF_PATTERN (0xAA) +/** Voltage supplied.*/ +#define CMD8_VOLTAGESUPPLIED_27_36 (((uint32_t) 1 ) << 8) + +/** + * @brief CMD9 command definitions + */ +#define CMD9_RCA(n) (((uint32_t) (n & 0xFFFF) ) << 16) + +/** + * @brief CMD13 command definitions + */ +#define CMD13_RCA(n) (((uint32_t) (n & 0xFFFF) ) << 16) + +/** + * @brief APP_CMD command definitions + */ +#define CMD55_RCA(n) (((uint32_t) (n & 0xFFFF) ) << 16) + +/** + * @brief ACMD41 command definitions + */ +#define ACMD41_OCR(n) (((uint32_t) n) & 0xFFFFFF) +#define ACMD41_S18R (((uint32_t) 1 ) << 24) +#define ACMD41_XPC (((uint32_t) 1 ) << 28) +#define ACMD41_HCS (((uint32_t) 1 ) << 30) + +/** + * @brief ACMD6 command definitions + */ +#define ACMD6_BUS_WIDTH(n) ((uint32_t) n & 0x03) +#define ACMD6_BUS_WIDTH_1 (0) +#define ACMD6_BUS_WIDTH_4 (2) + +/** @brief Card type defines + */ +#define CARD_TYPE_SD (1 << 0) +#define CARD_TYPE_4BIT (1 << 1) +#define CARD_TYPE_8BIT (1 << 2) +#define CARD_TYPE_HC (OCR_HC_CCS)/*!< high capacity card > 2GB */ + +/** + * @brief SD/MMC sector size in bytes + */ +#define MMC_SECTOR_SIZE 512 + +/** + * @brief Typical enumeration clock rate + */ +#define SD_MMC_ENUM_CLOCK 400000 + +/** + * @brief Max MMC clock rate + */ +#define MMC_MAX_CLOCK 20000000 + +/** + * @brief Type 0 MMC card max clock rate + */ +#define MMC_LOW_BUS_MAX_CLOCK 26000000 + +/** + * @brief Type 1 MMC card max clock rate + */ +#define MMC_HIGH_BUS_MAX_CLOCK 52000000 + +/** + * @brief Max SD clock rate + */ +#define SD_MAX_CLOCK 25000000 + +#ifdef __cplusplus +} +#endif + +/** + * @} + */ + +#endif /* __SDMMC_H */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc_17xx_40xx.h new file mode 100644 index 000000000..75c2f2b36 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/sdmmc_17xx_40xx.h @@ -0,0 +1,202 @@ +/* + * @brief LPC17xx/40xx SDMMC Card Interface driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __SDMMC_17XX_40XX_H_ +#define __SDMMC_17XX_40XX_H_ + +#include "sdmmc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup SDMMC_17XX_40XX CHIP: LPC17xx/40xx SDMMC card driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/* + * SD/MMC Response type definitions + */ +#define CMDRESP_NONE_TYPE (SDC_COMMAND_NO_RSP) +#define CMDRESP_R1_TYPE (SDC_COMMAND_SHORT_RSP) +#define CMDRESP_R1b_TYPE (SDC_COMMAND_SHORT_RSP) +#define CMDRESP_R2_TYPE (SDC_COMMAND_LONG_RSP) +#define CMDRESP_R3_TYPE (SDC_COMMAND_SHORT_RSP) +#define CMDRESP_R6_TYPE (SDC_COMMAND_SHORT_RSP) +#define CMDRESP_R7_TYPE (SDC_COMMAND_SHORT_RSP) + +#ifdef SDC_DMA_ENABLE + +/** + * @brief SDC Event structure + */ +typedef struct { + uint8_t DmaChannel; /*!< DMA Channel used for transfer data */ +} SDMMC_EVENT_T; + +#else + +/** + * @brief SDC Event structure + */ +typedef struct { + void *Buffer; /*!< Pointer to data buffer */ + uint32_t Size; /*!< Transfer size */ + uint32_t Index; /*!< Current transfer index */ + uint8_t Dir; /*!< Transfer direction 0: transmit, 1: receive */ +} SDMMC_EVENT_T; +#endif /* SDC_DMA_ENABLE */ + +/* + * SD command values (Command Index, Response) + */ +#define SD_GO_IDLE_STATE (SDC_COMMAND_INDEX(MMC_GO_IDLE_STATE) | CMDRESP_NONE_TYPE | SDC_COMMAND_INTERRUPT) /*!< GO_IDLE_STATE(MMC) or RESET(SD) */ +#define SD_CMD1_SEND_OP_COND (SDC_COMMAND_INDEX(MMC_SEND_OP_COND) | CMDRESP_R3_TYPE | 0) /*!< SEND_OP_COND(MMC) or ACMD41(SD) */ +#define SD_CMD2_ALL_SEND_CID (SDC_COMMAND_INDEX(MMC_ALL_SEND_CID) | CMDRESP_R2_TYPE | 0) /*!< ALL_SEND_CID */ +#define SD_CMD3_SET_RELATIVE_ADDR (SDC_COMMAND_INDEX(MMC_SET_RELATIVE_ADDR) | CMDRESP_R1_TYPE | 0) /*!< SET_RELATE_ADDR */ +#define SD_CMD3_SEND_RELATIVE_ADDR (SDC_COMMAND_INDEX(SD_SEND_RELATIVE_ADDR) | CMDRESP_R6_TYPE | 0) /*!< SEND_RELATE_ADDR */ +#define SD_CMD7_SELECT_CARD (SDC_COMMAND_INDEX(MMC_SELECT_CARD) | CMDRESP_R1b_TYPE | 0) /*!< SELECT/DESELECT_CARD */ +#define SD_CMD8_SEND_IF_COND (SDC_COMMAND_INDEX(SD_CMD8) | CMDRESP_R7_TYPE | 0) /*!< SEND_IF_COND */ +#define SD_CMD9_SEND_CSD (SDC_COMMAND_INDEX(MMC_SEND_CSD) | CMDRESP_R2_TYPE | 0) /*!< SEND_CSD */ +#define SD_CMD12_STOP_TRANSMISSION (SDC_COMMAND_INDEX(MMC_STOP_TRANSMISSION) | CMDRESP_R1_TYPE | 0) /*!< STOP_TRANSMISSION */ +#define SD_CMD13_SEND_STATUS (SDC_COMMAND_INDEX(MMC_SEND_STATUS) | CMDRESP_R1_TYPE | 0) /*!< SEND_STATUS */ + +/* Block-Oriented Read Commands (class 2) */ +#define SD_CMD16_SET_BLOCKLEN (SDC_COMMAND_INDEX(MMC_SET_BLOCKLEN) | CMDRESP_R1_TYPE | 0) /*!< SET_BLOCK_LEN */ +#define SD_CMD17_READ_SINGLE_BLOCK (SDC_COMMAND_INDEX(MMC_READ_SINGLE_BLOCK) | CMDRESP_R1_TYPE | 0) /*!< READ_SINGLE_BLOCK */ +#define SD_CMD18_READ_MULTIPLE_BLOCK (SDC_COMMAND_INDEX(MMC_READ_MULTIPLE_BLOCK) | CMDRESP_R1_TYPE | 0) /*!< READ_MULTIPLE_BLOCK */ + +/* Block-Oriented Write Commands (class 4) */ +#define SD_CMD24_WRITE_BLOCK (SDC_COMMAND_INDEX(MMC_WRITE_BLOCK) | CMDRESP_R1_TYPE | 0) /*!< WRITE_BLOCK */ +#define SD_CMD25_WRITE_MULTIPLE_BLOCK (SDC_COMMAND_INDEX(MMC_WRITE_MULTIPLE_BLOCK) | CMDRESP_R1_TYPE | 0) /*!< WRITE_MULTIPLE_BLOCK */ + +/* Erase Commands (class 5) */ +#define SD_CMD32_ERASE_WR_BLK_START (SDC_COMMAND_INDEX(SD_ERASE_WR_BLK_START) | CMDRESP_R1_TYPE | 0) /*!< ERASE_WR_BLK_START */ +#define SD_CMD33_ERASE_WR_BLK_END (SDC_COMMAND_INDEX(SD_ERASE_WR_BLK_END) | CMDRESP_R1_TYPE | 0) /*!< ERASE_WR_BLK_END */ +#define SD_CMD38_ERASE (SDC_COMMAND_INDEX(SD_ERASE) | CMDRESP_R1b_TYPE | 0) /*!< ERASE */ + +/* Application-Specific Commands (class 8) */ +#define SD_CMD55_APP_CMD (SDC_COMMAND_INDEX(MMC_APP_CMD) | CMDRESP_R1_TYPE | 0) /*!< APP_CMD */ +#define SD_ACMD6_SET_BUS_WIDTH (SDC_COMMAND_INDEX(SD_APP_SET_BUS_WIDTH) | CMDRESP_R1_TYPE | 0) /*!< SET_BUS_WIDTH */ +#define SD_ACMD13_SEND_SD_STATUS (SDC_COMMAND_INDEX(MMC_SEND_STATUS) | CMDRESP_R1_TYPE | 0) /*!< SEND_SD_STATUS */ +#define SD_ACMD41_SD_SEND_OP_COND (SDC_COMMAND_INDEX(SD_APP_OP_COND) | CMDRESP_R3_TYPE | 0) /*!< SD_SEND_OP_COND */ + +/** + * @brief SD card interrupt service routine + * @param pSDC : Pointer to SDC peripheral base address + * @param txBuf : Pointer to TX Buffer (If it is NULL, dont send data to card) + * @param txCnt : Pointer to buffer storing the current transmit index + * @param rxBuf : Pointer to RX Buffer (If it is NULL, dont read data from card) + * @param rxCnt : Pointer to buffer storing the current receive index + * @return Positive value: Data transfer + * Negative value: Error in data transfer + * Zero: Data transfer completed + */ +int32_t Chip_SDMMC_IRQHandler (LPC_SDC_T *pSDC, uint8_t *txBuf, uint32_t *txCnt, + uint8_t *rxBuf, uint32_t *rxCnt); + +/** + * @brief Function to enumerate the SD/MMC/SDHC/MMC+ cards + * @param pSDC : Pointer to SDC peripheral base address + * @param pCardInfo : Pointer to pre-allocated card info structure + * @return 1 if a card is acquired, otherwise 0 + */ +int32_t Chip_SDMMC_Acquire(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo); + +/** + * @brief Get card's current state (idle, transfer, program, etc.) + * @param pSDC : Pointer to SDC peripheral base address + * @param pCardInfo : Pointer to pre-allocated card info structure + * @return Current SD card state + */ +SDMMC_STATE_T Chip_SDMMC_GetCardState(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo); + +/** + * @brief Get 'card status' of SD Memory card + * @param pSDC : Pointer to SDC peripheral base address + * @param pCardInfo : Pointer to pre-allocated card info structure + * @return Current SD card status + */ +uint32_t Chip_SDMMC_GetCardStatus(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo); + +/** + * @brief Get 'sd status' of SD Memory card + * @param pSDC : Pointer to SDC peripheral base address + * @param pCardInfo : Pointer to pre-allocated card info structure + * @param pStatus : Pointer to buffer storing status (it must be 64-byte-length) + * @return Number of bytes read + */ +int32_t Chip_SDMMC_GetSDStatus(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo, uint32_t *pStatus); + +/** + * @brief Performs the read of data from the SD/MMC card + * @param pSDC : The base of SDC peripheral on the chip + * @param pCardInfo : Pointer to Card information structure + * @param buffer : Pointer to data buffer to copy to + * @param startblock : Start block number + * @param blockNum : Number of block to read + * @return Bytes read, or 0 on error + */ +int32_t Chip_SDMMC_ReadBlocks(LPC_SDC_T *pSDC, + SDMMC_CARD_T *pCardInfo, + void *buffer, + int32_t startblock, + int32_t blockNum); + +/** + * @brief Performs write of data to the SD/MMC card + * @param pSDC : The base of SDC peripheral on the chip + * @param pCardInfo : Pointer to Card information structure + * @param buffer : Pointer to data buffer to copy to + * @param startblock : Start block number + * @param blockNum : Number of block to write + * @return Number of bytes actually written, or 0 on error + */ +int32_t Chip_SDMMC_WriteBlocks(LPC_SDC_T *pSDC, + SDMMC_CARD_T *pCardInfo, + void *buffer, + int32_t startblock, + int32_t blockNum); + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __SDC_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/spi_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/spi_17xx_40xx.h new file mode 100644 index 000000000..56f766454 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/spi_17xx_40xx.h @@ -0,0 +1,416 @@ +/* + * @brief LPC17xx/40xx SPI driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __SPI_17XX_40XX_H_ +#define __SPI_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup SPI_17XX_40XX CHIP: LPC17xx/40xx SPI driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC175X_6X) + +/** + * @brief SPI register block structure + */ +typedef struct { /*!< SPI Structure */ + __IO uint32_t CR; /*!< SPI Control Register. This register controls the operation of the SPI. */ + __I uint32_t SR; /*!< SPI Status Register. This register shows the status of the SPI. */ + __IO uint32_t DR; /*!< SPI Data Register. This bi-directional register provides the transmit and receive data for the SPI. Transmit data is provided to the SPI0 by writing to this register. Data received by the SPI0 can be read from this register. */ + __IO uint32_t CCR; /*!< SPI Clock Counter Register. This register controls the frequency of a master's SCK0. */ + __I uint32_t RESERVED0[3]; + __IO uint32_t INT; /*!< SPI Interrupt Flag. This register contains the interrupt flag for the SPI interface. */ +} LPC_SPI_T; + +/* + * Macro defines for SPI Control register + */ +/* SPI CFG Register BitMask */ +#define SPI_CR_BITMASK ((uint32_t) 0xFFC) +/** Enable of controlling the number of bits per transfer */ +#define SPI_CR_BIT_EN ((uint32_t) (1 << 2)) +/** Mask of field of bit controlling */ +#define SPI_CR_BITS_MASK ((uint32_t) 0xF00) +/** Set the number of bits per a transfer */ +#define SPI_CR_BITS(n) ((uint32_t) ((n << 8) & 0xF00)) /* n is in range 8-16 */ +/** SPI Clock Phase Select*/ +#define SPI_CR_CPHA_FIRST ((uint32_t) (0)) /*Capture data on the first edge, Change data on the following edge*/ +#define SPI_CR_CPHA_SECOND ((uint32_t) (1 << 3)) /*Change data on the first edge, Capture data on the following edge*/ +/** SPI Clock Polarity Select*/ +#define SPI_CR_CPOL_LO ((uint32_t) (0)) /* The rest state of the clock (between frames) is low.*/ +#define SPI_CR_CPOL_HI ((uint32_t) (1 << 4)) /* The rest state of the clock (between frames) is high.*/ +/** SPI Slave Mode Select */ +#define SPI_CR_SLAVE_EN ((uint32_t) 0) +/** SPI Master Mode Select */ +#define SPI_CR_MASTER_EN ((uint32_t) (1 << 5)) +/** SPI MSB First mode enable */ +#define SPI_CR_MSB_FIRST_EN ((uint32_t) 0) /*Data will be transmitted and received in standard order (MSB first).*/ +/** SPI LSB First mode enable */ +#define SPI_CR_LSB_FIRST_EN ((uint32_t) (1 << 6)) /*Data will be transmitted and received in reverse order (LSB first).*/ +/** SPI interrupt enable */ +#define SPI_CR_INT_EN ((uint32_t) (1 << 7)) + +/* + * Macro defines for SPI Status register + */ +/** SPI STAT Register BitMask */ +#define SPI_SR_BITMASK ((uint32_t) 0xF8) +/** Slave abort Flag */ +#define SPI_SR_ABRT ((uint32_t) (1 << 3)) /* When 1, this bit indicates that a slave abort has occurred. */ +/* Mode fault Flag */ +#define SPI_SR_MODF ((uint32_t) (1 << 4)) /* when 1, this bit indicates that a Mode fault error has occurred. */ +/** Read overrun flag*/ +#define SPI_SR_ROVR ((uint32_t) (1 << 5)) /* When 1, this bit indicates that a read overrun has occurred. */ +/** Write collision flag. */ +#define SPI_SR_WCOL ((uint32_t) (1 << 6)) /* When 1, this bit indicates that a write collision has occurred.. */ +/** SPI transfer complete flag. */ +#define SPI_SR_SPIF ((uint32_t) (1 << 7)) /* When 1, this bit indicates when a SPI data transfer is complete.. */ +/** SPI error flag */ +#define SPI_SR_ERROR (SPI_SR_ABRT | SPI_SR_MODF | SPI_SR_ROVR | SPI_SR_WCOL) +/* + * Macro defines for SPI Test Control Register register + */ +/*Enable SPI Test Mode */ +#define SPI_TCR_TEST(n) ((uint32_t) ((n & 0x3F) << 1)) + +/* + * Macro defines for SPI Interrupt register + */ +/** SPI interrupt flag */ +#define SPI_INT_SPIF ((uint32_t) (1 << 0)) + +/** + * Macro defines for SPI Data register + */ +/** Receiver Data */ +#define SPI_DR_DATA(n) ((uint32_t) ((n) & 0xFFFF)) + +/** @brief SPI Mode*/ +typedef enum { + SPI_MODE_MASTER = SPI_CR_MASTER_EN, /* Master Mode */ + SPI_MODE_SLAVE = SPI_CR_SLAVE_EN, /* Slave Mode */ +} SPI_MODE_T; + +/** @brief SPI Clock Mode*/ +typedef enum { + SPI_CLOCK_CPHA0_CPOL0 = SPI_CR_CPOL_LO | SPI_CR_CPHA_FIRST, /**< CPHA = 0, CPOL = 0 */ + SPI_CLOCK_CPHA0_CPOL1 = SPI_CR_CPOL_HI | SPI_CR_CPHA_FIRST, /**< CPHA = 0, CPOL = 1 */ + SPI_CLOCK_CPHA1_CPOL0 = SPI_CR_CPOL_LO | SPI_CR_CPHA_SECOND, /**< CPHA = 1, CPOL = 0 */ + SPI_CLOCK_CPHA1_CPOL1 = SPI_CR_CPOL_HI | SPI_CR_CPHA_SECOND, /**< CPHA = 1, CPOL = 1 */ + SPI_CLOCK_MODE0 = SPI_CLOCK_CPHA0_CPOL0,/**< alias */ + SPI_CLOCK_MODE1 = SPI_CLOCK_CPHA1_CPOL0,/**< alias */ + SPI_CLOCK_MODE2 = SPI_CLOCK_CPHA0_CPOL1,/**< alias */ + SPI_CLOCK_MODE3 = SPI_CLOCK_CPHA1_CPOL1,/**< alias */ +} SPI_CLOCK_MODE_T; + +/** @brief SPI Data Order Mode*/ +typedef enum { + SPI_DATA_MSB_FIRST = SPI_CR_MSB_FIRST_EN, /* Standard Order */ + SPI_DATA_LSB_FIRST = SPI_CR_LSB_FIRST_EN, /* Reverse Order */ +} SPI_DATA_ORDER_T; + +/* + * @brief Number of bits per frame + */ +typedef enum { + SPI_BITS_8 = SPI_CR_BITS(8), /**< 8 bits/frame */ + SPI_BITS_9 = SPI_CR_BITS(9), /**< 9 bits/frame */ + SPI_BITS_10 = SPI_CR_BITS(10), /**< 10 bits/frame */ + SPI_BITS_11 = SPI_CR_BITS(11), /**< 11 bits/frame */ + SPI_BITS_12 = SPI_CR_BITS(12), /**< 12 bits/frame */ + SPI_BITS_13 = SPI_CR_BITS(13), /**< 13 bits/frame */ + SPI_BITS_14 = SPI_CR_BITS(14), /**< 14 bits/frame */ + SPI_BITS_15 = SPI_CR_BITS(15), /**< 15 bits/frame */ + SPI_BITS_16 = SPI_CR_BITS(16), /**< 16 bits/frame */ +} SPI_BITS_T; + +/** SPI callback function type*/ +typedef void (*SPI_CALLBACK_T)(void); +/* + * @brief SPI config format + */ +typedef struct { + SPI_BITS_T bits; /*!< bits/frame */ + SPI_CLOCK_MODE_T clockMode; /*!< Format config: clock phase/polarity */ + SPI_DATA_ORDER_T dataOrder; /*!< Data order (MSB first/LSB first) */ +} SPI_CONFIG_FORMAT_T; + +/* + * @brief SPI data setup structure + */ +typedef struct { + uint8_t *pTxData; /*!< Pointer to transmit data */ + uint8_t *pRxData; /*!< Pointer to receive data */ + uint32_t cnt; /*!< Transfer counter */ + uint32_t length; /*!< Length of transfer data */ + SPI_CALLBACK_T fnBefFrame; /*!< Function to call before sending frame */ + SPI_CALLBACK_T fnAftFrame; /*!< Function to call after sending frame */ + SPI_CALLBACK_T fnBefTransfer; /*!< Function to call before starting a transfer */ + SPI_CALLBACK_T fnAftTransfer; /*!< Function to call after a transfer complete */ +} SPI_DATA_SETUP_T; + +/** + * @brief Get the current status of SPI controller + * @return SPI controller status (Or-ed value of SPI_SR_*) + */ +STATIC INLINE uint32_t Chip_SPI_GetStatus(LPC_SPI_T *pSPI) +{ + return pSPI->SR; +} + +/** + * @brief Send SPI 16-bit data + * @param pSPI : The base of SPI peripheral on the chip + * @param data : Transmit Data + * @return Nothing + */ +STATIC INLINE void Chip_SPI_SendFrame(LPC_SPI_T *pSPI, uint16_t data) +{ + pSPI->DR = SPI_DR_DATA(data); +} + +/** + * @brief Get received SPI data + * @param pSPI : The base of SPI peripheral on the chip + * @return receive data + */ +STATIC INLINE uint16_t Chip_SPI_ReceiveFrame(LPC_SPI_T *pSPI) +{ + return SPI_DR_DATA(pSPI->DR); +} + +/** + * @brief Set up output clocks per bit for SPI bus + * @param pSPI : The base of SPI peripheral on the chip + * @param counter : the number of SPI peripheral clock cycles that make up an SPI clock + * @return Nothing + * @note The counter must be an even number greater than or equal to 8.
+ * The SPI SCK rate = PCLK_SPI / counter. + */ +STATIC INLINE void Chip_SPI_SetClockCounter(LPC_SPI_T *pSPI, uint32_t counter) +{ + pSPI->CCR = counter; +} + +/** + * @brief Set up the SPI frame format + * @param pSPI : The base SPI peripheral on the chip + * @param format : Pointer to Frame format structure + * @return Nothing + */ +STATIC INLINE void Chip_SPI_SetFormat(LPC_SPI_T *pSPI, SPI_CONFIG_FORMAT_T *format) +{ + pSPI->CR = (pSPI->CR & (~0xF1C)) | SPI_CR_BIT_EN | format->bits | format->clockMode | format->dataOrder; +} + +/** + * @brief Get the number of bits transferred in each frame + * @param pSPI : The base of SPI peripheral on the chip + * @return the number of bits transferred in each frame + */ +STATIC INLINE SPI_BITS_T Chip_SPI_GetDataSize(LPC_SPI_T *pSPI) +{ + return (pSPI->CR & SPI_CR_BIT_EN) ? ((SPI_BITS_T) (pSPI->CR & SPI_CR_BITS_MASK)) : SPI_BITS_8; +} + +/** + * @brief Get the current CPHA & CPOL setting + * @param pSPI : The base of SPI peripheral on the chip + * @return CPHA & CPOL setting + */ +STATIC INLINE SPI_CLOCK_MODE_T Chip_SPI_GetClockMode(LPC_SPI_T *pSPI) +{ + return (SPI_CLOCK_MODE_T) (pSPI->CR & (3 << 3)); +} + +/** + * @brief Set the SPI working as master or slave mode + * @param pSPI : The base of SPI peripheral on the chip + * @return Operating mode + */ +STATIC INLINE SPI_MODE_T Chip_SPI_GetMode(LPC_SPI_T *pSPI) +{ + return (SPI_MODE_T) (pSPI->CR & (1 << 5)); +} + +/** + * @brief Set the SPI operating modes, master or slave + * @param pSPI : The base SPI peripheral on the chip + * @param mode : master mode/slave mode + * @return Nothing + */ +STATIC INLINE void Chip_SPI_SetMode(LPC_SPI_T *pSPI, SPI_MODE_T mode) +{ + pSPI->CR = (pSPI->CR & (~(1 << 5))) | mode; +} + +/** + * @brief Set the clock frequency for SPI interface + * @param pSPI : The base SPI peripheral on the chip + * @param bitRate : The SPI bit rate + * @return Nothing + */ +void Chip_SPI_SetBitRate(LPC_SPI_T *pSPI, uint32_t bitRate); + +/** + * @brief Enable SPI interrupt + * @param pSPI : The base SPI peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SPI_Int_Enable(LPC_SPI_T *pSPI) +{ + pSPI->CR |= SPI_CR_INT_EN; +} + +/** + * @brief Disable SPI interrupt + * @param pSPI : The base SPI peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SPI_Int_Disable(LPC_SPI_T *pSPI) +{ + pSPI->CR &= ~SPI_CR_INT_EN; +} + +/** + * @brief Get the interrupt status + * @param pSPI : The base of SPI peripheral on the chip + * @return SPI interrupt Status (Or-ed bit value of SPI_INT_*) + */ +STATIC INLINE uint32_t Chip_SPI_Int_GetStatus(LPC_SPI_T *pSPI) +{ + return pSPI->INT; +} + +/** + * @brief Clear the interrupt status + * @param pSPI : The base of SPI peripheral on the chip + * @param mask : SPI interrupt mask (Or-ed bit value of SPI_INT_*) + * @return Nothing + */ +STATIC INLINE void Chip_SPI_Int_ClearStatus(LPC_SPI_T *pSPI, uint32_t mask) +{ + pSPI->INT = mask; +} + +/** + * @brief Initialize the SPI + * @param pSPI : The base SPI peripheral on the chip + * @return Nothing + */ +void Chip_SPI_Init(LPC_SPI_T *pSPI); + +/** + * @brief Deinitialise the SPI + * @param pSPI : The base of SPI peripheral on the chip + * @return Nothing + * @note The SPI controller is disabled + */ +void Chip_SPI_DeInit(LPC_SPI_T *pSPI); + +/** + * @brief Clean all data in RX FIFO of SPI + * @param pSPI : The base SPI peripheral on the chip + * @return Nothing + */ +void Chip_SPI_Int_FlushData(LPC_SPI_T *pSPI); + +/** + * @brief SPI Interrupt Read/Write with 8-bit frame width + * @param pSPI : The base SPI peripheral on the chip + * @param xf_setup : Pointer to a SPI_DATA_SETUP_T structure that contains specified + * information about transmit/receive data configuration + * @return SUCCESS or ERROR + */ +Status Chip_SPI_Int_RWFrames8Bits(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *xf_setup); + +/** + * @brief SPI Interrupt Read/Write with 16-bit frame width + * @param pSPI : The base SPI peripheral on the chip + * @param xf_setup : Pointer to a SPI_DATA_SETUP_T structure that contains specified + * information about transmit/receive data configuration + * @return SUCCESS or ERROR + */ +Status Chip_SPI_Int_RWFrames16Bits(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *xf_setup); + +/** + * @brief SPI Polling Read/Write in blocking mode + * @param pSPI : The base SPI peripheral on the chip + * @param pXfSetup : Pointer to a SPI_DATA_SETUP_T structure that contains specified + * information about transmit/receive data configuration + * @return Actual data length has been transferred + * @note + * This function can be used in both master and slave mode. It starts with writing phase and after that, + * a reading phase is generated to read any data available in RX_FIFO. All needed information is prepared + * through xf_setup param. + */ +uint32_t Chip_SPI_RWFrames_Blocking(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *pXfSetup); + +/** + * @brief SPI Polling Write in blocking mode + * @param pSPI : The base SPI peripheral on the chip + * @param buffer : Buffer address + * @param buffer_len : Buffer length + * @return Actual data length has been transferred + * @note + * This function can be used in both master and slave mode. First, a writing operation will send + * the needed data. After that, a dummy reading operation is generated to clear data buffer + */ +uint32_t Chip_SPI_WriteFrames_Blocking(LPC_SPI_T *pSPI, uint8_t *buffer, uint32_t buffer_len); + +/** + * @brief SPI Polling Read in blocking mode + * @param pSPI : The base SPI peripheral on the chip + * @param buffer : Buffer address + * @param buffer_len : The length of buffer + * @return Actual data length has been transferred + * @note + * This function can be used in both master and slave mode. First, a dummy writing operation is generated + * to clear data buffer. After that, a reading operation will receive the needed data + */ +uint32_t Chip_SPI_ReadFrames_Blocking(LPC_SPI_T *pSPI, uint8_t *buffer, uint32_t buffer_len); + +#endif /* defined(CHIP_LPC175X_6X) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __SPI_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/spifi_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/spifi_17xx_40xx.h new file mode 100644 index 000000000..01807ac82 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/spifi_17xx_40xx.h @@ -0,0 +1,79 @@ +/* + * @brief LPC17xx/40xx SPIFI driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __SPIFI_17XX_40XX_H_ +#define __SPIFI_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup SPIFI_17XX_40XX CHIP: LPC17xx/40xx SPIFI Driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if defined(CHIP_LPC40XX) + +/** SPIFI memory base address */ +#define SPIFLASH_BASE_ADDRESS (0x28000000) +/** SPIFI API ROM address */ +#define SPIFI_ROM_PTR (0x1FFF1954) + +/** + * @brief Initialize the SPIFI + * @return None + */ +STATIC INLINE void Chip_SPIFI_Init(void) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_SPIFI); +} + +/** + * @brief Shutdown the SPIFI + * @return None + */ +STATIC INLINE void Chip_SPIFI_DeInit(void) +{ + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_SPIFI); +} + +#endif /* defined(CHIP_LPC40XX) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __SPIFI_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/ssp_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/ssp_17xx_40xx.h new file mode 100644 index 000000000..aadec567b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/ssp_17xx_40xx.h @@ -0,0 +1,598 @@ +/* + * @brief LPC17xx/40xx SSP driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __SSP_17XX_40XX_H_ +#define __SSP_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup SSP_17XX_40XX CHIP: LPC17xx/40xx SSP driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief SSP register block structure + */ +typedef struct { /*!< SSPn Structure */ + __IO uint32_t CR0; /*!< Control Register 0. Selects the serial clock rate, bus type, and data size. */ + __IO uint32_t CR1; /*!< Control Register 1. Selects master/slave and other modes. */ + __IO uint32_t DR; /*!< Data Register. Writes fill the transmit FIFO, and reads empty the receive FIFO. */ + __I uint32_t SR; /*!< Status Register */ + __IO uint32_t CPSR; /*!< Clock Prescale Register */ + __IO uint32_t IMSC; /*!< Interrupt Mask Set and Clear Register */ + __I uint32_t RIS; /*!< Raw Interrupt Status Register */ + __I uint32_t MIS; /*!< Masked Interrupt Status Register */ + __O uint32_t ICR; /*!< SSPICR Interrupt Clear Register */ + __IO uint32_t DMACR; /*!< SSPn DMA control register */ +} LPC_SSP_T; + +/** + * Macro defines for CR0 register + */ + +/** SSP data size select, must be 4 bits to 16 bits */ +#define SSP_CR0_DSS(n) ((uint32_t) ((n) & 0xF)) +/** SSP control 0 Motorola SPI mode */ +#define SSP_CR0_FRF_SPI ((uint32_t) (0 << 4)) +/** SSP control 0 TI synchronous serial mode */ +#define SSP_CR0_FRF_TI ((uint32_t) (1 << 4)) +/** SSP control 0 National Micro-wire mode */ +#define SSP_CR0_FRF_MICROWIRE ((uint32_t) (2 << 4)) +/** SPI clock polarity bit (used in SPI mode only), (1) = maintains the + bus clock high between frames, (0) = low */ +#define SSP_CR0_CPOL_LO ((uint32_t) (0)) +#define SSP_CR0_CPOL_HI ((uint32_t) (1 << 6)) +/** SPI clock out phase bit (used in SPI mode only), (1) = captures data + on the second clock transition of the frame, (0) = first */ +#define SSP_CR0_CPHA_FIRST ((uint32_t) (0)) +#define SSP_CR0_CPHA_SECOND ((uint32_t) (1 << 7)) +/** SSP serial clock rate value load macro, divider rate is + PERIPH_CLK / (cpsr * (SCR + 1)) */ +#define SSP_CR0_SCR(n) ((uint32_t) ((n & 0xFF) << 8)) +/** SSP CR0 bit mask */ +#define SSP_CR0_BITMASK ((uint32_t) (0xFFFF)) +/** SSP CR0 bit mask */ +#define SSP_CR0_BITMASK ((uint32_t) (0xFFFF)) +/** SSP serial clock rate value load macro, divider rate is + PERIPH_CLK / (cpsr * (SCR + 1)) */ +#define SSP_CR0_SCR(n) ((uint32_t) ((n & 0xFF) << 8)) + +/** + * Macro defines for CR1 register + */ + +/** SSP control 1 loopback mode enable bit */ +#define SSP_CR1_LBM_EN ((uint32_t) (1 << 0)) +/** SSP control 1 enable bit */ +#define SSP_CR1_SSP_EN ((uint32_t) (1 << 1)) +/** SSP control 1 slave enable */ +#define SSP_CR1_SLAVE_EN ((uint32_t) (1 << 2)) +#define SSP_CR1_MASTER_EN ((uint32_t) (0)) +/** SSP control 1 slave out disable bit, disables transmit line in slave + mode */ +#define SSP_CR1_SO_DISABLE ((uint32_t) (1 << 3)) +/** SSP CR1 bit mask */ +#define SSP_CR1_BITMASK ((uint32_t) (0x0F)) + +/** SSP CPSR bit mask */ +#define SSP_CPSR_BITMASK ((uint32_t) (0xFF)) +/** + * Macro defines for DR register + */ + +/** SSP data bit mask */ +#define SSP_DR_BITMASK(n) ((n) & 0xFFFF) + +/** + * Macro defines for SR register + */ + +/** SSP SR bit mask */ +#define SSP_SR_BITMASK ((uint32_t) (0x1F)) + +/** ICR bit mask */ +#define SSP_ICR_BITMASK ((uint32_t) (0x03)) + +/** + * @brief SSP Type of Status + */ +typedef enum _SSP_STATUS { + SSP_STAT_TFE = ((uint32_t)(1 << 0)),/**< TX FIFO Empty */ + SSP_STAT_TNF = ((uint32_t)(1 << 1)),/**< TX FIFO not full */ + SSP_STAT_RNE = ((uint32_t)(1 << 2)),/**< RX FIFO not empty */ + SSP_STAT_RFF = ((uint32_t)(1 << 3)),/**< RX FIFO full */ + SSP_STAT_BSY = ((uint32_t)(1 << 4)),/**< SSP Busy */ +} SSP_STATUS_T; + +/** + * @brief SSP Type of Interrupt Mask + */ +typedef enum _SSP_INTMASK { + SSP_RORIM = ((uint32_t)(1 << 0)), /**< Overun */ + SSP_RTIM = ((uint32_t)(1 << 1)),/**< TimeOut */ + SSP_RXIM = ((uint32_t)(1 << 2)),/**< Rx FIFO is at least half full */ + SSP_TXIM = ((uint32_t)(1 << 3)),/**< Tx FIFO is at least half empty */ + SSP_INT_MASK_BITMASK = ((uint32_t)(0xF)), +} SSP_INTMASK_T; + +/** + * @brief SSP Type of Mask Interrupt Status + */ +typedef enum _SSP_MASKINTSTATUS { + SSP_RORMIS = ((uint32_t)(1 << 0)), /**< Overun */ + SSP_RTMIS = ((uint32_t)(1 << 1)), /**< TimeOut */ + SSP_RXMIS = ((uint32_t)(1 << 2)), /**< Rx FIFO is at least half full */ + SSP_TXMIS = ((uint32_t)(1 << 3)), /**< Tx FIFO is at least half empty */ + SSP_MASK_INT_STAT_BITMASK = ((uint32_t)(0xF)), +} SSP_MASKINTSTATUS_T; + +/** + * @brief SSP Type of Raw Interrupt Status + */ +typedef enum _SSP_RAWINTSTATUS { + SSP_RORRIS = ((uint32_t)(1 << 0)), /**< Overun */ + SSP_RTRIS = ((uint32_t)(1 << 1)), /**< TimeOut */ + SSP_RXRIS = ((uint32_t)(1 << 2)), /**< Rx FIFO is at least half full */ + SSP_TXRIS = ((uint32_t)(1 << 3)), /**< Tx FIFO is at least half empty */ + SSP_RAW_INT_STAT_BITMASK = ((uint32_t)(0xF)), +} SSP_RAWINTSTATUS_T; + +typedef enum _SSP_INTCLEAR { + SSP_RORIC = 0x0, + SSP_RTIC = 0x1, + SSP_INT_CLEAR_BITMASK = 0x3, +} SSP_INTCLEAR_T; + +typedef enum _SSP_DMA { + SSP_DMA_RX = (1u), /**< DMA RX Enable */ + SSP_DMA_TX = (1u << 1), /**< DMA TX Enable */ + SSP_DMA_BITMASK = ((uint32_t)(0x3)), +} SSP_DMA_T; + +/* + * @brief SSP clock format + */ +typedef enum CHIP_SSP_CLOCK_FORMAT { + SSP_CLOCK_CPHA0_CPOL0 = (0 << 6), /**< CPHA = 0, CPOL = 0 */ + SSP_CLOCK_CPHA0_CPOL1 = (1u << 6), /**< CPHA = 0, CPOL = 1 */ + SSP_CLOCK_CPHA1_CPOL0 = (2u << 6), /**< CPHA = 1, CPOL = 0 */ + SSP_CLOCK_CPHA1_CPOL1 = (3u << 6), /**< CPHA = 1, CPOL = 1 */ + SSP_CLOCK_MODE0 = SSP_CLOCK_CPHA0_CPOL0,/**< alias */ + SSP_CLOCK_MODE1 = SSP_CLOCK_CPHA1_CPOL0,/**< alias */ + SSP_CLOCK_MODE2 = SSP_CLOCK_CPHA0_CPOL1,/**< alias */ + SSP_CLOCK_MODE3 = SSP_CLOCK_CPHA1_CPOL1,/**< alias */ +} CHIP_SSP_CLOCK_MODE_T; + +/* + * @brief SSP frame format + */ +typedef enum CHIP_SSP_FRAME_FORMAT { + SSP_FRAMEFORMAT_SPI = (0 << 4), /**< Frame format: SPI */ + CHIP_SSP_FRAME_FORMAT_TI = (1u << 4), /**< Frame format: TI SSI */ + SSP_FRAMEFORMAT_MICROWIRE = (2u << 4), /**< Frame format: Microwire */ +} CHIP_SSP_FRAME_FORMAT_T; + +/* + * @brief Number of bits per frame + */ +typedef enum CHIP_SSP_BITS { + SSP_BITS_4 = (3u << 0), /*!< 4 bits/frame */ + SSP_BITS_5 = (4u << 0), /*!< 5 bits/frame */ + SSP_BITS_6 = (5u << 0), /*!< 6 bits/frame */ + SSP_BITS_7 = (6u << 0), /*!< 7 bits/frame */ + SSP_BITS_8 = (7u << 0), /*!< 8 bits/frame */ + SSP_BITS_9 = (8u << 0), /*!< 9 bits/frame */ + SSP_BITS_10 = (9u << 0), /*!< 10 bits/frame */ + SSP_BITS_11 = (10u << 0), /*!< 11 bits/frame */ + SSP_BITS_12 = (11u << 0), /*!< 12 bits/frame */ + SSP_BITS_13 = (12u << 0), /*!< 13 bits/frame */ + SSP_BITS_14 = (13u << 0), /*!< 14 bits/frame */ + SSP_BITS_15 = (14u << 0), /*!< 15 bits/frame */ + SSP_BITS_16 = (15u << 0), /*!< 16 bits/frame */ +} CHIP_SSP_BITS_T; + +/* + * @brief SSP config format + */ +typedef struct SSP_ConfigFormat { + CHIP_SSP_BITS_T bits; /*!< Format config: bits/frame */ + CHIP_SSP_CLOCK_MODE_T clockMode; /*!< Format config: clock phase/polarity */ + CHIP_SSP_FRAME_FORMAT_T frameFormat; /*!< Format config: SPI/TI/Microwire */ +} SSP_ConfigFormat; + +/** + * @brief Enable SSP operation + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SSP_Enable(LPC_SSP_T *pSSP) +{ + pSSP->CR1 |= SSP_CR1_SSP_EN; +} + +/** + * @brief Disable SSP operation + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SSP_Disable(LPC_SSP_T *pSSP) +{ + pSSP->CR1 &= (~SSP_CR1_SSP_EN) & SSP_CR1_BITMASK; +} + +/** + * @brief Enable loopback mode + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + * @note Serial input is taken from the serial output (MOSI or MISO) rather + * than the serial input pin + */ +STATIC INLINE void Chip_SSP_EnableLoopBack(LPC_SSP_T *pSSP) +{ + pSSP->CR1 |= SSP_CR1_LBM_EN; +} + +/** + * @brief Disable loopback mode + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + * @note Serial input is taken from the serial output (MOSI or MISO) rather + * than the serial input pin + */ +STATIC INLINE void Chip_SSP_DisableLoopBack(LPC_SSP_T *pSSP) +{ + pSSP->CR1 &= (~SSP_CR1_LBM_EN) & SSP_CR1_BITMASK; +} + +/** + * @brief Get the current status of SSP controller + * @param pSSP : The base of SSP peripheral on the chip + * @param Stat : Type of status, should be : + * - SSP_STAT_TFE + * - SSP_STAT_TNF + * - SSP_STAT_RNE + * - SSP_STAT_RFF + * - SSP_STAT_BSY + * @return SSP controller status, SET or RESET + */ +STATIC INLINE FlagStatus Chip_SSP_GetStatus(LPC_SSP_T *pSSP, SSP_STATUS_T Stat) +{ + return (pSSP->SR & Stat) ? SET : RESET; +} + +/** + * @brief Get the masked interrupt status + * @param pSSP : The base of SSP peripheral on the chip + * @return SSP Masked Interrupt Status Register value + * @note The return value contains a 1 for each interrupt condition that is asserted and enabled (masked) + */ +STATIC INLINE uint32_t Chip_SSP_GetIntStatus(LPC_SSP_T *pSSP) +{ + return pSSP->MIS; +} + +/** + * @brief Get the raw interrupt status + * @param pSSP : The base of SSP peripheral on the chip + * @param RawInt : Interrupt condition to be get status, shoud be : + * - SSP_RORRIS + * - SSP_RTRIS + * - SSP_RXRIS + * - SSP_TXRIS + * @return Raw interrupt status corresponding to interrupt condition , SET or RESET + * @note Get the status of each interrupt condition ,regardless of whether or not the interrupt is enabled + */ +STATIC INLINE IntStatus Chip_SSP_GetRawIntStatus(LPC_SSP_T *pSSP, SSP_RAWINTSTATUS_T RawInt) +{ + return (pSSP->RIS & RawInt) ? SET : RESET; +} + +/** + * @brief Get the number of bits transferred in each frame + * @param pSSP : The base of SSP peripheral on the chip + * @return the number of bits transferred in each frame minus one + * @note The return value is 0x03 -> 0xF corresponding to 4bit -> 16bit transfer + */ +STATIC INLINE uint8_t Chip_SSP_GetDataSize(LPC_SSP_T *pSSP) +{ + return SSP_CR0_DSS(pSSP->CR0); +} + +/** + * @brief Clear the corresponding interrupt condition(s) in the SSP controller + * @param pSSP : The base of SSP peripheral on the chip + * @param IntClear: Type of cleared interrupt, should be : + * - SSP_RORIC + * - SSP_RTIC + * @return Nothing + * @note Software can clear one or more interrupt condition(s) in the SSP controller + */ +STATIC INLINE void Chip_SSP_ClearIntPending(LPC_SSP_T *pSSP, SSP_INTCLEAR_T IntClear) +{ + pSSP->ICR = IntClear; +} + +/** + * @brief Enable interrupt for the SSP + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SSP_Int_Enable(LPC_SSP_T *pSSP) +{ + pSSP->IMSC |= SSP_TXIM; +} + +/** + * @brief Disable interrupt for the SSP + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SSP_Int_Disable(LPC_SSP_T *pSSP) +{ + pSSP->IMSC &= (~SSP_TXIM); +} + +/** + * @brief Get received SSP data + * @param pSSP : The base of SSP peripheral on the chip + * @return SSP 16-bit data received + */ +STATIC INLINE uint16_t Chip_SSP_ReceiveFrame(LPC_SSP_T *pSSP) +{ + return (uint16_t) (SSP_DR_BITMASK(pSSP->DR)); +} + +/** + * @brief Send SSP 16-bit data + * @param pSSP : The base of SSP peripheral on the chip + * @param tx_data : SSP 16-bit data to be transmited + * @return Nothing + */ +STATIC INLINE void Chip_SSP_SendFrame(LPC_SSP_T *pSSP, uint16_t tx_data) +{ + pSSP->DR = SSP_DR_BITMASK(tx_data); +} + +/** + * @brief Set up output clocks per bit for SSP bus + * @param pSSP : The base of SSP peripheral on the chip + * @param clk_rate fs: The number of prescaler-output clocks per bit on the bus, minus one + * @param prescale : The factor by which the Prescaler divides the SSP peripheral clock PCLK + * @return Nothing + * @note The bit frequency is PCLK / (prescale x[clk_rate+1]) + */ +void Chip_SSP_SetClockRate(LPC_SSP_T *pSSP, uint32_t clk_rate, uint32_t prescale); + +/** + * @brief Set up the SSP frame format + * @param pSSP : The base of SSP peripheral on the chip + * @param bits : The number of bits transferred in each frame, should be SSP_BITS_4 to SSP_BITS_16 + * @param frameFormat : Frame format, should be : + * - SSP_FRAMEFORMAT_SPI + * - SSP_FRAME_FORMAT_TI + * - SSP_FRAMEFORMAT_MICROWIRE + * @param clockMode : Select Clock polarity and Clock phase, should be : + * - SSP_CLOCK_CPHA0_CPOL0 + * - SSP_CLOCK_CPHA0_CPOL1 + * - SSP_CLOCK_CPHA1_CPOL0 + * - SSP_CLOCK_CPHA1_CPOL1 + * @return Nothing + * @note Note: The clockFormat is only used in SPI mode + */ +STATIC INLINE void Chip_SSP_SetFormat(LPC_SSP_T *pSSP, uint32_t bits, uint32_t frameFormat, uint32_t clockMode) +{ + pSSP->CR0 = (pSSP->CR0 & ~0xFF) | bits | frameFormat | clockMode; +} + +/** + * @brief Set the SSP working as master or slave mode + * @param pSSP : The base of SSP peripheral on the chip + * @param mode : Operating mode, should be + * - SSP_MODE_MASTER + * - SSP_MODE_SLAVE + * @return Nothing + */ +STATIC INLINE void Chip_SSP_Set_Mode(LPC_SSP_T *pSSP, uint32_t mode) +{ + pSSP->CR1 = (pSSP->CR1 & ~(1 << 2)) | mode; +} + +/** + * @brief Enable DMA for SSP + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SSP_DMA_Enable(LPC_SSP_T *pSSP) +{ + pSSP->DMACR |= SSP_DMA_BITMASK; +} + +/** + * @brief Disable DMA for SSP + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + */ +STATIC INLINE void Chip_SSP_DMA_Disable(LPC_SSP_T *pSSP) +{ + pSSP->DMACR &= ~SSP_DMA_BITMASK; +} + +/* + * @brief SSP mode + */ +typedef enum CHIP_SSP_MODE { + SSP_MODE_MASTER = (0 << 2), /**< Master mode */ + SSP_MODE_SLAVE = (1u << 2), /**< Slave mode */ +} CHIP_SSP_MODE_T; + +/* + * @brief SPI address + */ +typedef struct { + uint8_t port; /*!< Port Number */ + uint8_t pin; /*!< Pin number */ +} SPI_Address_t; + +/* + * @brief SSP data setup structure + */ +typedef struct { + void *tx_data; /*!< Pointer to transmit data */ + uint32_t tx_cnt; /*!< Transmit counter */ + void *rx_data; /*!< Pointer to transmit data */ + uint32_t rx_cnt; /*!< Receive counter */ + uint32_t length; /*!< Length of transfer data */ +} Chip_SSP_DATA_SETUP_T; + +/** SSP configuration parameter defines */ +/** Clock phase control bit */ +#define SSP_CPHA_FIRST SSP_CR0_CPHA_FIRST +#define SSP_CPHA_SECOND SSP_CR0_CPHA_SECOND + +/** Clock polarity control bit */ +/* There's no bug here!!! + * - If bit[6] in SSPnCR0 is 0: SSP controller maintains the bus clock low between frames. + * That means the active clock is in HI state. + * - If bit[6] in SSPnCR0 is 1 (SSP_CR0_CPOL_HI): SSP controller maintains the bus clock + * high between frames. That means the active clock is in LO state. + */ +#define SSP_CPOL_HI SSP_CR0_CPOL_LO +#define SSP_CPOL_LO SSP_CR0_CPOL_HI + +/** SSP master mode enable */ +#define SSP_SLAVE_MODE SSP_CR1_SLAVE_EN +#define SSP_MASTER_MODE SSP_CR1_MASTER_EN + +/** + * @brief Clean all data in RX FIFO of SSP + * @param pSSP : The base SSP peripheral on the chip + * @return Nothing + */ +void Chip_SSP_Int_FlushData(LPC_SSP_T *pSSP); + +/** + * @brief SSP Interrupt Read/Write with 8-bit frame width + * @param pSSP : The base SSP peripheral on the chip + * @param xf_setup : Pointer to a SSP_DATA_SETUP_T structure that contains specified + * information about transmit/receive data configuration + * @return SUCCESS or ERROR + */ +Status Chip_SSP_Int_RWFrames8Bits(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup); + +/** + * @brief SSP Interrupt Read/Write with 16-bit frame width + * @param pSSP : The base SSP peripheral on the chip + * @param xf_setup : Pointer to a SSP_DATA_SETUP_T structure that contains specified + * information about transmit/receive data configuration + * @return SUCCESS or ERROR + */ +Status Chip_SSP_Int_RWFrames16Bits(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup); + +/** + * @brief SSP Polling Read/Write in blocking mode + * @param pSSP : The base SSP peripheral on the chip + * @param xf_setup : Pointer to a SSP_DATA_SETUP_T structure that contains specified + * information about transmit/receive data configuration + * @return Actual data length has been transferred + * @note + * This function can be used in both master and slave mode. It starts with writing phase and after that, + * a reading phase is generated to read any data available in RX_FIFO. All needed information is prepared + * through xf_setup param. + */ +uint32_t Chip_SSP_RWFrames_Blocking(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup); + +/** + * @brief SSP Polling Write in blocking mode + * @param pSSP : The base SSP peripheral on the chip + * @param buffer : Buffer address + * @param buffer_len : Buffer length + * @return Actual data length has been transferred + * @note + * This function can be used in both master and slave mode. First, a writing operation will send + * the needed data. After that, a dummy reading operation is generated to clear data buffer + */ +uint32_t Chip_SSP_WriteFrames_Blocking(LPC_SSP_T *pSSP, uint8_t *buffer, uint32_t buffer_len); + +/** + * @brief SSP Polling Read in blocking mode + * @param pSSP : The base SSP peripheral on the chip + * @param buffer : Buffer address + * @param buffer_len : The length of buffer + * @return Actual data length has been transferred + * @note + * This function can be used in both master and slave mode. First, a dummy writing operation is generated + * to clear data buffer. After that, a reading operation will receive the needed data + */ +uint32_t Chip_SSP_ReadFrames_Blocking(LPC_SSP_T *pSSP, uint8_t *buffer, uint32_t buffer_len); + +/** + * @brief Initialize the SSP + * @param pSSP : The base SSP peripheral on the chip + * @return Nothing + */ +void Chip_SSP_Init(LPC_SSP_T *pSSP); + +/** + * @brief Deinitialise the SSP + * @param pSSP : The base of SSP peripheral on the chip + * @return Nothing + * @note The SSP controller is disabled + */ +void Chip_SSP_DeInit(LPC_SSP_T *pSSP); + +/** + * @brief Set the SSP operating modes, master or slave + * @param pSSP : The base SSP peripheral on the chip + * @param master : 1 to set master, 0 to set slave + * @return Nothing + */ +void Chip_SSP_SetMaster(LPC_SSP_T *pSSP, bool master); + +/** + * @brief Set the clock frequency for SSP interface + * @param pSSP : The base SSP peripheral on the chip + * @param bitRate : The SSP bit rate + * @return Nothing + */ +void Chip_SSP_SetBitRate(LPC_SSP_T *pSSP, uint32_t bitRate); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __SSP_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/stopwatch.h b/hw/mcu/nxp/lpc_chip_40xx/inc/stopwatch.h new file mode 100644 index 000000000..c298735fa --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/stopwatch.h @@ -0,0 +1,137 @@ +/* + * @brief Common stopwatch support + * + * @note + * Copyright(C) NXP Semiconductors, 2013 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __STOPWATCH_H_ +#define __STOPWATCH_H_ + +#include "cmsis.h" + +/** @defgroup Stop_Watch CHIP: Stopwatch primitives. + * @ingroup CHIP_Common + * @{ + */ + +/** + * @brief Initialize stopwatch + * @return Nothing + */ +void StopWatch_Init(void); + +/** + * @brief Start a stopwatch + * @return Current cycle count + */ +uint32_t StopWatch_Start(void); + +/** + * @brief Returns number of ticks elapsed since stopwatch was started + * @param startTime : Time returned by StopWatch_Start(). + * @return Number of ticks elapsed since stopwatch was started + */ +STATIC INLINE uint32_t StopWatch_Elapsed(uint32_t startTime) +{ + return StopWatch_Start() - startTime; +} + +/** + * @brief Returns number of ticks per second of the stopwatch timer + * @return Number of ticks per second of the stopwatch timer + */ +uint32_t StopWatch_TicksPerSecond(void); + +/** + * @brief Converts from stopwatch ticks to mS. + * @param ticks : Duration in ticks to convert to mS. + * @return Number of mS in given number of ticks + */ +uint32_t StopWatch_TicksToMs(uint32_t ticks); + +/** + * @brief Converts from stopwatch ticks to uS. + * @param ticks : Duration in ticks to convert to uS. + * @return Number of uS in given number of ticks + */ +uint32_t StopWatch_TicksToUs(uint32_t ticks); + +/** + * @brief Converts from mS to stopwatch ticks. + * @param mS : Duration in mS to convert to ticks. + * @return Number of ticks in given number of mS + */ +uint32_t StopWatch_MsToTicks(uint32_t mS); + +/** + * @brief Converts from uS to stopwatch ticks. + * @param uS : Duration in uS to convert to ticks. + * @return Number of ticks in given number of uS + */ +uint32_t StopWatch_UsToTicks(uint32_t uS); + +/** + * @brief Delays the given number of ticks using stopwatch primitives + * @param ticks : Number of ticks to delay + * @return Nothing + */ +STATIC INLINE void StopWatch_DelayTicks(uint32_t ticks) +{ + uint32_t startTime = StopWatch_Start(); + while (StopWatch_Elapsed(startTime) < ticks) {} +} + +/** + * @brief Delays the given number of mS using stopwatch primitives + * @param mS : Number of mS to delay + * @return Nothing + */ +STATIC INLINE void StopWatch_DelayMs(uint32_t mS) +{ + uint32_t ticks = StopWatch_MsToTicks(mS); + uint32_t startTime = StopWatch_Start(); + while (StopWatch_Elapsed(startTime) < ticks) {} +} + +/** + * @brief Delays the given number of uS using stopwatch primitives + * @param uS : Number of uS to delay + * @return Nothing + */ +STATIC INLINE void StopWatch_DelayUs(uint32_t uS) +{ + uint32_t ticks = StopWatch_UsToTicks(uS); + uint32_t startTime = StopWatch_Start(); + while (StopWatch_Elapsed(startTime) < ticks) {} +} + +/** + * @} + */ + +#endif /* __STOPWATCH_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/sys_config.h b/hw/mcu/nxp/lpc_chip_40xx/inc/sys_config.h new file mode 100644 index 000000000..bbfb9d7a7 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/sys_config.h @@ -0,0 +1,42 @@ +/* + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __SYS_CONFIG_H_ +#define __SYS_CONFIG_H_ + +/* Build for 407x/8x chip family */ +#define CHIP_LPC40XX + +/* For the LPC4074, the __FPU_PRESENT definition should be set to 0 */ +// #define __FPU_PRESENT 0 + +/* Enable DMA in SDC driver */ +#define SDC_DMA_ENABLE + +#endif /* __SYS_CONFIG_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/sysctl_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/sysctl_17xx_40xx.h new file mode 100644 index 000000000..04b96de4e --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/sysctl_17xx_40xx.h @@ -0,0 +1,360 @@ +/* + * @brief LPC17xx/40xx System and Control driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef _SYSCTL_17XX_40XX_H_ +#define _SYSCTL_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup SYSCTL_17XX_40XX CHIP: LPC17xx/40xx System Control block driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief LPC17XX/40XX Clock and Power PLL register block structure + */ +typedef struct { + __IO uint32_t PLLCON; /*!< (R/W) PLL Control Register */ + __IO uint32_t PLLCFG; /*!< (R/W) PLL Configuration Register */ + __I uint32_t PLLSTAT; /*!< (R/ ) PLL Status Register */ + __O uint32_t PLLFEED; /*!< ( /W) PLL Feed Register */ + uint32_t RESERVED1[4]; +} SYSCTL_PLL_REGS_T; + +/** + * Selectable PLLs + */ +typedef enum { + SYSCTL_MAIN_PLL, /*!< Main PLL (PLL0) */ + SYSCTL_USB_PLL, /*!< USB PLL (PLL1) */ +} CHIP_SYSCTL_PLL_T; + +/** + * @brief LPC17XX/40XX Clock and Power register block structure + */ +typedef struct { + __IO uint32_t FLASHCFG; /*!< Offset: 0x000 (R/W) Flash Accelerator Configuration Register */ + uint32_t RESERVED0[15]; + __IO uint32_t MEMMAP; /*!< Offset: 0x000 (R/W) Flash Accelerator Configuration Register */ + uint32_t RESERVED1[15]; + SYSCTL_PLL_REGS_T PLL[SYSCTL_USB_PLL + 1]; /*!< Offset: 0x080: PLL0 and PLL1 */ + __IO uint32_t PCON; /*!< Offset: 0x0C0 (R/W) Power Control Register */ + __IO uint32_t PCONP; /*!< Offset: 0x0C4 (R/W) Power Control for Peripherals Register */ +#if defined(CHIP_LPC175X_6X) + uint32_t RESERVED2[15]; +#elif defined(CHIP_LPC177X_8X) + uint32_t RESERVED2[14]; + __IO uint32_t EMCCLKSEL; /*!< Offset: 0x100 (R/W) External Memory Controller Clock Selection Register */ +#else + __IO uint32_t PCONP1; /*!< Offset: 0x0C8 (R/W) Power Control 1 for Peripherals Register */ + uint32_t RESERVED2[13]; + __IO uint32_t EMCCLKSEL; /*!< Offset: 0x100 (R/W) External Memory Controller Clock Selection Register */ +#endif + __IO uint32_t CCLKSEL; /*!< Offset: 0x104 (R/W) CPU Clock Selection Register */ + __IO uint32_t USBCLKSEL; /*!< Offset: 0x108 (R/W) USB Clock Selection Register */ + __IO uint32_t CLKSRCSEL; /*!< Offset: 0x10C (R/W) Clock Source Select Register */ + __IO uint32_t CANSLEEPCLR; /*!< Offset: 0x110 (R/W) CAN Sleep Clear Register */ + __IO uint32_t CANWAKEFLAGS; /*!< Offset: 0x114 (R/W) CAN Wake-up Flags Register */ + uint32_t RESERVED3[10]; + __IO uint32_t EXTINT; /*!< Offset: 0x140 (R/W) External Interrupt Flag Register */ + uint32_t RESERVED4; + __IO uint32_t EXTMODE; /*!< Offset: 0x148 (R/W) External Interrupt Mode Register */ + __IO uint32_t EXTPOLAR; /*!< Offset: 0x14C (R/W) External Interrupt Polarity Register */ + uint32_t RESERVED5[12]; + __IO uint32_t RSID; /*!< Offset: 0x180 (R/W) Reset Source Identification Register */ +#if defined(CHIP_LPC175X_6X) || defined(CHIP_LPC40XX) + uint32_t RESERVED6[7]; +#elif defined(CHIP_LPC177X_8X) + uint32_t RESERVED6; + uint32_t MATRIXARB; + uint32_t RESERVED6A[5]; +#endif + __IO uint32_t SCS; /*!< Offset: 0x1A0 (R/W) System Controls and Status Register */ + __IO uint32_t RESERVED7; +#if defined(CHIP_LPC175X_6X) + __IO uint32_t PCLKSEL[2]; /*!< Offset: 0x1A8 (R/W) Peripheral Clock Selection Register */ + uint32_t RESERVED8[4]; +#else + __IO uint32_t PCLKSEL; /*!< Offset: 0x1A8 (R/W) Peripheral Clock Selection Register */ + uint32_t RESERVED9; + __IO uint32_t PBOOST; /*!< Offset: 0x1B0 (R/W) Power Boost control register */ + __IO uint32_t SPIFICLKSEL; + __IO uint32_t LCD_CFG; /*!< Offset: 0x1B8 (R/W) LCD Configuration and clocking control Register */ + uint32_t RESERVED10; +#endif + __IO uint32_t USBIntSt; /*!< Offset: 0x1C0 (R/W) USB Interrupt Status Register */ + __IO uint32_t DMAREQSEL; /*!< Offset: 0x1C4 (R/W) DMA Request Select Register */ + __IO uint32_t CLKOUTCFG; /*!< Offset: 0x1C8 (R/W) Clock Output Configuration Register */ +#if defined(CHIP_LPC175X_6X) + uint32_t RESERVED11[6]; +#else + __IO uint32_t RSTCON[2]; /*!< Offset: 0x1CC (R/W) RESET Control0/1 Registers */ + uint32_t RESERVED11[2]; + __IO uint32_t EMCDLYCTL; /*!< Offset: 0x1DC (R/W) SDRAM programmable delays */ + __IO uint32_t EMCCAL; /*!< Offset: 0x1E0 (R/W) Calibration of programmable delays */ +#endif +} LPC_SYSCTL_T; + +/** + * @brief FLASH Access time definitions + */ +typedef enum { + FLASHTIM_20MHZ_CPU = 0, /*!< Flash accesses use 1 CPU clocks. Use for up to 20 MHz CPU clock */ + FLASHTIM_40MHZ_CPU = 1, /*!< Flash accesses use 2 CPU clocks. Use for up to 40 MHz CPU clock */ + FLASHTIM_60MHZ_CPU = 2, /*!< Flash accesses use 3 CPU clocks. Use for up to 60 MHz CPU clock */ + FLASHTIM_80MHZ_CPU = 3, /*!< Flash accesses use 4 CPU clocks. Use for up to 80 MHz CPU clock */ + FLASHTIM_100MHZ_CPU = 4, /*!< Flash accesses use 5 CPU clocks. Use for up to 100 MHz CPU clock */ +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + FLASHTIM_120MHZ_CPU = 3, /*!< Flash accesses use 4 CPU clocks. Use for up to 120 MHz CPU clock with power boot on*/ +#else + FLASHTIM_120MHZ_CPU = 4, /*!< Flash accesses use 5 CPU clocks. Use for up to 120 Mhz for LPC1759 and LPC1769 only.*/ +#endif + FLASHTIM_SAFE_SETTING = 5, /*!< Flash accesses use 6 CPU clocks. Safe setting for any allowed conditions */ +} FMC_FLASHTIM_T; + +/** + * @brief Set FLASH memory access time in clocks + * @param clks : Clock cycles for FLASH access (minus 1) + * @return Nothing + * @note See the user manual for valid settings for this register for when + * power boot is enabled or off. + */ +STATIC INLINE void Chip_SYSCTL_SetFLASHAccess(FMC_FLASHTIM_T clks) +{ + uint32_t tmp = LPC_SYSCTL->FLASHCFG & 0xFFF; + + /* Don't alter lower bits */ + LPC_SYSCTL->FLASHCFG = tmp | (clks << 12); +} + +/** + * System memory remap modes used to remap interrupt vectors + */ +typedef enum CHIP_SYSCTL_BOOT_MODE_REMAP { + REMAP_BOOT_LOADER_MODE, /*!< Interrupt vectors are re-mapped to Boot ROM */ + REMAP_USER_FLASH_MODE /*!< Interrupt vectors are not re-mapped and reside in Flash */ +} CHIP_SYSCTL_BOOT_MODE_REMAP_T; + +/** + * @brief Re-map interrupt vectors + * @param remap : system memory map value + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_Map(CHIP_SYSCTL_BOOT_MODE_REMAP_T remap) +{ + LPC_SYSCTL->MEMMAP = (uint32_t) remap; +} + +/** + * System reset status + */ +#define SYSCTL_RST_POR (1 << 0) /*!< POR reset status */ +#define SYSCTL_RST_EXTRST (1 << 1) /*!< External reset status */ +#define SYSCTL_RST_WDT (1 << 2) /*!< Watchdog reset status */ +#define SYSCTL_RST_BOD (1 << 3) /*!< Brown-out detect reset status */ +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) +#define SYSCTL_RST_SYSRST (1 << 4) /*!< software system reset status */ +#define SYSCTL_RST_LOCKUP (1 << 5) /*!< "lockup" reset status */ +#endif + +/** + * @brief Get system reset status + * @return An Or'ed value of SYSCTL_RST_* + * @note This function returns the detected reset source(s). + */ +STATIC INLINE uint32_t Chip_SYSCTL_GetSystemRSTStatus(void) +{ + return LPC_SYSCTL->RSID; +} + +/** + * @brief Clear system reset status + * @param reset : An Or'ed value of SYSCTL_RST_* status to clear + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_ClearSystemRSTStatus(uint32_t reset) +{ + LPC_SYSCTL->RSID = reset; +} + +/** + * @brief Enable brown-out detection + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_EnableBOD(void) +{ + LPC_SYSCTL->PCON |= (1 << 3); +} + +/** + * @brief Disable brown-out detection + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_DisableBOD(void) +{ + LPC_SYSCTL->PCON &= ~(1 << 3); +} + +/** + * @brief Enable brown-out detection reset + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_EnableBODReset(void) +{ + LPC_SYSCTL->PCON |= (1 << 4); +} + +/** + * @brief Disable brown-out detection reset + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_DisableBODReset(void) +{ + LPC_SYSCTL->PCON &= ~(1 << 4); +} + +/** + * @brief Enable brown-out detection reduced power mode + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_EnableBODRPM(void) +{ + LPC_SYSCTL->PCON |= (1 << 5); +} + +/** + * @brief Disable brown-out detection reduced power mode + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_DisableBODRPM(void) +{ + LPC_SYSCTL->PCON &= ~(1 << 5); +} + +#define SYSCTL_PD_SMFLAG (1 << 8) /*!< Sleep Mode entry flag */ +#define SYSCTL_PD_DSFLAG (1 << 9) /*!< Deep Sleep entry flag */ +#define SYSCTL_PD_PDFLAG (1 << 10) /*!< Power-down entry flag */ +#define SYSCTL_PD_DPDFLAG (1 << 11) /*!< Deep Power-down entry flag */ + +/** + * @brief Returns and clears the current sleep mode entry flags + * @param flags: One or more flags to clear, SYSCTL_PD_* + * @return An Or'ed value of the sleep flags, SYSCTL_PD_* + * @note These flags indicate the successful entry of one or more + * sleep modes. + */ +uint32_t Chip_SYSCTL_GetClrSleepFlags(uint32_t flags); + +#if !defined(CHIP_LPC175X_6X) +/** + * @brief Enable power boost for clock operation over 100MHz + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_EnableBoost(void) +{ + LPC_SYSCTL->PBOOST = 0x3; +} + +/** + * @brief Disable power boost for clock operation under 100MHz + * @return Nothing + */ +STATIC INLINE void Chip_SYSCTL_DisableBoost(void) +{ + LPC_SYSCTL->PBOOST = 0x0; +} + +#endif + +#if !defined(CHIP_LPC175X_6X) +/** + * Peripheral reset numbers + * This is a list of peripherals that can be reset + */ +typedef enum { + SYSCTL_RESET_LCD, /*!< LCD reset */ + SYSCTL_RESET_TIMER0, /*!< Timer 0 reset */ + SYSCTL_RESET_TIMER1, /*!< Timer 1 reset */ + SYSCTL_RESET_UART0, /*!< UART 0 reset */ + SYSCTL_RESET_UART1, /*!< UART 1 reset */ + SYSCTL_RESET_PWM0, /*!< PWM0 reset */ + SYSCTL_RESET_PWM1, /*!< PWM1 reset */ + SYSCTL_RESET_I2C0, /*!< I2C0 reset */ + SYSCTL_RESET_UART4, /*!< UART 4 reset */ + SYSCTL_RESET_RTC, /*!< RTC reset */ + SYSCTL_RESET_SSP1, /*!< SSP1 reset */ + SYSCTL_RESET_EMC, /*!< EMC reset */ + SYSCTL_RESET_ADC, /*!< ADC reset */ + SYSCTL_RESET_CAN1, /*!< CAN1 reset */ + SYSCTL_RESET_CAN2, /*!< CAN2 reset */ + SYSCTL_RESET_GPIO, /*!< GPIO reset */ + SYSCTL_RESET_SPIFI, /*!< SPIFI reset */ + SYSCTL_RESET_MCPWM, /*!< MCPWM reset */ + SYSCTL_RESET_QEI, /*!< QEI reset */ + SYSCTL_RESET_I2C1, /*!< I2C1 reset */ + SYSCTL_RESET_SSP2, /*!< SSP2 reset */ + SYSCTL_RESET_SSP0, /*!< SSP0 reset */ + SYSCTL_RESET_TIMER2, /*!< Timer 2 reset */ + SYSCTL_RESET_TIMER3, /*!< Timer 3 reset */ + SYSCTL_RESET_UART2, /*!< UART 2 reset */ + SYSCTL_RESET_UART3, /*!< UART 3 reset */ + SYSCTL_RESET_I2C2, /*!< I2C2 reset */ + SYSCTL_RESET_I2S, /*!< I2S reset */ + SYSCTL_RESET_PCSDC, /*!< SD Card interface reset */ + SYSCTL_RESET_GPDMA, /*!< GP DMA reset */ + SYSCTL_RESET_ENET, /*!< EMAC/Ethernet reset */ + SYSCTL_RESET_USB, /*!< USB reset */ + SYSCTL_RESET_IOCON, /*!< IOCON reset */ + SYSCTL_RESET_DAC, /*!< DAC reset */ + SYSCTL_RESET_CANACC, /*!< CAN acceptance filter reset */ +} CHIP_SYSCTL_RESET_T; + +/** + * @brief Resets a peripheral + * @param periph: Peripheral to reset + * @return Nothing + */ +void Chip_SYSCTL_PeriphReset(CHIP_SYSCTL_RESET_T periph); + +#endif + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _SYSCTL_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/timer_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/timer_17xx_40xx.h new file mode 100644 index 000000000..1278926bf --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/timer_17xx_40xx.h @@ -0,0 +1,445 @@ +/* + * @brief LPC17xx/40xx 16/32-bit Timer/PWM driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __TIMER_17XX_40XX_H_ +#define __TIMER_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup TIMER_17XX_40XX CHIP: LPc17xx/40xx 16/32-bit Timer driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief 32-bit Standard timer register block structure + */ +typedef struct { /*!< TIMERn Structure */ + __IO uint32_t IR; /*!< Interrupt Register. The IR can be written to clear interrupts. The IR can be read to identify which of eight possible interrupt sources are pending. */ + __IO uint32_t TCR; /*!< Timer Control Register. The TCR is used to control the Timer Counter functions. The Timer Counter can be disabled or reset through the TCR. */ + __IO uint32_t TC; /*!< Timer Counter. The 32 bit TC is incremented every PR+1 cycles of PCLK. The TC is controlled through the TCR. */ + __IO uint32_t PR; /*!< Prescale Register. The Prescale Counter (below) is equal to this value, the next clock increments the TC and clears the PC. */ + __IO uint32_t PC; /*!< Prescale Counter. The 32 bit PC is a counter which is incremented to the value stored in PR. When the value in PR is reached, the TC is incremented and the PC is cleared. The PC is observable and controllable through the bus interface. */ + __IO uint32_t MCR; /*!< Match Control Register. The MCR is used to control if an interrupt is generated and if the TC is reset when a Match occurs. */ + __IO uint32_t MR[4]; /*!< Match Register. MR can be enabled through the MCR to reset the TC, stop both the TC and PC, and/or generate an interrupt every time MR matches the TC. */ + __IO uint32_t CCR; /*!< Capture Control Register. The CCR controls which edges of the capture inputs are used to load the Capture Registers and whether or not an interrupt is generated when a capture takes place. */ + __IO uint32_t CR[4]; /*!< Capture Register. CR is loaded with the value of TC when there is an event on the CAPn.0 input. */ + __IO uint32_t EMR; /*!< External Match Register. The EMR controls the external match pins MATn.0-3 (MAT0.0-3 and MAT1.0-3 respectively). */ + __I uint32_t RESERVED0[12]; + __IO uint32_t CTCR; /*!< Count Control Register. The CTCR selects between Timer and Counter mode, and in Counter mode selects the signal and edge(s) for counting. */ +} LPC_TIMER_T; + +/** Macro to clear interrupt pending */ +#define TIMER_IR_CLR(n) _BIT(n) + +/** Macro for getting a timer match interrupt bit */ +#define TIMER_MATCH_INT(n) (_BIT((n) & 0x0F)) +/** Macro for getting a capture event interrupt bit */ +#define TIMER_CAP_INT(n) (_BIT((((n) & 0x0F) + 4))) + +/** Timer/counter enable bit */ +#define TIMER_ENABLE ((uint32_t) (1 << 0)) +/** Timer/counter reset bit */ +#define TIMER_RESET ((uint32_t) (1 << 1)) + +/** Bit location for interrupt on MRx match, n = 0 to 3 */ +#define TIMER_INT_ON_MATCH(n) (_BIT(((n) * 3))) +/** Bit location for reset on MRx match, n = 0 to 3 */ +#define TIMER_RESET_ON_MATCH(n) (_BIT((((n) * 3) + 1))) +/** Bit location for stop on MRx match, n = 0 to 3 */ +#define TIMER_STOP_ON_MATCH(n) (_BIT((((n) * 3) + 2))) + +/** Bit location for CAP.n on CRx rising edge, n = 0 to 3 */ +#define TIMER_CAP_RISING(n) (_BIT(((n) * 3))) +/** Bit location for CAP.n on CRx falling edge, n = 0 to 3 */ +#define TIMER_CAP_FALLING(n) (_BIT((((n) * 3) + 1))) +/** Bit location for CAP.n on CRx interrupt enable, n = 0 to 3 */ +#define TIMER_INT_ON_CAP(n) (_BIT((((n) * 3) + 2))) + +/** + * @brief Initialize a timer + * @param pTMR : Pointer to timer IP register address + * @return Nothing + */ +void Chip_TIMER_Init(LPC_TIMER_T *pTMR); + +/** + * @brief Shutdown a timer + * @param pTMR : Pointer to timer IP register address + * @return Nothing + */ +void Chip_TIMER_DeInit(LPC_TIMER_T *pTMR); + +/** + * @brief Determine if a match interrupt is pending + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match interrupt number to check + * @return false if the interrupt is not pending, otherwise true + * @note Determine if the match interrupt for the passed timer and match + * counter is pending. + */ +STATIC INLINE bool Chip_TIMER_MatchPending(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + return (bool) ((pTMR->IR & TIMER_MATCH_INT(matchnum)) != 0); +} + +/** + * @brief Determine if a capture interrupt is pending + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture interrupt number to check + * @return false if the interrupt is not pending, otherwise true + * @note Determine if the capture interrupt for the passed capture pin is + * pending. + */ +STATIC INLINE bool Chip_TIMER_CapturePending(LPC_TIMER_T *pTMR, int8_t capnum) +{ + return (bool) ((pTMR->IR & TIMER_CAP_INT(capnum)) != 0); +} + +/** + * @brief Clears a (pending) match interrupt + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match interrupt number to clear + * @return Nothing + * @note Clears a pending timer match interrupt. + */ +STATIC INLINE void Chip_TIMER_ClearMatch(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + pTMR->IR = TIMER_IR_CLR(matchnum); +} + +/** + * @brief Clears a (pending) capture interrupt + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture interrupt number to clear + * @return Nothing + * @note Clears a pending timer capture interrupt. + */ +STATIC INLINE void Chip_TIMER_ClearCapture(LPC_TIMER_T *pTMR, int8_t capnum) +{ + pTMR->IR = (0x10 << capnum); +} + +/** + * @brief Enables the timer (starts count) + * @param pTMR : Pointer to timer IP register address + * @return Nothing + * @note Enables the timer to start counting. + */ +STATIC INLINE void Chip_TIMER_Enable(LPC_TIMER_T *pTMR) +{ + pTMR->TCR |= TIMER_ENABLE; +} + +/** + * @brief Disables the timer (stops count) + * @param pTMR : Pointer to timer IP register address + * @return Nothing + * @note Disables the timer to stop counting. + */ +STATIC INLINE void Chip_TIMER_Disable(LPC_TIMER_T *pTMR) +{ + pTMR->TCR &= ~TIMER_ENABLE; +} + +/** + * @brief Returns the current timer count + * @param pTMR : Pointer to timer IP register address + * @return Current timer terminal count value + * @note Returns the current timer terminal count. + */ +STATIC INLINE uint32_t Chip_TIMER_ReadCount(LPC_TIMER_T *pTMR) +{ + return pTMR->TC; +} + +/** + * @brief Returns the current prescale count + * @param pTMR : Pointer to timer IP register address + * @return Current timer prescale count value + * @note Returns the current prescale count. + */ +STATIC INLINE uint32_t Chip_TIMER_ReadPrescale(LPC_TIMER_T *pTMR) +{ + return pTMR->PC; +} + +/** + * @brief Sets the prescaler value + * @param pTMR : Pointer to timer IP register address + * @param prescale : Prescale value to set the prescale register to + * @return Nothing + * @note Sets the prescale count value. + */ +STATIC INLINE void Chip_TIMER_PrescaleSet(LPC_TIMER_T *pTMR, uint32_t prescale) +{ + pTMR->PR = prescale; +} + +/** + * @brief Sets a timer match value + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match timer to set match count for + * @param matchval : Match value for the selected match count + * @return Nothing + * @note Sets one of the timer match values. + */ +STATIC INLINE void Chip_TIMER_SetMatch(LPC_TIMER_T *pTMR, int8_t matchnum, uint32_t matchval) +{ + pTMR->MR[matchnum] = matchval; +} + +/** + * @brief Reads a capture register + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture register to read + * @return The selected capture register value + * @note Returns the selected capture register value. + */ +STATIC INLINE uint32_t Chip_TIMER_ReadCapture(LPC_TIMER_T *pTMR, int8_t capnum) +{ + return pTMR->CR[capnum]; +} + +/** + * @brief Resets the timer terminal and prescale counts to 0 + * @param pTMR : Pointer to timer IP register address + * @return Nothing + */ +void Chip_TIMER_Reset(LPC_TIMER_T *pTMR); + +/** + * @brief Enables a match interrupt that fires when the terminal count + * matches the match counter value. + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match timer, 0 to 3 + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_MatchEnableInt(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + pTMR->MCR |= TIMER_INT_ON_MATCH(matchnum); +} + +/** + * @brief Disables a match interrupt for a match counter. + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match timer, 0 to 3 + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_MatchDisableInt(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + pTMR->MCR &= ~TIMER_INT_ON_MATCH(matchnum); +} + +/** + * @brief For the specific match counter, enables reset of the terminal count register when a match occurs + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match timer, 0 to 3 + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_ResetOnMatchEnable(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + pTMR->MCR |= TIMER_RESET_ON_MATCH(matchnum); +} + +/** + * @brief For the specific match counter, disables reset of the terminal count register when a match occurs + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match timer, 0 to 3 + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_ResetOnMatchDisable(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + pTMR->MCR &= ~TIMER_RESET_ON_MATCH(matchnum); +} + +/** + * @brief Enable a match timer to stop the terminal count when a + * match count equals the terminal count. + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match timer, 0 to 3 + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_StopOnMatchEnable(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + pTMR->MCR |= TIMER_STOP_ON_MATCH(matchnum); +} + +/** + * @brief Disable stop on match for a match timer. Disables a match timer + * to stop the terminal count when a match count equals the terminal count. + * @param pTMR : Pointer to timer IP register address + * @param matchnum : Match timer, 0 to 3 + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_StopOnMatchDisable(LPC_TIMER_T *pTMR, int8_t matchnum) +{ + pTMR->MCR &= ~TIMER_STOP_ON_MATCH(matchnum); +} + +/** + * @brief Enables capture on on rising edge of selected CAP signal for the + * selected capture register, enables the selected CAPn.capnum signal to load + * the capture register with the terminal coount on a rising edge. + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture signal/register to use + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_CaptureRisingEdgeEnable(LPC_TIMER_T *pTMR, int8_t capnum) +{ + pTMR->CCR |= TIMER_CAP_RISING(capnum); +} + +/** + * @brief Disables capture on on rising edge of selected CAP signal. For the + * selected capture register, disables the selected CAPn.capnum signal to load + * the capture register with the terminal coount on a rising edge. + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture signal/register to use + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_CaptureRisingEdgeDisable(LPC_TIMER_T *pTMR, int8_t capnum) +{ + pTMR->CCR &= ~TIMER_CAP_RISING(capnum); +} + +/** + * @brief Enables capture on on falling edge of selected CAP signal. For the + * selected capture register, enables the selected CAPn.capnum signal to load + * the capture register with the terminal coount on a falling edge. + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture signal/register to use + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_CaptureFallingEdgeEnable(LPC_TIMER_T *pTMR, int8_t capnum) +{ + pTMR->CCR |= TIMER_CAP_FALLING(capnum); +} + +/** + * @brief Disables capture on on falling edge of selected CAP signal. For the + * selected capture register, disables the selected CAPn.capnum signal to load + * the capture register with the terminal coount on a falling edge. + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture signal/register to use + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_CaptureFallingEdgeDisable(LPC_TIMER_T *pTMR, int8_t capnum) +{ + pTMR->CCR &= ~TIMER_CAP_FALLING(capnum); +} + +/** + * @brief Enables interrupt on capture of selected CAP signal. For the + * selected capture register, an interrupt will be generated when the enabled + * rising or falling edge on CAPn.capnum is detected. + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture signal/register to use + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_CaptureEnableInt(LPC_TIMER_T *pTMR, int8_t capnum) +{ + pTMR->CCR |= TIMER_INT_ON_CAP(capnum); +} + +/** + * @brief Disables interrupt on capture of selected CAP signal + * @param pTMR : Pointer to timer IP register address + * @param capnum : Capture signal/register to use + * @return Nothing + */ +STATIC INLINE void Chip_TIMER_CaptureDisableInt(LPC_TIMER_T *pTMR, int8_t capnum) +{ + pTMR->CCR &= ~TIMER_INT_ON_CAP(capnum); +} + +/** + * @brief Standard timer initial match pin state and change state + */ +typedef enum IP_TIMER_PIN_MATCH_STATE { + TIMER_EXTMATCH_DO_NOTHING = 0, /*!< Timer match state does nothing on match pin */ + TIMER_EXTMATCH_CLEAR = 1, /*!< Timer match state sets match pin low */ + TIMER_EXTMATCH_SET = 2, /*!< Timer match state sets match pin high */ + TIMER_EXTMATCH_TOGGLE = 3 /*!< Timer match state toggles match pin */ +} TIMER_PIN_MATCH_STATE_T; + +/** + * @brief Sets external match control (MATn.matchnum) pin control. For the pin + * selected with matchnum, sets the function of the pin that occurs on + * a terminal count match for the match count. + * @param pTMR : Pointer to timer IP register address + * @param initial_state : Initial state of the pin, high(1) or low(0) + * @param matchState : Selects the match state for the pin + * @param matchnum : MATn.matchnum signal to use + * @return Nothing + * @note For the pin selected with matchnum, sets the function of the pin that occurs on + * a terminal count match for the match count. + */ +void Chip_TIMER_ExtMatchControlSet(LPC_TIMER_T *pTMR, int8_t initial_state, + TIMER_PIN_MATCH_STATE_T matchState, int8_t matchnum); + +/** + * @brief Standard timer clock and edge for count source + */ +typedef enum IP_TIMER_CAP_SRC_STATE { + TIMER_CAPSRC_RISING_PCLK = 0, /*!< Timer ticks on PCLK rising edge */ + TIMER_CAPSRC_RISING_CAPN = 1, /*!< Timer ticks on CAPn.x rising edge */ + TIMER_CAPSRC_FALLING_CAPN = 2, /*!< Timer ticks on CAPn.x falling edge */ + TIMER_CAPSRC_BOTH_CAPN = 3 /*!< Timer ticks on CAPn.x both edges */ +} TIMER_CAP_SRC_STATE_T; + +/** + * @brief Sets timer count source and edge with the selected passed from CapSrc. + * If CapSrc selected a CAPn pin, select the specific CAPn pin with the capnum value. + * @param pTMR : Pointer to timer IP register address + * @param capSrc : timer clock source and edge + * @param capnum : CAPn.capnum pin to use (if used) + * @return Nothing + * @note If CapSrc selected a CAPn pin, select the specific CAPn pin with the capnum value. + */ +STATIC INLINE void Chip_TIMER_TIMER_SetCountClockSrc(LPC_TIMER_T *pTMR, + TIMER_CAP_SRC_STATE_T capSrc, + int8_t capnum) +{ + pTMR->CTCR = (uint32_t) capSrc | ((uint32_t) capnum) << 2; +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __TIMER_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/uart_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/uart_17xx_40xx.h new file mode 100644 index 000000000..f423b600c --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/uart_17xx_40xx.h @@ -0,0 +1,814 @@ +/* + * @brief LPC17xx/40xx UART chip driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __UART_17XX_40XX_H_ +#define __UART_17XX_40XX_H_ + +#include "ring_buffer.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup UART_17XX_40XX CHIP: LPC17xx/40xx UART driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief USART register block structure + */ +typedef struct { /*!< USARTn Structure */ + + union { + __IO uint32_t DLL; /*!< Divisor Latch LSB. Least significant byte of the baud rate divisor value. The full divisor is used to generate a baud rate from the fractional rate divider (DLAB = 1). */ + __O uint32_t THR; /*!< Transmit Holding Register. The next character to be transmitted is written here (DLAB = 0). */ + __I uint32_t RBR; /*!< Receiver Buffer Register. Contains the next received character to be read (DLAB = 0). */ + }; + + union { + __IO uint32_t IER; /*!< Interrupt Enable Register. Contains individual interrupt enable bits for the 7 potential UART interrupts (DLAB = 0). */ + __IO uint32_t DLM; /*!< Divisor Latch MSB. Most significant byte of the baud rate divisor value. The full divisor is used to generate a baud rate from the fractional rate divider (DLAB = 1). */ + }; + + union { + __O uint32_t FCR; /*!< FIFO Control Register. Controls UART FIFO usage and modes. */ + __I uint32_t IIR; /*!< Interrupt ID Register. Identifies which interrupt(s) are pending. */ + }; + + __IO uint32_t LCR; /*!< Line Control Register. Contains controls for frame formatting and break generation. */ + __IO uint32_t MCR; /*!< Modem Control Register. Only present on USART ports with full modem support. */ + __I uint32_t LSR; /*!< Line Status Register. Contains flags for transmit and receive status, including line errors. */ + __I uint32_t MSR; /*!< Modem Status Register. Only present on USART ports with full modem support. */ + __IO uint32_t SCR; /*!< Scratch Pad Register. Eight-bit temporary storage for software. */ + __IO uint32_t ACR; /*!< Auto-baud Control Register. Contains controls for the auto-baud feature. */ + __IO uint32_t ICR; /*!< IrDA control register (not all UARTS) */ + __IO uint32_t FDR; /*!< Fractional Divider Register. Generates a clock input for the baud rate divider. */ + __IO uint32_t OSR; /*!< Oversampling Register. Controls the degree of oversampling during each bit time. Only on some UARTS. */ + __IO uint32_t TER1; /*!< Transmit Enable Register. Turns off USART transmitter for use with software flow control. */ + uint32_t RESERVED0[3]; + __IO uint32_t HDEN; /*!< Half-duplex enable Register- only on some UARTs */ + __I uint32_t RESERVED1[1]; + __IO uint32_t SCICTRL; /*!< Smart card interface control register- only on some UARTs */ + + __IO uint32_t RS485CTRL; /*!< RS-485/EIA-485 Control. Contains controls to configure various aspects of RS-485/EIA-485 modes. */ + __IO uint32_t RS485ADRMATCH; /*!< RS-485/EIA-485 address match. Contains the address match value for RS-485/EIA-485 mode. */ + __IO uint32_t RS485DLY; /*!< RS-485/EIA-485 direction control delay. */ + + union { + __IO uint32_t SYNCCTRL; /*!< Synchronous mode control register. Only on USARTs. */ + __I uint32_t FIFOLVL; /*!< FIFO Level register. Provides the current fill levels of the transmit and receive FIFOs. */ + }; + + __IO uint32_t TER2; /*!< Transmit Enable Register. Only on LPC177X_8X UART4 and LPC18XX/43XX USART0/2/3. */ +} LPC_USART_T; + + +/** + * @brief Macro defines for UART Receive Buffer register + */ +#define UART_RBR_MASKBIT (0xFF) /*!< UART Received Buffer mask bit (8 bits) */ + +/** + * @brief Macro defines for UART Divisor Latch LSB register + */ +#define UART_LOAD_DLL(div) ((div) & 0xFF) /*!< Macro for loading LSB of divisor */ +#define UART_DLL_MASKBIT (0xFF) /*!< Divisor latch LSB bit mask */ + +/** + * @brief Macro defines for UART Divisor Latch MSB register + */ +#define UART_LOAD_DLM(div) (((div) >> 8) & 0xFF) /*!< Macro for loading MSB of divisors */ +#define UART_DLM_MASKBIT (0xFF) /*!< Divisor latch MSB bit mask */ + +/** + * @brief Macro defines for UART Interrupt Enable Register + */ +#define UART_IER_RBRINT (1 << 0) /*!< RBR Interrupt enable */ +#define UART_IER_THREINT (1 << 1) /*!< THR Interrupt enable */ +#define UART_IER_RLSINT (1 << 2) /*!< RX line status interrupt enable */ +#define UART_IER_MSINT (1 << 3) /*!< Modem status interrupt enable - valid for 11xx, 17xx/40xx UART1, 18xx/43xx UART1 only */ +#define UART_IER_CTSINT (1 << 7) /*!< CTS signal transition interrupt enable - valid for 17xx/40xx UART1, 18xx/43xx UART1 only */ +#define UART_IER_ABEOINT (1 << 8) /*!< Enables the end of auto-baud interrupt */ +#define UART_IER_ABTOINT (1 << 9) /*!< Enables the auto-baud time-out interrupt */ +#define UART_IER_BITMASK (0x307) /*!< UART interrupt enable register bit mask - valid for 13xx, 17xx/40xx UART0/2/3, 18xx/43xx UART0/2/3 only*/ +#define UART1_IER_BITMASK (0x30F) /*!< UART1 interrupt enable register bit mask - valid for 11xx only */ +#define UART2_IER_BITMASK (0x38F) /*!< UART2 interrupt enable register bit mask - valid for 17xx/40xx UART1, 18xx/43xx UART1 only */ + +/** + * @brief Macro defines for UART Interrupt Identification Register + */ +#define UART_IIR_INTSTAT_PEND (1 << 0) /*!< Interrupt pending status - Active low */ +#define UART_IIR_FIFO_EN (3 << 6) /*!< These bits are equivalent to FCR[0] */ +#define UART_IIR_ABEO_INT (1 << 8) /*!< End of auto-baud interrupt */ +#define UART_IIR_ABTO_INT (1 << 9) /*!< Auto-baud time-out interrupt */ +#define UART_IIR_BITMASK (0x3CF) /*!< UART interrupt identification register bit mask */ + +/* Interrupt ID bit definitions */ +#define UART_IIR_INTID_MASK (7 << 1) /*!< Interrupt identification: Interrupt ID mask */ +#define UART_IIR_INTID_RLS (3 << 1) /*!< Interrupt identification: Receive line interrupt */ +#define UART_IIR_INTID_RDA (2 << 1) /*!< Interrupt identification: Receive data available interrupt */ +#define UART_IIR_INTID_CTI (6 << 1) /*!< Interrupt identification: Character time-out indicator interrupt */ +#define UART_IIR_INTID_THRE (1 << 1) /*!< Interrupt identification: THRE interrupt */ +#define UART_IIR_INTID_MODEM (0 << 1) /*!< Interrupt identification: Modem interrupt */ + +/** + * @brief Macro defines for UART FIFO Control Register + */ +#define UART_FCR_FIFO_EN (1 << 0) /*!< UART FIFO enable */ +#define UART_FCR_RX_RS (1 << 1) /*!< UART RX FIFO reset */ +#define UART_FCR_TX_RS (1 << 2) /*!< UART TX FIFO reset */ +#define UART_FCR_DMAMODE_SEL (1 << 3) /*!< UART DMA mode selection - valid for 17xx/40xx, 18xx/43xx only */ +#define UART_FCR_BITMASK (0xCF) /*!< UART FIFO control bit mask */ + +#define UART_TX_FIFO_SIZE (16) + +/* FIFO trigger level bit definitions */ +#define UART_FCR_TRG_LEV0 (0) /*!< UART FIFO trigger level 0: 1 character */ +#define UART_FCR_TRG_LEV1 (1 << 6) /*!< UART FIFO trigger level 1: 4 character */ +#define UART_FCR_TRG_LEV2 (2 << 6) /*!< UART FIFO trigger level 2: 8 character */ +#define UART_FCR_TRG_LEV3 (3 << 6) /*!< UART FIFO trigger level 3: 14 character */ + +/** + * @brief Macro defines for UART Line Control Register + */ +/* UART word length select bit definitions */ +#define UART_LCR_WLEN_MASK (3 << 0) /*!< UART word length select bit mask */ +#define UART_LCR_WLEN5 (0 << 0) /*!< UART word length select: 5 bit data mode */ +#define UART_LCR_WLEN6 (1 << 0) /*!< UART word length select: 6 bit data mode */ +#define UART_LCR_WLEN7 (2 << 0) /*!< UART word length select: 7 bit data mode */ +#define UART_LCR_WLEN8 (3 << 0) /*!< UART word length select: 8 bit data mode */ + +/* UART Stop bit select bit definitions */ +#define UART_LCR_SBS_MASK (1 << 2) /*!< UART stop bit select: bit mask */ +#define UART_LCR_SBS_1BIT (0 << 2) /*!< UART stop bit select: 1 stop bit */ +#define UART_LCR_SBS_2BIT (1 << 2) /*!< UART stop bit select: 2 stop bits (in 5 bit data mode, 1.5 stop bits) */ + +/* UART Parity enable bit definitions */ +#define UART_LCR_PARITY_EN (1 << 3) /*!< UART Parity Enable */ +#define UART_LCR_PARITY_DIS (0 << 3) /*!< UART Parity Disable */ +#define UART_LCR_PARITY_ODD (0 << 4) /*!< UART Parity select: Odd parity */ +#define UART_LCR_PARITY_EVEN (1 << 4) /*!< UART Parity select: Even parity */ +#define UART_LCR_PARITY_F_1 (2 << 4) /*!< UART Parity select: Forced 1 stick parity */ +#define UART_LCR_PARITY_F_0 (3 << 4) /*!< UART Parity select: Forced 0 stick parity */ +#define UART_LCR_BREAK_EN (1 << 6) /*!< UART Break transmission enable */ +#define UART_LCR_DLAB_EN (1 << 7) /*!< UART Divisor Latches Access bit enable */ +#define UART_LCR_BITMASK (0xFF) /*!< UART line control bit mask */ + +/** + * @brief Macro defines for UART Modem Control Register + */ +#define UART_MCR_DTR_CTRL (1 << 0) /*!< Source for modem output pin DTR */ +#define UART_MCR_RTS_CTRL (1 << 1) /*!< Source for modem output pin RTS */ +#define UART_MCR_LOOPB_EN (1 << 4) /*!< Loop back mode select */ +#define UART_MCR_AUTO_RTS_EN (1 << 6) /*!< Enable Auto RTS flow-control */ +#define UART_MCR_AUTO_CTS_EN (1 << 7) /*!< Enable Auto CTS flow-control */ +#define UART_MCR_BITMASK (0xD3) /*!< UART bit mask value */ + +/** + * @brief Macro defines for UART Line Status Register + */ +#define UART_LSR_RDR (1 << 0) /*!< Line status: Receive data ready */ +#define UART_LSR_OE (1 << 1) /*!< Line status: Overrun error */ +#define UART_LSR_PE (1 << 2) /*!< Line status: Parity error */ +#define UART_LSR_FE (1 << 3) /*!< Line status: Framing error */ +#define UART_LSR_BI (1 << 4) /*!< Line status: Break interrupt */ +#define UART_LSR_THRE (1 << 5) /*!< Line status: Transmit holding register empty */ +#define UART_LSR_TEMT (1 << 6) /*!< Line status: Transmitter empty */ +#define UART_LSR_RXFE (1 << 7) /*!< Line status: Error in RX FIFO */ +#define UART_LSR_TXFE (1 << 8) /*!< Line status: Error in RX FIFO */ +#define UART_LSR_BITMASK (0xFF) /*!< UART Line status bit mask */ +#define UART1_LSR_BITMASK (0x1FF) /*!< UART1 Line status bit mask - valid for 11xx, 18xx/43xx UART0/2/3 only */ + +/** + * @brief Macro defines for UART Modem Status Register + */ +#define UART_MSR_DELTA_CTS (1 << 0) /*!< Modem status: State change of input CTS */ +#define UART_MSR_DELTA_DSR (1 << 1) /*!< Modem status: State change of input DSR */ +#define UART_MSR_LO2HI_RI (1 << 2) /*!< Modem status: Low to high transition of input RI */ +#define UART_MSR_DELTA_DCD (1 << 3) /*!< Modem status: State change of input DCD */ +#define UART_MSR_CTS (1 << 4) /*!< Modem status: Clear To Send State */ +#define UART_MSR_DSR (1 << 5) /*!< Modem status: Data Set Ready State */ +#define UART_MSR_RI (1 << 6) /*!< Modem status: Ring Indicator State */ +#define UART_MSR_DCD (1 << 7) /*!< Modem status: Data Carrier Detect State */ +#define UART_MSR_BITMASK (0xFF) /*!< Modem status: MSR register bit-mask value */ + +/** + * @brief Macro defines for UART Auto baudrate control register + */ +#define UART_ACR_START (1 << 0) /*!< UART Auto-baud start */ +#define UART_ACR_MODE (1 << 1) /*!< UART Auto baudrate Mode 1 */ +#define UART_ACR_AUTO_RESTART (1 << 2) /*!< UART Auto baudrate restart */ +#define UART_ACR_ABEOINT_CLR (1 << 8) /*!< UART End of auto-baud interrupt clear */ +#define UART_ACR_ABTOINT_CLR (1 << 9) /*!< UART Auto-baud time-out interrupt clear */ +#define UART_ACR_BITMASK (0x307) /*!< UART Auto Baudrate register bit mask */ + +/** + * Autobaud modes + */ +#define UART_ACR_MODE0 (0) /*!< Auto baudrate Mode 0 */ +#define UART_ACR_MODE1 (1) /*!< Auto baudrate Mode 1 */ + +/** + * @brief Macro defines for UART RS485 Control register + */ +#define UART_RS485CTRL_NMM_EN (1 << 0) /*!< RS-485/EIA-485 Normal Multi-drop Mode (NMM) is disabled */ +#define UART_RS485CTRL_RX_DIS (1 << 1) /*!< The receiver is disabled */ +#define UART_RS485CTRL_AADEN (1 << 2) /*!< Auto Address Detect (AAD) is enabled */ +#define UART_RS485CTRL_SEL_DTR (1 << 3) /*!< If direction control is enabled (bit DCTRL = 1), pin DTR is + used for direction control */ +#define UART_RS485CTRL_DCTRL_EN (1 << 4) /*!< Enable Auto Direction Control */ +#define UART_RS485CTRL_OINV_1 (1 << 5) /*!< This bit reverses the polarity of the direction + control signal on the RTS (or DTR) pin. The direction control pin + will be driven to logic "1" when the transmitter has data to be sent */ +#define UART_RS485CTRL_BITMASK (0x3F) /*!< RS485 control bit-mask value */ + +/** + * @brief Macro defines for UART IrDA Control Register - valid for 11xx, 17xx/40xx UART0/2/3, 18xx/43xx UART3 only + */ +#define UART_ICR_IRDAEN (1 << 0) /*!< IrDA mode enable */ +#define UART_ICR_IRDAINV (1 << 1) /*!< IrDA serial input inverted */ +#define UART_ICR_FIXPULSE_EN (1 << 2) /*!< IrDA fixed pulse width mode */ +#define UART_ICR_PULSEDIV(n) ((n & 0x07) << 3) /*!< PulseDiv - Configures the pulse when FixPulseEn = 1 */ +#define UART_ICR_BITMASK (0x3F) /*!< UART IRDA bit mask */ + +/** + * @brief Macro defines for UART half duplex register - ???? + */ +#define UART_HDEN_HDEN ((1 << 0)) /*!< enable half-duplex mode*/ + +/** + * @brief Macro defines for UART Smart card interface Control Register - valid for 11xx, 18xx/43xx UART0/2/3 only + */ +#define UART_SCICTRL_SCIEN (1 << 0) /*!< enable asynchronous half-duplex smart card interface*/ +#define UART_SCICTRL_NACKDIS (1 << 1) /*!< NACK response is inhibited*/ +#define UART_SCICTRL_PROTSEL_T1 (1 << 2) /*!< ISO7816-3 protocol T1 is selected*/ +#define UART_SCICTRL_TXRETRY(n) ((n & 0x07) << 5) /*!< number of retransmission*/ +#define UART_SCICTRL_GUARDTIME(n) ((n & 0xFF) << 8) /*!< Extra guard time*/ + +/** + * @brief Macro defines for UART Fractional Divider Register + */ +#define UART_FDR_DIVADDVAL(n) (n & 0x0F) /*!< Baud-rate generation pre-scaler divisor */ +#define UART_FDR_MULVAL(n) ((n << 4) & 0xF0) /*!< Baud-rate pre-scaler multiplier value */ +#define UART_FDR_BITMASK (0xFF) /*!< UART Fractional Divider register bit mask */ + +/** + * @brief Macro defines for UART Tx Enable Register + */ +#define UART_TER1_TXEN (1 << 7) /*!< Transmit enable bit - valid for 11xx, 13xx, 17xx/40xx only */ +#define UART_TER2_TXEN (1 << 0) /*!< Transmit enable bit - valid for 18xx/43xx only */ + +/** + * @brief Macro defines for UART Synchronous Control Register - 11xx, 18xx/43xx UART0/2/3 only + */ +#define UART_SYNCCTRL_SYNC (1 << 0) /*!< enable synchronous mode*/ +#define UART_SYNCCTRL_CSRC_MASTER (1 << 1) /*!< synchronous master mode*/ +#define UART_SYNCCTRL_FES (1 << 2) /*!< sample on falling edge*/ +#define UART_SYNCCTRL_TSBYPASS (1 << 3) /*!< to be defined*/ +#define UART_SYNCCTRL_CSCEN (1 << 4) /*!< Continuous running clock enable (master mode only)*/ +#define UART_SYNCCTRL_STARTSTOPDISABLE (1 << 5) /*!< Do not send start/stop bit*/ +#define UART_SYNCCTRL_CCCLR (1 << 6) /*!< stop continuous clock*/ + +/** + * @brief Transmit a single data byte through the UART peripheral + * @param pUART : Pointer to selected UART peripheral + * @param data : Byte to transmit + * @return Nothing + * @note This function attempts to place a byte into the UART transmit + * FIFO or transmit hold register regard regardless of UART state + */ +STATIC INLINE void Chip_UART_SendByte(LPC_USART_T *pUART, uint8_t data) +{ + pUART->THR = (uint32_t) data; +} + +/** + * @brief Read a single byte data from the UART peripheral + * @param pUART : Pointer to selected UART peripheral + * @return A single byte of data read + * @note This function reads a byte from the UART receive FIFO or + * receive hold register regard regardless of UART state. The + * FIFO status should be read first prior to using this function + */ +STATIC INLINE uint8_t Chip_UART_ReadByte(LPC_USART_T *pUART) +{ + return (uint8_t) (pUART->RBR & UART_RBR_MASKBIT); +} + +/** + * @brief Enable UART interrupts + * @param pUART : Pointer to selected UART peripheral + * @param intMask : OR'ed Interrupts to enable in the Interrupt Enable Register (IER) + * @return Nothing + * @note Use an OR'ed value of UART_IER_* definitions with this function + * to enable specific UART interrupts. The Divisor Latch Access Bit + * (DLAB) in LCR must be cleared in order to access the IER register. + * This function doesn't alter the DLAB state + */ +STATIC INLINE void Chip_UART_IntEnable(LPC_USART_T *pUART, uint32_t intMask) +{ + pUART->IER |= intMask; +} + +/** + * @brief Disable UART interrupts + * @param pUART : Pointer to selected UART peripheral + * @param intMask : OR'ed Interrupts to disable in the Interrupt Enable Register (IER) + * @return Nothing + * @note Use an OR'ed value of UART_IER_* definitions with this function + * to disable specific UART interrupts. The Divisor Latch Access Bit + * (DLAB) in LCR must be cleared in order to access the IER register. + * This function doesn't alter the DLAB state + */ +STATIC INLINE void Chip_UART_IntDisable(LPC_USART_T *pUART, uint32_t intMask) +{ + pUART->IER &= ~intMask; +} + +/** + * @brief Returns UART interrupts that are enabled + * @param pUART : Pointer to selected UART peripheral + * @return Returns the enabled UART interrupts + * @note Use an OR'ed value of UART_IER_* definitions with this function + * to determine which interrupts are enabled. You can check + * for multiple enabled bits if needed. + */ +STATIC INLINE uint32_t Chip_UART_GetIntsEnabled(LPC_USART_T *pUART) +{ + return pUART->IER; +} + +/** + * @brief Read the Interrupt Identification Register (IIR) + * @param pUART : Pointer to selected UART peripheral + * @return Current pending interrupt status per the IIR register + */ +STATIC INLINE uint32_t Chip_UART_ReadIntIDReg(LPC_USART_T *pUART) +{ + return pUART->IIR; +} + +/** + * @brief Setup the UART FIFOs + * @param pUART : Pointer to selected UART peripheral + * @param fcr : FIFO control register setup OR'ed flags + * @return Nothing + * @note Use OR'ed value of UART_FCR_* definitions with this function + * to select specific options. For example, to enable the FIFOs + * with a RX trip level of 8 characters, use something like + * (UART_FCR_FIFO_EN | UART_FCR_TRG_LEV2) + */ +STATIC INLINE void Chip_UART_SetupFIFOS(LPC_USART_T *pUART, uint32_t fcr) +{ + pUART->FCR = fcr; +} + +/** + * @brief Configure data width, parity and stop bits + * @param pUART : Pointer to selected pUART peripheral + * @param config : UART configuration, OR'ed values of UART_LCR_* defines + * @return Nothing + * @note Select OR'ed config options for the UART from the UART_LCR_* + * definitions. For example, a configuration of 8 data bits, 1 + * stop bit, and even (enabled) parity would be + * (UART_LCR_WLEN8 | UART_LCR_SBS_1BIT | UART_LCR_PARITY_EN | UART_LCR_PARITY_EVEN) + */ +STATIC INLINE void Chip_UART_ConfigData(LPC_USART_T *pUART, uint32_t config) +{ + pUART->LCR = config; +} + +/** + * @brief Enable access to Divisor Latches + * @param pUART : Pointer to selected UART peripheral + * @return Nothing + */ +STATIC INLINE void Chip_UART_EnableDivisorAccess(LPC_USART_T *pUART) +{ + pUART->LCR |= UART_LCR_DLAB_EN; +} + +/** + * @brief Disable access to Divisor Latches + * @param pUART : Pointer to selected UART peripheral + * @return Nothing + */ +STATIC INLINE void Chip_UART_DisableDivisorAccess(LPC_USART_T *pUART) +{ + pUART->LCR &= ~UART_LCR_DLAB_EN; +} + +/** + * @brief Set LSB and MSB divisor latch registers + * @param pUART : Pointer to selected UART peripheral + * @param dll : Divisor Latch LSB value + * @param dlm : Divisor Latch MSB value + * @return Nothing + * @note The Divisor Latch Access Bit (DLAB) in LCR must be set in + * order to access the USART Divisor Latches. This function + * doesn't alter the DLAB state. + */ +STATIC INLINE void Chip_UART_SetDivisorLatches(LPC_USART_T *pUART, uint8_t dll, uint8_t dlm) +{ + pUART->DLL = (uint32_t) dll; + pUART->DLM = (uint32_t) dlm; +} + + +/** + * @brief Return modem control register/status + * @param pUART : Pointer to selected UART peripheral + * @return Modem control register (status) + * @note Mask bits of the returned status value with UART_MCR_* + * definitions for specific statuses. + */ +STATIC INLINE uint32_t Chip_UART_ReadModemControl(LPC_USART_T *pUART) +{ + return pUART->MCR; +} + +/** + * @brief Set modem control register/status + * @param pUART : Pointer to selected UART peripheral + * @param mcr : Modem control register flags to set + * @return Nothing + * @note Use an Or'ed value of UART_MCR_* definitions with this + * call to set specific options. + */ +STATIC INLINE void Chip_UART_SetModemControl(LPC_USART_T *pUART, uint32_t mcr) +{ + pUART->MCR |= mcr; +} + +/** + * @brief Clear modem control register/status + * @param pUART : Pointer to selected UART peripheral + * @param mcr : Modem control register flags to clear + * @return Nothing + * @note Use an Or'ed value of UART_MCR_* definitions with this + * call to clear specific options. + */ +STATIC INLINE void Chip_UART_ClearModemControl(LPC_USART_T *pUART, uint32_t mcr) +{ + pUART->MCR &= ~mcr; +} + +/** + * @brief Return Line Status register/status (LSR) + * @param pUART : Pointer to selected UART peripheral + * @return Line Status register (status) + * @note Mask bits of the returned status value with UART_LSR_* + * definitions for specific statuses. + */ +STATIC INLINE uint32_t Chip_UART_ReadLineStatus(LPC_USART_T *pUART) +{ + return pUART->LSR; +} + +/** + * @brief Return Modem Status register/status (MSR) + * @param pUART : Pointer to selected UART peripheral + * @return Modem Status register (status) + * @note Mask bits of the returned status value with UART_MSR_* + * definitions for specific statuses. + */ +STATIC INLINE uint32_t Chip_UART_ReadModemStatus(LPC_USART_T *pUART) +{ + return pUART->MSR; +} + +/** + * @brief Write a byte to the scratchpad register + * @param pUART : Pointer to selected UART peripheral + * @param data : Byte value to write + * @return Nothing + */ +STATIC INLINE void Chip_UART_SetScratch(LPC_USART_T *pUART, uint8_t data) +{ + pUART->SCR = (uint32_t) data; +} + +/** + * @brief Returns current byte value in the scratchpad register + * @param pUART : Pointer to selected UART peripheral + * @return Byte value read from scratchpad register + */ +STATIC INLINE uint8_t Chip_UART_ReadScratch(LPC_USART_T *pUART) +{ + return (uint8_t) (pUART->SCR & 0xFF); +} + +/** + * @brief Set autobaud register options + * @param pUART : Pointer to selected UART peripheral + * @param acr : Or'ed values to set for ACR register + * @return Nothing + * @note Use an Or'ed value of UART_ACR_* definitions with this + * call to set specific options. + */ +STATIC INLINE void Chip_UART_SetAutoBaudReg(LPC_USART_T *pUART, uint32_t acr) +{ + pUART->ACR |= acr; +} + +/** + * @brief Clear autobaud register options + * @param pUART : Pointer to selected UART peripheral + * @param acr : Or'ed values to clear for ACR register + * @return Nothing + * @note Use an Or'ed value of UART_ACR_* definitions with this + * call to clear specific options. + */ +STATIC INLINE void Chip_UART_ClearAutoBaudReg(LPC_USART_T *pUART, uint32_t acr) +{ + pUART->ACR &= ~acr; +} + +/** + * @brief Set RS485 control register options + * @param pUART : Pointer to selected UART peripheral + * @param ctrl : Or'ed values to set for RS485 control register + * @return Nothing + * @note Use an Or'ed value of UART_RS485CTRL_* definitions with this + * call to set specific options. + */ +STATIC INLINE void Chip_UART_SetRS485Flags(LPC_USART_T *pUART, uint32_t ctrl) +{ + pUART->RS485CTRL |= ctrl; +} + +/** + * @brief Clear RS485 control register options + * @param pUART : Pointer to selected UART peripheral + * @param ctrl : Or'ed values to clear for RS485 control register + * @return Nothing + * @note Use an Or'ed value of UART_RS485CTRL_* definitions with this + * call to clear specific options. + */ +STATIC INLINE void Chip_UART_ClearRS485Flags(LPC_USART_T *pUART, uint32_t ctrl) +{ + pUART->RS485CTRL &= ~ctrl; +} + +/** + * @brief Set RS485 address match value + * @param pUART : Pointer to selected UART peripheral + * @param addr : Address match value for RS-485/EIA-485 mode + * @return Nothing + */ +STATIC INLINE void Chip_UART_SetRS485Addr(LPC_USART_T *pUART, uint8_t addr) +{ + pUART->RS485ADRMATCH = (uint32_t) addr; +} + +/** + * @brief Read RS485 address match value + * @param pUART : Pointer to selected UART peripheral + * @return Address match value for RS-485/EIA-485 mode + */ +STATIC INLINE uint8_t Chip_UART_GetRS485Addr(LPC_USART_T *pUART) +{ + return (uint8_t) (pUART->RS485ADRMATCH & 0xFF); +} + +/** + * @brief Set RS485 direction control (RTS or DTR) delay value + * @param pUART : Pointer to selected UART peripheral + * @param dly : direction control (RTS or DTR) delay value + * @return Nothing + * @note This delay time is in periods of the baud clock. Any delay + * time from 0 to 255 bit times may be programmed. + */ +STATIC INLINE void Chip_UART_SetRS485Delay(LPC_USART_T *pUART, uint8_t dly) +{ + pUART->RS485DLY = (uint32_t) dly; +} + +/** + * @brief Read RS485 direction control (RTS or DTR) delay value + * @param pUART : Pointer to selected UART peripheral + * @return direction control (RTS or DTR) delay value + * @note This delay time is in periods of the baud clock. Any delay + * time from 0 to 255 bit times may be programmed. + */ +STATIC INLINE uint8_t Chip_UART_GetRS485Delay(LPC_USART_T *pUART) +{ + return (uint8_t) (pUART->RS485DLY & 0xFF); +} + +/** + * @brief Initializes the pUART peripheral + * @param pUART : Pointer to selected pUART peripheral + * @return Nothing + */ +void Chip_UART_Init(LPC_USART_T *pUART); + +/** + * @brief De-initializes the pUART peripheral. + * @param pUART : Pointer to selected pUART peripheral + * @return Nothing + */ +void Chip_UART_DeInit(LPC_USART_T *pUART); + +/** + * @brief Enable transmission on UART TxD pin + * @param pUART : Pointer to selected pUART peripheral + * @return Nothing + */ +void Chip_UART_TXEnable(LPC_USART_T *pUART); + +/** + * @brief Disable transmission on UART TxD pin + * @param pUART : Pointer to selected pUART peripheral + * @return Nothing + */ +void Chip_UART_TXDisable(LPC_USART_T *pUART); + +/** + * @brief Check whether if UART is busy or not + * @param pUART : Pointer to selected pUART peripheral + * @return RESET if UART is not busy, otherwise return SET + */ +FlagStatus Chip_UART_CheckBusy(LPC_USART_T *pUART); + +/** + * @brief Transmit a byte array through the UART peripheral (non-blocking) + * @param pUART : Pointer to selected UART peripheral + * @param data : Pointer to bytes to transmit + * @param numBytes : Number of bytes to transmit + * @return The actual number of bytes placed into the FIFO + * @note This function places data into the transmit FIFO until either + * all the data is in the FIFO or the FIFO is full. This function + * will not block in the FIFO is full. The actual number of bytes + * placed into the FIFO is returned. This function ignores errors. + */ +int Chip_UART_Send(LPC_USART_T *pUART, const void *data, int numBytes); + +/** + * @brief Read data through the UART peripheral (non-blocking) + * @param pUART : Pointer to selected UART peripheral + * @param data : Pointer to bytes array to fill + * @param numBytes : Size of the passed data array + * @return The actual number of bytes read + * @note This function reads data from the receive FIFO until either + * all the data has been read or the passed buffer is completely full. + * This function will not block. This function ignores errors. + */ +int Chip_UART_Read(LPC_USART_T *pUART, void *data, int numBytes); + +/** + * @brief Sets best dividers to get a target bit rate (without fractional divider) + * @param pUART : Pointer to selected UART peripheral + * @param baudrate : Target baud rate (baud rate = bit rate) + * @return The actual baud rate, or 0 if no rate can be found + */ +uint32_t Chip_UART_SetBaud(LPC_USART_T *pUART, uint32_t baudrate); + +/** + * @brief Sets best dividers to get a target bit rate (with fractional divider) + * @param pUART : Pointer to selected UART peripheral + * @param baudrate : Target baud rate (baud rate = bit rate) + * @return The actual baud rate, or 0 if no rate can be found + */ +uint32_t Chip_UART_SetBaudFDR(LPC_USART_T *pUART, uint32_t baudrate); + +/** + * @brief Transmit a byte array through the UART peripheral (blocking) + * @param pUART : Pointer to selected UART peripheral + * @param data : Pointer to data to transmit + * @param numBytes : Number of bytes to transmit + * @return The number of bytes transmitted + * @note This function will send or place all bytes into the transmit + * FIFO. This function will block until the last bytes are in the FIFO. + */ +int Chip_UART_SendBlocking(LPC_USART_T *pUART, const void *data, int numBytes); + +/** + * @brief Read data through the UART peripheral (blocking) + * @param pUART : Pointer to selected UART peripheral + * @param data : Pointer to data array to fill + * @param numBytes : Size of the passed data array + * @return The size of the dat array + * @note This function reads data from the receive FIFO until the passed + * buffer is completely full. The function will block until full. + * This function ignores errors. + */ +int Chip_UART_ReadBlocking(LPC_USART_T *pUART, void *data, int numBytes); + +/** + * @brief UART receive-only interrupt handler for ring buffers + * @param pUART : Pointer to selected UART peripheral + * @param pRB : Pointer to ring buffer structure to use + * @return Nothing + * @note If ring buffer support is desired for the receive side + * of data transfer, the UART interrupt should call this + * function for a receive based interrupt status. + */ +void Chip_UART_RXIntHandlerRB(LPC_USART_T *pUART, RINGBUFF_T *pRB); + +/** + * @brief UART transmit-only interrupt handler for ring buffers + * @param pUART : Pointer to selected UART peripheral + * @param pRB : Pointer to ring buffer structure to use + * @return Nothing + * @note If ring buffer support is desired for the transmit side + * of data transfer, the UART interrupt should call this + * function for a transmit based interrupt status. + */ +void Chip_UART_TXIntHandlerRB(LPC_USART_T *pUART, RINGBUFF_T *pRB); + +/** + * @brief Populate a transmit ring buffer and start UART transmit + * @param pUART : Pointer to selected UART peripheral + * @param pRB : Pointer to ring buffer structure to use + * @param data : Pointer to buffer to move to ring buffer + * @param bytes : Number of bytes to move + * @return The number of bytes placed into the ring buffer + * @note Will move the data into the TX ring buffer and start the + * transfer. If the number of bytes returned is less than the + * number of bytes to send, the ring buffer is considered full. + */ +uint32_t Chip_UART_SendRB(LPC_USART_T *pUART, RINGBUFF_T *pRB, const void *data, int bytes); + +/** + * @brief Copy data from a receive ring buffer + * @param pUART : Pointer to selected UART peripheral + * @param pRB : Pointer to ring buffer structure to use + * @param data : Pointer to buffer to fill from ring buffer + * @param bytes : Size of the passed buffer in bytes + * @return The number of bytes placed into the ring buffer + * @note Will move the data from the RX ring buffer up to the + * the maximum passed buffer size. Returns 0 if there is + * no data in the ring buffer. + */ +int Chip_UART_ReadRB(LPC_USART_T *pUART, RINGBUFF_T *pRB, void *data, int bytes); + +/** + * @brief UART receive/transmit interrupt handler for ring buffers + * @param pUART : Pointer to selected UART peripheral + * @param pRXRB : Pointer to transmit ring buffer + * @param pTXRB : Pointer to receive ring buffer + * @return Nothing + * @note This provides a basic implementation of the UART IRQ + * handler for support of a ring buffer implementation for + * transmit and receive. + */ +void Chip_UART_IRQRBHandler(LPC_USART_T *pUART, RINGBUFF_T *pRXRB, RINGBUFF_T *pTXRB); + +/** + * @brief Returns the Auto Baud status + * @param pUART : Pointer to selected UART peripheral + * @return RESET if autobaud not completed, SET if autobaud completed + */ +FlagStatus Chip_UART_GetABEOStatus(LPC_USART_T *pUART); + +/** + * @brief Start/stop autobaud operation + * @param pUART : Pointer to selected UART peripheral + * @param mode : Autobaud mode (UART_ACR_MODE0 or UART_ACR_MODE1) + * @param autorestart : Enable autorestart (true to enable or false to disable) + * @param NewState : ENABLE to start autobaud operation, DISABLE to + * stop autobaud operation + * @return Nothing + */ +void Chip_UART_ABCmd(LPC_USART_T *pUART, uint32_t mode, bool autorestart, + FunctionalState NewState); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __UART_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/usb_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/usb_17xx_40xx.h new file mode 100644 index 000000000..d510a3aef --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/usb_17xx_40xx.h @@ -0,0 +1,160 @@ +/* + * @brief LPC17xx/40xx USB driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licenser disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __USB_17XX_40XX_H_ +#define __USB_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup USB_17XX_40XX CHIP: LPC17xx/40xx USB Device, Host, & OTG driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +/** + * @brief USB register block structure + */ +typedef struct { + __I uint32_t Revision; /* USB Host Registers */ + __IO uint32_t Control; + __IO uint32_t CommandStatus; + __IO uint32_t InterruptStatus; + __IO uint32_t InterruptEnable; + __IO uint32_t InterruptDisable; + __IO uint32_t HCCA; + __I uint32_t PeriodCurrentED; + __IO uint32_t ControlHeadED; + __IO uint32_t ControlCurrentED; + __IO uint32_t BulkHeadED; + __IO uint32_t BulkCurrentED; + __I uint32_t DoneHead; + __IO uint32_t FmInterval; + __I uint32_t FmRemaining; + __I uint32_t FmNumber; + __IO uint32_t PeriodicStart; + __IO uint32_t LSTreshold; + __IO uint32_t RhDescriptorA; + __IO uint32_t RhDescriptorB; + __IO uint32_t RhStatus; + __IO uint32_t RhPortStatus1; + __IO uint32_t RhPortStatus2; + uint32_t RESERVED0[40]; + __I uint32_t Module_ID; + + __I uint32_t IntSt; /* USB On-The-Go Registers */ + __IO uint32_t IntEn; + __O uint32_t IntSet; + __O uint32_t IntClr; + __IO uint32_t StCtrl; + __IO uint32_t Tmr; + uint32_t RESERVED1[58]; + + __I uint32_t DevIntSt; /* USB Device Interrupt Registers */ + __IO uint32_t DevIntEn; + __O uint32_t DevIntClr; + __O uint32_t DevIntSet; + + __O uint32_t CmdCode; /* USB Device SIE Command Registers */ + __I uint32_t CmdData; + + __I uint32_t RxData; /* USB Device Transfer Registers */ + __O uint32_t TxData; + __I uint32_t RxPLen; + __O uint32_t TxPLen; + __IO uint32_t Ctrl; + __O uint32_t DevIntPri; + + __I uint32_t EpIntSt; /* USB Device Endpoint Interrupt Regs */ + __IO uint32_t EpIntEn; + __O uint32_t EpIntClr; + __O uint32_t EpIntSet; + __O uint32_t EpIntPri; + + __IO uint32_t ReEp; /* USB Device Endpoint Realization Reg*/ + __O uint32_t EpInd; + __IO uint32_t MaxPSize; + + __I uint32_t DMARSt; /* USB Device DMA Registers */ + __O uint32_t DMARClr; + __O uint32_t DMARSet; + uint32_t RESERVED2[9]; + __IO uint32_t UDCAH; + __I uint32_t EpDMASt; + __O uint32_t EpDMAEn; + __O uint32_t EpDMADis; + __I uint32_t DMAIntSt; + __IO uint32_t DMAIntEn; + uint32_t RESERVED3[2]; + __I uint32_t EoTIntSt; + __O uint32_t EoTIntClr; + __O uint32_t EoTIntSet; + __I uint32_t NDDRIntSt; + __O uint32_t NDDRIntClr; + __O uint32_t NDDRIntSet; + __I uint32_t SysErrIntSt; + __O uint32_t SysErrIntClr; + __O uint32_t SysErrIntSet; + uint32_t RESERVED4[15]; + + union { + __I uint32_t I2C_RX; /* USB OTG I2C Registers */ + __O uint32_t I2C_TX; + }; + + __IO uint32_t I2C_STS; + __IO uint32_t I2C_CTL; + __IO uint32_t I2C_CLKHI; + __O uint32_t I2C_CLKLO; + uint32_t RESERVED5[824]; + + union { + __IO uint32_t USBClkCtrl; /* USB Clock Control Registers */ + __IO uint32_t OTGClkCtrl; + }; + + union { + __I uint32_t USBClkSt; + __I uint32_t OTGClkSt; + }; + +} LPC_USB_T; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __USB_17Xx_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/inc/wwdt_17xx_40xx.h b/hw/mcu/nxp/lpc_chip_40xx/inc/wwdt_17xx_40xx.h new file mode 100644 index 000000000..b314c9e5d --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/inc/wwdt_17xx_40xx.h @@ -0,0 +1,276 @@ +/* + * @brief LPC17xx/40xx WWDT driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#ifndef __WWDT_17XX_40XX_H_ +#define __WWDT_17XX_40XX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup WWDT_17XX_40XX CHIP: LPC17xx/40xx Windowed Watchdog driver + * @ingroup CHIP_17XX_40XX_Drivers + * @{ + */ + +#if !defined(CHIP_LPC175X_6X) +#define WATCHDOG_WINDOW_SUPPORT +#endif + +#if defined(CHIP_LPC175X_6X) +#define WATCHDOG_CLKSEL_SUPPORT +#endif + +/** WDT oscillator frequency value */ +#define WDT_OSC (500000 / 4) /*!< Dedicated oscillator that provides a 500 kHz clock to Watchdog timer*/ + +/** + * @brief Windowed Watchdog register block structure + */ +typedef struct { /*!< WWDT Structure */ + __IO uint32_t MOD; /*!< Watchdog mode register. This register contains the basic mode and status of the Watchdog Timer. */ + __IO uint32_t TC; /*!< Watchdog timer constant register. This register determines the time-out value. */ + __O uint32_t FEED; /*!< Watchdog feed sequence register. Writing 0xAA followed by 0x55 to this register reloads the Watchdog timer with the value contained in WDTC. */ + __I uint32_t TV; /*!< Watchdog timer value register. This register reads out the current value of the Watchdog timer. */ +#ifdef WATCHDOG_CLKSEL_SUPPORT + __IO uint32_t CLKSEL; /*!< Watchdog clock select register. */ +#else + __I uint32_t RESERVED0; +#endif +#ifdef WATCHDOG_WINDOW_SUPPORT + __IO uint32_t WARNINT; /*!< Watchdog warning interrupt register. This register contains the Watchdog warning interrupt compare value. */ + __IO uint32_t WINDOW; /*!< Watchdog timer window register. This register contains the Watchdog window value. */ +#endif +} LPC_WWDT_T; + +/** + * @brief Watchdog Mode register definitions + */ +/** Watchdog Mode Bitmask */ +#define WWDT_WDMOD_BITMASK ((uint32_t) 0x1F) +/** WWDT interrupt enable bit */ +#define WWDT_WDMOD_WDEN ((uint32_t) (1 << 0)) +/** WWDT interrupt enable bit */ +#define WWDT_WDMOD_WDRESET ((uint32_t) (1 << 1)) +/** WWDT time out flag bit */ +#define WWDT_WDMOD_WDTOF ((uint32_t) (1 << 2)) +/** WDT Time Out flag bit */ +#define WWDT_WDMOD_WDINT ((uint32_t) (1 << 3)) +#if !defined(CHIP_LPC175X_6X) +/** WWDT Protect flag bit */ +#define WWDT_WDMOD_WDPROTECT ((uint32_t) (1 << 4)) +#endif + +/** + * @brief Initialize the Watchdog timer + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @return None + */ +void Chip_WWDT_Init(LPC_WWDT_T *pWWDT); + +/** + * @brief Shutdown the Watchdog timer + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @return None + */ +STATIC INLINE void Chip_WWDT_DeInit(LPC_WWDT_T *pWWDT) {} + +/** + * @brief Set WDT timeout constant value used for feed + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @param timeout : WDT timeout in ticks, between WWDT_TICKS_MIN and WWDT_TICKS_MAX + * @return none + */ +STATIC INLINE void Chip_WWDT_SetTimeOut(LPC_WWDT_T *pWWDT, uint32_t timeout) +{ + pWWDT->TC = timeout; +} + +/** + * @brief Feed watchdog timer + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @return None + * @note If this function isn't called, a watchdog timer warning will occur. + * After the warning, a timeout will occur if a feed has happened. + */ +STATIC INLINE void Chip_WWDT_Feed(LPC_WWDT_T *pWWDT) +{ + pWWDT->FEED = 0xAA; + pWWDT->FEED = 0x55; +} + +#if defined(WATCHDOG_WINDOW_SUPPORT) +/** + * @brief Set WWDT warning interrupt + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @param timeout : WDT warning in ticks, between 0 and 1023 + * @return None + * @note This is the number of ticks after the watchdog interrupt that the + * warning interrupt will be generated. + */ +STATIC INLINE void Chip_WWDT_SetWarning(LPC_WWDT_T *pWWDT, uint32_t timeout) +{ + pWWDT->WARNINT = timeout; +} + +/** + * @brief Set WWDT window time + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @param timeout : WDT timeout in ticks, between WWDT_TICKS_MIN and WWDT_TICKS_MAX + * @return None + * @note The watchdog timer must be fed between the timeout from the Chip_WWDT_SetTimeOut() + * function and this function, with this function defining the last tick before the + * watchdog window interrupt occurs. + */ +STATIC INLINE void Chip_WWDT_SetWindow(LPC_WWDT_T *pWWDT, uint32_t timeout) +{ + pWWDT->WINDOW = timeout; +} + +#endif + +/** + * @brief Enable watchdog timer options + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @param options : An or'ed set of options of values + * WWDT_WDMOD_WDEN, WWDT_WDMOD_WDRESET, and WWDT_WDMOD_WDPROTECT + * @return None + * @note You can enable more than one option at once (ie, WWDT_WDMOD_WDRESET | + * WWDT_WDMOD_WDPROTECT), but use the WWDT_WDMOD_WDEN after all other options + * are set (or unset) with no other options. If WWDT_WDMOD_LOCK is used, it cannot + * be unset. + */ +STATIC INLINE void Chip_WWDT_SetOption(LPC_WWDT_T *pWWDT, uint32_t options) +{ + pWWDT->MOD |= options; +} + +/** + * @brief Disable/clear watchdog timer options + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @param options : An or'ed set of options of values + * WWDT_WDMOD_WDEN, WWDT_WDMOD_WDRESET, and WWDT_WDMOD_WDPROTECT + * @return None + * @note You can disable more than one option at once (ie, WWDT_WDMOD_WDRESET | + * WWDT_WDMOD_WDTOF). + */ +STATIC INLINE void Chip_WWDT_UnsetOption(LPC_WWDT_T *pWWDT, uint32_t options) +{ + pWWDT->MOD &= (~options) & WWDT_WDMOD_BITMASK; +} + +/** + * @brief Enable WWDT activity + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @return None + */ +STATIC INLINE void Chip_WWDT_Start(LPC_WWDT_T *pWWDT) +{ + Chip_WWDT_SetOption(pWWDT, WWDT_WDMOD_WDEN); + Chip_WWDT_Feed(pWWDT); +} + +/** + * @brief Read WWDT status flag + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @return Watchdog status, an Or'ed value of WWDT_WDMOD_* + */ +STATIC INLINE uint32_t Chip_WWDT_GetStatus(LPC_WWDT_T *pWWDT) +{ + return pWWDT->MOD; +} + +/** + * @brief Clear WWDT interrupt status flags + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @param status : Or'ed value of status flag(s) that you want to clear, should be: + * - WWDT_WDMOD_WDTOF: Clear watchdog timeout flag + * - WWDT_WDMOD_WDINT: Clear watchdog warning flag + * @return None + */ +void Chip_WWDT_ClearStatusFlag(LPC_WWDT_T *pWWDT, uint32_t status); + +/** + * @brief Get the current value of WDT + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @return current value of WDT + */ +STATIC INLINE uint32_t Chip_WWDT_GetCurrentCount(LPC_WWDT_T *pWWDT) +{ + return pWWDT->TV; +} + +#if defined(WATCHDOG_CLKSEL_SUPPORT) +/** + * @brief Watchdog Timer Clock Source Selection register definitions + */ +/** Clock source select bitmask */ +#define WWDT_CLKSEL_BITMASK ((uint32_t) 0x10000003) +/** Clock source select */ +#define WWDT_CLKSEL_SOURCE(n) ((uint32_t) (n & 0x03)) +/** Lock the clock source selection */ +#define WWDT_CLKSEL_LOCK ((uint32_t) (1 << 31)) + +/** + * @brief Watchdog Clock Source definitions + */ +typedef enum { + WWDT_CLKSRC_IRC = WWDT_CLKSEL_SOURCE(0), /*!< Internal RC oscillator */ +#if defined(CHIP_LPC175X_6X) + WWDT_CLKSRC_WATCHDOG_PCLK = WWDT_CLKSEL_SOURCE(1), /*!< APB peripheral clock (watchdog pclk) */ + WWDT_CLKSRC_RTC_CLK = WWDT_CLKSEL_SOURCE(2), /*!< RTC oscillator (rtc_clk) */ +#else + WWDT_CLKSRC_WATCHDOG_WDOSC = WWDT_CLKSEL_SOURCE(1), /*!< Watchdog oscillator (WDOSC) */ +#endif +} CHIP_WWDT_CLK_SRC_T; + +/** + * @brief Get the current value of WDT + * @param pWWDT : The base of WatchDog Timer peripheral on the chip + * @param wdtClkSrc : Selected watchdog clock source + * @return Nothing + */ +STATIC INLINE void Chip_WWDT_SelClockSource(LPC_WWDT_T *pWWDT, CHIP_WWDT_CLK_SRC_T wdtClkSrc) +{ + pWWDT->CLKSEL = wdtClkSrc & WWDT_CLKSEL_BITMASK; +} + +#endif + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __WWDT_17XX_40XX_H_ */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/adc_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/adc_17xx_40xx.c new file mode 100644 index 000000000..13a61b525 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/adc_17xx_40xx.c @@ -0,0 +1,256 @@ +/* + * @brief LPC17xx/40xx A/D conversion driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/* Get the number of clock for a full conversion */ +STATIC INLINE uint8_t getFullConvClk(void) +{ +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + return 31; +#elif defined(CHIP_LPC175X_6X) + return 65; +#else + return 0; +#endif + +} + +/* Get divider value */ +STATIC uint8_t getClkDiv(LPC_ADC_T *pADC, bool burstMode, uint32_t adcRate, uint8_t clks) +{ + uint32_t adcBlockFreq; + uint32_t fullAdcRate; + uint8_t div; + + /* The APB clock (PCLK_ADC0) is divided by (CLKDIV+1) to produce the clock for + A/D converter, which should be less than or equal to 4.5MHz. + A fully conversion requires (bits_accuracy+1) of these clocks. + ADC Clock = PCLK_ADC0 / (CLKDIV + 1); + ADC rate = ADC clock / (the number of clocks required for each conversion); + */ +#if defined(CHIP_LPC175X_6X) + adcBlockFreq = Chip_Clock_GetPeripheralClockRate(SYSCTL_PCLK_ADC); +#else + adcBlockFreq = Chip_Clock_GetPeripheralClockRate(); +#endif +#if defined(ADC_ACC_12BITS) + fullAdcRate = adcRate * getFullConvClk(); +#else + if (burstMode) { + fullAdcRate = adcRate * clks; + } + else { + fullAdcRate = adcRate * getFullConvClk(); + } +#endif + /* Get the round value by fomular: (2*A + B)/(2*B) */ + div = ((adcBlockFreq * 2 + fullAdcRate) / (fullAdcRate * 2)) - 1; + return div; +} + +/* Set start mode for ADC */ +void setStartMode(LPC_ADC_T *pADC, uint8_t start_mode) +{ + uint32_t temp; + temp = pADC->CR & (~ADC_CR_START_MASK); + pADC->CR = temp | (ADC_CR_START_MODE_SEL((uint32_t) start_mode)); +} + +/* Get the ADC value */ +Status readAdcVal(LPC_ADC_T *pADC, uint8_t channel, uint16_t *data) +{ + uint32_t temp; + temp = pADC->DR[channel]; + if (!ADC_DR_DONE(temp)) { + return ERROR; + } + /* if(ADC_DR_OVERRUN(temp) && (pADC->CR & ADC_CR_BURST)) */ + /* return ERROR; */ + *data = (uint16_t) ADC_DR_RESULT(temp); + return SUCCESS; +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the ADC peripheral and the ADC setup structure to default value */ +void Chip_ADC_Init(LPC_ADC_T *pADC, ADC_CLOCK_SETUP_T *ADCSetup) +{ + uint8_t div; + uint32_t cr = 0; + uint32_t clk; + + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_ADC); + +#if defined(ADC_TRIM_SUPPORT) + pADC->ADTRM = 0xF00; +#endif + pADC->INTEN = 0; /* Disable all interrupts */ + + cr |= ADC_CR_PDN; + + ADCSetup->adcRate = ADC_MAX_SAMPLE_RATE; + ADCSetup->bitsAccuracy = 0; /* LPC17xx/40xx doesn't support this setting */ + clk = 0; + ADCSetup->burstMode = false; + div = getClkDiv(pADC, false, ADCSetup->adcRate, clk); + cr |= ADC_CR_CLKDIV(div); +#if !defined(ADC_ACC_12BITS) + cr |= ADC_CR_BITACC(ADCSetup->bitsAccuracy); +#endif /*defined(ADC_ACC_12BITS)*/ + pADC->CR = cr; +} + +/* Shutdown ADC */ +void Chip_ADC_DeInit(LPC_ADC_T *pADC) +{ + pADC->INTEN = 0x00000100; + pADC->CR = 0; + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_ADC); +} + +/* Get the ADC value */ +Status Chip_ADC_ReadValue(LPC_ADC_T *pADC, uint8_t channel, uint16_t *data) +{ + return readAdcVal(pADC, channel, data); +} + +/* Get ADC Channel status from ADC data register */ +FlagStatus Chip_ADC_ReadStatus(LPC_ADC_T *pADC, uint8_t channel, uint32_t StatusType) +{ + switch (StatusType) { + case ADC_DR_DONE_STAT: + return (pADC->STAT & (1UL << channel)) ? SET : RESET; + + case ADC_DR_OVERRUN_STAT: + channel += 8; + return (pADC->STAT & (1UL << channel)) ? SET : RESET; + + case ADC_DR_ADINT_STAT: + return pADC->STAT >> 16 ? SET : RESET; + + default: + break; + } + return RESET; +} + +/* Enable/Disable interrupt for ADC channel */ +void Chip_ADC_Int_SetChannelCmd(LPC_ADC_T *pADC, uint8_t channel, FunctionalState NewState) +{ + if (NewState == ENABLE) { + pADC->INTEN |= (1UL << channel); + } + else { + pADC->INTEN &= (~(1UL << channel)); + } +} + +/* Select the mode starting the AD conversion */ +void Chip_ADC_SetStartMode(LPC_ADC_T *pADC, ADC_START_MODE_T mode, ADC_EDGE_CFG_T EdgeOption) +{ + if ((mode != ADC_START_NOW) && (mode != ADC_NO_START)) { + if (EdgeOption) { + pADC->CR |= ADC_CR_EDGE; + } + else { + pADC->CR &= ~ADC_CR_EDGE; + } + } + setStartMode(pADC, (uint8_t) mode); +} + +/* Set the ADC Sample rate */ +void Chip_ADC_SetSampleRate(LPC_ADC_T *pADC, ADC_CLOCK_SETUP_T *ADCSetup, uint32_t rate) +{ + uint8_t div; + uint32_t cr; + + cr = pADC->CR & (~ADC_SAMPLE_RATE_CONFIG_MASK); + ADCSetup->adcRate = rate; + div = getClkDiv(pADC, ADCSetup->burstMode, rate, (11 - ADCSetup->bitsAccuracy)); + cr |= ADC_CR_CLKDIV(div); +#if !defined(ADC_ACC_12BITS) + cr |= ADC_CR_BITACC(ADCSetup->bitsAccuracy); +#endif /*defined(ADC_ACC_12BITS)*/ + pADC->CR = cr; +} + +/* Enable or disable the ADC channel on ADC peripheral */ +void Chip_ADC_EnableChannel(LPC_ADC_T *pADC, ADC_CHANNEL_T channel, FunctionalState NewState) +{ + if (NewState == ENABLE) { + pADC->CR |= ADC_CR_CH_SEL(channel); + } + else { + pADC->CR &= ~ADC_CR_START_MASK; + pADC->CR &= ~ADC_CR_CH_SEL(channel); + } +} + +/* Enable burst mode */ +void Chip_ADC_SetBurstCmd(LPC_ADC_T *pADC, FunctionalState NewState) +{ + setStartMode(pADC, ADC_NO_START); + + if (NewState == DISABLE) { + pADC->CR &= ~ADC_CR_BURST; + } + else { + pADC->CR |= ADC_CR_BURST; + } +} + +/* Read the ADC value and convert it to 8bits value */ +Status Chip_ADC_ReadByte(LPC_ADC_T *pADC, ADC_CHANNEL_T channel, uint8_t *data) +{ + uint16_t temp; + Status rt; + + rt = readAdcVal(pADC, channel, &temp); + *data = (uint8_t) temp; + + return rt; +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/can_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/can_17xx_40xx.c new file mode 100644 index 000000000..636d9df89 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/can_17xx_40xx.c @@ -0,0 +1,1507 @@ +/* + * @brief LPC17xx/40xx CAN driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/* Set Bus Timing */ +STATIC void setBusTiming(LPC_CAN_T *pCAN, IP_CAN_BUS_TIMING_T *pBusTiming) { + /* Enter to Reset Mode */ + Chip_CAN_SetMode(pCAN, CAN_RESET_MODE, ENABLE); + + /* Set Bus Timing */ + pCAN->BTR = CAN_BTR_BRP(pBusTiming->BRP) + | CAN_BTR_SJW(pBusTiming->SJW) + | CAN_BTR_TESG1(pBusTiming->TESG1) + | CAN_BTR_TESG2(pBusTiming->TESG2); + + if (pBusTiming->SAM) { + pCAN->BTR |= CAN_BTR_SAM; + } + + /* Exit from Reset Mode */ + Chip_CAN_SetMode(pCAN, CAN_RESET_MODE, DISABLE); +} + +/* Get start row, end row of the given section */ +STATIC void getSectionAddress(LPC_CANAF_T *pCANAF, + CANAF_RAM_SECTION_T SectionID, uint16_t *StartAddr, uint16_t *EndAddr) +{ + if (SectionID == CANAF_RAM_FULLCAN_SEC) { + *StartAddr = 0; + } + else { + *StartAddr = CANAF_ENDADDR_VAL(pCANAF->ENDADDR[SectionID - 1]); + } + *EndAddr = CANAF_ENDADDR_VAL(pCANAF->ENDADDR[SectionID]); + + if (*EndAddr > 0) { + *EndAddr -= 1; /* Minus 1 to get the actual end row */ + } + else { + *EndAddr = *StartAddr; + } +} + +/* Get the total number of entries in LUT */ +STATIC INLINE uint16_t getTotalEntryNum(LPC_CANAF_T *pCANAF) +{ + return CANAF_ENDADDR_VAL(pCANAF->ENDADDR[CANAF_RAM_EFF_GRP_SEC]); /* Extended ID Group section is the last section of LUT */ +} + +/* Set the End Address of a section. EndAddr = the number of the last row of the section + 1. */ +STATIC INLINE void setSectionEndAddress(LPC_CANAF_T *pCANAF, + CANAF_RAM_SECTION_T SectionID, uint16_t EndAddr) +{ + pCANAF->ENDADDR[SectionID] = CANAF_ENDADDR(EndAddr); +} + +/* Get information of the received frame. Return ERROR means no message came.*/ +STATIC INLINE Status getReceiveFrameInfo(LPC_CAN_T *pCAN, + IP_CAN_001_RX_T *pRxFrame) +{ + *pRxFrame = pCAN->RX; + return (pCAN->SR & CAN_SR_RBS(0)) ? SUCCESS : ERROR; +} + +/* Set Tx Frame Information */ +STATIC INLINE void setSendFrameInfo(LPC_CAN_T *pCAN, CAN_BUFFER_ID_T TxBufID, + LPC_CAN_TX_T *pTxFrame) +{ + pCAN->TX[TxBufID] = *pTxFrame; +} + +/* Create the standard ID entry */ +STATIC uint16_t createStdIDEntry(CAN_STD_ID_ENTRY_T *pEntryInfo, bool IsFullCANEntry) +{ + uint16_t Entry = 0; + Entry = (pEntryInfo->CtrlNo & CAN_STD_ENTRY_CTRL_NO_MASK) << CAN_STD_ENTRY_CTRL_NO_POS; + Entry |= (pEntryInfo->Disable & CAN_STD_ENTRY_DISABLE_MASK) << CAN_STD_ENTRY_DISABLE_POS; + Entry |= (pEntryInfo->ID_11 & CAN_STD_ENTRY_ID_MASK) << CAN_STD_ENTRY_ID_POS; + if (IsFullCANEntry) { + Entry |= 1 << CAN_STD_ENTRY_IE_POS; + } + return Entry; +} + +STATIC INLINE uint16_t createUnUsedSTDEntry(uint8_t CtrlNo) +{ + return ((CtrlNo & CAN_STD_ENTRY_CTRL_NO_MASK) << CAN_STD_ENTRY_CTRL_NO_POS) | (1 << CAN_STD_ENTRY_DISABLE_POS); +} + +/* Get information from the standard ID entry */ +STATIC void readStdIDEntry(uint16_t EntryVal, CAN_STD_ID_ENTRY_T *pEntryInfo) +{ + pEntryInfo->CtrlNo = (EntryVal >> CAN_STD_ENTRY_CTRL_NO_POS) & CAN_STD_ENTRY_CTRL_NO_MASK; + pEntryInfo->Disable = (EntryVal >> CAN_STD_ENTRY_DISABLE_POS) & CAN_STD_ENTRY_DISABLE_MASK; + pEntryInfo->ID_11 = (EntryVal >> CAN_STD_ENTRY_ID_POS) & CAN_STD_ENTRY_ID_MASK; +} + +/* Setup Standard iD section */ +STATIC Status setupSTDSection(uint32_t *pCANAFRamAddr, + CAN_STD_ID_ENTRY_T *pStdCANSec, + uint16_t EntryNum, + bool IsFullCANEntry) +{ + uint16_t i; + uint16_t CurID = 0; + uint16_t Entry; + uint16_t EntryCnt = 0; + + /* Setup FullCAN section */ + for (i = 0; i < EntryNum; i += 2) { + /* First Entry */ + if (CurID > pStdCANSec[i].ID_11) { + return ERROR; + } + CurID = pStdCANSec[i].ID_11; + Entry = createStdIDEntry(&pStdCANSec[i], IsFullCANEntry); + pCANAFRamAddr[EntryCnt] = Entry << 16; + + /* Second Entry */ + if ((i + 1) < EntryNum) { + if (CurID > pStdCANSec[i + 1].ID_11) { + return ERROR; + } + CurID = pStdCANSec[i + 1].ID_11; + Entry = createStdIDEntry(&pStdCANSec[i + 1], IsFullCANEntry); + pCANAFRamAddr[EntryCnt] |= Entry; + } + else { + pCANAFRamAddr[EntryCnt] |= createUnUsedSTDEntry(pStdCANSec[0].CtrlNo); + } + EntryCnt++; + } + return SUCCESS; + +} + +/* Setup the Group Standard ID section */ +STATIC Status setupSTDRangeSection(uint32_t *pCANAFRamAddr, + CAN_STD_ID_RANGE_ENTRY_T *pStdRangeCANSec, + uint16_t EntryNum) +{ + return setupSTDSection(pCANAFRamAddr, (CAN_STD_ID_ENTRY_T *) pStdRangeCANSec, EntryNum * 2, false); +} + +/* Shift a number of entries down 1 position */ +STATIC void shiftSTDEntryDown(uint32_t *arr, int32_t num) +{ + uint32_t i = 0; + uint32_t prevRow, curRow; + + if (num <= 0) { + return; + } + + prevRow = arr[0]; + arr[0] = ((prevRow & 0xFFFF0000) >> 16); + for (i = 0; i < (num / 2); i++) { + curRow = arr[i + 1]; + arr[i + 1] = ((prevRow & 0xFFFF) << 16) | ((curRow & 0xFFFF0000) >> 16); + prevRow = curRow; + } + if ((num % 2) == 0) { + uint8_t CtrlNo = (prevRow >> CAN_STD_ENTRY_CTRL_NO_POS) & CAN_STD_ENTRY_CTRL_NO_MASK; + arr[num / 2] = ((prevRow & 0xFFFF) << 16) | createUnUsedSTDEntry(CtrlNo); + } +} + +/* Shift a number of entries up 1 position */ +STATIC void shiftSTDEntryUp(uint32_t *arr, int32_t num) +{ + int32_t i = 0; + uint32_t prevRow = 0, curRow = 0; + uint8_t CtrlNo = 0; + + if (num <= 0) { + return; + } + + curRow = arr[((num + 1) / 2) - 1]; + CtrlNo = (curRow >> CAN_STD_ENTRY_CTRL_NO_POS) & CAN_STD_ENTRY_CTRL_NO_MASK; + + /* If num is odd, the last row only includes one item. Therefore, there is nothing + to do with it. If num is even, shift the last item to one place of the row.*/ + if ((num % 2) == 0) { + arr[((num + 1) / 2) - 1] = ((curRow & 0xFFFF) << 16) | createUnUsedSTDEntry(CtrlNo); + } + /* Shift from the row before the last row */ + for (i = ((num + 1) / 2) - 1; i > 0; i--) { + prevRow = arr[i - 1]; + arr[i - 1] = ((curRow & 0xFFFF0000) >> 16) | ((prevRow & 0xFFFF) << 16); + curRow = prevRow; + } +} + +/* Create an extended ID entry */ +STATIC uint32_t createExtIDEntry(CAN_EXT_ID_ENTRY_T *pEntryInfo) +{ + uint32_t Entry = 0; + Entry = (pEntryInfo->CtrlNo & CAN_EXT_ENTRY_CTRL_NO_MASK) << CAN_EXT_ENTRY_CTRL_NO_POS; + Entry |= (pEntryInfo->ID_29 & CAN_EXT_ENTRY_ID_MASK) << CAN_EXT_ENTRY_ID_POS; + return Entry; +} + +/* Get information from an extended ID entry */ +STATIC void readExtIDEntry(uint32_t EntryVal, CAN_EXT_ID_ENTRY_T *pEntryInfo) +{ + pEntryInfo->CtrlNo = (EntryVal >> CAN_EXT_ENTRY_CTRL_NO_POS) & CAN_EXT_ENTRY_CTRL_NO_MASK; + pEntryInfo->ID_29 = (EntryVal >> CAN_EXT_ENTRY_ID_POS) & CAN_EXT_ENTRY_ID_MASK; +} + +/* Setup the Extended ID Section */ +STATIC Status setupEXTSection(uint32_t *pCANAFRamAddr, CAN_EXT_ID_ENTRY_T *pExtCANSec, uint16_t EntryNum) +{ + uint16_t i; + uint32_t CurID = 0; + uint32_t Entry; + uint16_t EntryCnt = 0; + + /* Setup FullCAN section */ + for (i = 0; i < EntryNum; i++) { + if (CurID > pExtCANSec[i].ID_29) { + return ERROR; + } + CurID = pExtCANSec[i].ID_29; + Entry = createExtIDEntry(&pExtCANSec[i]); + pCANAFRamAddr[EntryCnt] = Entry; + EntryCnt++; + } + return SUCCESS; + +} + +/* Setup Group Extended ID section */ +STATIC Status setupEXTRangeSection(uint32_t *pCANAFRamAddr, + CAN_EXT_ID_RANGE_ENTRY_T *pExtRangeCANSec, + uint16_t EntryNum) +{ + return setupEXTSection(pCANAFRamAddr, (CAN_EXT_ID_ENTRY_T *) pExtRangeCANSec, EntryNum * 2); +} + +/* Get entry value from the given start index of the given array. byteNum is 2 or 4 bytes */ +STATIC uint32_t getArrayVal(uint8_t *arr, uint32_t startIndex, uint8_t byteNum) +{ + uint8_t i = 0; + uint32_t retVal = 0; + uint32_t index; + + index = startIndex * byteNum; + if (byteNum == 2) { // each entry uses 2 bytes + if (startIndex % 2) { + index -= 2; // little endian + } + else { + index += 2; + } + } + + for (i = 0; i < byteNum; i++) { + retVal |= arr[index + i] << (8 * i); + } + return retVal; +} + +/* Search the index to insert the new entry */ +STATIC int32_t searchInsertIndex(uint32_t *arr, uint32_t arrNum, uint32_t val, uint32_t mask, uint8_t unitSize) +{ + uint32_t LowerIndex, UpperIndex, MidIndex; + uint32_t MidVal; + uint8_t *byteArray = (uint8_t *) arr; + + if (arrNum == 0) { + return 0; /* Insert into the first line */ + + } + LowerIndex = 0; + UpperIndex = arrNum - 1; + while (LowerIndex + 1 < UpperIndex) { + MidIndex = (LowerIndex + UpperIndex) / 2; + MidVal = getArrayVal(byteArray, MidIndex, unitSize) & mask; + if (MidVal == val) { + return -1; /* The new value is already in the array */ + } + else if (MidVal < val) { + LowerIndex = MidIndex + 1; + } + else { + UpperIndex = MidIndex - 1; + } + } + + if (((getArrayVal(byteArray, LowerIndex, unitSize) & mask) == val) || + ((getArrayVal(byteArray, UpperIndex, unitSize) & mask) == val)) { + return -1; /* The new value is already in the array */ + } + if ((getArrayVal(byteArray, LowerIndex, unitSize) & mask) > val) { + return LowerIndex; + } + if ((getArrayVal(byteArray, UpperIndex, unitSize) & mask) < val) { + return UpperIndex + 1; + } + + return UpperIndex; +} + +/* Insert an entry into FullCAN Table */ +STATIC Status insertSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + CAN_STD_ID_ENTRY_T *pEntry, + bool IsFullCANEntry) +{ + int32_t IDIndex = 0; + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0; + uint16_t i = 0; + uint32_t tmp = 0; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + if (getTotalEntryNum(pCANAF) >= CANAF_RAM_ENTRY_NUM) { + return ERROR; + } + + /* Check if a number of entries in section is odd or even */ + if (IsFullCANEntry) { + getSectionAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, &StartRow, &EndRow); + } + else { + getSectionAddress(pCANAF, CANAF_RAM_SFF_SEC, &StartRow, &EndRow); + + } + + if (EndRow > StartRow) { + EntryCnt = (EndRow - StartRow + 1) * 2; + if ((((pCANAFRam->MASK[EndRow] >> CAN_STD_ENTRY_ID_POS) & CAN_STD_ENTRY_ID_MASK) == + 0) && + (((pCANAFRam->MASK[EndRow] >> + CAN_STD_ENTRY_DISABLE_POS) & CAN_STD_ENTRY_DISABLE_MASK) == 1)) { /* Unsed entry */ + EntryCnt -= 1; + } + + } + + /* Search for Index of new entry */ + IDIndex = searchInsertIndex((uint32_t *) &pCANAFRam->MASK[StartRow], + EntryCnt, + pEntry->ID_11 & CAN_STD_ENTRY_ID_MASK, + CAN_STD_ENTRY_ID_MASK, + sizeof(uint16_t)); + if ((IDIndex == -1) || (IDIndex > EntryCnt )) { + return ERROR; + } + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + /* Move all remaining sections one place down + if new entry will increase FullCAN list */ + if ((EntryCnt % 2) == 0) { + uint16_t StartAddr, EndAddr; + + for (i = getTotalEntryNum(pCANAF); i > EndRow; i--) { + pCANAFRam->MASK[i] = pCANAFRam->MASK[i - 1]; + } + + if (IsFullCANEntry) { + getSectionAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, EndAddr + 2); + } + getSectionAddress(pCANAF, CANAF_RAM_SFF_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_SEC, EndAddr + 2); + getSectionAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, EndAddr + 2); + getSectionAddress(pCANAF, CANAF_RAM_EFF_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_SEC, EndAddr + 2); + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, EndAddr + 2); + } + + /* Shift rows behind the row of search index. If search index is low index of the row, shift the row of search index also. */ + if ((IDIndex % 2) == 0) { + shiftSTDEntryDown((uint32_t *) &pCANAFRam->MASK[StartRow + IDIndex / 2], EntryCnt - IDIndex); + } + else { + shiftSTDEntryDown((uint32_t *) &pCANAFRam->MASK[StartRow + IDIndex / 2 + 1], EntryCnt - IDIndex - 1); + } + + /* Insert new item */ + tmp = createStdIDEntry(pEntry, IsFullCANEntry); + if ((IDIndex % 2) == 0) { + if (IDIndex == EntryCnt) { + /* Insert unused item if the new item is the last item*/ + pCANAFRam->MASK[StartRow + IDIndex / 2] = (tmp << 16) | createUnUsedSTDEntry(pEntry->CtrlNo); + } + else { + uint32_t val; + val = pCANAFRam->MASK[StartRow + IDIndex / 2] & 0x0000FFFF; + /* Insert new item */ + pCANAFRam->MASK[StartRow + IDIndex / 2] = val | (tmp << 16); + } + } + else { + uint32_t val, valNext; + val = pCANAFRam->MASK[StartRow + IDIndex / 2]; + valNext = pCANAFRam->MASK[StartRow + IDIndex / 2 + 1]; + /* In case the new entry is not the last item, shift the item at the found index to the next row*/ + if (IDIndex < EntryCnt ) { + + pCANAFRam->MASK[StartRow + IDIndex / 2 + 1] = (valNext & 0x0000FFFF) | ((val & 0xFFFF) << 16); + } + pCANAFRam->MASK[StartRow + IDIndex / 2] = (val & 0xFFFF0000) | tmp; + } + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); + return SUCCESS; +} + +/* Read STD Entry */ +STATIC Status readSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + uint16_t Position, + bool IsFullCANEntry, + CAN_STD_ID_ENTRY_T *pEntry) + +{ + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0; + + /* Check if a number of entries in section is odd or even */ + if (IsFullCANEntry) { + getSectionAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, &StartRow, &EndRow); + } + else { + getSectionAddress(pCANAF, CANAF_RAM_SFF_SEC, &StartRow, &EndRow); + } + + if (EndRow > StartRow) { + EntryCnt = (EndRow - StartRow + 1) * 2; + if ((((pCANAFRam->MASK[EndRow] >> CAN_STD_ENTRY_ID_POS) & CAN_STD_ENTRY_ID_MASK) == + 0) && + (((pCANAFRam->MASK[EndRow] >> + CAN_STD_ENTRY_DISABLE_POS) & CAN_STD_ENTRY_DISABLE_MASK) == 1)) { /* Unsed entry */ + EntryCnt -= 1; + } + } + if (Position >= EntryCnt) { + return ERROR; + } + + if ((Position % 2) == 0) { + readStdIDEntry(pCANAFRam->MASK[StartRow + Position / 2] >> 16, pEntry); + } + else { + readStdIDEntry(pCANAFRam->MASK[StartRow + Position / 2] & 0xFFFF, pEntry); + } + + return SUCCESS; +} + +/* Remove STD Entry from given table */ +Status removeSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + int16_t IDIndex, + bool IsFullCANEntry) +{ + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0, i; + uint32_t tmp = 0; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + if (IDIndex < 0) { + return ERROR; + } + + if (getTotalEntryNum(pCANAF) >= CANAF_RAM_ENTRY_NUM) { + return ERROR; + } + + /* Check if a number of entries in section is odd or even */ + if (IsFullCANEntry) { + getSectionAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, &StartRow, &EndRow); + } + else { + getSectionAddress(pCANAF, CANAF_RAM_SFF_SEC, &StartRow, &EndRow); + } + + if (EndRow > StartRow) { + EntryCnt = (EndRow - StartRow + 1) * 2; + if ((((pCANAFRam->MASK[EndRow] >> CAN_STD_ENTRY_ID_POS) & CAN_STD_ENTRY_ID_MASK) == + 0) && + (((pCANAFRam->MASK[EndRow] >> + CAN_STD_ENTRY_DISABLE_POS) & CAN_STD_ENTRY_DISABLE_MASK) == 1)) { /* Unsed entry */ + EntryCnt -= 1; + } + + } + if (IDIndex >= EntryCnt) { + return ERROR; + } + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + /* Shift rows behind the row of remove index. If remove index is low index of the row, shift the row of remove index also. */ + tmp = pCANAFRam->MASK[StartRow + IDIndex / 2 + 1]; + if ((IDIndex % 2) == 0) { + shiftSTDEntryUp((uint32_t *) &pCANAFRam->MASK[StartRow + IDIndex / 2], EntryCnt - IDIndex); + } + else { + shiftSTDEntryUp((uint32_t *) &pCANAFRam->MASK[StartRow + IDIndex / 2 + 1], EntryCnt - IDIndex - 1); + + /* Set value for the entry at remove index */ + pCANAFRam->MASK[StartRow + IDIndex / 2] &= 0xFFFF0000; + if (IDIndex == (EntryCnt - 1)) { + uint8_t CtrlNo; + tmp = (pCANAFRam->MASK[StartRow + IDIndex / 2]) >> 16; + CtrlNo = (tmp >> CAN_STD_ENTRY_CTRL_NO_POS) & CAN_STD_ENTRY_CTRL_NO_MASK; + pCANAFRam->MASK[StartRow + IDIndex / 2] |= createUnUsedSTDEntry(CtrlNo); + } + else { + pCANAFRam->MASK[StartRow + IDIndex / 2] |= (tmp >> 16) & 0xFFFF; + } + } + /* Move all remaining sections one place up + if new entry will decrease FullCAN list */ + if (EntryCnt % 2) { + uint16_t StartAddr, EndAddr; + + for (i = EndRow; i < getTotalEntryNum(pCANAF); i++) { + pCANAFRam->MASK[i] = pCANAFRam->MASK[i + 1]; + } + + if (IsFullCANEntry) { + getSectionAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, EndAddr); + } + getSectionAddress(pCANAF, CANAF_RAM_SFF_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_SEC, EndAddr); + getSectionAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, EndAddr); + getSectionAddress(pCANAF, CANAF_RAM_EFF_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_SEC, EndAddr); + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, EndAddr); + } + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); + return SUCCESS; +} + +/* Remove LUT Entry from given table */ +Status removeLUTEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + CANAF_RAM_SECTION_T SectionID, + int16_t Position) +{ + uint16_t StartRow, EndRow; + uint16_t StartAddr, EndAddr; + uint16_t EntryCnt = 0; + uint8_t EntryRowNum = 1; + uint16_t i = 0; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + if (Position < 0) { + return ERROR; + } + + if (getTotalEntryNum(pCANAF) >= CANAF_RAM_ENTRY_NUM) { + return ERROR; + } + + if (SectionID == CANAF_RAM_FULLCAN_SEC) { + return removeSTDEntry(pCANAF, pCANAFRam, Position, true); + } + else if (SectionID == CANAF_RAM_SFF_SEC) { + return removeSTDEntry(pCANAF, pCANAFRam, Position, false); + } + + /* Get a number of rows for an entry */ + if (SectionID == CANAF_RAM_EFF_GRP_SEC) { + EntryRowNum = 2; + } + + /* Get Start Row, End Row */ + getSectionAddress(pCANAF, SectionID, &StartRow, &EndRow); + + if (EndRow > StartRow) { + EntryCnt = (EndRow - StartRow + 1) / EntryRowNum; + } + + if (Position >= EntryCnt) { + return ERROR; + } + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + /* Move all remaining sections one place up + if new entry will increase FullCAN list */ + for (i = StartRow + Position * EntryRowNum; i < getTotalEntryNum(pCANAF); i++) { + pCANAFRam->MASK[i] = pCANAFRam->MASK[i + EntryRowNum]; + } + + /* Get Start Row, End Row */ + switch (SectionID) { + case CANAF_RAM_SFF_GRP_SEC: + getSectionAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, EndAddr - EntryRowNum + 1); + + case CANAF_RAM_EFF_SEC: + getSectionAddress(pCANAF, CANAF_RAM_EFF_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_SEC, EndAddr - EntryRowNum + 1); + + case CANAF_RAM_EFF_GRP_SEC: + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartAddr, &EndAddr); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, EndAddr - EntryRowNum + 1); + break; + + default: + return ERROR; + } + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); + return SUCCESS; +} + +/* Clear AF LUT */ +void clearAFLUT(LPC_CANAF_T *pCanAF, LPC_CANAF_RAM_T *pCanAFRam) { + uint32_t i = 0; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCanAF); + + /* AF Off */ + Chip_CAN_SetAFMode(pCanAF, CAN_AF_OFF_MODE); + + /* Clear AF Ram region */ + for (i = 0; i < CANAF_RAM_ENTRY_NUM; i++) { + pCanAFRam->MASK[i] = 0; + } + + /* Reset address registers */ + setSectionEndAddress(pCanAF, CANAF_RAM_FULLCAN_SEC, 0); + setSectionEndAddress(pCanAF, CANAF_RAM_SFF_SEC, 0); + setSectionEndAddress(pCanAF, CANAF_RAM_SFF_GRP_SEC, 0); + setSectionEndAddress(pCanAF, CANAF_RAM_EFF_SEC, 0); + setSectionEndAddress(pCanAF, CANAF_RAM_EFF_GRP_SEC, 0); + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCanAF, CurMode); +} + +/* Returns clock for the peripheral block */ +STATIC CHIP_SYSCTL_CLOCK_T Chip_CAN_GetClockIndex(LPC_CAN_T *pCAN) +{ + CHIP_SYSCTL_CLOCK_T clkCAN; + + if (pCAN == LPC_CAN1) { + clkCAN = SYSCTL_CLOCK_CAN1; + } + else { + clkCAN = SYSCTL_CLOCK_CAN2; + } + + return clkCAN; +} + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) +/* Returns reset ID for the peripheral block */ +STATIC CHIP_SYSCTL_RESET_T Chip_CAN_GetResetIndex(LPC_CAN_T *pCAN) +{ + CHIP_SYSCTL_RESET_T resetCAN; + + if (pCAN == LPC_CAN1) { + resetCAN = SYSCTL_RESET_CAN1; + } + else { + resetCAN = SYSCTL_RESET_CAN2; + } + + return resetCAN; +} + +#endif + +#if defined(CHIP_LPC175X_6X) +/* Returns clock ID for the peripheral block */ +STATIC CHIP_SYSCTL_PCLK_T Chip_CAN_GetClkIndex(LPC_CAN_T *pCAN) +{ + CHIP_SYSCTL_PCLK_T clkCAN; + + if (pCAN == LPC_CAN1) { + clkCAN = SYSCTL_PCLK_CAN1; + } + else { + clkCAN = SYSCTL_PCLK_CAN2; + } + + return clkCAN; +} + +#endif + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize CAN Interface */ +void Chip_CAN_Init(LPC_CAN_T *pCAN, LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam) +{ + volatile uint32_t i; + + Chip_Clock_EnablePeriphClock(Chip_CAN_GetClockIndex(pCAN)); +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + Chip_SYSCTL_PeriphReset(Chip_CAN_GetResetIndex(pCAN)); +#endif + + /* Enter to Reset Mode */ + pCAN->MOD = CAN_MOD_RM; + + /* Disable all CAN Interrupts */ + pCAN->IER &= (~CAN_IER_BITMASK) & CAN_IER_BITMASK; + pCAN->GSR &= (~CAN_GSR_BITMASK) & CAN_GSR_BITMASK; + + /* Request command to release Rx, Tx buffer and clear data overrun */ + pCAN->CMR = CAN_CMR_RRB | CAN_CMR_AT | CAN_CMR_CDO; + + /* Read to clear interrupt pending in interrupt capture register */ + i = pCAN->ICR; + + /* Return to normal mode */ + pCAN->MOD = CAN_MOD_OPERATION; + + /* Initiialize Acceptance filter */ + clearAFLUT(pCANAF, pCANAFRam); + Chip_CAN_SetAFMode(pCANAF, CAN_AF_NORMAL_MODE); +} + +/* De-Initialize CAN Interface */ +void Chip_CAN_DeInit(LPC_CAN_T *pCAN) +{ + Chip_Clock_DisablePeriphClock(Chip_CAN_GetClockIndex(pCAN)); +} + +/* Set CAN Bit Rate */ +Status Chip_CAN_SetBitRate(LPC_CAN_T *pCAN, uint32_t BitRate) +{ + IP_CAN_BUS_TIMING_T BusTiming; + uint32_t result = 0; + uint8_t NT, TSEG1 = 0, TSEG2 = 0; + uint32_t CANPclk = 0; + uint32_t BRP = 0; + +#if defined(CHIP_LPC175X_6X) + CANPclk = Chip_Clock_GetPeripheralClockRate(Chip_CAN_GetClkIndex(pCAN)); +#else + CANPclk = Chip_Clock_GetPeripheralClockRate(); +#endif + result = CANPclk / BitRate; + + /* Calculate suitable nominal time value + * NT (nominal time) = (TSEG1 + TSEG2 + 3) + * NT <= 24 + * TSEG1 >= 2*TSEG2 + */ + for (NT = 24; NT > 0; NT = NT - 2) { + if ((result % NT) == 0) { + BRP = result / NT - 1; + + NT--; + + TSEG2 = (NT / 3) - 1; + + TSEG1 = NT - (NT / 3) - 1; + + break; + } + } + if (NT == 0) { + return ERROR; + } + + BusTiming.TESG1 = TSEG1; + BusTiming.TESG2 = TSEG2; + BusTiming.BRP = BRP; + BusTiming.SJW = 3; + BusTiming.SAM = 0; + setBusTiming(pCAN, &BusTiming); + return SUCCESS; +} + +/* Set CAN Mode */ +void Chip_CAN_SetMode(LPC_CAN_T *pCAN, CAN_MODE_T Mode, FunctionalState NewState) +{ + if ((Mode & CAN_MOD_LOM) || (Mode & CAN_MOD_STM)) { + /* Enter to Reset Mode */ + pCAN->MOD |= CAN_MOD_RM; + + /* Change to the given mode */ + if (NewState) { + pCAN->MOD |= Mode; + } + else { + pCAN->MOD &= (~Mode) & CAN_MOD_BITMASK; + } + + /* Release Reset Mode */ + pCAN->MOD &= (~CAN_MOD_RM) & CAN_MOD_BITMASK; + } + else { + if (NewState) { + pCAN->MOD |= Mode; + } + else { + pCAN->MOD &= (~Mode) & CAN_MOD_BITMASK; + } + } + +} + +/* Get Free TxBuf */ +CAN_BUFFER_ID_T Chip_CAN_GetFreeTxBuf(LPC_CAN_T *pCAN) +{ + CAN_BUFFER_ID_T TxBufID = CAN_BUFFER_1; + + /* Select a free buffer */ + for (TxBufID = (CAN_BUFFER_ID_T) 0; TxBufID < CAN_BUFFER_LAST; TxBufID++) { + if (Chip_CAN_GetStatus(pCAN) & CAN_SR_TBS(TxBufID)) { + break; + } + } + + return TxBufID; +} + +/* Set AF Lookup Table */ +Status Chip_CAN_SetAFLUT(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, CANAF_LUT_T *pAFSections) { + uint16_t EntryCnt = 0, FullCANEntryCnt = 0; + Status ret = ERROR; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + do { + /* Check a number of entries */ + if ((((pAFSections->FullCANEntryNum + 1) / 2) + + ((pAFSections->SffEntryNum + 1) / 2) + + (pAFSections->SffGrpEntryNum) + + (pAFSections->EffEntryNum) + + (pAFSections->EffGrpEntryNum * 2)) > CANAF_RAM_ENTRY_NUM) { + ret = ERROR; + break; + } + + /* Setup FullCAN section */ + ret = + setupSTDSection((uint32_t *) &pCANAFRam->MASK[EntryCnt], pAFSections->FullCANSec, + pAFSections->FullCANEntryNum, true); + if (ret == ERROR) { + break; + } + EntryCnt = (pAFSections->FullCANEntryNum + 1) >> 1; + FullCANEntryCnt = EntryCnt; + setSectionEndAddress(pCANAF, CANAF_RAM_FULLCAN_SEC, EntryCnt); + + /* Set up Individual Standard ID section */ + ret = + setupSTDSection((uint32_t *) &pCANAFRam->MASK[EntryCnt], + pAFSections->SffSec, + pAFSections->SffEntryNum, + false); + if (ret == ERROR) { + break; + } + + EntryCnt += (pAFSections->SffEntryNum + 1) >> 1; + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_SEC, EntryCnt); + + /* Set up Group Standard ID section */ + ret = + setupSTDRangeSection((uint32_t *) &pCANAFRam->MASK[EntryCnt], pAFSections->SffGrpSec, + pAFSections->SffGrpEntryNum); + if (ret == ERROR) { + break; + } + + EntryCnt += pAFSections->SffGrpEntryNum; + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, EntryCnt); + + /* Setup Individual Extended ID section */ + ret = + setupEXTSection((uint32_t *) &pCANAFRam->MASK[EntryCnt], pAFSections->EffSec, pAFSections->EffEntryNum); + if (ret == ERROR) { + break; + } + + EntryCnt += pAFSections->EffEntryNum; + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_SEC, EntryCnt); + + /* Setup Group Extended ID section */ + ret = + setupEXTRangeSection((uint32_t *) &pCANAFRam->MASK[EntryCnt], pAFSections->EffGrpSec, + pAFSections->EffGrpEntryNum); + if (ret == ERROR) { + break; + } + + EntryCnt += pAFSections->EffGrpEntryNum * 2; + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, EntryCnt); + + if ((FullCANEntryCnt > 0) && ((0x800 - 6 * FullCANEntryCnt) < EntryCnt)) { + ret = ERROR; + } + + } while (0); + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); + + return ret; +} + +/* Get the number of entries of the given section */ +uint16_t Chip_CAN_GetEntriesNum(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam, + CANAF_RAM_SECTION_T SectionID) +{ + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0; + + getSectionAddress(pCANAF, SectionID, &StartRow, &EndRow); + if (EndRow <= StartRow) { + return 0; + } + if ((SectionID == CANAF_RAM_FULLCAN_SEC) || + (SectionID == CANAF_RAM_SFF_SEC)) { + EntryCnt = (EndRow - StartRow + 1) * 2; + if ((((pCANAFRam->MASK[EndRow] >> CAN_STD_ENTRY_ID_POS) & CAN_STD_ENTRY_ID_MASK) == + 0) && + (((pCANAFRam->MASK[EndRow] >> + CAN_STD_ENTRY_DISABLE_POS) & CAN_STD_ENTRY_DISABLE_MASK) == 1)) { /* Unsed entry */ + EntryCnt -= 1; + } + } + else if ((SectionID == CANAF_RAM_SFF_GRP_SEC) || + (SectionID == CANAF_RAM_EFF_SEC)) { + EntryCnt = EndRow - StartRow + 1; + } + else { + EntryCnt = (EndRow - StartRow + 1) / 2; + } + return EntryCnt; +} + +/* Insert an entry into FullCAN Table */ +Status Chip_CAN_InsertFullCANEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + CAN_STD_ID_ENTRY_T *pEntry) { + return insertSTDEntry(pCANAF, pCANAFRam, pEntry, true); +} + +/* Insert an entry into Individual STD section */ +Status Chip_CAN_InsertSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + CAN_STD_ID_ENTRY_T *pEntry) +{ + return insertSTDEntry(pCANAF, pCANAFRam, pEntry, false); +} + +/* Insert an entry into Individual EXT section */ +Status Chip_CAN_InsertEXTEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + CAN_EXT_ID_ENTRY_T *pEntry) { + int32_t IDIndex = 0; + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0; + uint16_t i = 0; + uint32_t tmp = 0; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + if (getTotalEntryNum(pCANAF) >= CANAF_RAM_ENTRY_NUM) { + return ERROR; + } + + /* Check if a number of entries in section is odd or even */ + getSectionAddress(pCANAF, CANAF_RAM_EFF_SEC, &StartRow, &EndRow); + + if (EndRow > StartRow) { + EntryCnt = EndRow - StartRow + 1; + } + + /* Search for Index of new entry */ + IDIndex = searchInsertIndex((uint32_t *) &pCANAFRam->MASK[StartRow], + EntryCnt, + pEntry->ID_29 & CAN_EXT_ENTRY_ID_MASK, + CAN_EXT_ENTRY_ID_MASK, + sizeof(uint32_t)); + if ((IDIndex == -1) || (IDIndex > EntryCnt )) { + return ERROR; + } + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + /* Move all remaining sections one place down + if new entry will increase FullCAN list */ + + for (i = getTotalEntryNum(pCANAF); i > (StartRow + IDIndex); i--) { + pCANAFRam->MASK[i] = pCANAFRam->MASK[i - 1]; + } + + /* Insert new item */ + tmp = createExtIDEntry(pEntry); + pCANAFRam->MASK[StartRow + IDIndex] = tmp; + + /* Update address table */ + getSectionAddress(pCANAF, CANAF_RAM_EFF_SEC, &StartRow, &EndRow); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_SEC, EndRow + 2); + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartRow, &EndRow); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, EndRow + 2); + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); + return SUCCESS; +} + +Status Chip_CAN_InsertGroupSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + CAN_STD_ID_RANGE_ENTRY_T *pEntry) +{ + uint16_t InsertIndex = 0; + uint16_t StartRow, EndRow; + uint16_t LowerID = 0, UpperID = 0; + uint16_t i = 0; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + if (getTotalEntryNum(pCANAF) >= CANAF_RAM_ENTRY_NUM) { + return ERROR; + } + + getSectionAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, &StartRow, &EndRow); + + /* Search for Index of the entry which upper the new item */ + for (InsertIndex = StartRow; InsertIndex <= EndRow; InsertIndex++) { + LowerID = (pCANAFRam->MASK[InsertIndex] >> (16 + CAN_STD_ENTRY_ID_POS)) & CAN_STD_ENTRY_ID_MASK; + UpperID = (pCANAFRam->MASK[InsertIndex] >> CAN_STD_ENTRY_ID_POS) & CAN_STD_ENTRY_ID_MASK; + if (LowerID >= pEntry->LowerID.ID_11) { + break; + } + } + + /* Compare to the previous row (if any)*/ + if (InsertIndex > 0) { + uint16_t PrevUpperID; + PrevUpperID = (pCANAFRam->MASK[InsertIndex - 1] >> CAN_STD_ENTRY_ID_POS) & CAN_STD_ENTRY_ID_MASK; + + if (PrevUpperID >= pEntry->UpperID.ID_11) { + return SUCCESS; + } + + if (pEntry->UpperID.ID_11 < LowerID) { + if (pEntry->LowerID.ID_11 < PrevUpperID) { /* The new range is merged to the range of the previous row */ + uint32_t val = pCANAFRam->MASK[InsertIndex - 1] & 0xFFFF0000; + pCANAFRam->MASK[InsertIndex - 1] = val | createStdIDEntry(&pEntry->UpperID, false); + return SUCCESS; + } + else { + goto insert_grp_entry; + } + } + } + + /* Compare to the next row (if any)*/ + if ((EndRow) && (InsertIndex <= EndRow)) { + if (pEntry->UpperID.ID_11 >= UpperID) { /* The new range is merged to the range of the next row */ + uint32_t val; + val = createStdIDEntry(&pEntry->LowerID, false) << 16; + val |= createStdIDEntry(&pEntry->UpperID, false); + pCANAFRam->MASK[InsertIndex] = val; + return SUCCESS; + } + else if (pEntry->UpperID.ID_11 < UpperID) { + if (pEntry->UpperID.ID_11 > LowerID) { /* The new range is merged to the range of the next row */ + uint32_t val = pCANAFRam->MASK[InsertIndex] & 0x0000FFFF; + pCANAFRam->MASK[InsertIndex] = val | (createStdIDEntry(&pEntry->LowerID, false) << 16); + return SUCCESS; + } + } + } + +insert_grp_entry: + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + /* Move all remaining sections one place down + if new entry will increase FullCAN list */ + + for (i = getTotalEntryNum(pCANAF); i > InsertIndex; i--) { + pCANAFRam->MASK[i] = pCANAFRam->MASK[i - 1]; + } + + /* Insert new item */ + pCANAFRam->MASK[InsertIndex] = createStdIDEntry(&pEntry->LowerID, false) << 16; + pCANAFRam->MASK[InsertIndex] |= createStdIDEntry(&pEntry->UpperID, false); + + getSectionAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, &StartRow, &EndRow); + setSectionEndAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, EndRow + 2); + getSectionAddress(pCANAF, CANAF_RAM_EFF_SEC, &StartRow, &EndRow); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_SEC, EndRow + 2); + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartRow, &EndRow); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, EndRow + 2); + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); + return SUCCESS; +} + +Status Chip_CAN_InsertGroupEXTEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + CAN_EXT_ID_RANGE_ENTRY_T *pEntry) +{ + uint32_t InsertIndex = 0; + uint16_t StartRow, EndRow; + uint32_t LowerID = 0, UpperID = 0; + uint16_t i = 0; + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + if (getTotalEntryNum(pCANAF) >= CANAF_RAM_ENTRY_NUM) { + return ERROR; + } + + /* Check if a number of entries in section is odd or even */ + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartRow, &EndRow); + + /* Search for Index of new entry */ + for (InsertIndex = StartRow; InsertIndex <= EndRow; InsertIndex += 2) { + LowerID = (pCANAFRam->MASK[InsertIndex] >> CAN_EXT_ENTRY_ID_POS) & CAN_EXT_ENTRY_ID_MASK; + UpperID = (pCANAFRam->MASK[InsertIndex + 1] >> CAN_EXT_ENTRY_ID_POS) & CAN_EXT_ENTRY_ID_MASK; + if (LowerID >= pEntry->LowerID.ID_29) { + break; + } + } + + /* Compare to the previous row (if any)*/ + if (InsertIndex > 0) { + uint32_t PrevUpperID; + PrevUpperID = (pCANAFRam->MASK[(InsertIndex - 2) + 1] >> CAN_EXT_ENTRY_ID_POS) & CAN_EXT_ENTRY_ID_MASK; + + if (PrevUpperID >= pEntry->UpperID.ID_29) { + return SUCCESS; + } + + if (pEntry->UpperID.ID_29 < LowerID) { + if (pEntry->LowerID.ID_29 < PrevUpperID) { + pCANAFRam->MASK[(InsertIndex - 2) + 1] = createExtIDEntry(&pEntry->UpperID); + return SUCCESS; + } + else { + goto insert_grp_entry; + } + } + } + + if ((EndRow) && (InsertIndex < EndRow)) { + if (pEntry->UpperID.ID_29 >= UpperID) { + pCANAFRam->MASK[InsertIndex] = createExtIDEntry(&pEntry->LowerID); + pCANAFRam->MASK[InsertIndex + 1] = createExtIDEntry(&pEntry->UpperID); + return SUCCESS; + } + else if (pEntry->UpperID.ID_29 < UpperID) { + if (pEntry->UpperID.ID_29 > LowerID) { + pCANAFRam->MASK[InsertIndex] = createExtIDEntry(&pEntry->LowerID); + return SUCCESS; + } + } + } + +insert_grp_entry: + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + /* Move all remaining sections two places down + if new entry will increase FullCAN list */ + + for (i = getTotalEntryNum(pCANAF) + 1; i > InsertIndex; i--) { + pCANAFRam->MASK[i] = pCANAFRam->MASK[i - 2]; + } + + /* Insert new item */ + pCANAFRam->MASK[InsertIndex] = createExtIDEntry(&pEntry->LowerID); + pCANAFRam->MASK[InsertIndex + 1] = createExtIDEntry(&pEntry->UpperID); + + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartRow, &EndRow); + setSectionEndAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, EndRow + 3); + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); + return SUCCESS; +} + +/* Remove an entry into FullCAN Table */ +Status Chip_CAN_RemoveFullCANEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + int16_t Position) { + return removeLUTEntry(pCANAF, pCANAFRam, CANAF_RAM_FULLCAN_SEC, Position); +} + +/* Remove an entry into Individual STD section */ +Status Chip_CAN_RemoveSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + int16_t Position) +{ + return removeLUTEntry(pCANAF, pCANAFRam, CANAF_RAM_SFF_SEC, Position); +} + +/* Remove an entry into Group STD section */ +Status Chip_CAN_RemoveGroupSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + int16_t Position) +{ + return removeLUTEntry(pCANAF, pCANAFRam, CANAF_RAM_SFF_GRP_SEC, Position); +} + +/* Remove an entry into Individual EXT section */ +Status Chip_CAN_RemoveEXTEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + int16_t Position) { + return removeLUTEntry(pCANAF, pCANAFRam, CANAF_RAM_EFF_SEC, Position); +} + +/* Remove an entry into Group EXT section */ +Status Chip_CAN_RemoveGroupEXTEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + int16_t Position) +{ + return removeLUTEntry(pCANAF, pCANAFRam, CANAF_RAM_EFF_GRP_SEC, Position); +} + +Status Chip_CAN_ReadFullCANEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + uint16_t Position, + CAN_STD_ID_ENTRY_T *pEntry) +{ + return readSTDEntry(pCANAF, pCANAFRam, Position, true, pEntry); +} + +Status Chip_CAN_ReadSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + uint16_t Position, + CAN_STD_ID_ENTRY_T *pEntry) +{ + return readSTDEntry(pCANAF, pCANAFRam, Position, false, pEntry); +} + +Status Chip_CAN_ReadGroupSTDEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + uint16_t Position, + CAN_STD_ID_RANGE_ENTRY_T *pEntry) +{ + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0; + + getSectionAddress(pCANAF, CANAF_RAM_SFF_GRP_SEC, &StartRow, &EndRow); + + if (EndRow > StartRow) { + EntryCnt = EndRow - StartRow + 1; + } + if (Position >= EntryCnt) { + return ERROR; + } + + readStdIDEntry(pCANAFRam->MASK[StartRow + Position] >> 16, &pEntry->LowerID); + readStdIDEntry(pCANAFRam->MASK[StartRow + Position] & 0xFFFF, &pEntry->UpperID); + return SUCCESS; +} + +Status Chip_CAN_ReadEXTEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + uint16_t Position, + CAN_EXT_ID_ENTRY_T *pEntry) +{ + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0; + + getSectionAddress(pCANAF, CANAF_RAM_EFF_SEC, &StartRow, &EndRow); + + if (EndRow > StartRow) { + EntryCnt = EndRow - StartRow + 1; + } + if (Position >= EntryCnt) { + return ERROR; + } + + readExtIDEntry(pCANAFRam->MASK[StartRow + Position], pEntry); + return SUCCESS; +} + +Status Chip_CAN_ReadGroupEXTEntry(LPC_CANAF_T *pCANAF, + LPC_CANAF_RAM_T *pCANAFRam, + uint16_t Position, + CAN_EXT_ID_RANGE_ENTRY_T *pEntry) + +{ + uint16_t StartRow, EndRow; + uint16_t EntryCnt = 0; + + getSectionAddress(pCANAF, CANAF_RAM_EFF_GRP_SEC, &StartRow, &EndRow); + + if (EndRow > StartRow) { + EntryCnt = (EndRow - StartRow + 1) / 2; + } + if (Position >= EntryCnt) { + return ERROR; + } + + readExtIDEntry(pCANAFRam->MASK[StartRow + Position * 2], &pEntry->LowerID); + readExtIDEntry(pCANAFRam->MASK[StartRow + Position * 2 + 1], &pEntry->UpperID); + return SUCCESS; +} + +/* Send CAN Message */ +Status Chip_CAN_Send(LPC_CAN_T *pCAN, CAN_BUFFER_ID_T TxBufID, CAN_MSG_T *pMsg) +{ + uint8_t i = 0; + LPC_CAN_TX_T TxFrame; + + /* Write Frame Information */ + TxFrame.TFI = 0; + if (pMsg->Type & CAN_REMOTE_MSG) { + TxFrame.TFI |= CAN_TFI_RTR; + } + else { + TxFrame.TFI |= CAN_TFI_DLC(pMsg->DLC); + for (i = 0; i < (CAN_MSG_MAX_DATA_LEN + 3) / 4; i++) { + TxFrame.TD[i] = + pMsg->Data[4 * + i] | + (pMsg->Data[4 * i + + 1] << 8) | (pMsg->Data[4 * i + 2] << 16) | (pMsg->Data[4 * i + 3] << 24); + } + } + + if (pMsg->ID & CAN_EXTEND_ID_USAGE) { + TxFrame.TFI |= CAN_TFI_FF; + TxFrame.TID = CAN_TID_ID29(pMsg->ID); + } + else { + TxFrame.TID = CAN_TID_ID11(pMsg->ID); + } + + /* Set message information */ + setSendFrameInfo(pCAN, TxBufID, &TxFrame); + + /* Select buffer and Write Transmission Request */ + if (Chip_CAN_GetMode(pCAN) == CAN_SELFTEST_MODE) { + Chip_CAN_SetCmd(pCAN, CAN_CMR_STB(TxBufID) | CAN_CMR_SRR); + } + else { + Chip_CAN_SetCmd(pCAN, CAN_CMR_STB(TxBufID) | CAN_CMR_TR); + } + + return SUCCESS; +} + +/* Receive CAN Message */ +Status Chip_CAN_Receive(LPC_CAN_T *pCAN, CAN_MSG_T *pMsg) { + int8_t i; + IP_CAN_001_RX_T RxFrame; + if (getReceiveFrameInfo(pCAN, &RxFrame) == SUCCESS) { + + /* Read Message Identifier */ + if (RxFrame.RFS & CAN_RFS_FF) { + pMsg->ID = CAN_EXTEND_ID_USAGE | CAN_RID_ID_29(RxFrame.RID); + } + else { + pMsg->ID = CAN_RID_ID_11(RxFrame.RID); + } + + /* Read Data Length */ + pMsg->DLC = CAN_RFS_DLC(RxFrame.RFS); + + /* Read Message Type */ + pMsg->Type = 0; + if (RxFrame.RFS & CAN_RFS_RTR) { + pMsg->Type |= CAN_REMOTE_MSG; + } + else { + /* Read data only if the received message is not Remote message */ + for (i = 0; i < CAN_MSG_MAX_DATA_LEN; i++) { + pMsg->Data[i] = (RxFrame.RD[i / 4] >> (8 * (i % 4))) & 0xFF; + } + } + + /* Release received message */ + Chip_CAN_SetCmd(pCAN, CAN_CMR_RRB); + + return SUCCESS; + } + return ERROR; +} + +/* Enable/Disable FullCAN interrupt */ +void Chip_CAN_ConfigFullCANInt(LPC_CANAF_T *pCANAF, FunctionalState NewState) +{ + CAN_AF_MODE_T CurMode = Chip_CAN_GetAFMode(pCANAF); + + /* AF Off */ + Chip_CAN_SetAFMode(pCANAF, CAN_AF_OFF_MODE); + + if (NewState == ENABLE) { + pCANAF->FCANIE |= CANAF_FCANIE; + } + else { + pCANAF->FCANIE &= (~CANAF_FCANIE) & CANAF_FCANIE_BITMASK; + } + + /* Return to previous mode */ + Chip_CAN_SetAFMode(pCANAF, CurMode); +} + +/* Get interrupt status of the given object */ +uint32_t Chip_CAN_GetFullCANIntStatus(LPC_CANAF_T *pCANAF, uint8_t ObjID) +{ + if (ObjID < 64) { + return (pCANAF->FCANIC[ObjID / 32] & (1 << (ObjID % 32))) ? SET : RESET; + } + return RESET; +} + +/* Read FullCAN message received */ +Status Chip_CAN_FullCANReceive(LPC_CANAF_T *pCANAF, LPC_CANAF_RAM_T *pCANAFRam + , uint8_t ObjID, CAN_MSG_T *pMsg, uint8_t *pSCC) { + uint32_t *pSrc; + uint16_t FullCANEntryCnt; + pSrc = (uint32_t *) pCANAFRam; + + FullCANEntryCnt = getTotalEntryNum(pCANAF); + pSrc += FullCANEntryCnt + ObjID * 3; + /* If the AF hasn't finished updating msg info */ + if (((pSrc[0] >> CANAF_FULLCAN_MSG_SEM_POS) & CANAF_FULLCAN_MSG_SEM_BITMASK) != + CANAF_FULCAN_MSG_AF_FINISHED) { + return ERROR; + } + + /* Mark that CPU is handling message */ + pSrc[0] = CANAF_FULCAN_MSG_CPU_READING << CANAF_FULLCAN_MSG_SEM_POS; + + /* Read Message */ + *pSCC = (pSrc[0] >> CANAF_FULLCAN_MSG_SCC_POS) & CANAF_FULLCAN_MSG_SCC_BITMASK; + pMsg->ID = (pSrc[0] >> CANAF_FULLCAN_MSG_ID11_POS) & CANAF_FULLCAN_MSG_ID11_BITMASK; + pMsg->Type = 0; + if (pSrc[0] & (1 << CANAF_FULLCAN_MSG_RTR_POS)) { + pMsg->Type = CAN_REMOTE_MSG; + } + pMsg->DLC = (pSrc[0] >> CANAF_FULLCAN_MSG_DLC_POS) & CANAF_FULLCAN_MSG_DLC_BITMASK; + ((uint32_t *) pMsg->Data)[0] = pSrc[1]; + ((uint32_t *) pMsg->Data)[1] = pSrc[2]; + + /* Recheck message status to make sure data is not be updated while CPU is reading */ + if (((pSrc[0] >> CANAF_FULLCAN_MSG_SEM_POS) & CANAF_FULLCAN_MSG_SEM_BITMASK) != + CANAF_FULCAN_MSG_CPU_READING) { + return ERROR; + } + + return SUCCESS; +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/chip_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/chip_17xx_40xx.c new file mode 100644 index 000000000..0936096cd --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/chip_17xx_40xx.c @@ -0,0 +1,110 @@ +/* + * @brief LPC17xx/40xx Miscellaneous chip specific functions + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/* System Clock Frequency (Core Clock) */ +uint32_t SystemCoreClock; + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Update system core clock rate, should be called if the system has + a clock rate change */ +void SystemCoreClockUpdate(void) +{ + /* CPU core speed */ + SystemCoreClock = Chip_Clock_GetSystemClockRate(); +} + +/* Sets up USB PLL, all needed clocks and enables USB PHY on the chip. USB pins which are + muxed to different pads are not initialized here. This routine assumes that the XTAL + OSC is enabled and running prior to this call. */ +void Chip_USB_Init(void) +{ + +#if defined(CHIP_LPC175X_6X) + /* Setup USB PLL1 for a 48MHz clock + Input clock rate (FIN) is main oscillator = 12MHz + PLL1 Output = USBCLK = 48MHz = FIN * MSEL, so MSEL = 4. + FCCO = USBCLK = USBCLK * 2 * P. It must be between 156 MHz to 320 MHz. + so P = 2 and FCCO = 48MHz * 2 * 2 = 192MHz */ + Chip_Clock_SetupPLL(SYSCTL_USB_PLL, 3, 1); /* Multiply by 4, Divide by 2 */ + + /* Use PLL1 output as USB Clock Source */ + /* Enable PLL1 */ + Chip_Clock_EnablePLL(SYSCTL_USB_PLL, SYSCTL_PLL_ENABLE); + + /* Wait for PLL1 to lock */ + while (!Chip_Clock_IsUSBPLLLocked()) {} + + /* Connect PLL1 */ + Chip_Clock_EnablePLL(SYSCTL_USB_PLL, SYSCTL_PLL_ENABLE | SYSCTL_PLL_CONNECT); + + /* Wait for PLL1 to be connected */ + while (!Chip_Clock_IsUSBPLLConnected()) {} + +#else + + /* Select XTAL as clock source for USB block and divider as 1 */ + LPC_SYSCTL->USBCLKSEL = 0x1; + /* Setup USB PLL1 for a 48MHz clock + Input clock rate (FIN) is main oscillator = 12MHz + PLL output = 48MHz = FIN * MSEL, so MSEL = 4 + FCCO must be between 156 MHz to 320 MHz, where FCCO = PLL output * 2 * P, + so P = 2 and FCCO = 48MHz * 2 * 2 = 192MHz */ + Chip_Clock_SetupPLL(SYSCTL_USB_PLL, 3, 1); + + /* Wait for USB PLL to lock */ + while ((Chip_Clock_GetPLLStatus(SYSCTL_USB_PLL) & SYSCTL_PLLSTS_LOCKED) == 0) {} + + /* Select PLL1/USBPLL as clock source for USB block and divider as 1 */ + LPC_SYSCTL->USBCLKSEL = (SYSCTL_USBCLKSRC_USBPLL << 8) | 0x01; + +#endif /* defined(CHIP_LPC175X_6X) */ + + /* Enable AHB clock to the USB block and USB RAM. */ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_USB); + +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/clock_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/clock_17xx_40xx.c new file mode 100644 index 000000000..42e4d7cc8 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/clock_17xx_40xx.c @@ -0,0 +1,516 @@ +/* + * @brief LPC17xx/40xx System and Control driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Enables or connects a PLL */ +void Chip_Clock_EnablePLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t flags) { + uint32_t temp; + + temp = LPC_SYSCTL->PLL[PLLNum].PLLCON; + temp |= flags; + LPC_SYSCTL->PLL[PLLNum].PLLCON = temp; + Chip_Clock_FeedPLL(PLLNum); +} + +/* Disables or disconnects a PLL */ +void Chip_Clock_DisablePLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t flags) { + uint32_t temp; + + temp = LPC_SYSCTL->PLL[PLLNum].PLLCON; + temp &= ~flags; + LPC_SYSCTL->PLL[PLLNum].PLLCON = temp; + Chip_Clock_FeedPLL(PLLNum); +} + +/* Sets up a PLL */ +void Chip_Clock_SetupPLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t msel, uint32_t psel) { + uint32_t PLLcfg; + +#if defined(CHIP_LPC175X_6X) + /* PLL0 and PLL1 are slightly different */ + if (PLLNum == SYSCTL_MAIN_PLL) { + PLLcfg = (msel) | (psel << 16); + } + else { + PLLcfg = (msel) | (psel << 5); + } + +#else + PLLcfg = (msel) | (psel << 5); +#endif + + LPC_SYSCTL->PLL[PLLNum].PLLCFG = PLLcfg; + LPC_SYSCTL->PLL[PLLNum].PLLCON = 0x1; + Chip_Clock_FeedPLL(PLLNum); +} + +/* Enables power and clocking for a peripheral */ +void Chip_Clock_EnablePeriphClock(CHIP_SYSCTL_CLOCK_T clk) { + uint32_t bs = (uint32_t) clk; + +#if defined(CHIP_LPC40XX) + if (bs >= 32) { + LPC_SYSCTL->PCONP1 |= (1 << (bs - 32)); + } + else { + LPC_SYSCTL->PCONP |= (1 << bs); + } +#else + LPC_SYSCTL->PCONP |= (1 << bs); +#endif +} + +/* Disables power and clocking for a peripheral */ +void Chip_Clock_DisablePeriphClock(CHIP_SYSCTL_CLOCK_T clk) { + uint32_t bs = (uint32_t) clk; + +#if defined(CHIP_LPC40XX) + if (bs >= 32) { + LPC_SYSCTL->PCONP1 &= ~(1 << (bs - 32)); + } + else { + LPC_SYSCTL->PCONP |= ~(1 << bs); + } +#else + LPC_SYSCTL->PCONP |= ~(1 << bs); +#endif +} + +/* Returns power enables state for a peripheral */ +bool Chip_Clock_IsPeripheralClockEnabled(CHIP_SYSCTL_CLOCK_T clk) +{ + uint32_t bs = (uint32_t) clk; + +#if defined(CHIP_LPC40XX) + if (bs >= 32) { + bs = LPC_SYSCTL->PCONP1 & (1 << (bs - 32)); + } + else { + bs = LPC_SYSCTL->PCONP & (1 << bs); + } +#else + bs = LPC_SYSCTL->PCONP & (1 << bs); +#endif + + return (bool) (bs != 0); +} + +/* Sets the current CPU clock source */ +void Chip_Clock_SetCPUClockSource(CHIP_SYSCTL_CCLKSRC_T src) +{ +#if defined(CHIP_LPC175X_6X) + /* LPC175x/6x CPU clock source is based on PLL connect status */ + if (src == SYSCTL_CCLKSRC_MAINPLL) { + /* Connect PLL0 */ + Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT); + } + else { + Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT); + } +#else + /* LPC177x/8x and 407x/8x CPU clock source is based on CCLKSEL */ + if (src == SYSCTL_CCLKSRC_MAINPLL) { + /* Connect PLL0 */ + LPC_SYSCTL->CCLKSEL |= (1 << 8); + } + else { + LPC_SYSCTL->CCLKSEL &= ~(1 << 8); + } +#endif +} + +/* Returns the current CPU clock source */ +CHIP_SYSCTL_CCLKSRC_T Chip_Clock_GetCPUClockSource(void) +{ + CHIP_SYSCTL_CCLKSRC_T src; +#if defined(CHIP_LPC175X_6X) + /* LPC175x/6x CPU clock source is based on PLL connect status */ + if (Chip_Clock_IsMainPLLConnected()) { + src = SYSCTL_CCLKSRC_MAINPLL; + } + else { + src = SYSCTL_CCLKSRC_SYSCLK; + } +#else + /* LPC177x/8x and 407x/8x CPU clock source is based on CCLKSEL */ + if (LPC_SYSCTL->CCLKSEL & (1 << 8)) { + src = SYSCTL_CCLKSRC_MAINPLL; + } + else { + src = SYSCTL_CCLKSRC_SYSCLK; + } +#endif + + return src; +} + +/* Selects the CPU clock divider */ +void Chip_Clock_SetCPUClockDiv(uint32_t div) +{ +#if defined(CHIP_LPC175X_6X) + LPC_SYSCTL->CCLKSEL = div; +#else + uint32_t temp; + + /* Save state of CPU clock source bit */ + temp = LPC_SYSCTL->CCLKSEL & (1 << 8); + LPC_SYSCTL->CCLKSEL = temp | div; +#endif +} + +/* Gets the CPU clock divider */ +uint32_t Chip_Clock_GetCPUClockDiv(void) +{ +#if defined(CHIP_LPC175X_6X) + return (LPC_SYSCTL->CCLKSEL & 0xFF) + 1; +#else + return LPC_SYSCTL->CCLKSEL & 0x1F; +#endif +} + +#if !defined(CHIP_LPC175X_6X) +/* Selects the USB clock divider source */ +void Chip_Clock_SetUSBClockSource(CHIP_SYSCTL_USBCLKSRC_T src) +{ + uint32_t temp; + + /* Mask out current source, but keep divider */ + temp = LPC_SYSCTL->USBCLKSEL & ~(0x3 << 8); + LPC_SYSCTL->USBCLKSEL = temp | (((uint32_t) src) << 8); +} + +#endif + +/* Sets the USB clock divider */ +void Chip_Clock_SetUSBClockDiv(uint32_t div) +{ + uint32_t temp; + + /* Mask out current divider */ +#if defined(CHIP_LPC175X_6X) + temp = LPC_SYSCTL->USBCLKSEL & ~(0xF); +#else + temp = LPC_SYSCTL->USBCLKSEL & ~(0x1F); +#endif + LPC_SYSCTL->USBCLKSEL = temp | div; +} + +/* Gets the USB clock divider */ +uint32_t Chip_Clock_GetUSBClockDiv(void) +{ +#if defined(CHIP_LPC175X_6X) + return (LPC_SYSCTL->USBCLKSEL & 0xF) + 1; +#else + return (LPC_SYSCTL->USBCLKSEL & 0x1F) + 1; +#endif +} + +#if defined(CHIP_LPC175X_6X) +/* Selects a clock divider for a peripheral */ +void Chip_Clock_SetPCLKDiv(CHIP_SYSCTL_PCLK_T clk, CHIP_SYSCTL_CLKDIV_T div) +{ + uint32_t temp, bitIndex, regIndex = (uint32_t) clk; + + /* Get register array index and clock index into the register */ + bitIndex = ((regIndex % 16) * 2); + regIndex = regIndex / 16; + + /* Mask and update register */ + temp = LPC_SYSCTL->PCLKSEL[regIndex] & ~(0x3 << bitIndex); + temp |= (((uint32_t) div) << bitIndex); + LPC_SYSCTL->PCLKSEL[regIndex] = temp; +} + +/* Gets a clock divider for a peripheral */ +uint32_t Chip_Clock_GetPCLKDiv(CHIP_SYSCTL_PCLK_T clk) +{ + uint32_t div = 1, bitIndex, regIndex = ((uint32_t) clk) * 2; + + /* Get register array index and clock index into the register */ + bitIndex = regIndex % 32; + regIndex = regIndex / 32; + + /* Mask and update register */ + div = LPC_SYSCTL->PCLKSEL[regIndex]; + div = (div >> bitIndex) & 0x3; + if (div == SYSCTL_CLKDIV_4) { + div = 4; + } + else if (div == SYSCTL_CLKDIV_1) { + div = 1; + } + else if (div == SYSCTL_CLKDIV_2) { + div = 2; + } + else { + /* Special case for CAN clock divider */ + if ((clk == SYSCTL_PCLK_CAN1) || (clk == SYSCTL_PCLK_CAN2) || (clk == SYSCTL_PCLK_ACF)) { + div = 6; + } + else { + div = 8; + } + } + + return div; +} + +#endif + +/* Selects a source clock and divider rate for the CLKOUT pin */ +void Chip_Clock_SetCLKOUTSource(CHIP_SYSCTL_CLKOUTSRC_T src, + uint32_t div) +{ + uint32_t temp; + + temp = LPC_SYSCTL->CLKOUTCFG & ~0x1FF; + temp |= ((uint32_t) src) | ((div - 1) << 4); + LPC_SYSCTL->CLKOUTCFG = temp; +} + +/* Returns the current SYSCLK clock rate */ +uint32_t Chip_Clock_GetSYSCLKRate(void) +{ + /* Determine clock input rate to SYSCLK based on input selection */ + switch (Chip_Clock_GetMainPLLSource()) { + case (uint32_t) SYSCTL_PLLCLKSRC_IRC: + return Chip_Clock_GetIntOscRate(); + + case (uint32_t) SYSCTL_PLLCLKSRC_MAINOSC: + return Chip_Clock_GetMainOscRate(); + +#if defined(CHIP_LPC175X_6X) + case (uint32_t) SYSCTL_PLLCLKSRC_RTC: + return Chip_Clock_GetRTCOscRate(); +#endif + } + return 0; +} + +/* Returns the main PLL output clock rate */ +uint32_t Chip_Clock_GetMainPLLOutClockRate(void) +{ + uint32_t clkhr = 0; + +#if defined(CHIP_LPC175X_6X) + /* Only valid if enabled */ + if (Chip_Clock_IsMainPLLEnabled()) { + uint32_t msel, nsel; + + /* PLL0 rate is (FIN * 2 * MSEL) / NSEL, get MSEL and NSEL */ + msel = 1 + (LPC_SYSCTL->PLL[SYSCTL_MAIN_PLL].PLLCFG & 0x7FFF); + nsel = 1 + ((LPC_SYSCTL->PLL[SYSCTL_MAIN_PLL].PLLCFG >> 16) & 0xFF); + clkhr = (Chip_Clock_GetMainPLLInClockRate() * 2 * msel) / nsel; + } +#else + if (Chip_Clock_IsMainPLLEnabled()) { + uint32_t msel; + + /* PLL0 rate is (FIN * MSEL) */ + msel = 1 + (LPC_SYSCTL->PLL[SYSCTL_MAIN_PLL].PLLCFG & 0x1F); + clkhr = (Chip_Clock_GetMainPLLInClockRate() * msel); + } +#endif + + return (uint32_t) clkhr; +} + +/* Get USB output clock rate */ +uint32_t Chip_Clock_GetUSBPLLOutClockRate(void) +{ + uint32_t clkhr = 0; + + /* Only valid if enabled */ + if (Chip_Clock_IsUSBPLLEnabled()) { + uint32_t msel; + + /* PLL1 input clock (FIN) is always main oscillator */ + /* PLL1 rate is (FIN * MSEL) */ + msel = 1 + (LPC_SYSCTL->PLL[SYSCTL_USB_PLL].PLLCFG & 0x1F); + clkhr = (Chip_Clock_GetUSBPLLInClockRate() * msel); + } + + return (uint32_t) clkhr; +} + +/* Get the main clock rate */ +/* On 175x/6x devices, this is the input clock to the CPU divider. + Additionally, on 177x/8x and 407x/8x devices, this is also the + input clock to the peripheral divider. */ +uint32_t Chip_Clock_GetMainClockRate(void) +{ + switch (Chip_Clock_GetCPUClockSource()) { + case SYSCTL_CCLKSRC_MAINPLL: + return Chip_Clock_GetMainPLLOutClockRate(); + + case SYSCTL_CCLKSRC_SYSCLK: + return Chip_Clock_GetSYSCLKRate(); + + default: + return 0; + } +} + +/* Get CCLK rate */ +uint32_t Chip_Clock_GetSystemClockRate(void) +{ + return Chip_Clock_GetMainClockRate() / Chip_Clock_GetCPUClockDiv(); +} + +/* Returns the USB clock (USB_CLK) rate */ +uint32_t Chip_Clock_GetUSBClockRate(void) +{ + uint32_t div, clkrate; +#if defined(CHIP_LPC175X_6X) + /* The USB clock rate is derived from PLL1 or PLL0 */ + if (Chip_Clock_IsUSBPLLConnected()) { + /* Use PLL1 clock for USB source with divider of 1 */ + clkrate = Chip_Clock_GetUSBPLLOutClockRate(); + div = 1; + } + else { + clkrate = Chip_Clock_GetMainClockRate(); + div = Chip_Clock_GetUSBClockDiv(); + } + +#else + /* Get clock from source drving USB */ + switch (Chip_Clock_GetUSBClockSource()) { + case SYSCTL_USBCLKSRC_SYSCLK: + default: + clkrate = Chip_Clock_GetSYSCLKRate(); + break; + + case SYSCTL_USBCLKSRC_MAINPLL: + clkrate = Chip_Clock_GetMainPLLOutClockRate(); + break; + + case SYSCTL_USBCLKSRC_USBPLL: + clkrate = Chip_Clock_GetUSBPLLOutClockRate(); + break; + } + + div = Chip_Clock_GetUSBClockDiv(); +#endif + + return clkrate / div; +} + +#if !defined(CHIP_LPC175X_6X) +/* Selects the SPIFI clock divider source */ +void Chip_Clock_SetSPIFIClockSource(CHIP_SYSCTL_SPIFICLKSRC_T src) +{ + uint32_t temp; + + /* Mask out current source, but keep divider */ + temp = LPC_SYSCTL->SPIFICLKSEL & ~(0x3 << 8); + LPC_SYSCTL->SPIFICLKSEL = temp | (((uint32_t) src) << 8); +} + +/* Sets the SPIFI clock divider */ +void Chip_Clock_SetSPIFIClockDiv(uint32_t div) +{ + uint32_t temp; + + /* Mask out current divider */ + temp = LPC_SYSCTL->SPIFICLKSEL & ~(0x1F); + LPC_SYSCTL->SPIFICLKSEL = temp | div; +} + +/* Returns the SPIFI clock rate */ +uint32_t Chip_Clock_GetSPIFIClockRate(void) +{ + uint32_t div, clkrate; + + /* Get clock from source drving USB */ + switch (Chip_Clock_GetSPIFIClockSource()) { + case SYSCTL_SPIFICLKSRC_SYSCLK: + default: + clkrate = Chip_Clock_GetSYSCLKRate(); + break; + + case SYSCTL_SPIFICLKSRC_MAINPLL: + clkrate = Chip_Clock_GetMainPLLOutClockRate(); + break; + + case SYSCTL_SPIFICLKSRC_USBPLL: + clkrate = Chip_Clock_GetUSBPLLOutClockRate(); + break; + } + + div = Chip_Clock_GetSPIFIClockDiv(); + + return clkrate / div; +} + +#endif + +#if defined(CHIP_LPC175X_6X) +/* Returns the clock rate for a peripheral */ +uint32_t Chip_Clock_GetPeripheralClockRate(CHIP_SYSCTL_PCLK_T clk) { + /* 175x/6x clock is derived from CPU clock with CPU divider */ + return Chip_Clock_GetSystemClockRate() / Chip_Clock_GetPCLKDiv(clk); +} + +#else +/* Returns the clock rate for all peripherals */ +uint32_t Chip_Clock_GetPeripheralClockRate(void) +{ + uint32_t clkrate = 0, div; + + /* Get divider, a divider of 0 means the clock is disabled */ + div = Chip_Clock_GetPCLKDiv(); + if (div != 0) { + /* Derived from periperhal clock input and peripheral clock divider */ + clkrate = Chip_Clock_GetMainClockRate() / div; + } + + return clkrate; +} + +#endif diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/cmp_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/cmp_17xx_40xx.c new file mode 100644 index 000000000..cee9e43ee --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/cmp_17xx_40xx.c @@ -0,0 +1,64 @@ +/* + * @brief LPC17xx/40xx Comparator driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC40XX) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initializes the CMP */ +void Chip_CMP_Init(void) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_CMP); +} + +/* De-initializes the CMP */ +void Chip_CMP_DeInit(void) +{ + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_CMP); +} + +#endif /* defined(CHIP_LPC40XX) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/crc_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/crc_17xx_40xx.c new file mode 100644 index 000000000..4a44969a7 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/crc_17xx_40xx.c @@ -0,0 +1,110 @@ +/* + * @brief LPC17xx/40xx Cyclic Redundancy Check (CRC) Engine driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licenser disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Sets up the CRC engine with defaults based on the polynomial to be used */ +void Chip_CRC_UseDefaultConfig(CRC_POLY_T poly) +{ + switch (poly) { + case CRC_POLY_CRC16: + LPC_CRC->MODE = MODE_CFG_CRC16; + LPC_CRC->SEED = CRC_SEED_CRC16; + break; + + case CRC_POLY_CRC32: + LPC_CRC->MODE = MODE_CFG_CRC32; + LPC_CRC->SEED = CRC_SEED_CRC32; + break; + + case CRC_POLY_CCITT: + default: + LPC_CRC->MODE = MODE_CFG_CCITT; + LPC_CRC->SEED = CRC_SEED_CCITT; + break; + } +} + +/* configure CRC engine and compute CCITT checksum from 8-bit data */ +uint32_t Chip_CRC_CRC8(const uint8_t *data, uint32_t bytes) +{ + Chip_CRC_UseDefaultConfig(CRC_POLY_CCITT); + while (bytes > 0) { + Chip_CRC_Write8(*data); + data++; + bytes--; + } + return Chip_CRC_Sum(); +} + +/* Convenience function for computing a standard CRC16 checksum from 16-bit data block */ +uint32_t Chip_CRC_CRC16(const uint16_t *data, uint32_t hwords) +{ + Chip_CRC_UseDefaultConfig(CRC_POLY_CRC16); + while (hwords > 0) { + Chip_CRC_Write16(*data); + data++; + hwords--; + } + return Chip_CRC_Sum(); +} + +/* Convenience function for computing a standard CRC32 checksum from 32-bit data block */ +uint32_t Chip_CRC_CRC32(const uint32_t *data, uint32_t words) +{ + Chip_CRC_UseDefaultConfig(CRC_POLY_CRC32); + while (words > 0) { + Chip_CRC_Write32(*data); + data++; + words--; + } + return Chip_CRC_Sum(); +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/dac_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/dac_17xx_40xx.c new file mode 100644 index 000000000..4387b0234 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/dac_17xx_40xx.c @@ -0,0 +1,84 @@ +/* + * @brief LPC17xx/40xx D/A conversion driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the DAC peripheral */ +void Chip_DAC_Init(LPC_DAC_T *pDAC) +{ +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + Chip_SYSCTL_PeriphReset(SYSCTL_RESET_DAC); +#endif + + /* Set maximum update rate 1MHz */ + Chip_DAC_SetBias(pDAC, DAC_MAX_UPDATE_RATE_1MHz); +} + +/* Shutdown DAC peripheral */ +void Chip_DAC_DeInit(LPC_DAC_T *pDAC) +{} + +/* Update value to DAC buffer*/ +void Chip_DAC_UpdateValue(LPC_DAC_T *pDAC, uint32_t dac_value) +{ + uint32_t tmp; + + tmp = pDAC->CR & DAC_BIAS_EN; + tmp |= DAC_VALUE(dac_value); + /* Update value */ + pDAC->CR = tmp; +} + +/* Set Maximum update rate for DAC */ +void Chip_DAC_SetBias(LPC_DAC_T *pDAC, uint32_t bias) +{ + pDAC->CR &= ~DAC_BIAS_EN; + + if (bias == DAC_MAX_UPDATE_RATE_400kHz) { + pDAC->CR |= DAC_BIAS_EN; + } +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/eeprom_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/eeprom_17xx_40xx.c new file mode 100644 index 000000000..abad37880 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/eeprom_17xx_40xx.c @@ -0,0 +1,258 @@ +/* + * @brief LPC17xx/40xx EEPROM driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ +/* Setup EEPROM clock */ +STATIC void setClkDiv(LPC_EEPROM_T *pEEPROM) +{ + uint32_t clk; + + /* Setup EEPROM timing to 375KHz based on PCLK rate */ + clk = Chip_Clock_GetSystemClockRate(); + + /* Set EEPROM clock divide value*/ + pEEPROM->CLKDIV = clk / 375000 - 1; +} + +/* Setup EEPROM clock */ +STATIC void setWaitState(LPC_EEPROM_T *pEEPROM) +{ + uint32_t val, clk; + + /* Setup EEPROM timing to 375KHz based on PCLK rate */ + clk = Chip_Clock_GetSystemClockRate(); + + /* Setup EEPROM wait states to 15, 35, 35nS */ + val = ((((clk / 1000000) * 15) / 1000) + 1); + val |= (((((clk / 1000000) * 55) / 1000) + 1) << 8); + val |= (((((clk / 1000000) * 35) / 1000) + 1) << 16); + Chip_EEPROM_SetWaitState(pEEPROM, val); + +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initializes the EEPROM peripheral with specified parameter */ +void Chip_EEPROM_Init(LPC_EEPROM_T *pEEPROM) +{ + Chip_EEPROM_DisablePowerDown(pEEPROM); + setClkDiv(pEEPROM); + setWaitState(pEEPROM); +} + +/* Wait for interrupt */ +void Chip_EEPROM_WaitForIntStatus(LPC_EEPROM_T *pEEPROM, uint32_t mask) +{ + uint32_t status; + + while (1) { + status = Chip_EEPROM_GetIntStatus(pEEPROM); + if ((status & mask) == mask) { + break; + } + } + + Chip_EEPROM_ClearIntStatus(pEEPROM, mask); +} + +/* Erase data in page register */ +void Chip_EEPROM_ErasePageRegister(LPC_EEPROM_T *pEEPROM) +{ + uint32_t i = 0; + + Chip_EEPROM_ClearIntStatus(pEEPROM, EEPROM_INT_ENDOFRW); + + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_32BITS_WRITE); + + Chip_EEPROM_SetAddr(pEEPROM, 0, 0); + + for (i = 0; i < EEPROM_PAGE_SIZE; i += 4) { + Chip_EEPROM_WriteData(pEEPROM, 0); + Chip_EEPROM_WaitForIntStatus(pEEPROM, EEPROM_INT_ENDOFRW); + } + +} + +/* Write data to page register */ +uint32_t Chip_EEPROM_WritePageRegister(LPC_EEPROM_T *pEEPROM, uint16_t pageOffset, + uint8_t *pData, uint8_t wsize, uint32_t byteNum) +{ + uint32_t i = 0; + uint32_t mask = (1 << (8 * wsize)) - 1; + + Chip_EEPROM_ClearIntStatus(pEEPROM, EEPROM_INT_ENDOFRW); + + if (wsize == 1) { + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_8BITS_WRITE); + } + else if (wsize == 2) { + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_16BITS_WRITE); + } + else { + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_32BITS_WRITE); + } + + Chip_EEPROM_SetAddr(pEEPROM, 0, pageOffset); + + for (i = 0; i < byteNum; i += wsize) { + Chip_EEPROM_WriteData(pEEPROM, (*(uint32_t *) (&pData[i])) & mask); + Chip_EEPROM_WaitForIntStatus(pEEPROM, EEPROM_INT_ENDOFRW); + } + + return i; +} + +/* Write data from page register to non-volatile memory */ +void Chip_EEPROM_EraseProgramPage(LPC_EEPROM_T *pEEPROM, uint16_t pageAddr) +{ + Chip_EEPROM_ClearIntStatus(pEEPROM, EEPROM_CMD_ERASE_PRG_PAGE); + Chip_EEPROM_SetAddr(pEEPROM, pageAddr, 0); + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_ERASE_PRG_PAGE); + Chip_EEPROM_WaitForIntStatus(pEEPROM, EEPROM_INT_ENDOFPROG); +} + +/* Read data from non-volatile memory */ +uint32_t Chip_EEPROM_ReadPage(LPC_EEPROM_T *pEEPROM, + uint16_t pageOffset, + uint16_t pageAddr, + uint8_t *pData, + uint8_t rsize, + uint32_t byteNum) +{ + uint32_t i; + uint32_t mask = (1 << (8 * rsize)) - 1; + + Chip_EEPROM_ClearIntStatus(pEEPROM, EEPROM_INT_ENDOFRW); + Chip_EEPROM_SetAddr(pEEPROM, pageAddr, pageOffset); + + if (rsize == 1) { + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_8BITS_READ | EEPROM_CMD_RDPREFETCH); + } + else if (rsize == 2) { + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_16BITS_READ | EEPROM_CMD_RDPREFETCH); + } + else { + Chip_EEPROM_SetCmd(pEEPROM, EEPROM_CMD_32BITS_READ | EEPROM_CMD_RDPREFETCH); + } + + /* read and store data in buffer */ + for (i = 0; i < byteNum; i += rsize) { + (*(uint32_t *) (&pData[i]) ) &= ~mask; + (*(uint32_t *) (&pData[i]) ) |= (Chip_EEPROM_ReadData(pEEPROM) & mask); + Chip_EEPROM_WaitForIntStatus(pEEPROM, EEPROM_INT_ENDOFRW); + } + return i; +} + +/* Write data to EEPROM at specific address */ +Status Chip_EEPROM_Write(LPC_EEPROM_T *pEEPROM, + uint16_t pageOffset, + uint16_t pageAddr, + void *pData, + EEPROM_RWSIZE_T wsize, + uint32_t byteNum) +{ + uint32_t wTotalByteNum = 0; + uint32_t wOffset = (pageOffset & (EEPROM_PAGE_SIZE - 1)); + uint32_t wByteNum = EEPROM_PAGE_SIZE - wOffset; + while (byteNum) { + if (wByteNum > byteNum) { + wByteNum = byteNum; + } + /* update data to page register */ + Chip_EEPROM_WritePageRegister(pEEPROM, wOffset, + &((uint8_t *) pData)[wTotalByteNum], (uint8_t) wsize, wByteNum); + Chip_EEPROM_EraseProgramPage(pEEPROM, pageAddr); + wTotalByteNum += wByteNum; + byteNum -= wByteNum; + + /* Change to next page */ + pageAddr++; + wOffset = 0; + wByteNum = EEPROM_PAGE_SIZE; + } + return SUCCESS; +} + +/* Read data to EEPROM at specific address */ +void Chip_EEPROM_Read(LPC_EEPROM_T *pEEPROM, + uint16_t pageOffset, + uint16_t pageAddr, + void *pData, + EEPROM_RWSIZE_T rsize, + uint32_t byteNum) +{ + uint32_t rTotalByteNum = 0; + uint32_t rOffset = (pageOffset & (EEPROM_PAGE_SIZE - 1)); + uint32_t rByteNum = EEPROM_PAGE_SIZE - rOffset; + /* read and store data in buffer */ + while (byteNum) { + if (rByteNum > byteNum) { + rByteNum = byteNum; + } + /* update data to page register */ + Chip_EEPROM_ReadPage(pEEPROM, rOffset, pageAddr, + &((uint8_t *) pData)[rTotalByteNum], (uint8_t) rsize, rByteNum); + rTotalByteNum += rByteNum; + byteNum -= rByteNum; + + /* Change to next page */ + pageAddr++; + rOffset = 0; + rByteNum = EEPROM_PAGE_SIZE; + } +} + +/* Erase a page at the specific address */ +void Chip_EEPROM_Erase(LPC_EEPROM_T *pEEPROM, uint16_t pageAddr) +{ + Chip_EEPROM_ErasePageRegister(pEEPROM); + + Chip_EEPROM_EraseProgramPage(pEEPROM, pageAddr); +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/emc_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/emc_17xx_40xx.c new file mode 100644 index 000000000..9a4969101 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/emc_17xx_40xx.c @@ -0,0 +1,282 @@ +/* + * @brief LPC17xx/40xx EMC driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ +/* DIV function with result rounded up */ +#define EMC_DIV_ROUND_UP(x, y) ((x + y - 1) / y) + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +#ifndef EMC_SUPPORT_ONLY_PL172 +/* Get ARM External Memory Controller Version */ +STATIC uint32_t getARMPeripheralID(void) +{ + uint32_t *RegAdd; + RegAdd = (uint32_t *) ((uint32_t) LPC_EMC + 0xFE0); + return (RegAdd[0] & 0xFF) | ((RegAdd[1] & 0xFF) << 8) | + ((RegAdd[2] & 0xFF) << 16) | (RegAdd[3] << 24); +} + +#endif + +/* Calculate Clock Count from Timing Unit(nanoseconds) */ +STATIC uint32_t convertTimmingParam(uint32_t EMC_Clock, int32_t input_ns, uint32_t adjust) +{ + uint32_t temp; + if (input_ns < 0) { + return (-input_ns) >> 8; + } + temp = EMC_Clock / 1000000; /* MHz calculation */ + temp = temp * input_ns / 1000; + + /* round up */ + temp += 0xFF; + + /* convert to simple integer number format */ + temp >>= 8; + if (temp > adjust) { + return temp - adjust; + } + + return 0; +} + +/* Get Dynamic Memory Device Colum len */ +STATIC uint32_t getColsLen(uint32_t DynConfig) +{ + uint32_t DevBusWidth; + DevBusWidth = (DynConfig >> EMC_DYN_CONFIG_DEV_BUS_BIT) & 0x03; + if (DevBusWidth == 2) { + return 8; + } + else if (DevBusWidth == 1) { + return ((DynConfig >> (EMC_DYN_CONFIG_DEV_SIZE_BIT + 1)) & 0x03) + 8; + } + else if (DevBusWidth == 0) { + return ((DynConfig >> (EMC_DYN_CONFIG_DEV_SIZE_BIT + 1)) & 0x03) + 9; + } + + return 0; +} + +/* Initializes the Dynamic Controller according to the specified parameters + in the IP_EMC_DYN_CONFIG_T */ +void initDynMem(LPC_EMC_T *pEMC, IP_EMC_DYN_CONFIG_T *Dynamic_Config, uint32_t EMC_Clock) +{ + uint32_t ChipSelect, tmpclk; + int i; + + for (ChipSelect = 0; ChipSelect < 4; ChipSelect++) { + LPC_EMC_T *EMC_Reg_add = (LPC_EMC_T *) ((uint32_t) pEMC + (ChipSelect << 5)); + + EMC_Reg_add->DYNAMICRASCAS0 = Dynamic_Config->DevConfig[ChipSelect].RAS | + ((Dynamic_Config->DevConfig[ChipSelect].ModeRegister << + (8 - EMC_DYN_MODE_CAS_BIT)) & 0xF00); + EMC_Reg_add->DYNAMICCONFIG0 = Dynamic_Config->DevConfig[ChipSelect].DynConfig; + } + pEMC->DYNAMICREADCONFIG = Dynamic_Config->ReadConfig; /* Read strategy */ + + pEMC->DYNAMICRP = convertTimmingParam(EMC_Clock, Dynamic_Config->tRP, 1); + pEMC->DYNAMICRAS = convertTimmingParam(EMC_Clock, Dynamic_Config->tRAS, 1); + pEMC->DYNAMICSREX = convertTimmingParam(EMC_Clock, Dynamic_Config->tSREX, 1); + pEMC->DYNAMICAPR = convertTimmingParam(EMC_Clock, Dynamic_Config->tAPR, 1); + pEMC->DYNAMICDAL = convertTimmingParam(EMC_Clock, Dynamic_Config->tDAL, 0); + pEMC->DYNAMICWR = convertTimmingParam(EMC_Clock, Dynamic_Config->tWR, 1); + pEMC->DYNAMICRC = convertTimmingParam(EMC_Clock, Dynamic_Config->tRC, 1); + pEMC->DYNAMICRFC = convertTimmingParam(EMC_Clock, Dynamic_Config->tRFC, 1); + pEMC->DYNAMICXSR = convertTimmingParam(EMC_Clock, Dynamic_Config->tXSR, 1); + pEMC->DYNAMICRRD = convertTimmingParam(EMC_Clock, Dynamic_Config->tRRD, 1); + pEMC->DYNAMICMRD = convertTimmingParam(EMC_Clock, Dynamic_Config->tMRD, 1); + + /* TIM_Waitus(100); */ + /*FIXME: if Timer driver is ready, it should replace below "for" delay technic */ + for (i = 0; i < 1000; i++) { /* wait 100us */ + } + pEMC->DYNAMICCONTROL = 0x00000183; /* Issue NOP command */ + + /* TIM_Waitus(200); */ /* wait 200us */ + /*FIXME: if Timer driver is ready, it should replace below "for" delay technic */ + for (i = 0; i < 1000; i++) {} + pEMC->DYNAMICCONTROL = 0x00000103; /* Issue PALL command */ + + pEMC->DYNAMICREFRESH = 2; /* ( 2 * 16 ) -> 32 clock cycles */ + + /* FIXME: TIM_Waitus(200); */ /* wait 200us */ + for (i = 0; i < 80; i++) {} + + tmpclk = EMC_DIV_ROUND_UP(convertTimmingParam(EMC_Clock, Dynamic_Config->RefreshPeriod, 0), 16); + pEMC->DYNAMICREFRESH = tmpclk; + + pEMC->DYNAMICCONTROL = 0x00000083; /* Issue MODE command */ + + for (ChipSelect = 0; ChipSelect < 4; ChipSelect++) { + /*uint32_t burst_length;*/ + uint32_t DynAddr; + uint8_t Col_len; + + Col_len = getColsLen(Dynamic_Config->DevConfig[ChipSelect].DynConfig); + /* get bus wide: if 32bit, len is 4 else if 16bit len is 2 */ + /* burst_length = 1 << ((((Dynamic_Config->DynConfig[ChipSelect] >> 14) & 1)^1) +1); */ + if (Dynamic_Config->DevConfig[ChipSelect].DynConfig & (1 << EMC_DYN_CONFIG_DATA_BUS_WIDTH_BIT)) { + /*32bit bus */ + /*burst_length = 2;*/ + Col_len += 2; + } + else { + /*burst_length = 4;*/ + Col_len += 1; + } + DynAddr = Dynamic_Config->DevConfig[ChipSelect].BaseAddr; + + if (DynAddr != 0) { + uint32_t temp; + uint32_t ModeRegister; + ModeRegister = Dynamic_Config->DevConfig[ChipSelect].ModeRegister; + temp = *((volatile uint32_t *) (DynAddr | (ModeRegister << Col_len))); + temp = temp; + } + } + pEMC->DYNAMICCONTROL = 0x00000000; /* Issue NORMAL command */ + + /* enable buffers */ + pEMC->DYNAMICCONFIG0 |= 1 << 19; + pEMC->DYNAMICCONFIG1 |= 1 << 19; + pEMC->DYNAMICCONFIG2 |= 1 << 19; + pEMC->DYNAMICCONFIG3 |= 1 << 19; +} + +/* Initializes the Static Controller according to the specified parameters + * in the IP_EMC_STATIC_CONFIG_T + */ +void initStaticMem(LPC_EMC_T *pEMC, IP_EMC_STATIC_CONFIG_T *Static_Config, uint32_t EMC_Clock) +{ + LPC_EMC_T *EMC_Reg_add = (LPC_EMC_T *) ((uint32_t) pEMC + ((Static_Config->ChipSelect) << 5)); + EMC_Reg_add->STATICCONFIG0 = Static_Config->Config; + EMC_Reg_add->STATICWAITWEN0 = convertTimmingParam(EMC_Clock, Static_Config->WaitWen, 1); + EMC_Reg_add->STATICWAITOEN0 = convertTimmingParam(EMC_Clock, Static_Config->WaitOen, 0); + EMC_Reg_add->STATICWAITRD0 = convertTimmingParam(EMC_Clock, Static_Config->WaitRd, 1); + EMC_Reg_add->STATICWAITPAG0 = convertTimmingParam(EMC_Clock, Static_Config->WaitPage, 1); + EMC_Reg_add->STATICWAITWR0 = convertTimmingParam(EMC_Clock, Static_Config->WaitWr, 2); + EMC_Reg_add->STATICWAITTURN0 = convertTimmingParam(EMC_Clock, Static_Config->WaitTurn, 1); +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Dyanmic memory setup */ +void Chip_EMC_Dynamic_Init(IP_EMC_DYN_CONFIG_T *Dynamic_Config) +{ + uint32_t ClkFreq; + + /* Note clocks must be enabled prior to this call */ + ClkFreq = Chip_Clock_GetEMCClockRate(); + + initDynMem(LPC_EMC, Dynamic_Config, ClkFreq); +} + +/* Enable Dynamic Memory Controller */ +void Chip_EMC_Dynamic_Enable(uint8_t Enable) +{ + if (Enable) { + LPC_EMC->DYNAMICCONTROL |= EMC_DYN_CONTROL_ENABLE; + } + else { + LPC_EMC->DYNAMICCONTROL &= ~EMC_DYN_CONTROL_ENABLE; + } +} + +/* Static memory setup */ +void Chip_EMC_Static_Init(IP_EMC_STATIC_CONFIG_T *Static_Config) +{ + uint32_t ClkFreq; + + /* Note clocks must be enabled prior to this call */ + ClkFreq = Chip_Clock_GetEMCClockRate(); + + initStaticMem(LPC_EMC, Static_Config, ClkFreq); +} + +/* Mirror CS1 to CS0 and DYCS0 */ +void Chip_EMC_Mirror(uint8_t Enable) +{ + if (Enable) { + LPC_EMC->CONTROL |= 1 << 1; + } + else { + LPC_EMC->CONTROL &= ~(1 << 1); + } +} + +/* Enable EMC */ +void Chip_EMC_Enable(uint8_t Enable) +{ + if (Enable) { + LPC_EMC->CONTROL |= 1; + } + else { + LPC_EMC->CONTROL &= ~(1); + } +} + +/* Set EMC LowPower Mode */ +void Chip_EMC_LowPowerMode(uint8_t Enable) +{ + if (Enable) { + LPC_EMC->CONTROL |= 1 << 2; + } + else { + LPC_EMC->CONTROL &= ~(1 << 2); + } +} + +/* Initialize EMC */ +void Chip_EMC_Init(uint32_t Enable, uint32_t ClockRatio, uint32_t EndianMode) +{ + LPC_EMC->CONFIG = (EndianMode ? 1 : 0) | ((ClockRatio ? 1 : 0) << 8); + + /* Enable EMC 001 Normal Memory Map, No low power mode */ + LPC_EMC->CONTROL = (Enable ? 1 : 0); +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/enet_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/enet_17xx_40xx.c new file mode 100644 index 000000000..363a133da --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/enet_17xx_40xx.c @@ -0,0 +1,289 @@ +/* + * @brief LPC17xx/40xx ethernet driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/* Saved address for PHY and clock divider */ +STATIC uint32_t phyAddr; + +/* Divider index values for the MII PHY clock */ +STATIC const uint8_t EnetClkDiv[] = {4, 6, 8, 10, 14, 20, 28, 36, 40, 44, + 48, 52, 56, 60, 64}; + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +STATIC INLINE void resetENET(LPC_ENET_T *pENET) +{ + volatile uint32_t i; + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + Chip_SYSCTL_PeriphReset(SYSCTL_RESET_ENET); +#endif + + /* Reset ethernet peripheral */ + Chip_ENET_Reset(pENET); + for (i = 0; i < 100; i++) {} +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Basic Ethernet interface initialization */ +void Chip_ENET_Init(LPC_ENET_T *pENET, bool useRMII) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_ENET); + resetENET(pENET); + + /* Initial MAC configuration for full duplex, + 100Mbps, inter-frame gap use default values */ + pENET->MAC.MAC1 = ENET_MAC1_PARF; + pENET->MAC.MAC2 = ENET_MAC2_FULLDUPLEX | ENET_MAC2_CRCEN | ENET_MAC2_PADCRCEN; + + if (useRMII) { + pENET->CONTROL.COMMAND = ENET_COMMAND_FULLDUPLEX | ENET_COMMAND_PASSRUNTFRAME | ENET_COMMAND_RMII; + } + else { + pENET->CONTROL.COMMAND = ENET_COMMAND_FULLDUPLEX | ENET_COMMAND_PASSRUNTFRAME; + } + + pENET->MAC.IPGT = ENET_IPGT_FULLDUPLEX; + pENET->MAC.IPGR = ENET_IPGR_P2_DEF; + pENET->MAC.SUPP = ENET_SUPP_100Mbps_SPEED; + pENET->MAC.MAXF = ENET_ETH_MAX_FLEN; + pENET->MAC.CLRT = ENET_CLRT_DEF; + + /* Setup default filter */ + pENET->CONTROL.COMMAND |= ENET_COMMAND_PASSRXFILTER; + + /* Clear all MAC interrupts */ + pENET->MODULE_CONTROL.INTCLEAR = 0xFFFF; + + /* Disable MAC interrupts */ + pENET->MODULE_CONTROL.INTENABLE = 0; +} + +/* Ethernet interface shutdown */ +void Chip_ENET_DeInit(LPC_ENET_T *pENET) +{ + /* Disable packet reception */ + pENET->MAC.MAC1 &= ~ENET_MAC1_RXENABLE; + pENET->CONTROL.COMMAND = 0; + + /* Clear all MAC interrupts */ + pENET->MODULE_CONTROL.INTCLEAR = 0xFFFF; + + /* Disable MAC interrupts */ + pENET->MODULE_CONTROL.INTENABLE = 0; + + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_ENET); +} + +/* Sets up the PHY link clock divider and PHY address */ +void Chip_ENET_SetupMII(LPC_ENET_T *pENET, uint32_t div, uint8_t addr) +{ + /* Save clock divider and PHY address in MII address register */ + phyAddr = ENET_MADR_PHYADDR(addr); + + /* Write to MII configuration register and reset */ + pENET->MAC.MCFG = ENET_MCFG_CLOCKSEL(div) | ENET_MCFG_RES_MII; + + /* release reset */ + pENET->MAC.MCFG &= ~(ENET_MCFG_RES_MII); +} + +/* Find the divider index for a desired MII clock rate */ +uint32_t Chip_ENET_FindMIIDiv(LPC_ENET_T *pENET, uint32_t clockRate) +{ + uint32_t tmp, divIdx = 0; + + /* Find desired divider value */ + tmp = Chip_Clock_GetENETClockRate() / clockRate; + + /* Determine divider index from desired divider */ + for (divIdx = 0; divIdx < (sizeof(EnetClkDiv) / sizeof(EnetClkDiv[0])); divIdx++) { + /* Closest index, but not higher than desired rate */ + if (EnetClkDiv[divIdx] >= tmp) { + return divIdx; + } + } + + /* Use maximum divider index */ + return (sizeof(EnetClkDiv) / sizeof(EnetClkDiv[0])) - 1; +} + +/* Starts a PHY write via the MII */ +void Chip_ENET_StartMIIWrite(LPC_ENET_T *pENET, uint8_t reg, uint16_t data) +{ + /* Write value at PHY address and register */ + pENET->MAC.MCMD = 0; + pENET->MAC.MADR = phyAddr | ENET_MADR_REGADDR(reg); + pENET->MAC.MWTD = data; +} + +/*Starts a PHY read via the MII */ +void Chip_ENET_StartMIIRead(LPC_ENET_T *pENET, uint8_t reg) +{ + /* Read value at PHY address and register */ + pENET->MAC.MADR = phyAddr | ENET_MADR_REGADDR(reg); + pENET->MAC.MCMD = ENET_MCMD_READ; +} + +/* Read MII data */ +uint16_t Chip_ENET_ReadMIIData(LPC_ENET_T *pENET) +{ + pENET->MAC.MCMD = 0; + return pENET->MAC.MRDD; +} + +/* Sets full duplex for the ENET interface */ +void Chip_ENET_SetFullDuplex(LPC_ENET_T *pENET) +{ + pENET->MAC.MAC2 |= ENET_MAC2_FULLDUPLEX; + pENET->CONTROL.COMMAND |= ENET_COMMAND_FULLDUPLEX; + pENET->MAC.IPGT = ENET_IPGT_FULLDUPLEX; +} + +/* Sets half duplex for the ENET interface */ +void Chip_ENET_SetHalfDuplex(LPC_ENET_T *pENET) +{ + pENET->MAC.MAC2 &= ~ENET_MAC2_FULLDUPLEX; + pENET->CONTROL.COMMAND &= ~ENET_COMMAND_FULLDUPLEX; + pENET->MAC.IPGT = ENET_IPGT_HALFDUPLEX; +} + +/* Configures the initial ethernet transmit descriptors */ +void Chip_ENET_InitTxDescriptors(LPC_ENET_T *pENET, + ENET_TXDESC_T *pDescs, + ENET_TXSTAT_T *pStatus, + uint32_t descNum) +{ + /* Setup descriptor list base addresses */ + pENET->CONTROL.TX.DESCRIPTOR = (uint32_t) pDescs; + pENET->CONTROL.TX.DESCRIPTORNUMBER = descNum - 1; + pENET->CONTROL.TX.STATUS = (uint32_t) pStatus; + pENET->CONTROL.TX.PRODUCEINDEX = 0; +} + +/* Configures the initial ethernet receive descriptors */ +void Chip_ENET_InitRxDescriptors(LPC_ENET_T *pENET, + ENET_RXDESC_T *pDescs, + ENET_RXSTAT_T *pStatus, + uint32_t descNum) +{ + /* Setup descriptor list base addresses */ + pENET->CONTROL.RX.DESCRIPTOR = (uint32_t) pDescs; + pENET->CONTROL.RX.DESCRIPTORNUMBER = descNum - 1; + pENET->CONTROL.RX.STATUS = (uint32_t) pStatus; + pENET->CONTROL.RX.CONSUMEINDEX = 0; +} + +/* Get status for the descriptor list */ +ENET_BUFF_STATUS_T Chip_ENET_GetBufferStatus(LPC_ENET_T *pENET, + uint16_t produceIndex, + uint16_t consumeIndex, + uint16_t buffSize) +{ + /* Empty descriptor list */ + if (consumeIndex == produceIndex) { + return ENET_BUFF_EMPTY; + } + + /* Full descriptor list */ + if ((consumeIndex == 0) && + (produceIndex == (buffSize - 1))) { + return ENET_BUFF_FULL; + } + + /* Wrap-around, full descriptor list */ + if (consumeIndex == (produceIndex + 1)) { + return ENET_BUFF_FULL; + } + + return ENET_BUFF_PARTIAL_FULL; +} + +/* Get the number of descriptor filled */ +uint32_t Chip_ENET_GetFillDescNum(LPC_ENET_T *pENET, uint16_t produceIndex, uint16_t consumeIndex, uint16_t buffSize) +{ + /* Empty descriptor list */ + if (consumeIndex == produceIndex) { + return 0; + } + + if (consumeIndex > produceIndex) { + return (buffSize - consumeIndex) + produceIndex; + } + + return produceIndex - consumeIndex; +} + +/* Increase the current Tx Produce Descriptor Index */ +uint16_t Chip_ENET_IncTXProduceIndex(LPC_ENET_T *pENET) +{ + /* Get current TX produce index */ + uint32_t idx = pENET->CONTROL.TX.PRODUCEINDEX; + + /* Start frame transmission by incrementing descriptor */ + idx++; + if (idx > pENET->CONTROL.TX.DESCRIPTORNUMBER) { + idx = 0; + } + pENET->CONTROL.TX.PRODUCEINDEX = idx; + + return idx; +} + +/* Increase the current Rx Consume Descriptor Index */ +uint16_t Chip_ENET_IncRXConsumeIndex(LPC_ENET_T *pENET) +{ + /* Get current RX consume index */ + uint32_t idx = pENET->CONTROL.RX.CONSUMEINDEX; + + /* Consume descriptor */ + idx++; + if (idx > pENET->CONTROL.RX.DESCRIPTORNUMBER) { + idx = 0; + } + pENET->CONTROL.RX.CONSUMEINDEX = idx; + + return idx; +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/fpu_init.c b/hw/mcu/nxp/lpc_chip_40xx/src/fpu_init.c new file mode 100644 index 000000000..88125dda5 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/fpu_init.c @@ -0,0 +1,97 @@ +/* + * @brief FPU init code + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#if defined(CORE_M4) + +#include "sys_config.h" +#include "cmsis.h" +#include "stdint.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +#define LPC_CPACR 0xE000ED88 + +#define SCB_MVFR0 0xE000EF40 +#define SCB_MVFR0_RESET 0x10110021 + +#define SCB_MVFR1 0xE000EF44 +#define SCB_MVFR1_RESET 0x11000011 + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Early initialization of the FPU */ +void fpuInit(void) +{ +#if __FPU_PRESENT != 0 + // from arm trm manual: + // ; CPACR is located at address 0xE000ED88 + // LDR.W R0, =0xE000ED88 + // ; Read CPACR + // LDR R1, [R0] + // ; Set bits 20-23 to enable CP10 and CP11 coprocessors + // ORR R1, R1, #(0xF << 20) + // ; Write back the modified value to the CPACR + // STR R1, [R0] + + volatile uint32_t *regCpacr = (uint32_t *) LPC_CPACR; + volatile uint32_t *regMvfr0 = (uint32_t *) SCB_MVFR0; + volatile uint32_t *regMvfr1 = (uint32_t *) SCB_MVFR1; + volatile uint32_t Cpacr; + volatile uint32_t Mvfr0; + volatile uint32_t Mvfr1; + char vfpPresent = 0; + + Mvfr0 = *regMvfr0; + Mvfr1 = *regMvfr1; + + vfpPresent = ((SCB_MVFR0_RESET == Mvfr0) && (SCB_MVFR1_RESET == Mvfr1)); + + if (vfpPresent) { + Cpacr = *regCpacr; + Cpacr |= (0xF << 20); + *regCpacr = Cpacr; // enable CP10 and CP11 for full access + } +#endif /* __FPU_PRESENT != 0 */ +} + +#endif /* defined(CORE_M4 */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/gpdma_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/gpdma_17xx_40xx.c new file mode 100644 index 000000000..b19dc0ea8 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/gpdma_17xx_40xx.c @@ -0,0 +1,704 @@ +/* + * @brief LPC17xx/40xx GPDMA driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/* Channel array to monitor free channel */ +static DMA_ChannelHandle_t ChannelHandlerArray[GPDMA_NUMBER_CHANNELS]; + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) +/* Optimized Peripheral Source and Destination burst size (177x_8x,407x_8x) */ +static const uint8_t GPDMA_LUTPerBurst[] = { + 0, /* Reserved */ + GPDMA_BSIZE_8, /* SD Card */ + GPDMA_BSIZE_4, /* SSP0 Tx */ + GPDMA_BSIZE_4, /* SSP0 Rx */ + GPDMA_BSIZE_4, /* SSP1 Tx */ + GPDMA_BSIZE_4, /* SSP1 Rx */ + GPDMA_BSIZE_4, /* SSP2 Tx */ + GPDMA_BSIZE_4, /* SSP2 Rx */ + GPDMA_BSIZE_1, /* ADC */ + GPDMA_BSIZE_1, /* DAC */ + GPDMA_BSIZE_1, /* UART0 Tx */ + GPDMA_BSIZE_1, /* UART0 Rx */ + GPDMA_BSIZE_1, /* UART1 Tx */ + GPDMA_BSIZE_1, /* UART1 Rx */ + GPDMA_BSIZE_1, /* UART2 Tx */ + GPDMA_BSIZE_1, /* UART2 Rx */ + GPDMA_BSIZE_1, /* MAT0.0 */ + GPDMA_BSIZE_1, /* MAT0.1 */ + GPDMA_BSIZE_1, /* MAT1.0 */ + GPDMA_BSIZE_1, /* MAT1.1 */ + GPDMA_BSIZE_1, /* MAT2.0 */ + GPDMA_BSIZE_1, /* MAT2.1 */ + GPDMA_BSIZE_32, /* I2S channel 0 */ + GPDMA_BSIZE_32, /* I2S channel 1 */ + 0, /* Reserved */ + 0, /* Reserved */ + GPDMA_BSIZE_1, /* UART3 Tx */ + GPDMA_BSIZE_1, /* UART3 Rx */ + GPDMA_BSIZE_1, /* UART4 Tx */ + GPDMA_BSIZE_1, /* UART4 Rx */ + GPDMA_BSIZE_1, /* MAT3.0 */ + GPDMA_BSIZE_1, /* MAT3.1 */ +}; + +/* Optimized Peripheral Source and Destination transfer width (177x_8x,407x_8x) */ +static const uint8_t GPDMA_LUTPerWid[] = { + 0, /* Reserved */ + GPDMA_WIDTH_WORD, /* SD Card */ + GPDMA_WIDTH_BYTE, /* SSP0 Tx */ + GPDMA_WIDTH_BYTE, /* SSP0 Rx */ + GPDMA_WIDTH_BYTE, /* SSP1 Tx */ + GPDMA_WIDTH_BYTE, /* SSP1 Rx */ + GPDMA_WIDTH_BYTE, /* SSP2 Tx */ + GPDMA_WIDTH_BYTE, /* SSP2 Rx */ + GPDMA_WIDTH_WORD, /* ADC */ + GPDMA_WIDTH_HALFWORD, /* DAC */ + GPDMA_WIDTH_BYTE, /* UART0 Tx */ + GPDMA_WIDTH_BYTE, /* UART0 Rx */ + GPDMA_WIDTH_BYTE, /* UART1 Tx */ + GPDMA_WIDTH_BYTE, /* UART1 Rx */ + GPDMA_WIDTH_BYTE, /* UART2 Tx */ + GPDMA_WIDTH_BYTE, /* UART2 Rx */ + GPDMA_WIDTH_WORD, /* MAT0.0 */ + GPDMA_WIDTH_WORD, /* MAT0.1 */ + GPDMA_WIDTH_WORD, /* MAT1.0 */ + GPDMA_WIDTH_WORD, /* MAT1.1 */ + GPDMA_WIDTH_WORD, /* MAT2.0 */ + GPDMA_WIDTH_WORD, /* MAT2.1 */ + GPDMA_WIDTH_WORD, /* I2S channel 0 */ + GPDMA_WIDTH_WORD, /* I2S channel 1 */ + 0, /* Reserved */ + 0, /* Reserved */ + GPDMA_WIDTH_BYTE, /* UART3 Tx */ + GPDMA_WIDTH_BYTE, /* UART3 Rx */ + GPDMA_WIDTH_BYTE, /* UART4 Tx */ + GPDMA_WIDTH_BYTE, /* UART4 Rx */ + GPDMA_WIDTH_WORD, /* MAT3.0 */ + GPDMA_WIDTH_WORD, /* MAT3.1 */ +}; + +/* Lookup Table of Connection Type matched with (177x_8x,407x_8x) Peripheral Data (FIFO) register base address */ +volatile static const void *GPDMA_LUTPerAddr[] = { + 0, /* Reserved */ + (&LPC_SDC->FIFO), /* SD Card */ + (&LPC_SSP0->DR), /* SSP0 Tx */ + (&LPC_SSP0->DR), /* SSP0 Rx */ + (&LPC_SSP1->DR), /* SSP1 Tx */ + (&LPC_SSP1->DR), /* SSP1 Rx */ + (&LPC_SSP2->DR), /* SSP2 Tx */ + (&LPC_SSP2->DR), /* SSP2 Rx */ + (&LPC_ADC->GDR), /* ADC */ + (&LPC_DAC->CR), /* DAC */ + (&LPC_UART0-> /*RBTHDLR.*/ THR), /* UART0 Tx */ + (&LPC_UART0-> /*RBTHDLR.*/ RBR), /* UART0 Rx */ + (&LPC_UART1-> /*RBTHDLR.*/ THR), /* UART1 Tx */ + (&LPC_UART1-> /*RBTHDLR.*/ RBR), /* UART1 Rx */ + (&LPC_UART2-> /*RBTHDLR.*/ THR), /* UART2 Tx */ + (&LPC_UART2-> /*RBTHDLR.*/ RBR), /* UART2 Rx */ + (&LPC_TIMER0->MR[0]), /* MAT0.0 */ + (&LPC_TIMER0->MR[1]), /* MAT0.1 */ + (&LPC_TIMER1->MR[0]), /* MAT1.0 */ + (&LPC_TIMER1->MR[1]), /* MAT1.1 */ + (&LPC_TIMER2->MR[0]), /* MAT2.0 */ + (&LPC_TIMER2->MR[1]), /* MAT2.1 */ + (&LPC_I2S->TXFIFO), /* I2S Tx */ + (&LPC_I2S->RXFIFO), /* I2S Rx */ + 0, /* Reverse */ + 0, /* Reverse */ + (&LPC_UART3-> /*RBTHDLR.*/ THR), /* UART3 Tx */ + (&LPC_UART3-> /*RBTHDLR.*/ RBR), /* UART3 Rx */ + (&LPC_UART4-> /*RBTHDLR.*/ THR), /* UART4 Tx */ + (&LPC_UART4-> /*RBTHDLR.*/ RBR), /* UART4 Rx */ + (&LPC_TIMER3->MR[0]), /* MAT3.0 */ + (&LPC_TIMER3->MR[1]) /* MAT3.1 */ +}; + +#elif defined(CHIP_LPC175X_6X) +const uint8_t GPDMA_LUTPerBurst[] = { + GPDMA_BSIZE_4, // SSP0 Tx + GPDMA_BSIZE_4, // SSP0 Rx + GPDMA_BSIZE_4, // SSP1 Tx + GPDMA_BSIZE_4, // SSP1 Rx + GPDMA_BSIZE_1, // ADC + GPDMA_BSIZE_32, // I2S channel 0 + GPDMA_BSIZE_32, // I2S channel 1 + GPDMA_BSIZE_1, // DAC + GPDMA_BSIZE_1, // UART0 Tx + GPDMA_BSIZE_1, // UART0 Rx + GPDMA_BSIZE_1, // UART1 Tx + GPDMA_BSIZE_1, // UART1 Rx + GPDMA_BSIZE_1, // UART2 Tx + GPDMA_BSIZE_1, // UART2 Rx + GPDMA_BSIZE_1, // UART3 Tx + GPDMA_BSIZE_1, // UART3 Rx + GPDMA_BSIZE_1, // MAT0.0 + GPDMA_BSIZE_1, // MAT0.1 + GPDMA_BSIZE_1, // MAT1.0 + GPDMA_BSIZE_1, // MAT1.1 + GPDMA_BSIZE_1, // MAT2.0 + GPDMA_BSIZE_1, // MAT2.1 + GPDMA_BSIZE_1, // MAT3.0 + GPDMA_BSIZE_1 // MAT3.1 +}; + +/** + * @brief Optimized Peripheral Source and Destination transfer width + */ +const uint8_t GPDMA_LUTPerWid[] = { + GPDMA_WIDTH_BYTE, // SSP0 Tx + GPDMA_WIDTH_BYTE, // SSP0 Rx + GPDMA_WIDTH_BYTE, // SSP1 Tx + GPDMA_WIDTH_BYTE, // SSP1 Rx + GPDMA_WIDTH_WORD, // ADC + GPDMA_WIDTH_WORD, // I2S channel 0 + GPDMA_WIDTH_WORD, // I2S channel 1 + GPDMA_WIDTH_HALFWORD, // DAC + GPDMA_WIDTH_BYTE, // UART0 Tx + GPDMA_WIDTH_BYTE, // UART0 Rx + GPDMA_WIDTH_BYTE, // UART1 Tx + GPDMA_WIDTH_BYTE, // UART1 Rx + GPDMA_WIDTH_BYTE, // UART2 Tx + GPDMA_WIDTH_BYTE, // UART2 Rx + GPDMA_WIDTH_BYTE, // UART3 Tx + GPDMA_WIDTH_BYTE, // UART3 Rx + GPDMA_WIDTH_WORD, // MAT0.0 + GPDMA_WIDTH_WORD, // MAT0.1 + GPDMA_WIDTH_WORD, // MAT1.0 + GPDMA_WIDTH_WORD, // MAT1.1 + GPDMA_WIDTH_WORD, // MAT2.0 + GPDMA_WIDTH_WORD, // MAT2.1 + GPDMA_WIDTH_WORD, // MAT3.0 + GPDMA_WIDTH_WORD // MAT3.1 +}; + +/** + * @brief Peripheral Source and Destination address + */ +volatile const void *GPDMA_LUTPerAddr[] = { + (&LPC_SSP0->DR), // SSP0 Tx + (&LPC_SSP0->DR), // SSP0 Rx + (&LPC_SSP1->DR), // SSP1 Tx + (&LPC_SSP1->DR), // SSP1 Rx + (&LPC_ADC->GDR), // ADC + (&LPC_I2S->TXFIFO), // I2S Tx + (&LPC_I2S->RXFIFO), // I2S Rx + (&LPC_DAC->CR), // DAC + (&LPC_UART0-> /*RBTHDLR.*/ THR), // UART0 Tx + (&LPC_UART0-> /*RBTHDLR.*/ RBR), // UART0 Rx + (&LPC_UART1-> /*RBTHDLR.*/ THR), // UART1 Tx + (&LPC_UART1-> /*RBTHDLR.*/ RBR), // UART1 Rx + (&LPC_UART2-> /*RBTHDLR.*/ THR), // UART2 Tx + (&LPC_UART2-> /*RBTHDLR.*/ RBR), // UART2 Rx + (&LPC_UART3-> /*RBTHDLR.*/ THR), // UART3 Tx + (&LPC_UART3-> /*RBTHDLR.*/ RBR), // UART3 Rx + (&LPC_TIMER0->MR[0]), // MAT0.0 + (&LPC_TIMER0->MR[1]), // MAT0.1 + (&LPC_TIMER1->MR[0]), // MAT1.0 + (&LPC_TIMER1->MR[1]), // MAT1.1 + (&LPC_TIMER2->MR[0]), // MAT2.0 + (&LPC_TIMER2->MR[1]), // MAT2.1 + (&LPC_TIMER3->MR[0]), // MAT3.0 + (&LPC_TIMER3->MR[1]) // MAT3.1 + +}; +#endif + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/* Control which set of peripherals is connected to the DMA controller */ +STATIC uint8_t configDMAMux(uint32_t gpdma_peripheral_connection_number) +{ +#if defined(CHIP_LPC175X_6X) + if (gpdma_peripheral_connection_number > 15) { + LPC_SYSCTL->DMAREQSEL |= (1 << (gpdma_peripheral_connection_number - 16)); + return gpdma_peripheral_connection_number - 8; + } + else { + if (gpdma_peripheral_connection_number > 7) { + LPC_SYSCTL->DMAREQSEL &= ~(1 << (gpdma_peripheral_connection_number - 8)); + } + return gpdma_peripheral_connection_number; + } +#elif defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + if (gpdma_peripheral_connection_number > 15) { + LPC_SYSCTL->DMAREQSEL |= (1 << (gpdma_peripheral_connection_number - 16)); + return gpdma_peripheral_connection_number - 16; + } + else { + LPC_SYSCTL->DMAREQSEL &= ~(1 << (gpdma_peripheral_connection_number)); + return gpdma_peripheral_connection_number; + } +#endif +} + +uint32_t makeCtrlWord(const GPDMA_CH_CFG_T *GPDMAChannelConfig, + uint32_t GPDMA_LUTPerBurstSrcConn, + uint32_t GPDMA_LUTPerBurstDstConn, + uint32_t GPDMA_LUTPerWidSrcConn, + uint32_t GPDMA_LUTPerWidDstConn) +{ + uint32_t ctrl_word = 0; + + switch (GPDMAChannelConfig->TransferType) { + /* Memory to memory */ + case GPDMA_TRANSFERTYPE_M2M_CONTROLLER_DMA: + ctrl_word = GPDMA_DMACCxControl_TransferSize(GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize((4UL)) /**< Burst size = 32 */ + | GPDMA_DMACCxControl_DBSize((4UL)) /**< Burst size = 32 */ + | GPDMA_DMACCxControl_SWidth(GPDMAChannelConfig->TransferWidth) + | GPDMA_DMACCxControl_DWidth(GPDMAChannelConfig->TransferWidth) + | GPDMA_DMACCxControl_SI + | GPDMA_DMACCxControl_DI + | GPDMA_DMACCxControl_I; + break; + + case GPDMA_TRANSFERTYPE_M2P_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_M2P_CONTROLLER_PERIPHERAL: + ctrl_word = GPDMA_DMACCxControl_TransferSize((uint32_t) GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize(GPDMA_LUTPerBurstDstConn) + | GPDMA_DMACCxControl_DBSize(GPDMA_LUTPerBurstDstConn) + | GPDMA_DMACCxControl_SWidth(GPDMA_LUTPerWidDstConn) + | GPDMA_DMACCxControl_DWidth(GPDMA_LUTPerWidDstConn) + | GPDMA_DMACCxControl_DestTransUseAHBMaster1 + | GPDMA_DMACCxControl_SI + | GPDMA_DMACCxControl_I; + break; + + case GPDMA_TRANSFERTYPE_P2M_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_P2M_CONTROLLER_PERIPHERAL: + ctrl_word = GPDMA_DMACCxControl_TransferSize((uint32_t) GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize(GPDMA_LUTPerBurstSrcConn) + | GPDMA_DMACCxControl_DBSize(GPDMA_LUTPerBurstSrcConn) + | GPDMA_DMACCxControl_SWidth(GPDMA_LUTPerWidSrcConn) + | GPDMA_DMACCxControl_DWidth(GPDMA_LUTPerWidSrcConn) + | GPDMA_DMACCxControl_SrcTransUseAHBMaster1 + | GPDMA_DMACCxControl_DI + | GPDMA_DMACCxControl_I; + break; + + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DestPERIPHERAL: + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_SrcPERIPHERAL: + ctrl_word = GPDMA_DMACCxControl_TransferSize((uint32_t) GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize(GPDMA_LUTPerBurstSrcConn) + | GPDMA_DMACCxControl_DBSize(GPDMA_LUTPerBurstDstConn) + | GPDMA_DMACCxControl_SWidth(GPDMA_LUTPerWidSrcConn) + | GPDMA_DMACCxControl_DWidth(GPDMA_LUTPerWidDstConn) + | GPDMA_DMACCxControl_SrcTransUseAHBMaster1 + | GPDMA_DMACCxControl_DestTransUseAHBMaster1 + | GPDMA_DMACCxControl_I; + + break; + + /* Do not support any more transfer type, return ERROR */ + default: + return ERROR; + } + return ctrl_word; +} + +/* Set up the DPDMA according to the specification configuration details */ +Status setupChannel(LPC_GPDMA_T *pGPDMA, + GPDMA_CH_CFG_T *GPDMAChannelConfig, + uint32_t CtrlWord, + uint32_t LinkListItem, + uint8_t SrcPeripheral, + uint8_t DstPeripheral) +{ + GPDMA_CH_T *pDMAch; + + if (pGPDMA->ENBLDCHNS & ((((1UL << (GPDMAChannelConfig->ChannelNum)) & 0xFF)))) { + /* This channel is enabled, return ERROR, need to release this channel first */ + return ERROR; + } + + /* Get Channel pointer */ + pDMAch = (GPDMA_CH_T *) &(pGPDMA->CH[GPDMAChannelConfig->ChannelNum]); + + /* Reset the Interrupt status */ + pGPDMA->INTTCCLEAR = (((1UL << (GPDMAChannelConfig->ChannelNum)) & 0xFF)); + pGPDMA->INTERRCLR = (((1UL << (GPDMAChannelConfig->ChannelNum)) & 0xFF)); + + /* Assign Linker List Item value */ + pDMAch->LLI = LinkListItem; + + /* Enable DMA channels, little endian */ + pGPDMA->CONFIG = GPDMA_DMACConfig_E; + while (!(pGPDMA->CONFIG & GPDMA_DMACConfig_E)) {} + + pDMAch->SRCADDR = GPDMAChannelConfig->SrcAddr; + pDMAch->DESTADDR = GPDMAChannelConfig->DstAddr; + + /* Configure DMA Channel, enable Error Counter and Terminate counter */ + pDMAch->CONFIG = GPDMA_DMACCxConfig_IE + | GPDMA_DMACCxConfig_ITC /*| GPDMA_DMACCxConfig_E*/ + | GPDMA_DMACCxConfig_TransferType((uint32_t) GPDMAChannelConfig->TransferType) + | GPDMA_DMACCxConfig_SrcPeripheral(SrcPeripheral) + | GPDMA_DMACCxConfig_DestPeripheral(DstPeripheral); + + pDMAch->CONTROL = CtrlWord; + + return SUCCESS; +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the GPDMA */ +void Chip_GPDMA_Init(LPC_GPDMA_T *pGPDMA) +{ + uint8_t i; + + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_GPDMA); + + /* Reset all channel configuration register */ + for (i = 8; i > 0; i--) { + pGPDMA->CH[i - 1].CONFIG = 0; + } + + /* Clear all DMA interrupt and error flag */ + pGPDMA->INTTCCLEAR = 0xFF; + pGPDMA->INTERRCLR = 0xFF; + + /* Reset all channels are free */ + for (i = 0; i < GPDMA_NUMBER_CHANNELS; i++) { + ChannelHandlerArray[i].ChannelStatus = DISABLE; + } +} + +/* Shutdown the GPDMA */ +void Chip_GPDMA_DeInit(LPC_GPDMA_T *pGPDMA) +{ + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_GPDMA); +} + +/* Stop a stream DMA transfer */ +void Chip_GPDMA_Stop(LPC_GPDMA_T *pGPDMA, + uint8_t ChannelNum) +{ + Chip_GPDMA_ChannelCmd(pGPDMA, (ChannelNum), DISABLE); + if (Chip_GPDMA_IntGetStatus(pGPDMA, GPDMA_STAT_INTTC, ChannelNum)) { + /* Clear terminate counter Interrupt pending */ + Chip_GPDMA_ClearIntPending(pGPDMA, GPDMA_STATCLR_INTTC, ChannelNum); + } + if (Chip_GPDMA_IntGetStatus(pGPDMA, GPDMA_STAT_INTERR, ChannelNum)) { + /* Clear terminate counter Interrupt pending */ + Chip_GPDMA_ClearIntPending(pGPDMA, GPDMA_STATCLR_INTERR, ChannelNum); + } + ChannelHandlerArray[ChannelNum].ChannelStatus = DISABLE; +} + +/* The GPDMA stream interrupt status checking */ +Status Chip_GPDMA_Interrupt(LPC_GPDMA_T *pGPDMA, + uint8_t ChannelNum) +{ + + if (Chip_GPDMA_IntGetStatus(pGPDMA, GPDMA_STAT_INT, ChannelNum)) { + /* Check counter terminal status */ + if (Chip_GPDMA_IntGetStatus(pGPDMA, GPDMA_STAT_INTTC, ChannelNum)) { + /* Clear terminate counter Interrupt pending */ + Chip_GPDMA_ClearIntPending(pGPDMA, GPDMA_STATCLR_INTTC, ChannelNum); + return SUCCESS; + } + /* Check error terminal status */ + if (Chip_GPDMA_IntGetStatus(pGPDMA, GPDMA_STAT_INTERR, ChannelNum)) { + /* Clear error counter Interrupt pending */ + + Chip_GPDMA_ClearIntPending(pGPDMA, GPDMA_STATCLR_INTERR, ChannelNum); + return ERROR; + } + } + return ERROR; +} + +int Chip_GPDMA_InitChannelCfg(LPC_GPDMA_T *pGPDMA, + GPDMA_CH_CFG_T *GPDMACfg, + uint8_t ChannelNum, + uint32_t src, + uint32_t dst, + uint32_t Size, + GPDMA_FLOW_CONTROL_T TransferType) +{ + int rval = -1; + GPDMACfg->ChannelNum = ChannelNum; + GPDMACfg->TransferType = TransferType; + GPDMACfg->TransferSize = Size; + + switch (TransferType) { + case GPDMA_TRANSFERTYPE_M2M_CONTROLLER_DMA: + GPDMACfg->SrcAddr = (uint32_t) src; + GPDMACfg->DstAddr = (uint32_t) dst; + rval = 3; + GPDMACfg->TransferWidth = GPDMA_WIDTH_WORD; + GPDMACfg->TransferSize = Size / 4; + break; + + case GPDMA_TRANSFERTYPE_M2P_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_M2P_CONTROLLER_PERIPHERAL: + GPDMACfg->SrcAddr = (uint32_t) src; + rval = 1; + GPDMACfg->DstAddr = (uint32_t) GPDMA_LUTPerAddr[dst]; + break; + + case GPDMA_TRANSFERTYPE_P2M_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_P2M_CONTROLLER_PERIPHERAL: + GPDMACfg->SrcAddr = (uint32_t) GPDMA_LUTPerAddr[src]; + GPDMACfg->DstAddr = (uint32_t) dst; + rval = 2; + break; + + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DestPERIPHERAL: + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_SrcPERIPHERAL: + GPDMACfg->SrcAddr = (uint32_t) GPDMA_LUTPerAddr[src]; + GPDMACfg->DstAddr = (uint32_t) GPDMA_LUTPerAddr[dst]; + rval = 0; + break; + + default: + break; + } + return rval; +} + +/* Read the status from different registers according to the type */ +IntStatus Chip_GPDMA_IntGetStatus(LPC_GPDMA_T *pGPDMA, GPDMA_STATUS_T type, uint8_t channel) +{ + /** + * TODO check the channel <=8 type is exited + */ + switch (type) { + case GPDMA_STAT_INT:/* check status of DMA channel interrupts */ + return (IntStatus) (pGPDMA->INTSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_INTTC: /* check terminal count interrupt request status for DMA */ + return (IntStatus) (pGPDMA->INTTCSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_INTERR: /* check interrupt status for DMA channels */ + return (IntStatus) (pGPDMA->INTERRSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_RAWINTTC: /* check status of the terminal count interrupt for DMA channels */ + return (IntStatus) (pGPDMA->RAWINTTCSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_RAWINTERR: /* check status of the error interrupt for DMA channels */ + return (IntStatus) (pGPDMA->RAWINTERRSTAT & (((1UL << channel) & 0xFF))); + + default:/* check enable status for DMA channels */ + return (IntStatus) (pGPDMA->ENBLDCHNS & (((1UL << channel) & 0xFF))); + } +} + +/* Clear the Interrupt Flag from different registers according to the type */ +void Chip_GPDMA_ClearIntPending(LPC_GPDMA_T *pGPDMA, GPDMA_STATECLEAR_T type, uint8_t channel) +{ + if (type == GPDMA_STATCLR_INTTC) { + /* clears the terminal count interrupt request on DMA channel */ + pGPDMA->INTTCCLEAR = (((1UL << (channel)) & 0xFF)); + } + else { + /* clear the error interrupt request */ + pGPDMA->INTERRCLR = (((1UL << (channel)) & 0xFF)); + } +} + +/* Enable or Disable the GPDMA Channel */ +void Chip_GPDMA_ChannelCmd(LPC_GPDMA_T *pGPDMA, uint8_t channelNum, FunctionalState NewState) +{ + GPDMA_CH_T *pDMAch; + + /* Get Channel pointer */ + pDMAch = (GPDMA_CH_T *) &(pGPDMA->CH[channelNum]); + + if (NewState == ENABLE) { + pDMAch->CONFIG |= GPDMA_DMACCxConfig_E; + } + else { + pDMAch->CONFIG &= ~GPDMA_DMACCxConfig_E; + } +} + +/* Do a DMA transfer M2M, M2P,P2M or P2P */ +Status Chip_GPDMA_Transfer(LPC_GPDMA_T *pGPDMA, + uint8_t ChannelNum, + uint32_t src, + uint32_t dst, + GPDMA_FLOW_CONTROL_T TransferType, + uint32_t Size) +{ + GPDMA_CH_CFG_T GPDMACfg; + uint8_t SrcPeripheral = 0, DstPeripheral = 0; + uint32_t cwrd; + int ret; + + ret = Chip_GPDMA_InitChannelCfg(pGPDMA, &GPDMACfg, ChannelNum, src, dst, Size, TransferType); + if (ret < 0) { + return ERROR; + } + + /* Adjust src/dst index if they are memory */ + if (ret & 1) { + src = 0; + } + else { + SrcPeripheral = configDMAMux(src); + } + + if (ret & 2) { + dst = 0; + } + else { + DstPeripheral = configDMAMux(dst); + } + + cwrd = makeCtrlWord(&GPDMACfg, + (uint32_t) GPDMA_LUTPerBurst[src], + (uint32_t) GPDMA_LUTPerBurst[dst], + (uint32_t) GPDMA_LUTPerWid[src], + (uint32_t) GPDMA_LUTPerWid[dst]); + if (setupChannel(pGPDMA, &GPDMACfg, cwrd, 0, SrcPeripheral, DstPeripheral) == ERROR) { + return ERROR; + } + + /* Start the Channel */ + Chip_GPDMA_ChannelCmd(pGPDMA, ChannelNum, ENABLE); + return SUCCESS; +} + +Status Chip_GPDMA_PrepareDescriptor(LPC_GPDMA_T *pGPDMA, + DMA_TransferDescriptor_t *DMADescriptor, + uint32_t src, + uint32_t dst, + uint32_t Size, + GPDMA_FLOW_CONTROL_T TransferType, + const DMA_TransferDescriptor_t *NextDescriptor) +{ + int ret; + GPDMA_CH_CFG_T GPDMACfg; + + ret = Chip_GPDMA_InitChannelCfg(pGPDMA, &GPDMACfg, 0, src, dst, Size, TransferType); + if (ret < 0) { + return ERROR; + } + + /* Adjust src/dst index if they are memory */ + if (ret & 1) { + src = 0; + } + + if (ret & 2) { + dst = 0; + } + + DMADescriptor->src = GPDMACfg.SrcAddr; + DMADescriptor->dst = GPDMACfg.DstAddr; + DMADescriptor->lli = (uint32_t) NextDescriptor; + DMADescriptor->ctrl = makeCtrlWord(&GPDMACfg, + (uint32_t) GPDMA_LUTPerBurst[src], + (uint32_t) GPDMA_LUTPerBurst[dst], + (uint32_t) GPDMA_LUTPerWid[src], + (uint32_t) GPDMA_LUTPerWid[dst]); + + /* By default set interrupt only for last transfer */ + if (NextDescriptor) { + DMADescriptor->ctrl &= ~GPDMA_DMACCxControl_I; + } + + return SUCCESS; +} + +/* Do a DMA scatter-gather transfer M2M, M2P,P2M or P2P using DMA descriptors */ +Status Chip_GPDMA_SGTransfer(LPC_GPDMA_T *pGPDMA, + uint8_t ChannelNum, + const DMA_TransferDescriptor_t *DMADescriptor, + GPDMA_FLOW_CONTROL_T TransferType) +{ + const DMA_TransferDescriptor_t *dsc = DMADescriptor; + GPDMA_CH_CFG_T GPDMACfg; + uint8_t SrcPeripheral = 0, DstPeripheral = 0; + uint32_t src = DMADescriptor->src, dst = DMADescriptor->dst; + int ret; + + ret = Chip_GPDMA_InitChannelCfg(pGPDMA, &GPDMACfg, ChannelNum, src, dst, 0, TransferType); + if (ret < 0) { + return ERROR; + } + + /* Adjust src/dst index if they are memory */ + if (ret & 1) { + src = 0; + } + else { + SrcPeripheral = configDMAMux(src); + } + + if (ret & 2) { + dst = 0; + } + else { + DstPeripheral = configDMAMux(dst); + } + + if (setupChannel(pGPDMA, &GPDMACfg, dsc->ctrl, dsc->lli, SrcPeripheral, DstPeripheral) == ERROR) { + return ERROR; + } + + /* Start the Channel */ + Chip_GPDMA_ChannelCmd(pGPDMA, ChannelNum, ENABLE); + return SUCCESS; +} + +/* Get a free GPDMA channel for one DMA connection */ +uint8_t Chip_GPDMA_GetFreeChannel(LPC_GPDMA_T *pGPDMA, + uint32_t PeripheralConnection_ID) +{ + uint8_t temp = 0; + for (temp = 0; temp < GPDMA_NUMBER_CHANNELS; temp++) { + if (!Chip_GPDMA_IntGetStatus(pGPDMA, GPDMA_STAT_ENABLED_CH, + temp) && (ChannelHandlerArray[temp].ChannelStatus == DISABLE)) { + ChannelHandlerArray[temp].ChannelStatus = ENABLE; + return temp; + } + } + return 0; +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/gpio_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/gpio_17xx_40xx.c new file mode 100644 index 000000000..a029d057b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/gpio_17xx_40xx.c @@ -0,0 +1,46 @@ +/* + * @brief LPC17xx/40xx GPIO driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/gpioint_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/gpioint_17xx_40xx.c new file mode 100644 index 000000000..58b7ccf32 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/gpioint_17xx_40xx.c @@ -0,0 +1,46 @@ +/* + * @brief LPC17xx/40xx GPIO Interrupt driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/i2c_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/i2c_17xx_40xx.c new file mode 100644 index 000000000..f1711b533 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/i2c_17xx_40xx.c @@ -0,0 +1,561 @@ +/* + * @brief LPC17xx/40xx I2C driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ +/* Control flags */ +#define I2C_CON_FLAGS (I2C_CON_AA | I2C_CON_SI | I2C_CON_STO | I2C_CON_STA) +#define LPC_I2Cx(id) ((i2c[id].ip)) +#define SLAVE_ACTIVE(iic) (((iic)->flags & 0xFF00) != 0) + +#ifdef CHIP_LPC175X_6X +static const CHIP_SYSCTL_PCLK_T I2C_PeriphClk[I2C_NUM_INTERFACE] = { + SYSCTL_PCLK_I2C0, + SYSCTL_PCLK_I2C1, + SYSCTL_PCLK_I2C2 +}; +#endif + +/* I2C common interface structure */ +struct i2c_interface { + LPC_I2C_T *ip; /* IP base address of the I2C device */ + CHIP_SYSCTL_CLOCK_T clk; /* Clock used by I2C */ + I2C_EVENTHANDLER_T mEvent; /* Current active Master event handler */ + I2C_EVENTHANDLER_T sEvent; /* Slave transfer events */ + I2C_XFER_T *mXfer; /* Current active xfer pointer */ + I2C_XFER_T *sXfer; /* Pointer to store xfer when bus is busy */ + uint32_t flags; /* Flags used by I2C master and slave */ +}; + +/* Slave interface structure */ +struct i2c_slave_interface { + I2C_XFER_T *xfer; + I2C_EVENTHANDLER_T event; +}; + +/* I2C interfaces */ +static struct i2c_interface i2c[I2C_NUM_INTERFACE] = { + {LPC_I2C0, SYSCTL_CLOCK_I2C0, Chip_I2C_EventHandler, NULL, NULL, NULL, 0}, + {LPC_I2C1, SYSCTL_CLOCK_I2C1, Chip_I2C_EventHandler, NULL, NULL, NULL, 0}, + {LPC_I2C2, SYSCTL_CLOCK_I2C2, Chip_I2C_EventHandler, NULL, NULL, NULL, 0} +}; + +static struct i2c_slave_interface i2c_slave[I2C_NUM_INTERFACE][I2C_SLAVE_NUM_INTERFACE]; + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +STATIC INLINE void enableClk(I2C_ID_T id) +{ + Chip_Clock_EnablePeriphClock(i2c[id].clk); +} + +STATIC INLINE void disableClk(I2C_ID_T id) +{ + Chip_Clock_DisablePeriphClock(i2c[id].clk); +} + +/* Get the ADC Clock Rate */ +STATIC INLINE uint32_t getClkRate(I2C_ID_T id) +{ +#if defined(CHIP_LPC175X_6X) + return Chip_Clock_GetPeripheralClockRate(I2C_PeriphClk[id]); +#else + return Chip_Clock_GetPeripheralClockRate(); +#endif +} + +/* Enable I2C and start master transfer */ +STATIC INLINE void startMasterXfer(LPC_I2C_T *pI2C) +{ + /* Reset STA, STO, SI */ + pI2C->CONCLR = I2C_CON_SI | I2C_CON_STO | I2C_CON_STA | I2C_CON_AA; + + /* Enter to Master Transmitter mode */ + pI2C->CONSET = I2C_CON_I2EN | I2C_CON_STA; +} + +/* Enable I2C and enable slave transfers */ +STATIC INLINE void startSlaverXfer(LPC_I2C_T *pI2C) +{ + /* Reset STA, STO, SI */ + pI2C->CONCLR = I2C_CON_SI | I2C_CON_STO | I2C_CON_STA; + + /* Enter to Master Transmitter mode */ + pI2C->CONSET = I2C_CON_I2EN | I2C_CON_AA; +} + +/* Check if I2C bus is free */ +STATIC INLINE int isI2CBusFree(LPC_I2C_T *pI2C) +{ + return !(pI2C->CONSET & I2C_CON_STO); +} + +/* Get current state of the I2C peripheral */ +STATIC INLINE int getCurState(LPC_I2C_T *pI2C) +{ + return (int) (pI2C->STAT & I2C_STAT_CODE_BITMASK); +} + +/* Check if the active state belongs to master mode*/ +STATIC INLINE int isMasterState(LPC_I2C_T *pI2C) +{ + return getCurState(pI2C) < 0x60; +} + +/* Set OWN slave address for specific slave ID */ +STATIC void setSlaveAddr(LPC_I2C_T *pI2C, I2C_SLAVE_ID sid, uint8_t addr, uint8_t mask) +{ + uint32_t index = (uint32_t) sid - 1; + pI2C->MASK[index] = mask; + if (sid == I2C_SLAVE_0) { + pI2C->ADR0 = addr; + } + else { + volatile uint32_t *abase = &pI2C->ADR1; + abase[index - 1] = addr; + } +} + +/* Match the slave address */ +STATIC int isSlaveAddrMatching(uint8_t addr1, uint8_t addr2, uint8_t mask) +{ + mask |= 1; + return (addr1 & ~mask) == (addr2 & ~mask); +} + +/* Get the index of the active slave */ +STATIC I2C_SLAVE_ID lookupSlaveIndex(LPC_I2C_T *pI2C, uint8_t slaveAddr) +{ + if (!(slaveAddr >> 1)) { + return I2C_SLAVE_GENERAL; /* General call address */ + } + if (isSlaveAddrMatching(pI2C->ADR0, slaveAddr, pI2C->MASK[0])) { + return I2C_SLAVE_0; + } + if (isSlaveAddrMatching(pI2C->ADR1, slaveAddr, pI2C->MASK[1])) { + return I2C_SLAVE_1; + } + if (isSlaveAddrMatching(pI2C->ADR2, slaveAddr, pI2C->MASK[2])) { + return I2C_SLAVE_2; + } + if (isSlaveAddrMatching(pI2C->ADR3, slaveAddr, pI2C->MASK[3])) { + return I2C_SLAVE_3; + } + + /* If everything is fine the code should never come here */ + return I2C_SLAVE_GENERAL; +} + +/* Master transfer state change handler handler */ +int handleMasterXferState(LPC_I2C_T *pI2C, I2C_XFER_T *xfer) +{ + uint32_t cclr = I2C_CON_FLAGS; + + switch (getCurState(pI2C)) { + case 0x08: /* Start condition on bus */ + case 0x10: /* Repeated start condition */ + pI2C->DAT = (xfer->slaveAddr << 1) | (xfer->txSz == 0); + break; + + /* Tx handling */ + case 0x18: /* SLA+W sent and ACK received */ + case 0x28: /* DATA sent and ACK received */ + if (!xfer->txSz) { + cclr &= ~(xfer->rxSz ? I2C_CON_STA : I2C_CON_STO); + } + else { + pI2C->DAT = *xfer->txBuff++; + xfer->txSz--; + } + break; + + /* Rx handling */ + case 0x58: /* Data Received and NACK sent */ + cclr &= ~I2C_CON_STO; + + case 0x50: /* Data Received and ACK sent */ + *xfer->rxBuff++ = pI2C->DAT; + xfer->rxSz--; + + case 0x40: /* SLA+R sent and ACK received */ + if (xfer->rxSz > 1) { + cclr &= ~I2C_CON_AA; + } + break; + + /* NAK Handling */ + case 0x20: /* SLA+W sent NAK received */ + case 0x30: /* DATA sent NAK received */ + case 0x48: /* SLA+R sent NAK received */ + xfer->status = I2C_STATUS_NAK; + cclr &= ~I2C_CON_STO; + break; + + case 0x38: /* Arbitration lost */ + xfer->status = I2C_STATUS_ARBLOST; + break; + + /* Bus Error */ + case 0x00: + xfer->status = I2C_STATUS_BUSERR; + cclr &= ~I2C_CON_STO; + } + + /* Set clear control flags */ + pI2C->CONSET = cclr ^ I2C_CON_FLAGS; + pI2C->CONCLR = cclr; + + /* If stopped return 0 */ + if (!(cclr & I2C_CON_STO) || (xfer->status == I2C_STATUS_ARBLOST)) { + if (xfer->status == I2C_STATUS_BUSY) { + xfer->status = I2C_STATUS_DONE; + } + return 0; + } + return 1; +} + +/* Find the slave address of SLA+W or SLA+R */ +I2C_SLAVE_ID getSlaveIndex(LPC_I2C_T *pI2C) +{ + switch (getCurState(pI2C)) { + case 0x60: + case 0x68: + case 0x70: + case 0x78: + case 0xA8: + case 0xB0: + return lookupSlaveIndex(pI2C, pI2C->DAT); + } + + /* If everything is fine code should never come here */ + return I2C_SLAVE_GENERAL; +} + +/* Slave state machine handler */ +int handleSlaveXferState(LPC_I2C_T *pI2C, I2C_XFER_T *xfer) +{ + uint32_t cclr = I2C_CON_FLAGS; + int ret = RET_SLAVE_BUSY; + + xfer->status = I2C_STATUS_BUSY; + switch (getCurState(pI2C)) { + case 0x80: /* SLA: Data received + ACK sent */ + case 0x90: /* GC: Data received + ACK sent */ + *xfer->rxBuff++ = pI2C->DAT; + xfer->rxSz--; + ret = RET_SLAVE_RX; + if (xfer->rxSz > 1) { + cclr &= ~I2C_CON_AA; + } + break; + + case 0x60: /* Own SLA+W received */ + case 0x68: /* Own SLA+W received after losing arbitration */ + case 0x70: /* GC+W received */ + case 0x78: /* GC+W received after losing arbitration */ + xfer->slaveAddr = pI2C->DAT & ~1; + if (xfer->rxSz > 1) { + cclr &= ~I2C_CON_AA; + } + break; + + case 0xA8: /* SLA+R received */ + case 0xB0: /* SLA+R received after losing arbitration */ + xfer->slaveAddr = pI2C->DAT & ~1; + + case 0xB8: /* DATA sent and ACK received */ + pI2C->DAT = *xfer->txBuff++; + xfer->txSz--; + if (xfer->txSz > 0) { + cclr &= ~I2C_CON_AA; + } + ret = RET_SLAVE_TX; + break; + + case 0xC0: /* Data transmitted and NAK received */ + case 0xC8: /* Last data transmitted and ACK received */ + case 0x88: /* SLA: Data received + NAK sent */ + case 0x98: /* GC: Data received + NAK sent */ + case 0xA0: /* STOP/Repeated START condition received */ + ret = RET_SLAVE_IDLE; + cclr &= ~I2C_CON_AA; + xfer->status = I2C_STATUS_DONE; + if (xfer->slaveAddr & 1) { + cclr &= ~I2C_CON_STA; + } + break; + } + + /* Set clear control flags */ + pI2C->CONSET = cclr ^ I2C_CON_FLAGS; + pI2C->CONCLR = cclr; + + return ret; +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ +/* Chip event handler interrupt based */ +void Chip_I2C_EventHandler(I2C_ID_T id, I2C_EVENT_T event) +{ + struct i2c_interface *iic = &i2c[id]; + volatile I2C_STATUS_T *stat; + + /* Only WAIT event needs to be handled */ + if (event != I2C_EVENT_WAIT) { + return; + } + + stat = &iic->mXfer->status; + /* Wait for the status to change */ + while (*stat == I2C_STATUS_BUSY) {} +} + +/* Chip polling event handler */ +void Chip_I2C_EventHandlerPolling(I2C_ID_T id, I2C_EVENT_T event) +{ + struct i2c_interface *iic = &i2c[id]; + volatile I2C_STATUS_T *stat; + + /* Only WAIT event needs to be handled */ + if (event != I2C_EVENT_WAIT) { + return; + } + + stat = &iic->mXfer->status; + /* Call the state change handler till xfer is done */ + while (*stat == I2C_STATUS_BUSY) { + if (Chip_I2C_IsStateChanged(id)) { + Chip_I2C_MasterStateHandler(id); + } + } +} + +/* Initializes the LPC_I2C peripheral with specified parameter */ +void Chip_I2C_Init(I2C_ID_T id) +{ + enableClk(id); + + /* Set I2C operation to default */ + LPC_I2Cx(id)->CONCLR = (I2C_CON_AA | I2C_CON_SI | I2C_CON_STA | I2C_CON_I2EN); +} + +/* De-initializes the I2C peripheral registers to their default reset values */ +void Chip_I2C_DeInit(I2C_ID_T id) +{ + /* Disable I2C control */ + LPC_I2Cx(id)->CONCLR = I2C_CON_I2EN | I2C_CON_SI | I2C_CON_STO | I2C_CON_STA | I2C_CON_AA; + + disableClk(id); +} + +/* Set up clock rate for LPC_I2C peripheral */ +void Chip_I2C_SetClockRate(I2C_ID_T id, uint32_t clockrate) +{ + uint32_t SCLValue; + + SCLValue = (getClkRate(id) / clockrate); + LPC_I2Cx(id)->SCLH = (uint32_t) (SCLValue >> 1); + LPC_I2Cx(id)->SCLL = (uint32_t) (SCLValue - LPC_I2Cx(id)->SCLH); +} + +/* Get current clock rate for LPC_I2C peripheral */ +uint32_t Chip_I2C_GetClockRate(I2C_ID_T id) +{ + return getClkRate(id) / (LPC_I2Cx(id)->SCLH + LPC_I2Cx(id)->SCLL); +} + +/* Set the master event handler */ +int Chip_I2C_SetMasterEventHandler(I2C_ID_T id, I2C_EVENTHANDLER_T event) +{ + struct i2c_interface *iic = &i2c[id]; + if (!iic->mXfer) { + iic->mEvent = event; + } + return iic->mEvent == event; +} + +/* Get the master event handler */ +I2C_EVENTHANDLER_T Chip_I2C_GetMasterEventHandler(I2C_ID_T id) +{ + return i2c[id].mEvent; +} + +/* Transmit and Receive data in master mode */ +int Chip_I2C_MasterTransfer(I2C_ID_T id, I2C_XFER_T *xfer) +{ + struct i2c_interface *iic = &i2c[id]; + + iic->mEvent(id, I2C_EVENT_LOCK); + xfer->status = I2C_STATUS_BUSY; + iic->mXfer = xfer; + + /* If slave xfer not in progress */ + if (!iic->sXfer) { + startMasterXfer(iic->ip); + } + iic->mEvent(id, I2C_EVENT_WAIT); + iic->mXfer = 0; + + /* Wait for stop condition to appear on bus */ + while (!isI2CBusFree(iic->ip)) {} + + /* Start slave if one is active */ + if (SLAVE_ACTIVE(iic)) { + startSlaverXfer(iic->ip); + } + + iic->mEvent(id, I2C_EVENT_UNLOCK); + return (int) xfer->status; +} + +/* Master tx only */ +int Chip_I2C_MasterSend(I2C_ID_T id, uint8_t slaveAddr, const uint8_t *buff, uint8_t len) +{ + I2C_XFER_T xfer = {0}; + xfer.slaveAddr = slaveAddr; + xfer.txBuff = buff; + xfer.txSz = len; + while (Chip_I2C_MasterTransfer(id, &xfer) == I2C_STATUS_ARBLOST) {} + return len - xfer.txSz; +} + +/* Transmit one byte and receive an array of bytes after a repeated start condition is generated in Master mode. + * This function is useful for communicating with the I2C slave registers + */ +int Chip_I2C_MasterCmdRead(I2C_ID_T id, uint8_t slaveAddr, uint8_t cmd, uint8_t *buff, int len) +{ + I2C_XFER_T xfer = {0}; + xfer.slaveAddr = slaveAddr; + xfer.txBuff = &cmd; + xfer.txSz = 1; + xfer.rxBuff = buff; + xfer.rxSz = len; + while (Chip_I2C_MasterTransfer(id, &xfer) == I2C_STATUS_ARBLOST) {} + return len - xfer.rxSz; +} + +/* Sequential master read */ +int Chip_I2C_MasterRead(I2C_ID_T id, uint8_t slaveAddr, uint8_t *buff, int len) +{ + I2C_XFER_T xfer = {0}; + xfer.slaveAddr = slaveAddr; + xfer.rxBuff = buff; + xfer.rxSz = len; + while (Chip_I2C_MasterTransfer(id, &xfer) == I2C_STATUS_ARBLOST) {} + return len - xfer.rxSz; +} + +/* Check if master state is active */ +int Chip_I2C_IsMasterActive(I2C_ID_T id) +{ + return isMasterState(i2c[id].ip); +} + +/* State change handler for master transfer */ +void Chip_I2C_MasterStateHandler(I2C_ID_T id) +{ + if (!handleMasterXferState(i2c[id].ip, i2c[id].mXfer)) { + i2c[id].mEvent(id, I2C_EVENT_DONE); + } +} + +/* Setup slave function */ +void Chip_I2C_SlaveSetup(I2C_ID_T id, + I2C_SLAVE_ID sid, + I2C_XFER_T *xfer, + I2C_EVENTHANDLER_T event, + uint8_t addrMask) +{ + struct i2c_interface *iic = &i2c[id]; + struct i2c_slave_interface *si2c = &i2c_slave[id][sid]; + si2c->xfer = xfer; + si2c->event = event; + + /* Set up the slave address */ + if (sid != I2C_SLAVE_GENERAL) { + setSlaveAddr(iic->ip, sid, xfer->slaveAddr, addrMask); + } + + if (!SLAVE_ACTIVE(iic) && !iic->mXfer) { + startSlaverXfer(iic->ip); + } + iic->flags |= 1 << (sid + 8); +} + +/* I2C Slave event handler */ +void Chip_I2C_SlaveStateHandler(I2C_ID_T id) +{ + int ret; + struct i2c_interface *iic = &i2c[id]; + + /* Get the currently addressed slave */ + if (!iic->sXfer) { + struct i2c_slave_interface *si2c; + + I2C_SLAVE_ID sid = getSlaveIndex(iic->ip); + si2c = &i2c_slave[id][sid]; + iic->sXfer = si2c->xfer; + iic->sEvent = si2c->event; + } + + iic->sXfer->slaveAddr |= iic->mXfer != 0; + ret = handleSlaveXferState(iic->ip, iic->sXfer); + if (ret) { + if (iic->sXfer->status == I2C_STATUS_DONE) { + iic->sXfer = 0; + } + iic->sEvent(id, (I2C_EVENT_T) ret); + } +} + +/* Disable I2C device */ +void Chip_I2C_Disable(I2C_ID_T id) +{ + LPC_I2Cx(id)->CONCLR = I2C_I2CONCLR_I2ENC; +} + +/* State change checking */ +int Chip_I2C_IsStateChanged(I2C_ID_T id) +{ + return (LPC_I2Cx(id)->CONSET & I2C_CON_SI) != 0; +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/i2s_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/i2s_17xx_40xx.c new file mode 100644 index 000000000..6cdd43676 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/i2s_17xx_40xx.c @@ -0,0 +1,260 @@ +/* + * @brief LPC17xx/40xx I2S driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/* Get divider value */ +STATIC Status getClkDiv(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format, uint16_t *pxDiv, uint16_t *pyDiv, uint32_t *pN) +{ + uint32_t pClk; + uint32_t x, y; + uint64_t divider; + uint16_t dif; + uint16_t xDiv = 0, yDiv = 0; + uint32_t N; + uint16_t err, ErrorOptimal = 0xFFFF; + +#if defined(CHIP_LPC175X_6X) + pClk = Chip_Clock_GetPeripheralClockRate(SYSCTL_PCLK_I2S); +#else + pClk = Chip_Clock_GetPeripheralClockRate(); +#endif + + /* divider is a fixed point number with 16 fractional bits */ + divider = (((uint64_t) (format->SampleRate) * 2 * (format->WordWidth) * 2) << 16) / pClk; + /* find N that make x/y <= 1 -> divider <= 2^16 */ + for (N = 64; N > 0; N--) { + if ((divider * N) < (1 << 16)) { + break; + } + } + if (N == 0) { + return ERROR; + } + divider *= N; + for (y = 255; y > 0; y--) { + x = y * divider; + if (x & (0xFF000000)) { + continue; + } + dif = x & 0xFFFF; + if (dif > 0x8000) { + err = 0x10000 - dif; + } + else { + err = dif; + } + if (err == 0) { + yDiv = y; + break; + } + else if (err < ErrorOptimal) { + ErrorOptimal = err; + yDiv = y; + } + } + xDiv = ((uint64_t) yDiv * (format->SampleRate) * 2 * (format->WordWidth) * N * 2) / pClk; + if (xDiv >= 256) { + xDiv = 0xFF; + } + if (xDiv == 0) { + xDiv = 1; + } + + *pxDiv = xDiv; + *pyDiv = yDiv; + *pN = N; + return SUCCESS; +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the I2S interface */ +void Chip_I2S_Init(LPC_I2S_T *pI2S) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_I2S); +} + +/* Shutdown I2S */ +void Chip_I2S_DeInit(LPC_I2S_T *pI2S) +{ + pI2S->DAI = 0x07E1; + pI2S->DAO = 0x87E1; + pI2S->IRQ = 0; + pI2S->TXMODE = 0; + pI2S->RXMODE = 0; + pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_1] = 0; + pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_2] = 0; + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_I2S); +} + +/* Configure I2S for Audio Format input */ +Status Chip_I2S_TxConfig(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format) +{ + uint32_t temp; + uint16_t xDiv, yDiv; + uint32_t N; + + if (getClkDiv(pI2S, format, &xDiv, &yDiv, &N) == ERROR) { + return ERROR; + } + + temp = pI2S->DAO & (~(I2S_DAO_WORDWIDTH_MASK | I2S_DAO_MONO | I2S_DAO_SLAVE | I2S_DAO_WS_HALFPERIOD_MASK)); + if (format->WordWidth <= 8) { + temp |= I2S_WORDWIDTH_8; + } + else if (format->WordWidth <= 16) { + temp |= I2S_WORDWIDTH_16; + } + else { + temp |= I2S_WORDWIDTH_32; + } + + temp |= (format->ChannelNumber) == 1 ? I2S_MONO : I2S_STEREO; + temp |= I2S_MASTER_MODE; + temp |= I2S_DAO_WS_HALFPERIOD(format->WordWidth - 1); + pI2S->DAO = temp; + pI2S->TXMODE = I2S_TXMODE_CLKSEL(0); + pI2S->TXBITRATE = N - 1; + pI2S->TXRATE = yDiv | (xDiv << 8); + return SUCCESS; +} + +/* Configure I2S for Audio Format input */ +Status Chip_I2S_RxConfig(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format) +{ + uint32_t temp; + uint16_t xDiv, yDiv; + uint32_t N; + + if (getClkDiv(pI2S, format, &xDiv, &yDiv, &N) == ERROR) { + return ERROR; + } + temp = pI2S->DAI & (~(I2S_DAI_WORDWIDTH_MASK | I2S_DAI_MONO | I2S_DAI_SLAVE | I2S_DAI_WS_HALFPERIOD_MASK)); + if (format->WordWidth <= 8) { + temp |= I2S_WORDWIDTH_8; + } + else if (format->WordWidth <= 16) { + temp |= I2S_WORDWIDTH_16; + } + else { + temp |= I2S_WORDWIDTH_32; + } + + temp |= (format->ChannelNumber) == 1 ? I2S_MONO : I2S_STEREO; + temp |= I2S_MASTER_MODE; + temp |= I2S_DAI_WS_HALFPERIOD(format->WordWidth - 1); + pI2S->DAI = temp; + pI2S->RXMODE = I2S_RXMODE_CLKSEL(0); + pI2S->RXBITRATE = N - 1; + pI2S->RXRATE = yDiv | (xDiv << 8); + return SUCCESS; +} + +/* Enable/Disable Interrupt with a specific FIFO depth */ +void Chip_I2S_Int_TxCmd(LPC_I2S_T *pI2S, FunctionalState newState, uint8_t depth) +{ + uint32_t temp; + depth &= 0x0F; + if (newState == ENABLE) { + pI2S->IRQ |= 0x02; + } + else { + pI2S->IRQ &= (~0x02); + } + temp = pI2S->IRQ & (~I2S_IRQ_TX_DEPTH_MASK); + pI2S->IRQ = temp | (I2S_IRQ_TX_DEPTH(depth)); +} + +/* Enable/Disable Interrupt with a specific FIFO depth */ +void Chip_I2S_Int_RxCmd(LPC_I2S_T *pI2S, FunctionalState newState, uint8_t depth) +{ + uint32_t temp; + depth &= 0x0F; + if (newState == ENABLE) { + pI2S->IRQ |= 0x01; + } + else { + pI2S->IRQ &= (~0x01); + } + temp = pI2S->IRQ & (~I2S_IRQ_RX_DEPTH_MASK); + pI2S->IRQ = temp | (I2S_IRQ_RX_DEPTH(depth)); +} + +/* Enable/Disable DMA with a specific FIFO depth */ +void Chip_I2S_DMA_TxCmd(LPC_I2S_T *pI2S, + I2S_DMA_CHANNEL_T dmaNum, + FunctionalState newState, + uint8_t depth) +{ + /* Set FIFO Level */ + pI2S->DMA[dmaNum] &= ~(0x0F << 16); + pI2S->DMA[dmaNum] |= depth << 16; + /* Enable/Disable I2S transmit*/ + if (newState == ENABLE) { + pI2S->DMA[dmaNum] |= 0x02; + } + else { + pI2S->DMA[dmaNum] &= ~0x02; + } +} + +/* Enable/Disable DMA with a specific FIFO depth */ +void Chip_I2S_DMA_RxCmd(LPC_I2S_T *pI2S, + I2S_DMA_CHANNEL_T dmaNum, + FunctionalState newState, + uint8_t depth) +{ + /* Set FIFO Level */ + pI2S->DMA[dmaNum] &= ~(0x0F << 8); + pI2S->DMA[dmaNum] |= depth << 8; + /* Enable/Disable I2S Receive */ + if (newState == ENABLE) { + pI2S->DMA[dmaNum] |= 0x01; + } + else { + pI2S->DMA[dmaNum] &= ~0x01; + } +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/iap.c b/hw/mcu/nxp/lpc_chip_40xx/src/iap.c new file mode 100644 index 000000000..76f72a2f5 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/iap.c @@ -0,0 +1,175 @@ +/* + * @brief Common FLASH support functions + * + * @note + * Copyright(C) NXP Semiconductors, 2013 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Prepare sector for write operation */ +uint8_t Chip_IAP_PreSectorForReadWrite(uint32_t strSector, uint32_t endSector) +{ + uint32_t command[5], result[4]; + + command[0] = IAP_PREWRRITE_CMD; + command[1] = strSector; + command[2] = endSector; + iap_entry(command, result); + + return result[0]; +} + +/* Copy RAM to flash */ +uint8_t Chip_IAP_CopyRamToFlash(uint32_t dstAdd, uint32_t *srcAdd, uint32_t byteswrt) +{ + uint32_t command[5], result[4]; + + command[0] = IAP_WRISECTOR_CMD; + command[1] = dstAdd; + command[2] = (uint32_t) srcAdd; + command[3] = byteswrt; + command[4] = SystemCoreClock / 1000; + iap_entry(command, result); + + return result[0]; +} + +/* Erase sector */ +uint8_t Chip_IAP_EraseSector(uint32_t strSector, uint32_t endSector) +{ + uint32_t command[5], result[4]; + + command[0] = IAP_ERSSECTOR_CMD; + command[1] = strSector; + command[2] = endSector; + command[3] = SystemCoreClock / 1000; + iap_entry(command, result); + + return result[0]; +} + +/* Blank check sector */ +uint8_t Chip_IAP_BlankCheckSector(uint32_t strSector, uint32_t endSector) +{ + uint32_t command[5], result[4]; + + command[0] = IAP_BLANK_CHECK_SECTOR_CMD; + command[1] = strSector; + command[2] = endSector; + iap_entry(command, result); + + return result[0]; +} + +/* Read part identification number */ +uint32_t Chip_IAP_ReadPID() +{ + uint32_t command[5], result[4]; + + command[0] = IAP_REPID_CMD; + iap_entry(command, result); + + return result[1]; +} + +/* Read boot code version number */ +uint8_t Chip_IAP_ReadBootCode() +{ + uint32_t command[5], result[4]; + + command[0] = IAP_READ_BOOT_CODE_CMD; + iap_entry(command, result); + + return result[0]; +} + +/* IAP compare */ +uint8_t Chip_IAP_Compare(uint32_t dstAdd, uint32_t srcAdd, uint32_t bytescmp) +{ + uint32_t command[5], result[4]; + + command[0] = IAP_COMPARE_CMD; + command[1] = dstAdd; + command[2] = srcAdd; + command[3] = bytescmp; + iap_entry(command, result); + + return result[0]; +} + +/* Reinvoke ISP */ +uint8_t Chip_IAP_ReinvokeISP() +{ + uint32_t command[5], result[4]; + + command[0] = IAP_REINVOKE_ISP_CMD; + iap_entry(command, result); + + return result[0]; +} + +/* Read the unique ID */ +uint32_t Chip_IAP_ReadUID() +{ + uint32_t command[5], result[4]; + + command[0] = IAP_READ_UID_CMD; + iap_entry(command, result); + + return result[1]; +} + +/* Erase page */ +uint8_t Chip_IAP_ErasePage(uint32_t strPage, uint32_t endPage) +{ + uint32_t command[5], result[4]; + + command[0] = IAP_ERASE_PAGE_CMD; + command[1] = strPage; + command[2] = endPage; + command[3] = SystemCoreClock / 1000; + iap_entry(command, result); + + return result[0]; +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/iocon_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/iocon_17xx_40xx.c new file mode 100644 index 000000000..0e00a5b8e --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/iocon_17xx_40xx.c @@ -0,0 +1,83 @@ +/* + * @brief LPC17xx/40xx IOCON driver + * + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +#if defined(CHIP_LPC175X_6X) +/* Sets I/O Control pin mux */ +void Chip_IOCON_PinMuxSet(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t modefunc) +{ + Chip_IOCON_PinMux(pIOCON, port, pin, + /* mode is in bits 3:2 */ + modefunc >> 2, + /* func is in bits 1:0 */ + modefunc & 3 ); +} + +/* Setup pin modes and function */ +void Chip_IOCON_PinMux(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t mode, uint8_t func) +{ + uint8_t reg, bitPos; + uint32_t temp; + + bitPos = IOCON_BIT_INDEX(pin); + reg = IOCON_REG_INDEX(port,pin); + + temp = pIOCON->PINSEL[reg] & ~(0x03UL << bitPos); + pIOCON->PINSEL[reg] = temp | (func << bitPos); + + temp = pIOCON->PINMODE[reg] & ~(0x03UL << bitPos); + pIOCON->PINMODE[reg] = temp | (mode << bitPos); +} +#endif /* defined(CHIP_LPC175X_6X) */ + +/* Set all I/O Control pin muxing */ +void Chip_IOCON_SetPinMuxing(LPC_IOCON_T *pIOCON, const PINMUX_GRP_T* pinArray, uint32_t arrayLength) +{ + uint32_t ix; + + for (ix = 0; ix < arrayLength; ix++ ) { + Chip_IOCON_PinMuxSet(pIOCON, pinArray[ix].pingrp, pinArray[ix].pinnum, pinArray[ix].modefunc); + } +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/lcd_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/lcd_17xx_40xx.c new file mode 100644 index 000000000..c89ead222 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/lcd_17xx_40xx.c @@ -0,0 +1,210 @@ +/* + * @brief LCD chip driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +static LCD_CURSOR_SIZE_OPT_T LCD_Cursor_Size = LCD_CURSOR_64x64; + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the LCD controller */ +void Chip_LCD_Init(LPC_LCD_T *pLCD, LCD_CONFIG_T *LCD_ConfigStruct) +{ + uint32_t i, regValue, *pPal; + uint32_t pcd; + + /* Enable LCD Clock */ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_LCD); + + /* disable the display */ + pLCD->CTRL &= ~CLCDC_LCDCTRL_ENABLE; + + /* Setting LCD_TIMH register */ + regValue = ( ((((LCD_ConfigStruct->PPL / 16) - 1) & 0x3F) << 2) + | (( (LCD_ConfigStruct->HSW - 1) & 0xFF) << 8) + | (( (LCD_ConfigStruct->HFP - 1) & 0xFF) << 16) + | (( (LCD_ConfigStruct->HBP - 1) & 0xFF) << 24) ); + pLCD->TIMH = regValue; + + /* Setting LCD_TIMV register */ + regValue = ((((LCD_ConfigStruct->LPP - 1) & 0x3FF) << 0) + | (((LCD_ConfigStruct->VSW - 1) & 0x03F) << 10) + | (((LCD_ConfigStruct->VFP - 1) & 0x0FF) << 16) + | (((LCD_ConfigStruct->VBP - 1) & 0x0FF) << 24) ); + pLCD->TIMV = regValue; + + /* Generate the clock and signal polarity control word */ + regValue = 0; + regValue = (((LCD_ConfigStruct->ACB - 1) & 0x1F) << 6); + regValue |= (LCD_ConfigStruct->IOE & 1) << 14; + regValue |= (LCD_ConfigStruct->IPC & 1) << 13; + regValue |= (LCD_ConfigStruct->IHS & 1) << 12; + regValue |= (LCD_ConfigStruct->IVS & 1) << 11; + + /* Compute clocks per line based on panel type */ + switch (LCD_ConfigStruct->LCD) { + case LCD_MONO_4: + regValue |= ((((LCD_ConfigStruct->PPL / 4) - 1) & 0x3FF) << 16); + break; + + case LCD_MONO_8: + regValue |= ((((LCD_ConfigStruct->PPL / 8) - 1) & 0x3FF) << 16); + break; + + case LCD_CSTN: + regValue |= (((((LCD_ConfigStruct->PPL * 3) / 8) - 1) & 0x3FF) << 16); + break; + + case LCD_TFT: + default: + regValue |= /*1<<26 |*/ (((LCD_ConfigStruct->PPL - 1) & 0x3FF) << 16); + } + + /* panel clock divisor */ + pcd = 5;// LCD_ConfigStruct->pcd; /* TODO: should be calculated from LCDDCLK */ + pcd &= 0x3FF; + regValue |= ((pcd >> 5) << 27) | ((pcd) & 0x1F); + pLCD->POL = regValue; + + /* disable interrupts */ + pLCD->INTMSK = 0; + + /* set bits per pixel */ + regValue = LCD_ConfigStruct->BPP << 1; + + /* set color format RGB */ + regValue |= LCD_ConfigStruct->color_format << 8; + regValue |= LCD_ConfigStruct->LCD << 4; + if (LCD_ConfigStruct->Dual == 1) { + regValue |= 1 << 7; + } + pLCD->CTRL = regValue; + + /* clear palette */ + pPal = (uint32_t *) (&(pLCD->PAL)); + for (i = 0; i < 128; i++) { + *pPal = 0; + pPal++; + } +} + +/* Shutdown the LCD controller */ +void Chip_LCD_DeInit(LPC_LCD_T *pLCD) +{ + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_LCD); +} + +/* Configure Cursor */ +void Chip_LCD_Cursor_Config(LPC_LCD_T *pLCD, LCD_CURSOR_SIZE_OPT_T cursor_size, bool sync) +{ + LCD_Cursor_Size = cursor_size; + pLCD->CRSR_CFG = ((sync ? 1 : 0) << 1) | cursor_size; +} + +/* Write Cursor Image into Internal Cursor Image Buffer */ +void Chip_LCD_Cursor_WriteImage(LPC_LCD_T *pLCD, uint8_t cursor_num, void *Image) +{ + int i, j; + uint32_t *fifoptr, *crsr_ptr = (uint32_t *) Image; + + /* Check if Cursor Size was configured as 32x32 or 64x64*/ + if (LCD_Cursor_Size == LCD_CURSOR_32x32) { + i = cursor_num * 64; + j = i + 64; + } + else { + i = 0; + j = 256; + } + fifoptr = (void *) &(pLCD->CRSR_IMG[0]); + + /* Copy Cursor Image content to FIFO */ + for (; i < j; i++) { + + *fifoptr = *crsr_ptr; + crsr_ptr++; + fifoptr++; + } +} + +/* Load LCD Palette */ +void Chip_LCD_LoadPalette(LPC_LCD_T *pLCD, void *palette) +{ + LCD_PALETTE_ENTRY_T pal_entry, *ptr_pal_entry; + uint8_t i, *pal_ptr; + /* This function supports loading of the color palette from + the C file generated by the bmp2c utility. It expects the + palette to be passed as an array of 32-bit BGR entries having + the following format: + 2:0 - Not used + 7:3 - Blue + 10:8 - Not used + 15:11 - Green + 18:16 - Not used + 23:19 - Red + 31:24 - Not used + arg = pointer to input palette table address */ + ptr_pal_entry = &pal_entry; + pal_ptr = (uint8_t *) palette; + + /* 256 entry in the palette table */ + for (i = 0; i < 256 / 2; i++) { + pal_entry.Bl = (*pal_ptr++) >> 3; /* blue first */ + pal_entry.Gl = (*pal_ptr++) >> 3; /* get green */ + pal_entry.Rl = (*pal_ptr++) >> 3; /* get red */ + pal_ptr++; /* skip over the unused byte */ + /* do the most significant halfword of the palette */ + pal_entry.Bu = (*pal_ptr++) >> 3; /* blue first */ + pal_entry.Gu = (*pal_ptr++) >> 3; /* get green */ + pal_entry.Ru = (*pal_ptr++) >> 3; /* get red */ + pal_ptr++; /* skip over the unused byte */ + + pLCD->PAL[i] = *((uint32_t *) ptr_pal_entry); + } +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/pmu_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/pmu_17xx_40xx.c new file mode 100644 index 000000000..8b5a841ad --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/pmu_17xx_40xx.c @@ -0,0 +1,118 @@ +/* + * @brief LPC15xx PMU chip driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Enter MCU Sleep mode */ +void Chip_PMU_SleepState(LPC_PMU_T *pPMU) +{ + /* Select Sleep/Deep Sleep mode */ + pPMU->PCON &= ~(PMU_PCON_PM1_FLAG | PMU_PCON_PM0_FLAG); + + /* Clearing SLEEPDEEP bit in SCR makes it Sleep mode */ + SCB->SCR &= ~(1UL << SCB_SCR_SLEEPDEEP_Pos); + + /* Enter sleep mode */ + __WFI(); +} + +/* Enter MCU Deep Sleep mode */ +void Chip_PMU_DeepSleepState(LPC_PMU_T *pPMU) +{ + /* Select Sleep/Deep Sleep mode */ + pPMU->PCON &= ~(PMU_PCON_PM1_FLAG | PMU_PCON_PM0_FLAG); + + /* Setting SLEEPDEEP bit in SCR makes it Deep Sleep mode */ + SCB->SCR |= (1UL << SCB_SCR_SLEEPDEEP_Pos); + + /* Enter sleep mode */ + __WFI(); +} + +/* Enter MCU Power down mode */ +void Chip_PMU_PowerDownState(LPC_PMU_T *pPMU) +{ + /* Select power down mode */ + pPMU->PCON = (pPMU->PCON & ~PMU_PCON_PM1_FLAG) | PMU_PCON_PM0_FLAG; + + /* Setting SLEEPDEEP bit in SCR makes it power down mode */ + SCB->SCR |= (1UL << SCB_SCR_SLEEPDEEP_Pos); + + /* Enter sleep mode */ + __WFI(); +} + +/* Enter MCU Deep Power down mode */ +void Chip_PMU_DeepPowerDownState(LPC_PMU_T *pPMU) +{ + /* Select deep power down mode */ + pPMU->PCON |= PMU_PCON_PM1_FLAG | PMU_PCON_PM0_FLAG; + + /* Setting SLEEPDEEP bit in SCR makes it deep power down mode */ + SCB->SCR |= (1UL << SCB_SCR_SLEEPDEEP_Pos); + + /* Enter sleep mode */ + __WFI(); +} + +/* Put some of the peripheral in sleep mode */ +void Chip_PMU_Sleep(LPC_PMU_T *pPMU, CHIP_PMU_MCUPOWER_T SleepMode) +{ + if (SleepMode == PMU_MCU_DEEP_SLEEP) { + Chip_PMU_DeepSleepState(pPMU); + } + else if (SleepMode == PMU_MCU_POWER_DOWN) { + Chip_PMU_PowerDownState(pPMU); + } + else if (SleepMode == PMU_MCU_DEEP_PWRDOWN) { + Chip_PMU_DeepPowerDownState(pPMU); + } + else { + /* PMU_MCU_SLEEP */ + Chip_PMU_SleepState(pPMU); + } +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/ring_buffer.c b/hw/mcu/nxp/lpc_chip_40xx/src/ring_buffer.c new file mode 100644 index 000000000..47a0c34f9 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/ring_buffer.c @@ -0,0 +1,167 @@ +/* + * @brief Common ring buffer support functions + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include +#include "ring_buffer.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +#define RB_INDH(rb) ((rb)->head & ((rb)->count - 1)) +#define RB_INDT(rb) ((rb)->tail & ((rb)->count - 1)) + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize ring buffer */ +int RingBuffer_Init(RINGBUFF_T *RingBuff, void *buffer, int itemSize, int count) +{ + RingBuff->data = buffer; + RingBuff->count = count; + RingBuff->itemSz = itemSize; + RingBuff->head = RingBuff->tail = 0; + + return 1; +} + +/* Insert a single item into Ring Buffer */ +int RingBuffer_Insert(RINGBUFF_T *RingBuff, const void *data) +{ + uint8_t *ptr = RingBuff->data; + + /* We cannot insert when queue is full */ + if (RingBuffer_IsFull(RingBuff)) + return 0; + + ptr += RB_INDH(RingBuff) * RingBuff->itemSz; + memcpy(ptr, data, RingBuff->itemSz); + RingBuff->head++; + + return 1; +} + +/* Insert multiple items into Ring Buffer */ +int RingBuffer_InsertMult(RINGBUFF_T *RingBuff, const void *data, int num) +{ + uint8_t *ptr = RingBuff->data; + int cnt1, cnt2; + + /* We cannot insert when queue is full */ + if (RingBuffer_IsFull(RingBuff)) + return 0; + + /* Calculate the segment lengths */ + cnt1 = cnt2 = RingBuffer_GetFree(RingBuff); + if (RB_INDH(RingBuff) + cnt1 >= RingBuff->count) + cnt1 = RingBuff->count - RB_INDH(RingBuff); + cnt2 -= cnt1; + + cnt1 = MIN(cnt1, num); + num -= cnt1; + + cnt2 = MIN(cnt2, num); + num -= cnt2; + + /* Write segment 1 */ + ptr += RB_INDH(RingBuff) * RingBuff->itemSz; + memcpy(ptr, data, cnt1 * RingBuff->itemSz); + RingBuff->head += cnt1; + + /* Write segment 2 */ + ptr = (uint8_t *) RingBuff->data + RB_INDH(RingBuff) * RingBuff->itemSz; + data = (const uint8_t *) data + cnt1 * RingBuff->itemSz; + memcpy(ptr, data, cnt2 * RingBuff->itemSz); + RingBuff->head += cnt2; + + return cnt1 + cnt2; +} + +/* Pop single item from Ring Buffer */ +int RingBuffer_Pop(RINGBUFF_T *RingBuff, void *data) +{ + uint8_t *ptr = RingBuff->data; + + /* We cannot pop when queue is empty */ + if (RingBuffer_IsEmpty(RingBuff)) + return 0; + + ptr += RB_INDT(RingBuff) * RingBuff->itemSz; + memcpy(data, ptr, RingBuff->itemSz); + RingBuff->tail++; + + return 1; +} + +/* Pop multiple items from Ring buffer */ +int RingBuffer_PopMult(RINGBUFF_T *RingBuff, void *data, int num) +{ + uint8_t *ptr = RingBuff->data; + int cnt1, cnt2; + + /* We cannot insert when queue is empty */ + if (RingBuffer_IsEmpty(RingBuff)) + return 0; + + /* Calculate the segment lengths */ + cnt1 = cnt2 = RingBuffer_GetCount(RingBuff); + if (RB_INDT(RingBuff) + cnt1 >= RingBuff->count) + cnt1 = RingBuff->count - RB_INDT(RingBuff); + cnt2 -= cnt1; + + cnt1 = MIN(cnt1, num); + num -= cnt1; + + cnt2 = MIN(cnt2, num); + num -= cnt2; + + /* Write segment 1 */ + ptr += RB_INDT(RingBuff) * RingBuff->itemSz; + memcpy(data, ptr, cnt1 * RingBuff->itemSz); + RingBuff->tail += cnt1; + + /* Write segment 2 */ + ptr = (uint8_t *) RingBuff->data + RB_INDT(RingBuff) * RingBuff->itemSz; + data = (uint8_t *) data + cnt1 * RingBuff->itemSz; + memcpy(data, ptr, cnt2 * RingBuff->itemSz); + RingBuff->tail += cnt2; + + return cnt1 + cnt2; +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/ritimer_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/ritimer_17xx_40xx.c new file mode 100644 index 000000000..a94e6175c --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/ritimer_17xx_40xx.c @@ -0,0 +1,100 @@ +/* + * @brief LPC17xx/40xx RITimer driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC175X_6X) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the RIT */ +void Chip_RIT_Init(LPC_RITIMER_T *pRITimer) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_RIT); + pRITimer->COMPVAL = 0xFFFFFFFF; + pRITimer->MASK = 0x00000000; + pRITimer->CTRL = 0x0C; + pRITimer->COUNTER = 0x00000000; +} + +/* DeInitialize the RIT */ +void Chip_RIT_DeInit(LPC_RITIMER_T *pRITimer) +{ + Chip_RIT_Init(pRITimer); + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_RIT); +} + +/* Set timer interval value */ +void Chip_RIT_SetTimerInterval(LPC_RITIMER_T *pRITimer, uint32_t time_interval) +{ + uint32_t cmp_value; + + /* Determine aapproximate compare value based on clock rate and passed interval */ + cmp_value = (Chip_Clock_GetPeripheralClockRate(SYSCTL_PCLK_RIT) / 1000) * time_interval; + + /* Set timer compare value */ + Chip_RIT_SetCOMPVAL(pRITimer, cmp_value); + + /* Set timer enable clear bit to clear timer to 0 whenever + counter value equals the contents of RICOMPVAL */ + Chip_RIT_EnableCTRL(pRITimer, RIT_CTRL_ENCLR); +} + +/* Check whether interrupt is pending */ +IntStatus Chip_RIT_GetIntStatus(LPC_RITIMER_T *pRITimer) +{ + uint8_t result; + + if ((pRITimer->CTRL & RIT_CTRL_INT) == 1) { + result = SET; + } + else { + return RESET; + } + + return (IntStatus) result; +} + +#endif /* defined(CHIP_LPC175X_6X) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/rtc_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/rtc_17xx_40xx.c new file mode 100644 index 000000000..3ad88c28d --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/rtc_17xx_40xx.c @@ -0,0 +1,221 @@ +/* + * @brief LPC17xx/40xx RTC chip driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the RTC peripheral */ +void Chip_RTC_Init(LPC_RTC_T *pRTC) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_RTC); + + /* Disable RTC */ + Chip_RTC_Enable(pRTC, DISABLE); + + /* Disable Calibration */ + Chip_RTC_CalibCounterCmd(pRTC, DISABLE); + + /* Reset RTC Clock */ + Chip_RTC_ResetClockTickCounter(pRTC); + + /* Clear counter increment and alarm interrupt */ + pRTC->ILR = RTC_IRL_RTCCIF | RTC_IRL_RTCALF; + while (pRTC->ILR != 0) {} + + /* Clear all register to be default */ + pRTC->CIIR = 0x00; + pRTC->AMR = 0xFF; + pRTC->CALIBRATION = 0x00; +} + +/*De-initialize the RTC peripheral */ +void Chip_RTC_DeInit(LPC_RTC_T *pRTC) +{ + pRTC->CCR = 0x00; + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_RTC); +} + +/* Reset clock tick counter in the RTC peripheral */ +void Chip_RTC_ResetClockTickCounter(LPC_RTC_T *pRTC) +{ + do { + /* Reset RTC clock*/ + pRTC->CCR |= RTC_CCR_CTCRST; + } while ((pRTC->CCR & RTC_CCR_CTCRST) != RTC_CCR_CTCRST); + + do { + /* Finish resetting RTC clock */ + pRTC->CCR &= (~RTC_CCR_CTCRST) & RTC_CCR_BITMASK; + } while (pRTC->CCR & RTC_CCR_CTCRST); +} + +/* Start/Stop RTC peripheral */ +void Chip_RTC_Enable(LPC_RTC_T *pRTC, FunctionalState NewState) +{ + if (NewState == ENABLE) { + do { + pRTC->CCR |= RTC_CCR_CLKEN; + } while ((pRTC->CCR & RTC_CCR_CLKEN) == 0); + } + else { + pRTC->CCR &= (~RTC_CCR_CLKEN) & RTC_CCR_BITMASK; + } +} + +/* Enable/Disable Counter increment interrupt for a time type in the RTC peripheral */ +void Chip_RTC_CntIncrIntConfig(LPC_RTC_T *pRTC, uint32_t cntrMask, FunctionalState NewState) +{ + if (NewState == ENABLE) { + pRTC->CIIR |= cntrMask; + } + + else { + pRTC->CIIR &= (~cntrMask) & RTC_AMR_CIIR_BITMASK; + while (pRTC->CIIR & cntrMask) {} + } +} + +/* Enable/Disable Alarm interrupt for a time type in the RTC peripheral */ +void Chip_RTC_AlarmIntConfig(LPC_RTC_T *pRTC, uint32_t alarmMask, FunctionalState NewState) +{ + if (NewState == ENABLE) { + pRTC->AMR &= (~alarmMask) & RTC_AMR_CIIR_BITMASK; + } + else { + pRTC->AMR |= (alarmMask); + while ((pRTC->AMR & alarmMask) == 0) {} + } +} + +/* Set full time in the RTC peripheral */ +void Chip_RTC_SetFullTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime) +{ + RTC_TIMEINDEX_T i; + uint32_t ccr_val = pRTC->CCR; + + /* Temporarily disable */ + if (ccr_val & RTC_CCR_CLKEN) { + pRTC->CCR = ccr_val & (~RTC_CCR_CLKEN) & RTC_CCR_BITMASK; + } + + /* Date time setting */ + for (i = RTC_TIMETYPE_SECOND; i < RTC_TIMETYPE_LAST; i++) { + pRTC->TIME[i] = pFullTime->time[i]; + } + + /* Restore to old setting */ + pRTC->CCR = ccr_val; +} + +/* Get full time from the RTC peripheral */ +void Chip_RTC_GetFullTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime) +{ + RTC_TIMEINDEX_T i; + uint32_t secs = 0xFF; + + /* Read full time, but verify second tick didn't change during the read. If + it did, re-read the time again so it will be consistent across all fields. */ + while (secs != pRTC->TIME[RTC_TIMETYPE_SECOND]) { + secs = pFullTime->time[RTC_TIMETYPE_SECOND] = pRTC->TIME[RTC_TIMETYPE_SECOND]; + for (i = RTC_TIMETYPE_MINUTE; i < RTC_TIMETYPE_LAST; i++) { + pFullTime->time[i] = pRTC->TIME[i]; + } + } +} + +/* Set full alarm time in the RTC peripheral */ +void Chip_RTC_SetFullAlarmTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime) +{ + RTC_TIMEINDEX_T i; + + for (i = RTC_TIMETYPE_SECOND; i < RTC_TIMETYPE_LAST; i++) { + pRTC->ALRM[i] = pFullTime->time[i]; + } +} + +/* Get full alarm time in the RTC peripheral */ +void Chip_RTC_GetFullAlarmTime(LPC_RTC_T *pRTC, RTC_TIME_T *pFullTime) +{ + RTC_TIMEINDEX_T i; + + for (i = RTC_TIMETYPE_SECOND; i < RTC_TIMETYPE_LAST; i++) { + pFullTime->time[i] = pRTC->ALRM[i]; + } +} + +/* Enable/Disable calibration counter in the RTC peripheral */ +void Chip_RTC_CalibCounterCmd(LPC_RTC_T *pRTC, FunctionalState NewState) +{ + if (NewState == ENABLE) { + do { + pRTC->CCR &= (~RTC_CCR_CCALEN) & RTC_CCR_BITMASK; + } while (pRTC->CCR & RTC_CCR_CCALEN); + } + else { + pRTC->CCR |= RTC_CCR_CCALEN; + } +} + +#if RTC_EV_SUPPORT +/* Get first timestamp value */ +void Chip_RTC_EV_GetFirstTimeStamp(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch, RTC_EV_TIMESTAMP_T *pTimeStamp) +{ + pTimeStamp->sec = RTC_ER_TIMESTAMP_SEC(pRTC->ERFIRSTSTAMP[ch]); + pTimeStamp->min = RTC_ER_TIMESTAMP_MIN(pRTC->ERFIRSTSTAMP[ch]); + pTimeStamp->hour = RTC_ER_TIMESTAMP_HOUR(pRTC->ERFIRSTSTAMP[ch]); + pTimeStamp->dayofyear = RTC_ER_TIMESTAMP_DOY(pRTC->ERFIRSTSTAMP[ch]); +} + +/* Get last timestamp value */ +void Chip_RTC_EV_GetLastTimeStamp(LPC_RTC_T *pRTC, RTC_EV_CHANNEL_T ch, RTC_EV_TIMESTAMP_T *pTimeStamp) +{ + pTimeStamp->sec = RTC_ER_TIMESTAMP_SEC(pRTC->ERLASTSTAMP[ch]); + pTimeStamp->min = RTC_ER_TIMESTAMP_MIN(pRTC->ERLASTSTAMP[ch]); + pTimeStamp->hour = RTC_ER_TIMESTAMP_HOUR(pRTC->ERLASTSTAMP[ch]); + pTimeStamp->dayofyear = RTC_ER_TIMESTAMP_DOY(pRTC->ERLASTSTAMP[ch]); +} + +#endif /*RTC_EV_SUPPORT*/ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/sdc_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/sdc_17xx_40xx.c new file mode 100644 index 000000000..61ca5be39 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/sdc_17xx_40xx.c @@ -0,0 +1,247 @@ +/* + * @brief SD Card Interface registers and control functions + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +static void writeDelay(void) +{ + volatile uint8_t i; + for ( i = 0; i < 0x10; i++ ) { /* delay 3MCLK + 2PCLK */ + } +} + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Set power state of SDC peripheral */ +void Chip_SDC_PowerControl(LPC_SDC_T *pSDC, SDC_PWR_CTRL_T pwrMode, uint32_t flag) +{ + pSDC->POWER = SDC_PWR_CTRL(pwrMode) | flag; + writeDelay(); +} + +/* Set clock divider for SDC peripheral */ +void Chip_SDC_SetClockDiv(LPC_SDC_T *pSDC, uint8_t div) +{ + uint32_t temp; + temp = (pSDC->CLOCK & (~SDC_CLOCK_CLKDIV_BITMASK)); + pSDC->CLOCK = temp | (SDC_CLOCK_CLKDIV(div)); + writeDelay(); +} + +/* Clock control for SDC peripheral*/ +void Chip_SDC_ClockControl(LPC_SDC_T *pSDC, SDC_CLOCK_CTRL_T ctrlType, + FunctionalState NewState) +{ + if (NewState) { + pSDC->CLOCK |= (1 << ctrlType); + } + else { + pSDC->CLOCK &= (~(1 << ctrlType)); + } + writeDelay(); +} + +/* Initialize SDC peripheral */ +static void SDC_Init(LPC_SDC_T *pSDC) +{ + /* Disable SD_CLK */ + Chip_SDC_ClockControl(pSDC, SDC_CLOCK_ENABLE, DISABLE); + + /* Power-off */ + Chip_SDC_PowerControl(pSDC, SDC_POWER_OFF, 0); + writeDelay(); + + /* Disable all interrupts */ + pSDC->MASK0 = 0; + + /*Setting for timeout problem */ + pSDC->DATATIMER = 0x1FFFFFFF; + + pSDC->COMMAND = 0; + writeDelay(); + + pSDC->DATACTRL = 0; + writeDelay(); + + /* clear all pending interrupts */ + pSDC->CLEAR = SDC_CLEAR_ALL; +} + +/* Initializes the SDC card controller */ +void Chip_SDC_Init(LPC_SDC_T *pSDC) +{ + uint32_t i = 0; + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_SDC); + Chip_SYSCTL_PeriphReset(SYSCTL_RESET_PCSDC); + + /* Initialize GPDMA controller */ + Chip_GPDMA_Init(LPC_GPDMA); + + /* Initialize SDC peripheral */ + SDC_Init(pSDC); + + /* Power-up SDC Peripheral */ + Chip_SDC_PowerControl(pSDC, SDC_POWER_UP, 0); + + /* delays for the supply output is stable*/ + for ( i = 0; i < 0x80000; i++ ) {} + + Chip_SDC_SetClock(pSDC, SDC_IDENT_CLOCK_RATE); + Chip_SDC_ClockControl(pSDC, SDC_CLOCK_ENABLE, ENABLE); + + /* Power-on SDC Interface */ + Chip_SDC_PowerControl(pSDC, SDC_POWER_ON, 0); + +} + +/* Set Command Info */ +void Chip_SDC_SetCommand(LPC_SDC_T *pSDC, uint32_t Cmd, uint32_t Arg) +{ + /* Clear status register */ + pSDC->CLEAR = SDC_CLEAR_ALL; + + /* Set the argument first, finally command */ + pSDC->ARGUMENT = Arg; + + /* Write command value, enable the command */ + pSDC->COMMAND = Cmd | SDC_COMMAND_ENABLE; + + writeDelay(); +} + +/* Reset Command Info */ +void Chip_SDC_ResetCommand(LPC_SDC_T *pSDC) +{ + pSDC->CLEAR = SDC_CLEAR_ALL; + + pSDC->ARGUMENT = 0xFFFFFFFF; + + pSDC->COMMAND = 0; + + writeDelay(); +} + +/* Get Command response */ +void Chip_SDC_GetResp(LPC_SDC_T *pSDC, SDC_RESP_T *pResp) +{ + uint8_t i; + pResp->CmdIndex = SDC_RESPCOMMAND_VAL(pSDC->RESPCMD); + for (i = 0; i < SDC_CARDSTATUS_BYTENUM; i++) { + pResp->Data[i] = pSDC->RESPONSE[i]; + } +} + +/* Setup Data Transfer Information */ +void Chip_SDC_SetDataTransfer(LPC_SDC_T *pSDC, SDC_DATA_TRANSFER_T *pTransfer) +{ + uint32_t DataCtrl = 0; + pSDC->DATATIMER = pTransfer->Timeout; + pSDC->DATALENGTH = pTransfer->BlockNum * SDC_DATACTRL_BLOCKSIZE_VAL(pTransfer->BlockSize); + DataCtrl = SDC_DATACTRL_ENABLE; + DataCtrl |= ((uint32_t) pTransfer->Dir) | ((uint32_t) pTransfer->Mode) | SDC_DATACTRL_BLOCKSIZE( + pTransfer->BlockSize); + if (pTransfer->DMAUsed) { + DataCtrl |= SDC_DATACTRL_DMA_ENABLE; + } + pSDC->DATACTRL = DataCtrl; + writeDelay(); +} + +/* Write data to FIFO */ +void Chip_SDC_WriteFIFO(LPC_SDC_T *pSDC, uint32_t *pSrc, bool bFirstHalf) +{ + uint8_t start = 0, end = 7; + if (!bFirstHalf) { + start += 8; + end += 8; + } + for (; start <= end; start++) { + pSDC->FIFO[start] = *pSrc; + pSrc++; + } +} + +/* Read data from FIFO */ +void Chip_SDC_ReadFIFO(LPC_SDC_T *pSDC, uint32_t *pDst, bool bFirstHalf) +{ + uint8_t start = 0, end = 7; + + if (!bFirstHalf) { + start += 8; + end += 8; + } + for (; start <= end; start++) { + *pDst = pSDC->FIFO[start]; + pDst++; + } +} + +/* Set SD_CLK Clock */ +void Chip_SDC_SetClock(LPC_SDC_T *pSDC, uint32_t freq) +{ + uint32_t PClk; + uint32_t ClkValue = 0; + + PClk = Chip_Clock_GetPeripheralClockRate(); + + ClkValue = (PClk + 2 * freq - 1) / (2 * freq); + if (ClkValue > 0) { + ClkValue -= 1; + } + Chip_SDC_SetClockDiv(pSDC, ClkValue); +} + +/* Shutdown the SDC card controller */ +void Chip_SDC_DeInit(LPC_SDC_T *pSDC) +{ + /* Power-off */ + Chip_SDC_PowerControl(pSDC, SDC_POWER_OFF, 0); + + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_SDC); +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC4XX) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/sdmmc_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/sdmmc_17xx_40xx.c new file mode 100644 index 000000000..93b2b820f --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/sdmmc_17xx_40xx.c @@ -0,0 +1,1196 @@ +/* + * @brief LPC17xx/40xx SDMMC card driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ +#define CMD_TIMEOUT (0x10000) +#define DATA_TIMEOUT (0x1000000) +#define DATA_TIMER_VALUE_R (SDC_TRAN_CLOCK_RATE / 4) // 250ms +#define DATA_TIMER_VALUE_W (SDC_TRAN_CLOCK_RATE) // 1000ms +#define MS_ACQUIRE_DELAY (100) /*!< inter-command acquire oper condition delay in msec*/ + +/* SD Card HW has a data length regsiter of 16-bits. + * This supports max of 0xFFFF bytes of data transfer at a time. + * We will use transfers of 127 blocks of 512 bytes at a time + */ + #define SDMMC_MAX_BLK (127) + #define SDMMC_MAX_TFR_SIZE (SDMMC_MAX_BLK * MMC_SECTOR_SIZE) + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ +/* Send a command to card */ +STATIC int32_t sendCmd(LPC_SDC_T *pSDC, uint32_t Command, uint32_t Arg, uint32_t timeout) +{ + int32_t ret = SDC_RET_TIMEOUT; + uint32_t Status; + + /* Set Command Info */ + Chip_SDC_SetCommand(pSDC, Command, Arg); + + while (timeout) { + + Status = Chip_SDC_GetStatus(pSDC); + + /* check if command was sent */ + if (((Command & SDC_COMMAND_RSP_BITMASK) == SDC_COMMAND_NO_RSP) && (Status & SDC_STATUS_CMDSENT)) { + ret = SDC_RET_OK; + break; + } + /* check if response was received */ + if (Status & SDC_STATUS_CMDRESPEND) { + ret = SDC_RET_OK; + break; + } + + /* check command sending status */ + if (Status & SDC_STATUS_CMDERR) { + if (Status & SDC_STATUS_CMDCRCFAIL) { + if ((SDC_COMMAND_INDEX(Command) == MMC_SEND_OP_COND) || + (SDC_COMMAND_INDEX(Command) == SD_APP_OP_COND) || + (SDC_COMMAND_INDEX(Command) == MMC_STOP_TRANSMISSION)) { + ret = SDC_RET_OK; /* ignore CRC error if it's a resp for SEND_OP_COND or STOP_TRANSMISSION. */ + break; + } + } + ret = SDC_RET_CMD_FAILED; + break; + } + + timeout--; + } + + Chip_SDC_ResetCommand(pSDC); + + return ret; +} + +/* Function to send a command to card and get its response (if any)*/ +STATIC int32_t executeCmd(LPC_SDC_T *pSDC, uint32_t Command, uint32_t Arg, SDC_RESP_T *pResp) +{ + int32_t Ret = SDC_RET_FAILED; + + /* Send Command to card */ + Ret = sendCmd(pSDC, Command, Arg, CMD_TIMEOUT); + if (Ret != SDC_RET_OK) { + return Ret; + } + + /* Get response (if any) */ + if ((Command & SDC_COMMAND_RSP_BITMASK) != SDC_COMMAND_NO_RSP) { + + Chip_SDC_GetResp(pSDC, pResp); + + /* If the response is not R1, in the response field, the Expected Cmd data + won't be the same as the CMD data in SendCmd(). Below four cmds have + R2 or R3 response. We don't need to check if MCI_RESP_CMD is the same + as the Expected or not. */ + if ((SDC_COMMAND_INDEX(Command) != MMC_SEND_OP_COND) && + (SDC_COMMAND_INDEX(Command) != SD_APP_OP_COND) && + (SDC_COMMAND_INDEX(Command) != MMC_ALL_SEND_CID) && + (SDC_COMMAND_INDEX(Command) != MMC_SEND_CSD) && + (pResp->CmdIndex != SDC_COMMAND_INDEX(Command))) { + return SDC_RET_CMD_FAILED; + } + } + + return SDC_RET_OK; +} + +/* Check R1 response, the result is stored in pCheckResult parameter. */ +/* This function return 1 to exit the command execution, 0 to retry sending command */ +STATIC int32_t checkR1Response(uint32_t resp, int32_t *pCheckResult) +{ + int32_t Ret = 1; + + if (!(resp & R1_READY_FOR_DATA)) { + *pCheckResult = SDC_RET_NOT_READY; + Ret = 0; + } + else if (R1_STATUS(resp)) { + *pCheckResult = SDC_RET_FAILED; + } + else { + *pCheckResult = SDC_RET_OK; + } + return Ret; +} + +/* Send APP_CMD to card*/ +STATIC int32_t sendAppCmd(LPC_SDC_T *pSDC, uint16_t rca) + +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD55_APP_CMD, CMD55_RCA(rca), &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + if (Ret != SDC_RET_OK) { + return Ret; + } + if (Response.Data[0] & R1_APP_CMD) { + return SDC_RET_OK; + } + else { + Ret = SDC_RET_FAILED; + } + } + } + RetryCnt--; + } + return SDC_RET_FAILED; +} + +/* Send Reset command to card*/ +STATIC INLINE int32_t cardReset(LPC_SDC_T *pSDC) +{ + return executeCmd(pSDC, SD_GO_IDLE_STATE, 0, NULL); +} + +/* Send Interface condition to card*/ +STATIC int32_t sendIfCond(LPC_SDC_T *pSDC) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD8_SEND_IF_COND, (CMD8_VOLTAGESUPPLIED_27_36 | CMD8_CHECKPATTERN( + CMD8_DEF_PATTERN)), &Response); + if (Ret == SDC_RET_OK) { + if ((Response.Data[0] & CMDRESP_R7_VOLTAGE_ACCEPTED) && + (CMDRESP_R7_CHECK_PATTERN(Response.Data[0]) == CMD8_DEF_PATTERN)) { + return SDC_RET_OK; + } + return SDC_RET_BAD_PARAMETERS; + } + RetryCnt--; + } + return Ret; +} + +/* Send Operation condition to card */ +STATIC int32_t sendOpCond(LPC_SDC_T *pSDC, uint32_t *pOCR) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 0x200; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD1_SEND_OP_COND, SDC_OCR_27_36, &Response); + if (Ret == SDC_RET_OK) { + *pOCR = Response.Data[0]; + if (*pOCR & SDC_OCR_IDLE) { + if ((Response.Data[0] & SDC_OCR_27_36) != SDC_OCR_27_36) { + return SDC_RET_BAD_PARAMETERS; + } + return SDC_RET_OK; + } + } + RetryCnt--; + } + return SDC_RET_FAILED; +} + +/* Send ACMD41 command to card.If *Ocr = 0, it gets OCR. Otherwise, it starts initialization card. */ +/* Open Drain bit must be cleared before calling this function */ +STATIC int32_t sendAppOpCond(LPC_SDC_T *pSDC, uint16_t rca, bool hcs, uint32_t *pOcr, bool *pCCS) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t Argument; + uint32_t RetryCnt = 0x2000; /* The host repeatedly issues ACMD41 for at least 1 second or + until the busy bit are set to 1 */ + + Argument = ACMD41_OCR(*pOcr); + if (hcs) { + Argument |= ACMD41_HCS; + } + + while (RetryCnt > 0) { + Ret = sendAppCmd(pSDC, rca); + if (Ret == SDC_RET_OK) { + Ret = executeCmd(pSDC, SD_ACMD41_SD_SEND_OP_COND, Argument, &Response); + if (Ret == SDC_RET_OK) { + if (Response.Data[0] & CMDRESP_R3_INIT_COMPLETE) { + if (*pOcr == 0) { + *pOcr = CMDRESP_R3_OCR_VAL(Response.Data[0]); + return SDC_RET_OK; + } + if ((CMDRESP_R3_OCR_VAL(Response.Data[0]) & *pOcr) != *pOcr) { + return SDC_RET_BAD_PARAMETERS; + } + *pCCS = (Response.Data[0] & CMDRESP_R3_HC_CCS) ? true : false; + return SDC_RET_OK; + } + } + } + else { + return Ret; + } + RetryCnt--; + } + return SDC_RET_FAILED; +} + +/* Get CID */ +STATIC int32_t getCID(LPC_SDC_T *pSDC, uint32_t *pCID) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD2_ALL_SEND_CID, 0, &Response); + if (Ret == SDC_RET_OK) { + pCID[3] = Response.Data[0]; + pCID[2] = Response.Data[1]; + pCID[1] = Response.Data[2]; + pCID[0] = Response.Data[3]; + return SDC_RET_OK; + } + RetryCnt--; + } + return Ret; +} + +/* Set Addr */ +STATIC int32_t setAddr(LPC_SDC_T *pSDC, uint16_t addr) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD3_SET_RELATIVE_ADDR, CMD3_RCA(addr), &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + return Ret; + } + } + RetryCnt--; + } + return Ret; +} + +STATIC int32_t getAddr(LPC_SDC_T *pSDC, uint16_t *pRCA) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + *pRCA = 0; + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD3_SEND_RELATIVE_ADDR, 0, &Response); + if (Ret == SDC_RET_OK) { + if (!(CMDRESP_R6_CARD_STATUS(Response.Data[0]) & R1_READY_FOR_DATA)) { + Ret = SDC_RET_NOT_READY; + } + else if (R1_CURRENT_STATE(CMDRESP_R6_CARD_STATUS(Response.Data[0])) != SDMMC_STBY_ST) { + Ret = SDC_RET_ERR_STATE; + } + else { + *pRCA = CMDRESP_R6_RCA_VAL(Response.Data[0]); + return SDC_RET_OK; + } + } + RetryCnt--; + } + return Ret; +} + +STATIC int32_t getCSD(LPC_SDC_T *pSDC, uint16_t rca, uint32_t *pCSD) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD9_SEND_CSD, CMD9_RCA(rca), &Response); + if (Ret == SDC_RET_OK) { + pCSD[3] = Response.Data[0]; + pCSD[2] = Response.Data[1]; + pCSD[1] = Response.Data[2]; + pCSD[0] = Response.Data[3]; + return Ret; + } + RetryCnt--; + } + return Ret; +} + +/* Select card*/ +STATIC int32_t selectCard(LPC_SDC_T *pSDC, uint16_t addr) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD7_SELECT_CARD, CMD7_RCA(addr), &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + return Ret; + } + } + RetryCnt--; + } + return Ret; +} + +/* Get card status */ +STATIC int32_t getStatus(LPC_SDC_T *pSDC, uint16_t rca, uint32_t *pStatus) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + *pStatus = (uint32_t) -1; + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD13_SEND_STATUS, CMD13_RCA(rca), &Response); + if (Ret == SDC_RET_OK) { + checkR1Response(Response.Data[0], &Ret); + *pStatus = Response.Data[0]; + return Ret; + } + RetryCnt--; + } + return Ret; +} + +/* Set bus width. */ +STATIC int32_t getAppStatus(LPC_SDC_T *pSDC, uint16_t rca, uint32_t *pStatus) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint8_t RetryCnt = 0x20; + + while (RetryCnt > 0) { + Ret = sendAppCmd(pSDC, rca); + if (Ret == SDC_RET_OK) { + Ret = executeCmd(pSDC, SD_ACMD13_SEND_SD_STATUS, 0, &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + return Ret; + } + } + } + RetryCnt--; + } + return SDC_RET_FAILED; +} + +/* Helper function to get a bit field withing multi-word buffer. Used to get + fields with-in CSD & EXT-CSD */ +STATIC uint32_t getBits(LPC_SDC_T *pSDC, int32_t start, int32_t end, uint32_t *data) +{ + uint32_t v; + uint32_t i = end >> 5; + uint32_t j = start & 0x1f; + + if (i == (start >> 5)) { + v = (data[i] >> j); + } + else { + v = ((data[i] << (32 - j)) | (data[start >> 5] >> j)); + } + + return v & ((1 << (end - start + 1)) - 1); +} + +/* Function to process the CSD & EXT-CSD of the card */ +STATIC void processCSD(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo) +{ + int32_t CSize = 0; + int32_t CSizeMult = 0; + int32_t Mult = 0; + + /* compute block length based on CSD response */ + pCardInfo->block_len = 1 << getBits(pSDC, 80, 83, pCardInfo->csd); + + if ((pCardInfo->card_type & CARD_TYPE_HC) && (pCardInfo->card_type & CARD_TYPE_SD)) { + /* See section 5.3.3 CSD Register (CSD Version 2.0) of SD2.0 spec an explanation for the calculation of these values */ + CSize = getBits(pSDC, 48, 63, (uint32_t *) pCardInfo->csd) + 1; + pCardInfo->blocknr = CSize << 10; /* 512 byte blocks */ + } + else { + /* See section 5.3 of the 4.1 revision of the MMC specs for an explanation for the calculation of these values */ + CSize = getBits(pSDC, 62, 73, (uint32_t *) pCardInfo->csd); + CSizeMult = getBits(pSDC, 47, 49, (uint32_t *) pCardInfo->csd); + Mult = 1 << (CSizeMult + 2); + pCardInfo->blocknr = (CSize + 1) * Mult; + + /* adjust blocknr to 512/block */ + if (pCardInfo->block_len > MMC_SECTOR_SIZE) { + pCardInfo->blocknr = pCardInfo->blocknr * (pCardInfo->block_len >> 9); + } + } + + pCardInfo->device_size = pCardInfo->blocknr << 9; /* blocknr * 512 */ +} + +/* Set bus width. */ +STATIC int32_t setBusWidth(LPC_SDC_T *pSDC, uint16_t rca, uint8_t width) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint8_t RetryCnt = 0x20; + + while (RetryCnt > 0) { + Ret = sendAppCmd(pSDC, rca); + if (Ret == SDC_RET_OK) { + Ret = executeCmd(pSDC, SD_ACMD6_SET_BUS_WIDTH, ACMD6_BUS_WIDTH(width), &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + return Ret; + } + } + } + RetryCnt--; + } + return SDC_RET_FAILED; +} + +/* Puts current selected card in trans state */ +STATIC int32_t setTranState(LPC_SDC_T *pSDC, uint16_t rca) +{ + int32_t Ret = 0; + uint32_t status = 0; + SDMMC_STATE_T state; + + /* get current state of the card */ + Ret = getStatus(pSDC, rca, &status); + if (Ret != SDC_RET_OK) { + /* unable to get the card state. So return immediatly. */ + return Ret; + } + + /* check card state in response */ + state = (SDMMC_STATE_T) R1_CURRENT_STATE(status); + switch (state) { + case SDMMC_STBY_ST: + /* put card in 'Trans' state */ + Ret = selectCard(pSDC, rca); + if (Ret != SDC_RET_OK) { + /* unable to put the card in Trans state. So return immediatly. */ + return Ret; + } + getStatus(pSDC, rca, &status); + if (((SDMMC_STATE_T) R1_CURRENT_STATE(status)) != SDMMC_TRAN_ST) { + return SDC_RET_ERR_STATE; + } + break; + + case SDMMC_TRAN_ST: + /*do nothing */ + break; + + default: + /* card shouldn't be in other states so return */ + return SDC_RET_ERR_STATE; + } + + return SDC_RET_OK; +} + +/* Set bus width. */ +STATIC int32_t setblock_length(LPC_SDC_T *pSDC, uint32_t rca, uint32_t block_len) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint8_t RetryCnt = 0x20; + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD16_SET_BLOCKLEN, block_len, &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + return Ret; + } + } + RetryCnt--; + } + return SDC_RET_FAILED; +} + +/* Sets card data width and block size */ +STATIC int32_t setCardParams(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo) +{ + int32_t Ret; + + Chip_SDC_SetClock(pSDC, SDC_TRAN_CLOCK_RATE); + if (pCardInfo->card_type & CARD_TYPE_SD) { + Chip_SDC_ClockControl(pSDC, SDC_CLOCK_WIDEBUS_MODE, ENABLE); + Ret = setBusWidth(pSDC, pCardInfo->rca, ACMD6_BUS_WIDTH_4); + if (Ret != SDC_RET_OK) { + return Ret; + } + } + else { + Chip_SDC_ClockControl(pSDC, SDC_CLOCK_WIDEBUS_MODE, DISABLE); + } + + /* set block length */ + Ret = setblock_length(pSDC, pCardInfo->rca, MMC_SECTOR_SIZE); + return Ret; +} + +STATIC int32_t readBlocks(LPC_SDC_T *pSDC, uint32_t card_type, uint32_t startBlock, uint32_t blockNum) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t Command, Argument; + uint8_t RetryCnt = 0x20; + + if (blockNum == 1) { + Command = SD_CMD17_READ_SINGLE_BLOCK; + } + else { + Command = SD_CMD18_READ_MULTIPLE_BLOCK; + } + + /* Select single or multiple read based on number of blocks */ + /* if high capacity card use block indexing */ + if (card_type & CARD_TYPE_HC) { + Argument = startBlock; + } + else { /*fix at 512 bytes*/ + Argument = startBlock << 9; + } + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, Command, Argument, &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + return Ret; + } + } + RetryCnt--; + } + return Ret; +} + +STATIC int32_t writeBlocks(LPC_SDC_T *pSDC, uint32_t card_type, uint32_t startBlock, uint32_t blockNum) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t Command, Argument; + uint8_t RetryCnt = 0x20; + + if (blockNum == 1) { + Command = SD_CMD24_WRITE_BLOCK; + } + else { + Command = SD_CMD25_WRITE_MULTIPLE_BLOCK; + } + + /* if high capacity card use block indexing */ + if (card_type & CARD_TYPE_HC) { + Argument = startBlock; + } + else { /*fix at 512 bytes*/ + Argument = startBlock << 9; + + } + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, Command, Argument, &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + return Ret; + } + } + RetryCnt--; + } + return Ret; +} + +STATIC int32_t stopTranmission(LPC_SDC_T *pSDC, uint32_t rca) +{ + uint32_t Status; + int32_t Ret = SDC_RET_FAILED; + SDC_RESP_T Response; + uint32_t RetryCnt = 20; + + Ret = getStatus(pSDC, rca, &Status); + if (Ret != SDC_RET_OK) { + return SDC_RET_ERR_STATE; + } + + if (R1_CURRENT_STATE(Status) == SDMMC_TRAN_ST) { + return SDC_RET_OK; + } + + if ((R1_CURRENT_STATE(Status) != SDMMC_DATA_ST) && + (R1_CURRENT_STATE(Status) != SDMMC_RCV_ST)) { + return SDC_RET_ERR_STATE; + } + + while (RetryCnt > 0) { + Ret = executeCmd(pSDC, SD_CMD12_STOP_TRANSMISSION, 0, &Response); + if (Ret == SDC_RET_OK) { + if (checkR1Response(Response.Data[0], &Ret)) { + if (Ret != SDC_RET_OK) { + return Ret; + } + Ret = getStatus(pSDC, rca, &Status); + if ((R1_CURRENT_STATE(Status) == SDMMC_TRAN_ST) || (R1_CURRENT_STATE(Status) == SDMMC_PRG_ST)) { + return SDC_RET_OK; + } + return SDC_RET_ERR_STATE; + } + } + RetryCnt--; + } + return Ret; +} + +STATIC int32_t Chip_SDMMC_FIFOIRQHandler(LPC_SDC_T *pSDC, uint8_t *txBuf, uint32_t *txCnt, + uint8_t *rxBuf, uint32_t *rxCnt) +{ + uint32_t Status; + Status = Chip_SDC_GetStatus(pSDC); + + if (txBuf ) { + if (Status & SDC_STATUS_TXFIFOHALFEMPTY) { + if (*txCnt % 64) { + Chip_SDC_WriteFIFO(pSDC, (uint32_t *) &txBuf[*txCnt], false); + } + else { + Chip_SDC_WriteFIFO(pSDC, (uint32_t *) &txBuf[*txCnt], true); + } + *txCnt += 32; + } + } + + if (rxBuf ) { + if (Status & SDC_STATUS_RXFIFOHALFFULL) { + if (*rxCnt % 64) { + Chip_SDC_ReadFIFO(pSDC, (uint32_t *) &rxBuf[*rxCnt], false); + } + else { + Chip_SDC_ReadFIFO(pSDC, (uint32_t *) &rxBuf[*rxCnt], true); + } + *rxCnt += 32; + } + } + + Chip_SDC_ClearStatus(pSDC, SDC_STATUS_FIFO); + + return 1; +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* SDMMC IRQ handler function */ +int32_t Chip_SDMMC_IRQHandler(LPC_SDC_T *pSDC, uint8_t *txBuf, uint32_t *txCnt, + uint8_t *rxBuf, uint32_t *rxCnt) +{ + uint32_t Status; + + Status = Chip_SDC_GetStatus(pSDC); + + if ( Status & SDC_STATUS_DATAERR) { + Chip_SDC_ClearStatus(pSDC, SDC_STATUS_DATAERR); + return -1; /* Data transfer error */ + } + + if ( Status & SDC_STATUS_DATAEND) { + Chip_SDC_ClearStatus(pSDC, SDC_STATUS_DATAEND); + Chip_SDC_SetIntMask(pSDC, 0); + return 0; + } + + if ( Status & SDC_STATUS_DATABLOCKEND) { + Chip_SDC_ClearStatus(pSDC, SDC_STATUS_DATABLOCKEND); + return 1; + } + + if (Status & SDC_STATUS_FIFO) { + return Chip_SDMMC_FIFOIRQHandler(pSDC, txBuf, txCnt, rxBuf, rxCnt); + } + + return 1; +} + +/* Get card's current state (idle, transfer, program, etc.) */ +SDMMC_STATE_T Chip_SDMMC_GetCardState(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo) +{ + uint32_t Status; + + /* get current state of the card */ + getStatus(pSDC, pCardInfo->rca, &Status); + + /* check card state in response */ + return (SDMMC_STATE_T) R1_CURRENT_STATE(Status); +} + +/* Get current card status */ +uint32_t Chip_SDMMC_GetCardStatus(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo) +{ + uint32_t Status; + getStatus(pSDC, pCardInfo->rca, &Status); + return Status; +} + +/* Get current sd status */ +int32_t Chip_SDMMC_GetSDStatus(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo, uint32_t *pStatus) +{ + int32_t Ret; + uint16_t ByteNum = 64; + SDMMC_EVENT_T Event; + SDC_DATA_TRANSFER_T Transfer; + + /* Put to tran state */ + if (setTranState(pSDC, pCardInfo->rca) != SDC_RET_OK) { + return 0; + } + +#ifdef SDC_DMA_ENABLE + Chip_SDC_SetIntMask(pSDC, SDC_MASK0_DATA | SDC_MASK0_RXDATAERR); + Event.DmaChannel = Chip_GPDMA_GetFreeChannel(LPC_GPDMA, GPDMA_CONN_SDC); + + /* DMA Setup */ + Chip_GPDMA_Transfer(LPC_GPDMA, Event.DmaChannel, + GPDMA_CONN_SDC, + (uint32_t) pStatus, + GPDMA_TRANSFERTYPE_P2M_CONTROLLER_PERIPHERAL, + ByteNum); +#else + Chip_SDC_SetIntMask(pSDC, SDC_MASK0_DATA | SDC_MASK0_RXDATAERR | SDC_MASK0_RXFIFO); + + Event.Buffer = pStatus; + Event.Size = ByteNum; + Event.Index = 0; + Event.Dir = 1; +#endif + pCardInfo->evsetup_cb((void *) &Event); + + /* set transfer information */ + Transfer.BlockNum = 1; + Transfer.BlockSize = SDC_BLOCK_SIZE_64; /* 512 bit */ + Transfer.Dir = SDC_TRANSFER_DIR_FROMCARD; +#ifdef SDC_DMA_ENABLE + Transfer.DMAUsed = true; +#else + Transfer.DMAUsed = false; +#endif + Transfer.Mode = SDC_TRANSFER_MODE_BLOCK; + Transfer.Timeout = DATA_TIMER_VALUE_R; + Chip_SDC_SetDataTransfer(pSDC, &Transfer); + + /* Send ACMD13 command */ + Ret = getAppStatus(pSDC, pCardInfo->rca, pStatus); + if (Ret != SDC_RET_OK) { + ByteNum = 0; + goto send_end; + } + + /* Wait for transfer Finish */ + if ((pCardInfo->waitfunc_cb()) != 0) { + ByteNum = 0; + } + +send_end: +#ifdef SDC_DMA_ENABLE + Chip_GPDMA_Stop(LPC_GPDMA, Event.DmaChannel); +#endif + if (Chip_SDMMC_GetCardState(pSDC, pCardInfo) == SDMMC_DATA_ST) { + /* Send Stop transmission command */ + stopTranmission(pSDC, pCardInfo->rca); + } + + /*Wait for card enters to tran state*/ + while ((Chip_SDMMC_GetCardState(pSDC, pCardInfo) != SDMMC_TRAN_ST)) {} + + return ByteNum; +} + +/* Function to enumerate the SD/MMC/SDHC/MMC+ cards */ +int32_t Chip_SDMMC_Acquire(LPC_SDC_T *pSDC, SDMMC_CARD_T *pCardInfo) +{ + int32_t Ret; + + /* Initialize card info */ + pCardInfo->speed = SDC_TRAN_CLOCK_RATE; + pCardInfo->card_type = 0; + + /* During identification phase, the clock should be less than + 400Khz. Once we pass this phase, the normal clock can be set up + to 25Mhz on SD card and 20Mhz on MMC card. */ + Chip_SDC_SetClock(pSDC, SDC_IDENT_CLOCK_RATE); + + /* Clear Open Drain output control for SD */ + Chip_SDC_PowerControl(pSDC, SDC_POWER_ON, 0); + + /* Card Reset */ + Ret = cardReset(pSDC); + if (Ret != 0) { + return Ret; + } + + pCardInfo->msdelay_func(MS_ACQUIRE_DELAY); + + /* Send interface operation condiftion */ + Ret = sendIfCond(pSDC); + if (Ret == SDC_RET_BAD_PARAMETERS) { + return Ret; /* Non-compatible voltage range or check pattern is not correct */ + + } + /* Get Card Type */ + if (Ret == SDC_RET_OK) {/* Ver2.00 or later SD Memory Card*/ + bool CCS; + uint32_t OCR = SDC_OCR_27_36; + pCardInfo->card_type |= CARD_TYPE_SD; + Ret = sendAppOpCond(pSDC, 0, true, &OCR, &CCS); + if (CCS) { /* High Capacity or Extended Capacity SD Memory Card */ + pCardInfo->card_type |= CARD_TYPE_HC; + } + } + else { /*Ver2.00 or later SD Memory Card(voltage mismatch) or Ver1.X SD Memory Card + or not SD Memory Card*/ + bool CCS; + uint32_t OCR = SDC_OCR_27_36; + Ret = sendAppOpCond(pSDC, 0, false, &OCR, &CCS); + if (Ret == SDC_RET_OK) { + pCardInfo->card_type |= CARD_TYPE_SD; + } + else if (Ret == SDC_RET_BAD_PARAMETERS) { + return Ret; + } + else { /* MMC Card setup */ + uint32_t OCR; + /* Enter to Open Drain mode */ + Chip_SDC_PowerControl(pSDC, SDC_POWER_ON, SDC_PWR_OPENDRAIN); + pCardInfo->msdelay_func(MS_ACQUIRE_DELAY); + Ret = sendOpCond(pSDC, &OCR); + if (Ret != SDC_RET_OK) { + return Ret; + } + + } + } + + /* Read CID */ + getCID(pSDC, pCardInfo->cid); + + /* RCA send, for SD get RCA */ + if (pCardInfo->card_type & CARD_TYPE_SD) { + getAddr(pSDC, &pCardInfo->rca); + } + else { + pCardInfo->rca = 1; + setAddr(pSDC, pCardInfo->rca); + Chip_SDC_PowerControl(pSDC, SDC_POWER_ON, 0); /* enter to push-pull mode */ + } + + /* Get CSD */ + getCSD(pSDC, pCardInfo->rca, pCardInfo->csd); + + /* Compute card size, block size and no. of blocks based on CSD response recived. */ + if (pCardInfo->cid[0]) { + processCSD(pSDC, pCardInfo); + + if (setTranState(pSDC, pCardInfo->rca) != SDC_RET_OK) { + return 0; + } + + if (Chip_SDMMC_GetCardState(pSDC, pCardInfo) != SDMMC_TRAN_ST) { + return 0; + } + + if (setCardParams(pSDC, pCardInfo) != 0) { + return 0; + } + } + + return (pCardInfo->cid[0]) ? 1 : 0; +} + +/* Performs the read of data from the SD/MMC card */ +int32_t Chip_SDMMC_ReadBlocks(LPC_SDC_T *pSDC, + SDMMC_CARD_T *pCardInfo, + void *buffer, + int32_t startBlock, + int32_t blockNum) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_DATA_TRANSFER_T Transfer; + SDMMC_EVENT_T Event; + int32_t tfr_blk_cnt, start_blk = startBlock, block_cnt = blockNum; + int32_t ByteNum = blockNum * MMC_SECTOR_SIZE; + uint32_t buf_ptr = (uint32_t) buffer; + + /* if card is not acquired return immediately */ + if (( startBlock < 0) || ( (startBlock + blockNum) > pCardInfo->blocknr) ) { + return 0; + } + + /* Put to tran state */ + if (setTranState(pSDC, pCardInfo->rca) != SDC_RET_OK) { + return 0; + } + + /* Do data transfers in a loop */ + Transfer.BlockSize = SDC_BLOCK_SIZE_512; + Transfer.Dir = SDC_TRANSFER_DIR_FROMCARD; +#ifdef SDC_DMA_ENABLE + Transfer.DMAUsed = true; +#else + Transfer.DMAUsed = false; +#endif + Transfer.Mode = SDC_TRANSFER_MODE_BLOCK; + Transfer.Timeout = DATA_TIMER_VALUE_R; + + while (block_cnt > 0) { + if (block_cnt > SDMMC_MAX_BLK) { + tfr_blk_cnt = SDMMC_MAX_BLK; + } + else { + tfr_blk_cnt = block_cnt; + } + +#ifdef SDC_DMA_ENABLE + /* Enable Receive interrupts */ + Chip_SDC_SetIntMask(pSDC, SDC_MASK0_DATA | SDC_MASK0_RXDATAERR); + + /* Get DMA channel */ + Event.DmaChannel = Chip_GPDMA_GetFreeChannel(LPC_GPDMA, GPDMA_CONN_SDC); + + /* Start the DMA transfer */ + Chip_GPDMA_Transfer(LPC_GPDMA, Event.DmaChannel, + GPDMA_CONN_SDC, + buf_ptr, + GPDMA_TRANSFERTYPE_P2M_CONTROLLER_PERIPHERAL, + (tfr_blk_cnt * MMC_SECTOR_SIZE)); +#else + /* Enable Receive interrupts */ + Chip_SDC_SetIntMask(SDC_MASK0_DATA | SDC_MASK0_RXDATAERR | SDC_MASK0_RXFIFO); + + Event.Buffer = buf_ptr; + Event.Size = (tfr_blk_cnt * MMC_SECTOR_SIZE); + Event.Index = 0; + Event.Dir = 1; +#endif + /* Call Event Setup function */ + pCardInfo->evsetup_cb((void *) &Event); + + /* Set transfer information */ + Transfer.BlockNum = tfr_blk_cnt; + Chip_SDC_SetDataTransfer(pSDC, &Transfer); + + /* Send command for reading data */ + Ret = readBlocks(pSDC, pCardInfo->card_type, start_blk, tfr_blk_cnt); + if (Ret != SDC_RET_OK) { + ByteNum = 0; + goto send_end; + } + + /* Wait for transfer Finish */ + if ((pCardInfo->waitfunc_cb()) != 0) { + ByteNum = 0; + goto send_end; + } + +#ifdef SDC_DMA_ENABLE + Chip_GPDMA_Stop(LPC_GPDMA, Event.DmaChannel); +#endif + + /* Send stop transmission */ + if ((tfr_blk_cnt > 1) || (Chip_SDMMC_GetCardState(pSDC, pCardInfo) == SDMMC_DATA_ST)) { + /* Send Stop transmission command */ + stopTranmission(pSDC, pCardInfo->rca); + } + + /* Wait for card enter to tran state */ + while (Chip_SDMMC_GetCardState(pSDC, pCardInfo) != SDMMC_TRAN_ST) {} + + /* Update block counter, buffer address */ + block_cnt -= tfr_blk_cnt; + buf_ptr += (tfr_blk_cnt * MMC_SECTOR_SIZE); + start_blk += tfr_blk_cnt; + } + +send_end: + /* Stop the DMA in case of error */ + if (ByteNum == 0) { +#ifdef SDC_DMA_ENABLE + Chip_GPDMA_Stop(LPC_GPDMA, Event.DmaChannel); +#endif + + if ((blockNum > 1) || (Chip_SDMMC_GetCardState(pSDC, pCardInfo) == SDMMC_DATA_ST)) { + /* Send Stop transmission command */ + stopTranmission(pSDC, pCardInfo->rca); + } + + /* Wait for card enter to tran state */ + while (Chip_SDMMC_GetCardState(pSDC, pCardInfo) != SDMMC_TRAN_ST) {} + } + + return ByteNum; +} + +/* Performs write of data to the SD/MMC card */ +int32_t Chip_SDMMC_WriteBlocks(LPC_SDC_T *pSDC, + SDMMC_CARD_T *pCardInfo, + void *buffer, + int32_t startBlock, + int32_t blockNum) +{ + int32_t Ret = SDC_RET_FAILED; + SDC_DATA_TRANSFER_T Transfer; + SDMMC_EVENT_T Event; + int32_t tfr_blk_cnt, start_blk = startBlock, block_cnt = blockNum; + int32_t ByteNum = blockNum * MMC_SECTOR_SIZE; + uint32_t buf_ptr = (uint32_t) buffer; + + /* if card is not acquired return immediately */ + if (( startBlock < 0) || ( (startBlock + blockNum) > pCardInfo->blocknr) ) { + return 0; + } + + /* Put to tran state */ + if (setTranState(pSDC, pCardInfo->rca) != SDC_RET_OK) { + return 0; + } + + /* Do the trnasfers */ + Transfer.BlockSize = SDC_BLOCK_SIZE_512; + Transfer.Dir = SDC_TRANSFER_DIR_TOCARD; +#ifdef SDC_DMA_ENABLE + Transfer.DMAUsed = true; +#else + Transfer.DMAUsed = false; +#endif + Transfer.Mode = SDC_TRANSFER_MODE_BLOCK; + Transfer.Timeout = DATA_TIMER_VALUE_W; + while (block_cnt > 0) { + if (block_cnt > SDMMC_MAX_BLK) { + tfr_blk_cnt = SDMMC_MAX_BLK; + } + else { + tfr_blk_cnt = block_cnt; + } + + /* Send Write block(s) command */ + Ret = writeBlocks(pSDC, pCardInfo->card_type, start_blk, tfr_blk_cnt); + if (Ret != SDC_RET_OK) { + return 0; + } + + /* Wait for card enter to rcv state */ + while (Chip_SDMMC_GetCardState(pSDC, pCardInfo) != SDMMC_RCV_ST) {} + +#ifdef SDC_DMA_ENABLE + /* Enable Transmit interrupts */ + Chip_SDC_SetIntMask(pSDC, SDC_MASK0_DATA | SDC_MASK0_TXDATAERR); + + /* Get DMA channel */ + Event.DmaChannel = Chip_GPDMA_GetFreeChannel(LPC_GPDMA, GPDMA_CONN_SDC); + + /* Start the DMA transfer */ + Chip_GPDMA_Transfer(LPC_GPDMA, Event.DmaChannel, + buf_ptr, + GPDMA_CONN_SDC, + GPDMA_TRANSFERTYPE_M2P_CONTROLLER_PERIPHERAL, + (tfr_blk_cnt * MMC_SECTOR_SIZE)); +#else + /* Enable Transmit interrupts */ + Chip_SDC_SetIntMask(SDC_MASK0_DATA | SDC_MASK0_TXDATAERR | SDC_MASK0_TXFIFO); + + Event.Buffer = buf_ptr; + Event.Size = (tfr_blk_cnt * MMC_SECTOR_SIZE); + Event.Index = 0; + Event.Dir = 0; +#endif + /* Call Event Setup function */ + pCardInfo->evsetup_cb((void *) &Event); + + /* Set transfer information */ + Transfer.BlockNum = tfr_blk_cnt; + Chip_SDC_SetDataTransfer(pSDC, &Transfer); + + /* Wait for transfer done */ + if ((pCardInfo->waitfunc_cb()) != 0) { + ByteNum = 0; + goto end_send; + } + +#ifdef SDC_DMA_ENABLE + Chip_GPDMA_Stop(LPC_GPDMA, Event.DmaChannel); +#endif + + if ((tfr_blk_cnt > 1) || (Chip_SDMMC_GetCardState(pSDC, pCardInfo) == SDMMC_RCV_ST)) { + /* Send Stop transmission command */ + stopTranmission(pSDC, pCardInfo->rca); + } + + /*Wait for card enter to tran state*/ + while (Chip_SDMMC_GetCardState(pSDC, pCardInfo) != SDMMC_TRAN_ST) {} + + /* Update cnt */ + block_cnt -= tfr_blk_cnt; + buf_ptr += (tfr_blk_cnt * MMC_SECTOR_SIZE); + start_blk += tfr_blk_cnt; + } + +end_send: + if (ByteNum == 0) { +#ifdef SDC_DMA_ENABLE + Chip_GPDMA_Stop(LPC_GPDMA, Event.DmaChannel); +#endif + + if ((blockNum > 1) || (Chip_SDMMC_GetCardState(pSDC, pCardInfo) == SDMMC_RCV_ST)) { + /* Send Stop transmission command */ + stopTranmission(pSDC, pCardInfo->rca); + } + + /* Wait for card enter to tran state */ + while (Chip_SDMMC_GetCardState(pSDC, pCardInfo) != SDMMC_TRAN_ST) {} + } + + return ByteNum; +} + +#endif /* defined(CHIP_LPC177X_8X) || defined(CHIP_LPC4XX) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/spi_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/spi_17xx_40xx.c new file mode 100644 index 000000000..ac3ebe78a --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/spi_17xx_40xx.c @@ -0,0 +1,227 @@ +/* + * @brief LPC17xx/40xx SPI driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +#if defined(CHIP_LPC175X_6X) + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/* Execute callback function */ +STATIC void executeCallback(LPC_SPI_T *pSPI, SPI_CALLBACK_T pfunc) +{ + if (pfunc) { + (pfunc) (); + } +} + +/* Write byte(s) to FIFO buffer */ +STATIC void writeData(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *pXfSetup, uint32_t num_bytes) +{ + uint16_t data2write = 0xFFFF; + + if ( pXfSetup->pTxData) { + data2write = pXfSetup->pTxData[pXfSetup->cnt]; + if (num_bytes == 2) { + data2write |= pXfSetup->pTxData[pXfSetup->cnt + 1] << 8; + } + } + + Chip_SPI_SendFrame(pSPI, data2write); + +} + +/* Read byte(s) from FIFO buffer */ +STATIC void readData(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *pXfSetup, uint16_t rDat, uint32_t num_bytes) +{ + rDat = Chip_SPI_ReceiveFrame(pSPI); + if (pXfSetup->pRxData) { + pXfSetup->pRxData[pXfSetup->cnt] = rDat; + if (num_bytes == 2) { + pXfSetup->pRxData[pXfSetup->cnt + 1] = rDat >> 8; + } + } +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* SPI Polling Read/Write in blocking mode */ +uint32_t Chip_SPI_RWFrames_Blocking(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *pXfSetup) +{ + uint32_t status; + uint16_t rDat = 0x0000; + uint8_t bytes = 1; + + /* Clear status */ + Chip_SPI_Int_FlushData(pSPI); + + if (Chip_SPI_GetDataSize(pSPI) != SPI_BITS_8) { + bytes = 2; + } + + executeCallback(pSPI, pXfSetup->fnBefTransfer); + + while (pXfSetup->cnt < pXfSetup->length) { + + executeCallback(pSPI, pXfSetup->fnBefFrame); + + /* write data to buffer */ + writeData(pSPI, pXfSetup, bytes); + + /* Wait for transfer completes */ + while (1) { + status = Chip_SPI_GetStatus(pSPI); + /* Check error */ + if (status & SPI_SR_ERROR) { + goto rw_end; + } + if (status & SPI_SR_SPIF) { + break; + } + } + + executeCallback(pSPI, pXfSetup->fnAftFrame); + + /* Read data*/ + readData(pSPI, pXfSetup, rDat, bytes); + pXfSetup->cnt += bytes; + } + +rw_end: + executeCallback(pSPI, pXfSetup->fnAftTransfer); + return pXfSetup->cnt; +} + +/* Clean all data in RX FIFO of SPI */ +void Chip_SPI_Int_FlushData(LPC_SPI_T *pSPI) +{ + volatile uint32_t tmp; + Chip_SPI_GetStatus(pSPI); + tmp = Chip_SPI_ReceiveFrame(pSPI); + Chip_SPI_Int_ClearStatus(pSPI, SPI_INT_SPIF); +} + +/* SPI Interrupt Read/Write with 8-bit frame width */ +Status Chip_SPI_Int_RWFrames(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *pXfSetup, uint8_t bytes) +{ + uint32_t status; + uint16_t rDat = 0x0000; + + status = Chip_SPI_GetStatus(pSPI); + /* Check error status */ + if (status & SPI_SR_ERROR) { + return ERROR; + } + + Chip_SPI_Int_ClearStatus(pSPI, SPI_INT_SPIF); + if (status & SPI_SR_SPIF) { + executeCallback(pSPI, pXfSetup->fnAftFrame); + if (pXfSetup->cnt < pXfSetup->length) { + /* read data */ + readData(pSPI, pXfSetup, rDat, bytes); + pXfSetup->cnt += bytes; + } + } + + if (pXfSetup->cnt < pXfSetup->length) { + + executeCallback(pSPI, pXfSetup->fnBefFrame); + + /* Write data */ + writeData(pSPI, pXfSetup, bytes); + } + else { + executeCallback(pSPI, pXfSetup->fnAftTransfer); + } + return SUCCESS; +} + +/* SPI Interrupt Read/Write with 8-bit frame width */ +Status Chip_SPI_Int_RWFrames8Bits(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *pXfSetup) +{ + return Chip_SPI_Int_RWFrames(pSPI, pXfSetup, 1); +} + +/* SPI Interrupt Read/Write with 16-bit frame width */ +Status Chip_SPI_Int_RWFrames16Bits(LPC_SPI_T *pSPI, SPI_DATA_SETUP_T *pXfSetup) +{ + return Chip_SPI_Int_RWFrames(pSPI, pXfSetup, 2); +} + +/* Set the clock frequency for SPI interface */ +void Chip_SPI_SetBitRate(LPC_SPI_T *pSPI, uint32_t bitRate) +{ + uint32_t spiClk, counter; + /* Get SPI clock rate */ + spiClk = Chip_Clock_GetPeripheralClockRate(SYSCTL_PCLK_SPI); + + counter = spiClk / bitRate; + if (counter < 8) { + counter = 8; + } + counter = ((counter + 1) / 2) * 2; + + if (counter > 254) { + counter = 254; + } + + Chip_SPI_SetClockCounter(pSPI, counter); +} + +/* Initialize the SPI */ +void Chip_SPI_Init(LPC_SPI_T *pSPI) +{ + Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_SPI); + + Chip_SPI_SetMode(pSPI, SPI_MODE_MASTER); + pSPI->CR = (pSPI->CR & (~0xF1C)) | SPI_CR_BIT_EN | SPI_BITS_8 | SPI_CLOCK_CPHA0_CPOL0 | SPI_DATA_MSB_FIRST; + Chip_SPI_SetBitRate(pSPI, 400000); +} + +/* De-initializes the SPI peripheral */ +void Chip_SPI_DeInit(LPC_SPI_T *pSPI) +{ + Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_SPI); +} + +#endif /* defined(CHIP_LPC175X_6X) */ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/ssp_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/ssp_17xx_40xx.c new file mode 100644 index 000000000..112618e9b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/ssp_17xx_40xx.c @@ -0,0 +1,478 @@ +/* + * @brief LPC17xx/40xx SSP driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +STATIC void SSP_Write2BFifo(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup) +{ + if (xf_setup->tx_data) { + Chip_SSP_SendFrame(pSSP, (*(uint16_t *) ((uint32_t) xf_setup->tx_data + + xf_setup->tx_cnt))); + } + else { + Chip_SSP_SendFrame(pSSP, 0xFFFF); + } + + xf_setup->tx_cnt += 2; +} + +/** SSP macro: write 1 bytes to FIFO buffer */ +STATIC void SSP_Write1BFifo(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup) +{ + if (xf_setup->tx_data) { + Chip_SSP_SendFrame(pSSP, (*(uint8_t *) ((uint32_t) xf_setup->tx_data + xf_setup->tx_cnt))); + } + else { + Chip_SSP_SendFrame(pSSP, 0xFF); + } + + xf_setup->tx_cnt++; +} + +/** SSP macro: read 1 bytes from FIFO buffer */ +STATIC void SSP_Read2BFifo(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup) +{ + uint16_t rDat; + + while ((Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE) == SET) && + (xf_setup->rx_cnt < xf_setup->length)) { + rDat = Chip_SSP_ReceiveFrame(pSSP); + if (xf_setup->rx_data) { + *(uint16_t *) ((uint32_t) xf_setup->rx_data + xf_setup->rx_cnt) = rDat; + } + + xf_setup->rx_cnt += 2; + } +} + +/** SSP macro: read 2 bytes from FIFO buffer */ +STATIC void SSP_Read1BFifo(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup) +{ + uint16_t rDat; + + while ((Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE) == SET) && + (xf_setup->rx_cnt < xf_setup->length)) { + rDat = Chip_SSP_ReceiveFrame(pSSP); + if (xf_setup->rx_data) { + *(uint8_t *) ((uint32_t) xf_setup->rx_data + xf_setup->rx_cnt) = rDat; + } + + xf_setup->rx_cnt++; + } +} + +/* Returns clock for the peripheral block */ +STATIC CHIP_SYSCTL_CLOCK_T Chip_SSP_GetClockIndex(LPC_SSP_T *pSSP) +{ + CHIP_SYSCTL_CLOCK_T clkSSP; + + if (pSSP == LPC_SSP1) { + clkSSP = SYSCTL_CLOCK_SSP1; + } +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + else if (pSSP == LPC_SSP2) { + clkSSP = SYSCTL_CLOCK_SSP2; + } +#endif + else { + clkSSP = SYSCTL_CLOCK_SSP0; + } + + return clkSSP; +} + +#if defined(CHIP_LPC175X_6X) +/* Returns clock ID for the peripheral block */ +STATIC CHIP_SYSCTL_PCLK_T Chip_SSP_GetClkIndex(LPC_SSP_T *pSSP) +{ + CHIP_SYSCTL_PCLK_T clkSSP; + + if (pSSP == LPC_SSP0) { + clkSSP = SYSCTL_PCLK_SSP0; + } + else { + clkSSP = SYSCTL_PCLK_SSP1; + } + + return clkSSP; +} + +#endif + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/*Set up output clocks per bit for SSP bus*/ +void Chip_SSP_SetClockRate(LPC_SSP_T *pSSP, uint32_t clk_rate, uint32_t prescale) +{ + uint32_t temp; + temp = pSSP->CR0 & (~(SSP_CR0_SCR(0xFF))); + pSSP->CR0 = temp | (SSP_CR0_SCR(clk_rate)); + pSSP->CPSR = prescale; +} + +/* SSP Polling Read/Write in blocking mode */ +uint32_t Chip_SSP_RWFrames_Blocking(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup) +{ + /* Clear all remaining frames in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE)) { + Chip_SSP_ReceiveFrame(pSSP); + } + + /* Clear status */ + Chip_SSP_ClearIntPending(pSSP, SSP_INT_CLEAR_BITMASK); + + if (Chip_SSP_GetDataSize(pSSP) > SSP_BITS_8) { + while (xf_setup->rx_cnt < xf_setup->length || xf_setup->tx_cnt < xf_setup->length) { + /* write data to buffer */ + if (( Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF) == SET) && ( xf_setup->tx_cnt < xf_setup->length) ) { + SSP_Write2BFifo(pSSP, xf_setup); + } + + /* Check overrun error */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + SSP_Read2BFifo(pSSP, xf_setup); + } + } + else { + while (xf_setup->rx_cnt < xf_setup->length || xf_setup->tx_cnt < xf_setup->length) { + /* write data to buffer */ + if (( Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF) == SET) && ( xf_setup->tx_cnt < xf_setup->length) ) { + SSP_Write1BFifo(pSSP, xf_setup); + } + + /* Check overrun error */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + SSP_Read1BFifo(pSSP, xf_setup); + } + } + if (xf_setup->tx_data) { + return xf_setup->tx_cnt; + } + else if (xf_setup->rx_data) { + return xf_setup->rx_cnt; + } + + return 0; +} + +/* SSP Polling Write in blocking mode */ +uint32_t Chip_SSP_WriteFrames_Blocking(LPC_SSP_T *pSSP, uint8_t *buffer, uint32_t buffer_len) +{ + uint32_t tx_cnt = 0, rx_cnt = 0; + + /* Clear all remaining frames in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE)) { + Chip_SSP_ReceiveFrame(pSSP); + } + + /* Clear status */ + Chip_SSP_ClearIntPending(pSSP, SSP_INT_CLEAR_BITMASK); + + if (Chip_SSP_GetDataSize(pSSP) > SSP_BITS_8) { + uint16_t *wdata16; + + wdata16 = (uint16_t *) buffer; + + while (tx_cnt < buffer_len || rx_cnt < buffer_len) { + /* write data to buffer */ + if ((Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF) == SET) && (tx_cnt < buffer_len)) { + Chip_SSP_SendFrame(pSSP, *wdata16); + wdata16++; + tx_cnt += 2; + } + + /* Check overrun error */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE) == SET) { + Chip_SSP_ReceiveFrame(pSSP); /* read dummy data */ + rx_cnt += 2; + } + } + } + else { + uint8_t *wdata8; + + wdata8 = buffer; + + while (tx_cnt < buffer_len || rx_cnt < buffer_len) { + /* write data to buffer */ + if ((Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF) == SET) && (tx_cnt < buffer_len)) { + Chip_SSP_SendFrame(pSSP, *wdata8); + wdata8++; + tx_cnt++; + } + + /* Check overrun error */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE) == SET && rx_cnt < buffer_len) { + Chip_SSP_ReceiveFrame(pSSP); /* read dummy data */ + rx_cnt++; + } + } + } + + return tx_cnt; + +} + +/* SSP Polling Read in blocking mode */ +uint32_t Chip_SSP_ReadFrames_Blocking(LPC_SSP_T *pSSP, uint8_t *buffer, uint32_t buffer_len) +{ + uint32_t rx_cnt = 0, tx_cnt = 0; + + /* Clear all remaining frames in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE)) { + Chip_SSP_ReceiveFrame(pSSP); + } + + /* Clear status */ + Chip_SSP_ClearIntPending(pSSP, SSP_INT_CLEAR_BITMASK); + + if (Chip_SSP_GetDataSize(pSSP) > SSP_BITS_8) { + uint16_t *rdata16; + + rdata16 = (uint16_t *) buffer; + + while (tx_cnt < buffer_len || rx_cnt < buffer_len) { + /* write data to buffer */ + if ((Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF) == SET) && (tx_cnt < buffer_len)) { + Chip_SSP_SendFrame(pSSP, 0xFFFF); /* just send dummy data */ + tx_cnt += 2; + } + + /* Check overrun error */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE) == SET && rx_cnt < buffer_len) { + *rdata16 = Chip_SSP_ReceiveFrame(pSSP); + rdata16++; + rx_cnt += 2; + } + } + } + else { + uint8_t *rdata8; + + rdata8 = buffer; + + while (tx_cnt < buffer_len || rx_cnt < buffer_len) { + /* write data to buffer */ + if ((Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF) == SET) && (tx_cnt < buffer_len)) { + Chip_SSP_SendFrame(pSSP, 0xFF); /* just send dummy data */ + tx_cnt++; + } + + /* Check overrun error */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE) == SET && rx_cnt < buffer_len) { + *rdata8 = Chip_SSP_ReceiveFrame(pSSP); + rdata8++; + rx_cnt++; + } + } + } + + return rx_cnt; + +} + +/* Clean all data in RX FIFO of SSP */ +void Chip_SSP_Int_FlushData(LPC_SSP_T *pSSP) +{ + if (Chip_SSP_GetStatus(pSSP, SSP_STAT_BSY)) { + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_BSY)) {} + } + + /* Clear all remaining frames in RX FIFO */ + while (Chip_SSP_GetStatus(pSSP, SSP_STAT_RNE)) { + Chip_SSP_ReceiveFrame(pSSP); + } + + /* Clear status */ + Chip_SSP_ClearIntPending(pSSP, SSP_INT_CLEAR_BITMASK); +} + +/* SSP Interrupt Read/Write with 8-bit frame width */ +Status Chip_SSP_Int_RWFrames8Bits(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup) +{ + /* Check overrun error in RIS register */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + if ((xf_setup->tx_cnt != xf_setup->length) || (xf_setup->rx_cnt != xf_setup->length)) { + /* check if RX FIFO contains data */ + SSP_Read1BFifo(pSSP, xf_setup); + + while ((Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF)) && (xf_setup->tx_cnt != xf_setup->length)) { + /* Write data to buffer */ + SSP_Write1BFifo(pSSP, xf_setup); + + /* Check overrun error in RIS register */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + SSP_Read1BFifo(pSSP, xf_setup); + } + + return SUCCESS; + } + + return ERROR; +} + +/* SSP Interrupt Read/Write with 16-bit frame width */ +Status Chip_SSP_Int_RWFrames16Bits(LPC_SSP_T *pSSP, Chip_SSP_DATA_SETUP_T *xf_setup) +{ + /* Check overrun error in RIS register */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + if ((xf_setup->tx_cnt != xf_setup->length) || (xf_setup->rx_cnt != xf_setup->length)) { + /* check if RX FIFO contains data */ + SSP_Read2BFifo(pSSP, xf_setup); + + while ((Chip_SSP_GetStatus(pSSP, SSP_STAT_TNF)) && (xf_setup->tx_cnt != xf_setup->length)) { + /* Write data to buffer */ + SSP_Write2BFifo(pSSP, xf_setup); + + /* Check overrun error in RIS register */ + if (Chip_SSP_GetRawIntStatus(pSSP, SSP_RORRIS) == SET) { + return ERROR; + } + + /* Check for any data available in RX FIFO */ + SSP_Read2BFifo(pSSP, xf_setup); + } + + return SUCCESS; + } + + return ERROR; +} + +/* Set the SSP operating modes, master or slave */ +void Chip_SSP_SetMaster(LPC_SSP_T *pSSP, bool master) +{ + if (master) { + Chip_SSP_Set_Mode(pSSP, SSP_MODE_MASTER); + } + else { + Chip_SSP_Set_Mode(pSSP, SSP_MODE_SLAVE); + } +} + +/* Set the clock frequency for SSP interface */ +void Chip_SSP_SetBitRate(LPC_SSP_T *pSSP, uint32_t bitRate) +{ + uint32_t ssp_clk, cr0_div, cmp_clk, prescale; + +#if defined(CHIP_LPC175X_6X) + ssp_clk = Chip_Clock_GetPeripheralClockRate(Chip_SSP_GetClkIndex(pSSP)); +#else + ssp_clk = Chip_Clock_GetPeripheralClockRate(); +#endif + + cr0_div = 0; + cmp_clk = 0xFFFFFFFF; + prescale = 2; + + while (cmp_clk > bitRate) { + cmp_clk = ssp_clk / ((cr0_div + 1) * prescale); + if (cmp_clk > bitRate) { + cr0_div++; + if (cr0_div > 0xFF) { + cr0_div = 0; + prescale += 2; + } + } + } + + Chip_SSP_SetClockRate(pSSP, cr0_div, prescale); +} + +/* Initialize the SSP */ +void Chip_SSP_Init(LPC_SSP_T *pSSP) +{ + Chip_Clock_EnablePeriphClock(Chip_SSP_GetClockIndex(pSSP)); + + Chip_SSP_Set_Mode(pSSP, SSP_MODE_MASTER); + Chip_SSP_SetFormat(pSSP, SSP_BITS_8, SSP_FRAMEFORMAT_SPI, SSP_CLOCK_CPHA0_CPOL0); + Chip_SSP_SetBitRate(pSSP, 100000); +} + +/* De-initializes the SSP peripheral */ +void Chip_SSP_DeInit(LPC_SSP_T *pSSP) +{ + Chip_SSP_Disable(pSSP); + + Chip_Clock_DisablePeriphClock(Chip_SSP_GetClockIndex(pSSP)); +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/stopwatch_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/stopwatch_17xx_40xx.c new file mode 100644 index 000000000..856409440 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/stopwatch_17xx_40xx.c @@ -0,0 +1,110 @@ +/* + * @brief LPC17xx_40xx specific stopwatch implementation + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" +#include "stopwatch.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/* Precompute these to optimize runtime */ +static uint32_t ticksPerSecond; +static uint32_t ticksPerMs; +static uint32_t ticksPerUs; + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize stopwatch */ +void StopWatch_Init(void) +{ + /* Use timer 1. Set prescaler to divide by 8, should give ticks at 3.75 MHz. + That gives a useable stopwatch measurement range of about 19 minutes + (if system clock is running at 120 MHz). */ + const uint32_t prescaleDivisor = 8; + Chip_TIMER_Init(LPC_TIMER1); + Chip_TIMER_PrescaleSet(LPC_TIMER1, prescaleDivisor - 1); + Chip_TIMER_Enable(LPC_TIMER1); + + /* Pre-compute tick rate. Note that peripheral clock supplied to the + timer includes a fixed divide by 4. */ + ticksPerSecond = Chip_Clock_GetSystemClockRate() / prescaleDivisor / 4; + ticksPerMs = ticksPerSecond / 1000; + ticksPerUs = ticksPerSecond / 1000000; +} + +/* Start a stopwatch */ +uint32_t StopWatch_Start(void) +{ + /* Return the current timer count. */ + return Chip_TIMER_ReadCount(LPC_TIMER1); +} + +/* Returns number of ticks per second of the stopwatch timer */ +uint32_t StopWatch_TicksPerSecond(void) +{ + return ticksPerSecond; +} + +/* Converts from stopwatch ticks to mS. */ +uint32_t StopWatch_TicksToMs(uint32_t ticks) +{ + return ticks / ticksPerMs; +} + +/* Converts from stopwatch ticks to uS. */ +uint32_t StopWatch_TicksToUs(uint32_t ticks) +{ + return ticks / ticksPerUs; +} + +/* Converts from mS to stopwatch ticks. */ +uint32_t StopWatch_MsToTicks(uint32_t mS) +{ + return mS * ticksPerMs; +} + +/* Converts from uS to stopwatch ticks. */ +uint32_t StopWatch_UsToTicks(uint32_t uS) +{ + return uS * ticksPerUs; +} + diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/sysctl_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/sysctl_17xx_40xx.c new file mode 100644 index 000000000..ec5a3eb39 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/sysctl_17xx_40xx.c @@ -0,0 +1,70 @@ +/* + * @brief LPC17xx/40xx System and Control driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ +/* Returns and clears the current sleep mode entry flags */ +uint32_t Chip_SYSCTL_GetClrSleepFlags(uint32_t flags) { + uint32_t savedFlags = LPC_SYSCTL->PCON; + + LPC_SYSCTL->PCON = flags; + + return savedFlags & (SYSCTL_PD_SMFLAG | SYSCTL_PD_DSFLAG | + SYSCTL_PD_PDFLAG | SYSCTL_PD_DPDFLAG); +} + +#if !defined(CHIP_LPC175X_6X) +/* Resets a peripheral */ +void Chip_SYSCTL_PeriphReset(CHIP_SYSCTL_RESET_T periph) +{ + uint32_t bitIndex, regIndex = (uint32_t) periph; + + /* Get register array index and clock index into the register */ + bitIndex = (regIndex % 32); + regIndex = regIndex / 32; + + /* Reset peripheral */ + LPC_SYSCTL->RSTCON[regIndex] = (1 << bitIndex); + LPC_SYSCTL->RSTCON[regIndex] &= ~(1 << bitIndex); +} + +#endif /*!defined(CHIP_LPC175X_6X)*/ diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/sysinit_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/sysinit_17xx_40xx.c new file mode 100644 index 000000000..2cfb9b318 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/sysinit_17xx_40xx.c @@ -0,0 +1,178 @@ +/* + * @brief LPC17xx/40xx Chip specific SystemInit + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ +#if defined(CHIP_LPC175X_6X) +void Chip_SetupIrcClocking(void) +{ + /* Disconnect the Main PLL if it is connected already */ + if (Chip_Clock_IsMainPLLConnected()) { + Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT); + } + + /* Disable the PLL if it is enabled */ + if (Chip_Clock_IsMainPLLEnabled()) { + Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + } + + Chip_Clock_SetCPUClockDiv(0); + Chip_Clock_SetMainPLLSource(SYSCTL_PLLCLKSRC_IRC); + + /* FCCO = ((44+1) * 2 * 4MHz) / (0+1) = 360MHz */ + Chip_Clock_SetupPLL(SYSCTL_MAIN_PLL, 44, 0); + + Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + + Chip_Clock_SetCPUClockDiv(2); + while (!Chip_Clock_IsMainPLLLocked()) {} /* Wait for the PLL to Lock */ + + Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT); +} + +void Chip_SetupXtalClocking(void) +{ + /* Disconnect the Main PLL if it is connected already */ + if (Chip_Clock_IsMainPLLConnected()) { + Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT); + } + + /* Disable the PLL if it is enabled */ + if (Chip_Clock_IsMainPLLEnabled()) { + Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + } + + /* Enable the crystal */ + if (!Chip_Clock_IsCrystalEnabled()) + Chip_Clock_EnableCrystal(); + while(!Chip_Clock_IsCrystalEnabled()) {} + + /* Set PLL0 Source to Crystal Oscillator */ + Chip_Clock_SetCPUClockDiv(0); + Chip_Clock_SetMainPLLSource(SYSCTL_PLLCLKSRC_MAINOSC); + + /* FCCO = ((15+1) * 2 * 12MHz) / (0+1) = 384MHz */ + Chip_Clock_SetupPLL(SYSCTL_MAIN_PLL, 15, 0); + + Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + + /* 384MHz / (3+1) = 96MHz */ + Chip_Clock_SetCPUClockDiv(3); + while (!Chip_Clock_IsMainPLLLocked()) {} /* Wait for the PLL to Lock */ + + Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT); +} +#endif + +#if (defined(CHIP_LPC177X_8X) | defined(CHIP_LPC40XX)) +/* Clock and PLL initialization based on the internal oscillator */ +void Chip_SetupIrcClocking(void) +{ + /* Clock the CPU from SYSCLK, in case if it is clocked by PLL0 */ + Chip_Clock_SetCPUClockSource(SYSCTL_CCLKSRC_SYSCLK); + + /* Disable the PLL if it is enabled */ + if (Chip_Clock_IsMainPLLEnabled()) { + Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + } + + /* It is safe to switch the PLL Source to IRC */ + Chip_Clock_SetMainPLLSource(SYSCTL_PLLCLKSRC_IRC); + + /* FCCO = 12MHz * (9+1) * 2 * (0+1) = 240MHz */ + /* Fout = FCCO / ((0+1) * 2) = 120MHz */ + Chip_Clock_SetupPLL(SYSCTL_MAIN_PLL, 9, 0); + + Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + Chip_Clock_SetCPUClockDiv(1); + while (!Chip_Clock_IsMainPLLLocked()) {} /* Wait for the PLL to Lock */ + Chip_Clock_SetCPUClockSource(SYSCTL_CCLKSRC_MAINPLL); + + /* Peripheral clocking will be derived from PLL0 with a divider of 2 (60MHz) */ + Chip_Clock_SetPCLKDiv(2); +} + +/* Clock and PLL initialization based on the external oscillator */ +void Chip_SetupXtalClocking(void) +{ + /* Enable the crystal */ + if (!Chip_Clock_IsCrystalEnabled()) + Chip_Clock_EnableCrystal(); + + while(!Chip_Clock_IsCrystalEnabled()) {} + + /* Clock the CPU from SYSCLK, in case if it is clocked by PLL0 */ + Chip_Clock_SetCPUClockSource(SYSCTL_CCLKSRC_SYSCLK); + + /* Disable the PLL if it is enabled */ + if (Chip_Clock_IsMainPLLEnabled()) { + Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + } + + /* It is safe to switch the PLL Source to Crystal Oscillator */ + Chip_Clock_SetMainPLLSource(SYSCTL_PLLCLKSRC_MAINOSC); + + /* FCCO = 12MHz * (9+1) * 2 * (0+1) = 240MHz */ + /* Fout = FCCO / ((0+1) * 2) = 120MHz */ + Chip_Clock_SetupPLL(SYSCTL_MAIN_PLL, 9, 0); + + Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE); + Chip_Clock_SetCPUClockDiv(1); + + while (!Chip_Clock_IsMainPLLLocked()) {} /* Wait for the PLL to Lock */ + Chip_Clock_SetCPUClockSource(SYSCTL_CCLKSRC_MAINPLL); + + /* Peripheral clocking will be derived from PLL0 with a divider of 2 (60MHz) */ + Chip_Clock_SetPCLKDiv(2); +} +#endif + +/* Set up and initialize hardware prior to call to main */ +void Chip_SystemInit(void) +{ + /* Setup Chip clocking */ + Chip_SetupIrcClocking(); +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/timer_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/timer_17xx_40xx.c new file mode 100644 index 000000000..224adc33c --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/timer_17xx_40xx.c @@ -0,0 +1,116 @@ +/* + * @brief LPC17xx/40xx 16/32-bit Timer/PWM driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/* Returns clock for the peripheral block */ +STATIC CHIP_SYSCTL_CLOCK_T Chip_Timer_GetClockIndex(LPC_TIMER_T *pTMR) +{ + CHIP_SYSCTL_CLOCK_T clkTMR; + + if (pTMR == LPC_TIMER1) { + clkTMR = SYSCTL_CLOCK_TIMER1; + } + else if (pTMR == LPC_TIMER2) { + clkTMR = SYSCTL_CLOCK_TIMER2; + } + else if (pTMR == LPC_TIMER3) { + clkTMR = SYSCTL_CLOCK_TIMER3; + } + else { + clkTMR = SYSCTL_CLOCK_TIMER0; + } + + return clkTMR; +} + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize a timer */ +void Chip_TIMER_Init(LPC_TIMER_T *pTMR) +{ + Chip_Clock_EnablePeriphClock(Chip_Timer_GetClockIndex(pTMR)); +} + +/* Shutdown a timer */ +void Chip_TIMER_DeInit(LPC_TIMER_T *pTMR) +{ + Chip_Clock_DisablePeriphClock(Chip_Timer_GetClockIndex(pTMR)); +} + +/* Resets the timer terminal and prescale counts to 0 */ +void Chip_TIMER_Reset(LPC_TIMER_T *pTMR) +{ + uint32_t reg; + + /* Disable timer, set terminal count to non-0 */ + reg = pTMR->TCR; + pTMR->TCR = 0; + pTMR->TC = 1; + + /* Reset timer counter */ + pTMR->TCR = TIMER_RESET; + + /* Wait for terminal count to clear */ + while (pTMR->TC != 0) {} + + /* Restore timer state */ + pTMR->TCR = reg; +} + +/* Sets external match control (MATn.matchnum) pin control */ +void Chip_TIMER_ExtMatchControlSet(LPC_TIMER_T *pTMR, int8_t initial_state, + TIMER_PIN_MATCH_STATE_T matchState, int8_t matchnum) +{ + uint32_t mask, reg; + + /* Clear bits corresponding to selected match register */ + mask = (1 << matchnum) | (0x03 << (4 + (matchnum * 2))); + reg = pTMR->EMR &= ~mask; + + /* Set new configuration for selected match register */ + pTMR->EMR = reg | (((uint32_t) initial_state) << matchnum) | + (((uint32_t) matchState) << (4 + (matchnum * 2))); +} diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/uart_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/uart_17xx_40xx.c new file mode 100644 index 000000000..88555bdf3 --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/uart_17xx_40xx.c @@ -0,0 +1,533 @@ +/* + * @brief LPC11xx UART chip driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/* Autobaud status flag */ +STATIC volatile FlagStatus ABsyncSts = RESET; + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/* Returns clock for the peripheral block */ +STATIC CHIP_SYSCTL_CLOCK_T Chip_UART_GetClockIndex(LPC_USART_T *pUART) +{ + CHIP_SYSCTL_CLOCK_T clkUART; + + if (pUART == LPC_UART1) { + clkUART = SYSCTL_CLOCK_UART1; + } + else if (pUART == LPC_UART2) { + clkUART = SYSCTL_CLOCK_UART2; + } + else if (pUART == LPC_UART3) { + clkUART = SYSCTL_CLOCK_UART3; + } +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + else if (pUART == LPC_UART4) { + clkUART = SYSCTL_CLOCK_UART4; + } +#endif + else { + clkUART = SYSCTL_CLOCK_UART0; + } + + return clkUART; +} + +/* UART Autobaud command interrupt handler */ +STATIC void Chip_UART_ABIntHandler(LPC_USART_T *pUART) +{ + /* Handle End Of Autobaud interrupt */ + if((Chip_UART_ReadIntIDReg(pUART) & UART_IIR_ABEO_INT) != 0) { + Chip_UART_SetAutoBaudReg(pUART, UART_ACR_ABEOINT_CLR); + Chip_UART_IntDisable(pUART, UART_IER_ABEOINT); + if (ABsyncSts == RESET) { + ABsyncSts = SET; + } + } + + /* Handle Autobaud Timeout interrupt */ + if((Chip_UART_ReadIntIDReg(pUART) & UART_IIR_ABTO_INT) != 0) { + Chip_UART_SetAutoBaudReg(pUART, UART_ACR_ABTOINT_CLR); + Chip_UART_IntDisable(pUART, UART_IER_ABTOINT); + } +} + +#if defined(CHIP_LPC175X_6X) +/* Returns clock ID for the peripheral block */ +STATIC CHIP_SYSCTL_PCLK_T Chip_UART_GetClkIndex(LPC_USART_T *pUART) +{ + CHIP_SYSCTL_PCLK_T clkUART; + + if (pUART == LPC_UART1) { + clkUART = SYSCTL_PCLK_UART1; + } + else if (pUART == LPC_UART2) { + clkUART = SYSCTL_PCLK_UART2; + } + else if (pUART == LPC_UART3) { + clkUART = SYSCTL_PCLK_UART3; + } + else { + clkUART = SYSCTL_PCLK_UART0; + } + + return clkUART; +} +#endif + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initializes the pUART peripheral */ +void Chip_UART_Init(LPC_USART_T *pUART) +{ + uint32_t tmp; + + (void) tmp; + + /* Enable UART clocking. UART base clock(s) must already be enabled */ + Chip_Clock_EnablePeriphClock(Chip_UART_GetClockIndex(pUART)); + + /* Enable FIFOs by default, reset them */ + Chip_UART_SetupFIFOS(pUART, (UART_FCR_FIFO_EN | UART_FCR_RX_RS | UART_FCR_TX_RS)); + + /* Disable Tx */ + Chip_UART_TXDisable(pUART); + + /* Disable interrupts */ + pUART->IER = 0; + /* Set LCR to default state */ + pUART->LCR = 0; + /* Set ACR to default state */ + pUART->ACR = 0; + /* Set RS485 control to default state */ + pUART->RS485CTRL = 0; + /* Set RS485 delay timer to default state */ + pUART->RS485DLY = 0; + /* Set RS485 addr match to default state */ + pUART->RS485ADRMATCH = 0; + + /* Clear MCR */ + if (pUART == LPC_UART1) { + /* Set Modem Control to default state */ + pUART->MCR = 0; + /*Dummy Reading to Clear Status */ + tmp = pUART->MSR; + } + + /* Default 8N1, with DLAB disabled */ + Chip_UART_ConfigData(pUART, (UART_LCR_WLEN8 | UART_LCR_SBS_1BIT | UART_LCR_PARITY_DIS)); + + /* Disable fractional divider */ + pUART->FDR = 0x10; +} + +/* De-initializes the pUART peripheral */ +void Chip_UART_DeInit(LPC_USART_T *pUART) +{ + /* Disable Tx */ + Chip_UART_TXDisable(pUART); + + /* Disable clock */ + Chip_Clock_DisablePeriphClock(Chip_UART_GetClockIndex(pUART)); +} + +/* Enable transmission on UART TxD pin */ +void Chip_UART_TXEnable(LPC_USART_T *pUART) +{ +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + if(pUART == LPC_UART4) { + pUART->TER2 = UART_TER2_TXEN; + } + else { +#endif + pUART->TER1 = UART_TER1_TXEN; +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + } +#endif +} + +/* Disable transmission on UART TxD pin */ +void Chip_UART_TXDisable(LPC_USART_T *pUART) +{ +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + if(pUART == LPC_UART4) { + pUART->TER2 = 0; + } + else { +#endif + pUART->TER1 = 0; +#if defined(CHIP_LPC177X_8X) || defined(CHIP_LPC40XX) + } +#endif +} + +/* Transmit a byte array through the UART peripheral (non-blocking) */ +int Chip_UART_Send(LPC_USART_T *pUART, const void *data, int numBytes) +{ + int sent = 0; + uint8_t *p8 = (uint8_t *) data; + + /* Send until the transmit FIFO is full or out of bytes */ + while ((sent < numBytes) && + ((Chip_UART_ReadLineStatus(pUART) & UART_LSR_THRE) != 0)) { + Chip_UART_SendByte(pUART, *p8); + p8++; + sent++; + } + + return sent; +} + +/* Check whether if UART is busy or not */ +FlagStatus Chip_UART_CheckBusy(LPC_USART_T *pUART) +{ + if (pUART->LSR & UART_LSR_TEMT) { + return RESET; + } + else { + return SET; + } +} + +/* Transmit a byte array through the UART peripheral (blocking) */ +int Chip_UART_SendBlocking(LPC_USART_T *pUART, const void *data, int numBytes) +{ + int pass, sent = 0; + uint8_t *p8 = (uint8_t *) data; + + while (numBytes > 0) { + pass = Chip_UART_Send(pUART, p8, numBytes); + numBytes -= pass; + sent += pass; + p8 += pass; + } + + return sent; +} + +/* Read data through the UART peripheral (non-blocking) */ +int Chip_UART_Read(LPC_USART_T *pUART, void *data, int numBytes) +{ + int readBytes = 0; + uint8_t *p8 = (uint8_t *) data; + + /* Send until the transmit FIFO is full or out of bytes */ + while ((readBytes < numBytes) && + ((Chip_UART_ReadLineStatus(pUART) & UART_LSR_RDR) != 0)) { + *p8 = Chip_UART_ReadByte(pUART); + p8++; + readBytes++; + } + + return readBytes; +} + +/* Read data through the UART peripheral (blocking) */ +int Chip_UART_ReadBlocking(LPC_USART_T *pUART, void *data, int numBytes) +{ + int pass, readBytes = 0; + uint8_t *p8 = (uint8_t *) data; + + while (readBytes < numBytes) { + pass = Chip_UART_Read(pUART, p8, numBytes); + numBytes -= pass; + readBytes += pass; + p8 += pass; + } + + return readBytes; +} + +/* Determines and sets best dividers to get a target bit rate */ +uint32_t Chip_UART_SetBaud(LPC_USART_T *pUART, uint32_t baudrate) +{ + uint32_t div, divh, divl, clkin; + + /* Determine UART clock in rate without FDR */ +#if defined(CHIP_LPC175X_6X) + clkin = Chip_Clock_GetPeripheralClockRate(Chip_UART_GetClkIndex(pUART)); +#else + clkin = Chip_Clock_GetPeripheralClockRate(); +#endif + div = clkin / (baudrate * 16); + + /* High and low halves of the divider */ + divh = div / 256; + divl = div - (divh * 256); + + Chip_UART_EnableDivisorAccess(pUART); + Chip_UART_SetDivisorLatches(pUART, divl, divh); + Chip_UART_DisableDivisorAccess(pUART); + + /* Fractional FDR already setup for 1 in UART init */ + + return clkin / div; +} + +/* UART receive-only interrupt handler for ring buffers */ +void Chip_UART_RXIntHandlerRB(LPC_USART_T *pUART, RINGBUFF_T *pRB) +{ + /* New data will be ignored if data not popped in time */ + while (Chip_UART_ReadLineStatus(pUART) & UART_LSR_RDR) { + uint8_t ch = Chip_UART_ReadByte(pUART); + RingBuffer_Insert(pRB, &ch); + } +} + +/* UART transmit-only interrupt handler for ring buffers */ +void Chip_UART_TXIntHandlerRB(LPC_USART_T *pUART, RINGBUFF_T *pRB) +{ + uint8_t ch; + + /* Fill FIFO until full or until TX ring buffer is empty */ + while ((Chip_UART_ReadLineStatus(pUART) & UART_LSR_THRE) != 0 && + RingBuffer_Pop(pRB, &ch)) { + Chip_UART_SendByte(pUART, ch); + } +} + +/* Populate a transmit ring buffer and start UART transmit */ +uint32_t Chip_UART_SendRB(LPC_USART_T *pUART, RINGBUFF_T *pRB, const void *data, int bytes) +{ + uint32_t ret; + uint8_t *p8 = (uint8_t *) data; + + /* Don't let UART transmit ring buffer change in the UART IRQ handler */ + Chip_UART_IntDisable(pUART, UART_IER_THREINT); + + /* Move as much data as possible into transmit ring buffer */ + ret = RingBuffer_InsertMult(pRB, p8, bytes); + Chip_UART_TXIntHandlerRB(pUART, pRB); + + /* Add additional data to transmit ring buffer if possible */ + ret += RingBuffer_InsertMult(pRB, (p8 + ret), (bytes - ret)); + + /* Enable UART transmit interrupt */ + Chip_UART_IntEnable(pUART, UART_IER_THREINT); + + return ret; +} + +/* Copy data from a receive ring buffer */ +int Chip_UART_ReadRB(LPC_USART_T *pUART, RINGBUFF_T *pRB, void *data, int bytes) +{ + (void) pUART; + + return RingBuffer_PopMult(pRB, (uint8_t *) data, bytes); +} + +/* UART receive/transmit interrupt handler for ring buffers */ +void Chip_UART_IRQRBHandler(LPC_USART_T *pUART, RINGBUFF_T *pRXRB, RINGBUFF_T *pTXRB) +{ + /* Handle transmit interrupt if enabled */ + if (pUART->IER & UART_IER_THREINT) { + Chip_UART_TXIntHandlerRB(pUART, pTXRB); + + /* Disable transmit interrupt if the ring buffer is empty */ + if (RingBuffer_IsEmpty(pTXRB)) { + Chip_UART_IntDisable(pUART, UART_IER_THREINT); + } + } + + /* Handle receive interrupt */ + Chip_UART_RXIntHandlerRB(pUART, pRXRB); + + /* Handle Autobaud interrupts */ + Chip_UART_ABIntHandler(pUART); +} + +/* Determines and sets best dividers to get a target baud rate */ +uint32_t Chip_UART_SetBaudFDR(LPC_USART_T *pUART, uint32_t baudrate) + +{ + uint32_t uClk; + uint32_t actualRate = 0, d, m, bestd, bestm, tmp; + uint32_t current_error, best_error; + uint64_t best_divisor, divisor; + uint32_t recalcbaud; + + /* Get Clock rate */ +#if defined(CHIP_LPC175X_6X) + uClk = Chip_Clock_GetPeripheralClockRate(Chip_UART_GetClkIndex(pUART)); +#else + uClk = Chip_Clock_GetPeripheralClockRate(); +#endif + + /* In the Uart IP block, baud rate is calculated using FDR and DLL-DLM registers + * The formula is : + * BaudRate= uClk * (mulFracDiv/(mulFracDiv+dividerAddFracDiv) / (16 * (DLL) + * It involves floating point calculations. That's the reason the formulae are adjusted with + * Multiply and divide method.*/ + /* The value of mulFracDiv and dividerAddFracDiv should comply to the following expressions: + * 0 < mulFracDiv <= 15, 0 <= dividerAddFracDiv <= 15 */ + best_error = 0xFFFFFFFF;/* Worst case */ + bestd = 0; + bestm = 0; + best_divisor = 0; + for (m = 1; m <= 15; m++) { + for (d = 0; d < m; d++) { + + /* The result here is a fixed point number. The integer portion is in the upper 32 bits. + * The fractional portion is in the lower 32 bits. + */ + divisor = ((uint64_t) uClk << 28) * m / (baudrate * (m + d)); + + /* The fractional portion is the error. */ + current_error = divisor & 0xFFFFFFFF; + + /* Snag the integer portion of the divisor. */ + tmp = divisor >> 32; + + /* If closer to the next divisor... */ + if (current_error > ((uint32_t) 1 << 31)) { + + /* Increment to the next divisor... */ + tmp++; + + /* Now the error is the distance to the next divisor... */ + current_error = -current_error; + } + + /* Can't use a divisor that's less than 1 or more than 65535. */ + if ((tmp < 1) || (tmp > 65535)) { + /* Out of range */ + continue; + } + + /* Also, if fractional divider is enabled can't use a divisor that is less than 3. */ + if ((d != 0) && (tmp < 3)) { + /* Out of range */ + continue; + } + + /* Do we have a new best? */ + if (current_error < best_error) { + best_error = current_error; + best_divisor = tmp; + bestd = d; + bestm = m; + + /* If error is 0, that's perfect. We're done. */ + if (best_error == 0) { + break; + } + } + } /* for (d) */ + + /* If error is 0, that's perfect. We're done. */ + if (best_error == 0) { + break; + } + } /* for (m) */ + + if (best_divisor == 0) { + /* can not find best match */ + return 0; + } + + recalcbaud = (uClk >> 4) * bestm / (best_divisor * (bestm + bestd)); + + /* reuse best_error to evaluate baud error */ + if (baudrate > recalcbaud) { + best_error = baudrate - recalcbaud; + } + else { + best_error = recalcbaud - baudrate; + } + + best_error = (best_error * 100) / baudrate; + + /* Update UART registers */ + Chip_UART_EnableDivisorAccess(pUART); + Chip_UART_SetDivisorLatches(pUART, UART_LOAD_DLL(best_divisor), UART_LOAD_DLM(best_divisor)); + Chip_UART_DisableDivisorAccess(pUART); + + /* Set best fractional divider */ + pUART->FDR = (UART_FDR_MULVAL(bestm) | UART_FDR_DIVADDVAL(bestd)); + + /* Return actual baud rate */ + actualRate = recalcbaud; + + return actualRate; +} + +/* UART interrupt service routine */ +FlagStatus Chip_UART_GetABEOStatus(LPC_USART_T *pUART) +{ + (void) pUART; + return ABsyncSts; +} + +/* Start/Stop Auto Baudrate activity */ +void Chip_UART_ABCmd(LPC_USART_T *pUART, uint32_t mode, bool autorestart, FunctionalState NewState) +{ + uint32_t tmp = 0; + + if (NewState == ENABLE) { + /* Clear DLL and DLM value */ + pUART->LCR |= UART_LCR_DLAB_EN; + pUART->DLL = 0; + pUART->DLM = 0; + pUART->LCR &= ~UART_LCR_DLAB_EN; + + /* FDR value must be reset to default value */ + pUART->FDR = 0x10; + + if (mode == UART_ACR_MODE1) { + tmp = UART_ACR_START | UART_ACR_MODE; + } + else { + tmp = UART_ACR_START; + } + + if (autorestart == true) { + tmp |= UART_ACR_AUTO_RESTART; + } + pUART->ACR = tmp; + } + else { + pUART->ACR = 0; + } +} + diff --git a/hw/mcu/nxp/lpc_chip_40xx/src/wwdt_17xx_40xx.c b/hw/mcu/nxp/lpc_chip_40xx/src/wwdt_17xx_40xx.c new file mode 100644 index 000000000..ad3121e5b --- /dev/null +++ b/hw/mcu/nxp/lpc_chip_40xx/src/wwdt_17xx_40xx.c @@ -0,0 +1,72 @@ +/* + * @brief LPC17xx/40xx WWDT chip driver + * + * @note + * Copyright(C) NXP Semiconductors, 2014 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the Watchdog timer */ +void Chip_WWDT_Init(LPC_WWDT_T *pWWDT) +{ + /* Disable watchdog */ + pWWDT->MOD = 0; + pWWDT->TC = 0xFF; +#if defined(WATCHDOG_WINDOW_SUPPORT) + pWWDT->WARNINT = 0xFFFF; + pWWDT->WINDOW = 0xFFFFFF; +#endif +} + +/* Clear WWDT interrupt status flags */ +void Chip_WWDT_ClearStatusFlag(LPC_WWDT_T *pWWDT, uint32_t status) +{ + if (status & WWDT_WDMOD_WDTOF) { + pWWDT->MOD &= (~WWDT_WDMOD_WDTOF) & WWDT_WDMOD_BITMASK; + } + + if (status & WWDT_WDMOD_WDINT) { + pWWDT->MOD |= WWDT_WDMOD_WDINT; + } +} diff --git a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c similarity index 96% rename from src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c rename to src/portable/nxp/lpc17_40/dcd_lpc17_40.c index e94670a92..549420f22 100644 --- a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c +++ b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c @@ -1,590 +1,590 @@ -/**************************************************************************/ -/*! - @file dcd_lpc175x_6x.c - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, hathach (tinyusb.org) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. 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. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 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. - - This file is part of the tinyusb stack. -*/ -/**************************************************************************/ - -#include "tusb_option.h" - -#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X) - -#include "device/dcd.h" -#include "dcd_lpc175x_6x.h" -#include "chip.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -#define DCD_ENDPOINT_MAX 32 - -typedef struct ATTR_ALIGNED(4) -{ - //------------- Word 0 -------------// - uint32_t next; - - //------------- Word 1 -------------// - uint16_t atle_mode : 2; // 00: normal, 01: ATLE (auto length extraction) - uint16_t next_valid : 1; - uint16_t : 1; ///< reserved - uint16_t isochronous : 1; // is an iso endpoint - uint16_t max_packet_size : 11; - - volatile uint16_t buflen; // bytes for non-iso, number of packets for iso endpoint - - //------------- Word 2 -------------// - volatile uint32_t buffer; - - //------------- Word 3 -------------// - volatile uint16_t retired : 1; // initialized to zero - volatile uint16_t status : 4; - volatile uint16_t iso_last_packet_valid : 1; - volatile uint16_t atle_lsb_extracted : 1; // used in ATLE mode - volatile uint16_t atle_msb_extracted : 1; // used in ATLE mode - volatile uint16_t atle_mess_len_position : 6; // used in ATLE mode - uint16_t : 2; - - volatile uint16_t present_count; // For non-iso : The number of bytes transferred by the DMA engine - // For iso : number of packets - - //------------- Word 4 -------------// - // uint32_t iso_packet_size_addr; // iso only, can be omitted for non-iso -}dma_desc_t; - -TU_VERIFY_STATIC( sizeof(dma_desc_t) == 16, "size is not correct"); // TODO not support ISO for now - -typedef struct -{ - // must be 128 byte aligned - volatile dma_desc_t* udca[DCD_ENDPOINT_MAX]; - - // TODO DMA does not support control transfer (0-1 are not used, offset to reduce memory) - dma_desc_t dd[DCD_ENDPOINT_MAX]; - - struct - { - uint8_t* out_buffer; - uint8_t out_bytes; - volatile bool out_received; // indicate if data is already received in endpoint - - uint8_t in_bytes; - } control; - -} dcd_data_t; - -ATTR_ALIGNED(128) static dcd_data_t _dcd; - - -//--------------------------------------------------------------------+ -// SIE Command -//--------------------------------------------------------------------+ -static void sie_cmd_code (sie_cmdphase_t phase, uint8_t code_data) -{ - LPC_USB->DevIntClr = (DEV_INT_COMMAND_CODE_EMPTY_MASK | DEV_INT_COMMAND_DATA_FULL_MASK); - LPC_USB->CmdCode = (phase << 8) | (code_data << 16); - - uint32_t const wait_flag = (phase == SIE_CMDPHASE_READ) ? DEV_INT_COMMAND_DATA_FULL_MASK : DEV_INT_COMMAND_CODE_EMPTY_MASK; - while ((LPC_USB->DevIntSt & wait_flag) == 0) {} - - LPC_USB->DevIntClr = wait_flag; -} - -static void sie_write (uint8_t cmd_code, uint8_t data_len, uint8_t data) -{ - sie_cmd_code(SIE_CMDPHASE_COMMAND, cmd_code); - - if (data_len) - { - sie_cmd_code(SIE_CMDPHASE_WRITE, data); - } -} - -static uint8_t sie_read (uint8_t cmd_code) -{ - sie_cmd_code(SIE_CMDPHASE_COMMAND , cmd_code); - sie_cmd_code(SIE_CMDPHASE_READ , cmd_code); - return (uint8_t) LPC_USB->CmdData; -} - -//--------------------------------------------------------------------+ -// PIPE HELPER -//--------------------------------------------------------------------+ -static inline uint8_t ep_addr2idx(uint8_t ep_addr) -{ - return 2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0); -} - -static void set_ep_size(uint8_t ep_id, uint16_t max_packet_size) -{ - // follows example in 11.10.4.2 - LPC_USB->ReEp |= BIT_(ep_id); - LPC_USB->EpInd = ep_id; // select index before setting packet size - LPC_USB->MaxPSize = max_packet_size; - - while ((LPC_USB->DevIntSt & DEV_INT_ENDPOINT_REALIZED_MASK) == 0) {} - LPC_USB->DevIntClr = DEV_INT_ENDPOINT_REALIZED_MASK; -} - - -//--------------------------------------------------------------------+ -// CONTROLLER API -//--------------------------------------------------------------------+ -static void bus_reset(void) -{ - // step 7 : slave mode set up - LPC_USB->EpIntClr = 0xFFFFFFFF; // clear all pending interrupt - LPC_USB->DevIntClr = 0xFFFFFFFF; // clear all pending interrupt - LPC_USB->EpIntEn = 0x03UL; // control endpoint cannot use DMA, non-control all use DMA - LPC_USB->EpIntPri = 0x03UL; // fast for control endpoint - - // step 8 : DMA set up - LPC_USB->EpDMADis = 0xFFFFFFFF; // firstly disable all dma - LPC_USB->DMARClr = 0xFFFFFFFF; // clear all pending interrupt - LPC_USB->EoTIntClr = 0xFFFFFFFF; - LPC_USB->NDDRIntClr = 0xFFFFFFFF; - LPC_USB->SysErrIntClr = 0xFFFFFFFF; - - tu_memclr(&_dcd, sizeof(dcd_data_t)); -} - -bool dcd_init(uint8_t rhport) -{ - (void) rhport; - - //------------- user manual 11.13 usb device controller initialization -------------// - // step 6 : set up control endpoint - set_ep_size(0, CFG_TUD_ENDOINT0_SIZE); - set_ep_size(1, CFG_TUD_ENDOINT0_SIZE); - - bus_reset(); - - LPC_USB->DevIntEn = (DEV_INT_DEVICE_STATUS_MASK | DEV_INT_ENDPOINT_FAST_MASK | DEV_INT_ENDPOINT_SLOW_MASK | DEV_INT_ERROR_MASK); - LPC_USB->UDCAH = (uint32_t) _dcd.udca; - LPC_USB->DMAIntEn = (DMA_INT_END_OF_XFER_MASK /*| DMA_INT_NEW_DD_REQUEST_MASK*/ | DMA_INT_ERROR_MASK); - - sie_write(SIE_CMDCODE_DEVICE_STATUS, 1, 1); // connect - - // USB IRQ priority should be set by application previously - NVIC_ClearPendingIRQ(USB_IRQn); - NVIC_EnableIRQ(USB_IRQn); - - return TUSB_ERROR_NONE; -} - -void dcd_connect(uint8_t rhport) -{ - (void) rhport; - sie_write(SIE_CMDCODE_DEVICE_STATUS, 1, 1); -} - -void dcd_set_address(uint8_t rhport, uint8_t dev_addr) -{ - (void) rhport; - sie_write(SIE_CMDCODE_SET_ADDRESS, 1, 0x80 | dev_addr); // 7th bit is : device_enable -} - -void dcd_set_config(uint8_t rhport, uint8_t config_num) -{ - (void) rhport; - (void) config_num; - sie_write(SIE_CMDCODE_CONFIGURE_DEVICE, 1, 1); -} - -//--------------------------------------------------------------------+ -// CONTROL HELPER -//--------------------------------------------------------------------+ -static inline uint8_t byte2dword(uint8_t bytes) -{ - return (bytes + 3) / 4; // length in dwords -} - -static void control_ep_write(void const * buffer, uint8_t len) -{ - uint32_t const * buf32 = (uint32_t const *) buffer; - - LPC_USB->Ctrl = USBCTRL_WRITE_ENABLE_MASK; // logical endpoint = 0 - LPC_USB->TxPLen = (uint32_t) len; - - for (uint8_t count = 0; count < byte2dword(len); count++) - { - LPC_USB->TxData = *buf32; // NOTE: cortex M3 have no problem with alignment - buf32++; - } - - LPC_USB->Ctrl = 0; - - // select control IN & validate the endpoint - sie_write(SIE_CMDCODE_ENDPOINT_SELECT+1, 0, 0); - sie_write(SIE_CMDCODE_BUFFER_VALIDATE , 0, 0); -} - -static uint8_t control_ep_read(void * buffer, uint8_t len) -{ - LPC_USB->Ctrl = USBCTRL_READ_ENABLE_MASK; // logical endpoint = 0 - while ((LPC_USB->RxPLen & USBRXPLEN_PACKET_READY_MASK) == 0) {} // TODO blocking, should have timeout - - len = tu_min8(len, (uint8_t) (LPC_USB->RxPLen & USBRXPLEN_PACKET_LENGTH_MASK) ); - uint32_t *buf32 = (uint32_t*) buffer; - - for (uint8_t count=0; count < byte2dword(len); count++) - { - *buf32 = LPC_USB->RxData; - buf32++; - } - - LPC_USB->Ctrl = 0; - - // select control OUT & clear the endpoint - sie_write(SIE_CMDCODE_ENDPOINT_SELECT+0, 0, 0); - sie_write(SIE_CMDCODE_BUFFER_CLEAR , 0, 0); - - return len; -} - -//--------------------------------------------------------------------+ -// DCD Endpoint Port -//--------------------------------------------------------------------+ -bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) -{ - (void) rhport; - - uint8_t const epnum = edpt_number(p_endpoint_desc->bEndpointAddress); - uint8_t const ep_id = ep_addr2idx(p_endpoint_desc->bEndpointAddress); - - // Endpoint type is fixed to endpoint number - // 1: interrupt, 2: Bulk, 3: Iso and so on - switch ( p_endpoint_desc->bmAttributes.xfer ) - { - case TUSB_XFER_INTERRUPT: - TU_ASSERT((epnum % 3) == 1); - break; - - case TUSB_XFER_BULK: - TU_ASSERT((epnum % 3) == 2 || (epnum == 15)); - break; - - case TUSB_XFER_ISOCHRONOUS: - TU_ASSERT((epnum % 3) == 3 && (epnum != 15)); - break; - - default: - break; - } - - //------------- Realize Endpoint with Max Packet Size -------------// - set_ep_size(ep_id, p_endpoint_desc->wMaxPacketSize.size); - - //------------- first DD prepare -------------// - dma_desc_t* const dd = &_dcd.dd[ep_id]; - tu_memclr(dd, sizeof(dma_desc_t)); - - dd->isochronous = (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) ? 1 : 0; - dd->max_packet_size = p_endpoint_desc->wMaxPacketSize.size; - dd->retired = 1; // invalid at first - - sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS + ep_id, 1, 0); // clear all endpoint status - - return true; -} - -bool dcd_edpt_busy(uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - - uint8_t ep_id = ep_addr2idx( ep_addr ); - return (_dcd.udca[ep_id] != NULL && !_dcd.udca[ep_id]->retired); -} - -void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - - if ( edpt_number(ep_addr) == 0 ) - { - sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+0, 1, SIE_SET_ENDPOINT_STALLED_MASK | SIE_SET_ENDPOINT_CONDITION_STALLED_MASK); - }else - { - uint8_t ep_id = ep_addr2idx( ep_addr ); - sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+ep_id, 1, SIE_SET_ENDPOINT_STALLED_MASK); - } -} - -void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - uint8_t ep_id = ep_addr2idx(ep_addr); - - sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+ep_id, 1, 0); -} - -bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - - uint8_t const ep_state = sie_read(SIE_CMDCODE_ENDPOINT_SELECT + ep_addr2idx(ep_addr)); - return (ep_state & SIE_SELECT_ENDPOINT_STALL_MASK) ? true : false; -} - -static bool control_xact(uint8_t rhport, uint8_t dir, uint8_t * buffer, uint8_t len) -{ - (void) rhport; - - if ( dir ) - { - _dcd.control.in_bytes = len; - control_ep_write(buffer, len); - }else - { - if ( _dcd.control.out_received ) - { - // Already received the DATA OUT packet - _dcd.control.out_received = false; - _dcd.control.out_buffer = NULL; - _dcd.control.out_bytes = 0; - - uint8_t received = control_ep_read(buffer, len); - dcd_event_xfer_complete(0, 0, received, XFER_RESULT_SUCCESS, true); - }else - { - _dcd.control.out_buffer = buffer; - _dcd.control.out_bytes = len; - } - } - - return true; -} - -bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) -{ - // Control transfer is not DMA support, and must be done in slave mode - if ( edpt_number(ep_addr) == 0 ) - { - return control_xact(rhport, edpt_dir(ep_addr), buffer, (uint8_t) total_bytes); - } - else - { - uint8_t ep_id = ep_addr2idx(ep_addr); - dma_desc_t* dd = &_dcd.dd[ep_id]; - - // Prepare DMA descriptor - // Isochronous & max packet size must be preserved, Other fields of dd should be clear - uint16_t const ep_size = dd->max_packet_size; - uint8_t is_iso = dd->isochronous; - - tu_memclr(dd, sizeof(dma_desc_t)); - dd->isochronous = is_iso; - dd->max_packet_size = ep_size; - dd->buffer = (uint32_t) buffer; - dd->buflen = total_bytes; - - _dcd.udca[ep_id] = dd; - - if ( ep_id % 2 ) - { - // Clear EP interrupt before Enable DMA - LPC_USB->EpIntEn &= ~BIT_(ep_id); - LPC_USB->EpDMAEn = BIT_(ep_id); - - // endpoint IN need to actively raise DMA request - LPC_USB->DMARSet = BIT_(ep_id); - }else - { - // Enable DMA - LPC_USB->EpDMAEn = BIT_(ep_id); - } - - return true; - } -} - -//--------------------------------------------------------------------+ -// ISR -//--------------------------------------------------------------------+ - -// handle control xfer (slave mode) -static void control_xfer_isr(uint8_t rhport, uint32_t ep_int_status) -{ - // Control out complete - if ( ep_int_status & BIT_(0) ) - { - bool is_setup = sie_read(SIE_CMDCODE_ENDPOINT_SELECT+0) & SIE_SELECT_ENDPOINT_SETUP_RECEIVED_MASK; - - LPC_USB->EpIntClr = BIT_(0); - - if (is_setup) - { - uint8_t setup_packet[8]; - control_ep_read(setup_packet, 8); // TODO read before clear setup above - - dcd_event_setup_received(rhport, setup_packet, true); - } - else if ( _dcd.control.out_buffer ) - { - // software queued transfer previously - uint8_t received = control_ep_read(_dcd.control.out_buffer, _dcd.control.out_bytes); - - _dcd.control.out_buffer = NULL; - _dcd.control.out_bytes = 0; - - dcd_event_xfer_complete(rhport, 0, received, XFER_RESULT_SUCCESS, true); - }else - { - // hardware auto ack packet -> mark as received - _dcd.control.out_received = true; - } - } - - // Control In complete - if ( ep_int_status & BIT_(1) ) - { - LPC_USB->EpIntClr = BIT_(1); - dcd_event_xfer_complete(rhport, TUSB_DIR_IN_MASK, _dcd.control.in_bytes, XFER_RESULT_SUCCESS, true); - } -} - -// handle bus event signal -static void bus_event_isr(uint8_t rhport) -{ - uint8_t const dev_status = sie_read(SIE_CMDCODE_DEVICE_STATUS); - if (dev_status & SIE_DEV_STATUS_RESET_MASK) - { - bus_reset(); - dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); - } - - if (dev_status & SIE_DEV_STATUS_CONNECT_CHANGE_MASK) - { - // device is disconnected, require using VBUS (P1_30) - dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true); - } - - if (dev_status & SIE_DEV_STATUS_SUSPEND_CHANGE_MASK) - { - if (dev_status & SIE_DEV_STATUS_SUSPEND_MASK) - { - dcd_event_bus_signal(rhport, DCD_EVENT_SUSPENDED, true); - } - else - { - dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); - } - } -} - -// Helper to complete a DMA descriptor for non-control transfer -static void dd_complete_isr(uint8_t rhport, uint8_t ep_id) -{ - dma_desc_t* const dd = &_dcd.dd[ep_id]; - uint8_t result = (dd->status == DD_STATUS_NORMAL || dd->status == DD_STATUS_DATA_UNDERUN) ? XFER_RESULT_SUCCESS : XFER_RESULT_FAILED; - uint8_t const ep_addr = (ep_id / 2) | ((ep_id & 0x01) ? TUSB_DIR_IN_MASK : 0); - - dcd_event_xfer_complete(rhport, ep_addr, dd->present_count, result, true); -} - -// main USB IRQ handler -void hal_dcd_isr(uint8_t rhport) -{ - uint32_t const dev_int_status = LPC_USB->DevIntSt & LPC_USB->DevIntEn; - LPC_USB->DevIntClr = dev_int_status;// Acknowledge handled interrupt - - // Bus event - if (dev_int_status & DEV_INT_DEVICE_STATUS_MASK) - { - bus_event_isr(rhport); - } - - // Endpoint interrupt - uint32_t const ep_int_status = LPC_USB->EpIntSt & LPC_USB->EpIntEn; - - // Control Endpoint are fast - if (dev_int_status & DEV_INT_ENDPOINT_FAST_MASK) - { - // Note clear USBEpIntClr will also clear the setup received bit --> clear after handle setup packet - // Only clear USBEpIntClr 1 endpoint each, and should wait for CDFULL bit set - control_xfer_isr(rhport, ep_int_status); - } - - // non-control IN are slow - if (dev_int_status & DEV_INT_ENDPOINT_SLOW_MASK) - { - for ( uint8_t ep_id = 3; ep_id < DCD_ENDPOINT_MAX; ep_id += 2 ) - { - if ( BIT_TEST_(ep_int_status, ep_id) ) - { - LPC_USB->EpIntClr = BIT_(ep_id); - - // Clear Ep interrupt for next DMA - LPC_USB->EpIntEn &= ~BIT_(ep_id); - - dd_complete_isr(rhport, ep_id); - } - } - } - - // DMA transfer complete (RAM <-> EP) for Non-Control - // OUT: USB transfer is fully complete - // IN : UBS transfer is still on-going -> enable EpIntEn to know when it is complete - uint32_t const dma_int_status = LPC_USB->DMAIntSt & LPC_USB->DMAIntEn; - if (dma_int_status & DMA_INT_END_OF_XFER_MASK) - { - uint32_t const eot = LPC_USB->EoTIntSt; - LPC_USB->EoTIntClr = eot; // acknowledge interrupt source - - for ( uint8_t ep_id = 2; ep_id < DCD_ENDPOINT_MAX; ep_id++ ) - { - if ( BIT_TEST_(eot, ep_id) ) - { - if ( ep_id & 0x01 ) - { - // IN enable EpInt for end of usb transfer - LPC_USB->EpIntEn |= BIT_(ep_id); - }else - { - // OUT - dd_complete_isr(rhport, ep_id); - } - } - } - } - - // Errors - if ( (dev_int_status & DEV_INT_ERROR_MASK) || (dma_int_status & DMA_INT_ERROR_MASK) ) - { - uint32_t error_status = sie_read(SIE_CMDCODE_READ_ERROR_STATUS); - (void) error_status; - TU_BREAKPOINT(); - } -} - -#endif +/**************************************************************************/ +/*! + @file dcd_lpc175x_6x.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. 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. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 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. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX) + +#include "device/dcd.h" +#include "dcd_lpc175x_6x.h" +#include "chip.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +#define DCD_ENDPOINT_MAX 32 + +typedef struct ATTR_ALIGNED(4) +{ + //------------- Word 0 -------------// + uint32_t next; + + //------------- Word 1 -------------// + uint16_t atle_mode : 2; // 00: normal, 01: ATLE (auto length extraction) + uint16_t next_valid : 1; + uint16_t : 1; ///< reserved + uint16_t isochronous : 1; // is an iso endpoint + uint16_t max_packet_size : 11; + + volatile uint16_t buflen; // bytes for non-iso, number of packets for iso endpoint + + //------------- Word 2 -------------// + volatile uint32_t buffer; + + //------------- Word 3 -------------// + volatile uint16_t retired : 1; // initialized to zero + volatile uint16_t status : 4; + volatile uint16_t iso_last_packet_valid : 1; + volatile uint16_t atle_lsb_extracted : 1; // used in ATLE mode + volatile uint16_t atle_msb_extracted : 1; // used in ATLE mode + volatile uint16_t atle_mess_len_position : 6; // used in ATLE mode + uint16_t : 2; + + volatile uint16_t present_count; // For non-iso : The number of bytes transferred by the DMA engine + // For iso : number of packets + + //------------- Word 4 -------------// + // uint32_t iso_packet_size_addr; // iso only, can be omitted for non-iso +}dma_desc_t; + +TU_VERIFY_STATIC( sizeof(dma_desc_t) == 16, "size is not correct"); // TODO not support ISO for now + +typedef struct +{ + // must be 128 byte aligned + volatile dma_desc_t* udca[DCD_ENDPOINT_MAX]; + + // TODO DMA does not support control transfer (0-1 are not used, offset to reduce memory) + dma_desc_t dd[DCD_ENDPOINT_MAX]; + + struct + { + uint8_t* out_buffer; + uint8_t out_bytes; + volatile bool out_received; // indicate if data is already received in endpoint + + uint8_t in_bytes; + } control; + +} dcd_data_t; + +ATTR_ALIGNED(128) static dcd_data_t _dcd; + + +//--------------------------------------------------------------------+ +// SIE Command +//--------------------------------------------------------------------+ +static void sie_cmd_code (sie_cmdphase_t phase, uint8_t code_data) +{ + LPC_USB->DevIntClr = (DEV_INT_COMMAND_CODE_EMPTY_MASK | DEV_INT_COMMAND_DATA_FULL_MASK); + LPC_USB->CmdCode = (phase << 8) | (code_data << 16); + + uint32_t const wait_flag = (phase == SIE_CMDPHASE_READ) ? DEV_INT_COMMAND_DATA_FULL_MASK : DEV_INT_COMMAND_CODE_EMPTY_MASK; + while ((LPC_USB->DevIntSt & wait_flag) == 0) {} + + LPC_USB->DevIntClr = wait_flag; +} + +static void sie_write (uint8_t cmd_code, uint8_t data_len, uint8_t data) +{ + sie_cmd_code(SIE_CMDPHASE_COMMAND, cmd_code); + + if (data_len) + { + sie_cmd_code(SIE_CMDPHASE_WRITE, data); + } +} + +static uint8_t sie_read (uint8_t cmd_code) +{ + sie_cmd_code(SIE_CMDPHASE_COMMAND , cmd_code); + sie_cmd_code(SIE_CMDPHASE_READ , cmd_code); + return (uint8_t) LPC_USB->CmdData; +} + +//--------------------------------------------------------------------+ +// PIPE HELPER +//--------------------------------------------------------------------+ +static inline uint8_t ep_addr2idx(uint8_t ep_addr) +{ + return 2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0); +} + +static void set_ep_size(uint8_t ep_id, uint16_t max_packet_size) +{ + // follows example in 11.10.4.2 + LPC_USB->ReEp |= BIT_(ep_id); + LPC_USB->EpInd = ep_id; // select index before setting packet size + LPC_USB->MaxPSize = max_packet_size; + + while ((LPC_USB->DevIntSt & DEV_INT_ENDPOINT_REALIZED_MASK) == 0) {} + LPC_USB->DevIntClr = DEV_INT_ENDPOINT_REALIZED_MASK; +} + + +//--------------------------------------------------------------------+ +// CONTROLLER API +//--------------------------------------------------------------------+ +static void bus_reset(void) +{ + // step 7 : slave mode set up + LPC_USB->EpIntClr = 0xFFFFFFFF; // clear all pending interrupt + LPC_USB->DevIntClr = 0xFFFFFFFF; // clear all pending interrupt + LPC_USB->EpIntEn = 0x03UL; // control endpoint cannot use DMA, non-control all use DMA + LPC_USB->EpIntPri = 0x03UL; // fast for control endpoint + + // step 8 : DMA set up + LPC_USB->EpDMADis = 0xFFFFFFFF; // firstly disable all dma + LPC_USB->DMARClr = 0xFFFFFFFF; // clear all pending interrupt + LPC_USB->EoTIntClr = 0xFFFFFFFF; + LPC_USB->NDDRIntClr = 0xFFFFFFFF; + LPC_USB->SysErrIntClr = 0xFFFFFFFF; + + tu_memclr(&_dcd, sizeof(dcd_data_t)); +} + +bool dcd_init(uint8_t rhport) +{ + (void) rhport; + + //------------- user manual 11.13 usb device controller initialization -------------// + // step 6 : set up control endpoint + set_ep_size(0, CFG_TUD_ENDOINT0_SIZE); + set_ep_size(1, CFG_TUD_ENDOINT0_SIZE); + + bus_reset(); + + LPC_USB->DevIntEn = (DEV_INT_DEVICE_STATUS_MASK | DEV_INT_ENDPOINT_FAST_MASK | DEV_INT_ENDPOINT_SLOW_MASK | DEV_INT_ERROR_MASK); + LPC_USB->UDCAH = (uint32_t) _dcd.udca; + LPC_USB->DMAIntEn = (DMA_INT_END_OF_XFER_MASK /*| DMA_INT_NEW_DD_REQUEST_MASK*/ | DMA_INT_ERROR_MASK); + + sie_write(SIE_CMDCODE_DEVICE_STATUS, 1, 1); // connect + + // USB IRQ priority should be set by application previously + NVIC_ClearPendingIRQ(USB_IRQn); + NVIC_EnableIRQ(USB_IRQn); + + return TUSB_ERROR_NONE; +} + +void dcd_connect(uint8_t rhport) +{ + (void) rhport; + sie_write(SIE_CMDCODE_DEVICE_STATUS, 1, 1); +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + sie_write(SIE_CMDCODE_SET_ADDRESS, 1, 0x80 | dev_addr); // 7th bit is : device_enable +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + sie_write(SIE_CMDCODE_CONFIGURE_DEVICE, 1, 1); +} + +//--------------------------------------------------------------------+ +// CONTROL HELPER +//--------------------------------------------------------------------+ +static inline uint8_t byte2dword(uint8_t bytes) +{ + return (bytes + 3) / 4; // length in dwords +} + +static void control_ep_write(void const * buffer, uint8_t len) +{ + uint32_t const * buf32 = (uint32_t const *) buffer; + + LPC_USB->Ctrl = USBCTRL_WRITE_ENABLE_MASK; // logical endpoint = 0 + LPC_USB->TxPLen = (uint32_t) len; + + for (uint8_t count = 0; count < byte2dword(len); count++) + { + LPC_USB->TxData = *buf32; // NOTE: cortex M3 have no problem with alignment + buf32++; + } + + LPC_USB->Ctrl = 0; + + // select control IN & validate the endpoint + sie_write(SIE_CMDCODE_ENDPOINT_SELECT+1, 0, 0); + sie_write(SIE_CMDCODE_BUFFER_VALIDATE , 0, 0); +} + +static uint8_t control_ep_read(void * buffer, uint8_t len) +{ + LPC_USB->Ctrl = USBCTRL_READ_ENABLE_MASK; // logical endpoint = 0 + while ((LPC_USB->RxPLen & USBRXPLEN_PACKET_READY_MASK) == 0) {} // TODO blocking, should have timeout + + len = tu_min8(len, (uint8_t) (LPC_USB->RxPLen & USBRXPLEN_PACKET_LENGTH_MASK) ); + uint32_t *buf32 = (uint32_t*) buffer; + + for (uint8_t count=0; count < byte2dword(len); count++) + { + *buf32 = LPC_USB->RxData; + buf32++; + } + + LPC_USB->Ctrl = 0; + + // select control OUT & clear the endpoint + sie_write(SIE_CMDCODE_ENDPOINT_SELECT+0, 0, 0); + sie_write(SIE_CMDCODE_BUFFER_CLEAR , 0, 0); + + return len; +} + +//--------------------------------------------------------------------+ +// DCD Endpoint Port +//--------------------------------------------------------------------+ +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(p_endpoint_desc->bEndpointAddress); + uint8_t const ep_id = ep_addr2idx(p_endpoint_desc->bEndpointAddress); + + // Endpoint type is fixed to endpoint number + // 1: interrupt, 2: Bulk, 3: Iso and so on + switch ( p_endpoint_desc->bmAttributes.xfer ) + { + case TUSB_XFER_INTERRUPT: + TU_ASSERT((epnum % 3) == 1); + break; + + case TUSB_XFER_BULK: + TU_ASSERT((epnum % 3) == 2 || (epnum == 15)); + break; + + case TUSB_XFER_ISOCHRONOUS: + TU_ASSERT((epnum % 3) == 3 && (epnum != 15)); + break; + + default: + break; + } + + //------------- Realize Endpoint with Max Packet Size -------------// + set_ep_size(ep_id, p_endpoint_desc->wMaxPacketSize.size); + + //------------- first DD prepare -------------// + dma_desc_t* const dd = &_dcd.dd[ep_id]; + tu_memclr(dd, sizeof(dma_desc_t)); + + dd->isochronous = (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) ? 1 : 0; + dd->max_packet_size = p_endpoint_desc->wMaxPacketSize.size; + dd->retired = 1; // invalid at first + + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS + ep_id, 1, 0); // clear all endpoint status + + return true; +} + +bool dcd_edpt_busy(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t ep_id = ep_addr2idx( ep_addr ); + return (_dcd.udca[ep_id] != NULL && !_dcd.udca[ep_id]->retired); +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + if ( edpt_number(ep_addr) == 0 ) + { + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+0, 1, SIE_SET_ENDPOINT_STALLED_MASK | SIE_SET_ENDPOINT_CONDITION_STALLED_MASK); + }else + { + uint8_t ep_id = ep_addr2idx( ep_addr ); + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+ep_id, 1, SIE_SET_ENDPOINT_STALLED_MASK); + } +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + uint8_t ep_id = ep_addr2idx(ep_addr); + + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+ep_id, 1, 0); +} + +bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const ep_state = sie_read(SIE_CMDCODE_ENDPOINT_SELECT + ep_addr2idx(ep_addr)); + return (ep_state & SIE_SELECT_ENDPOINT_STALL_MASK) ? true : false; +} + +static bool control_xact(uint8_t rhport, uint8_t dir, uint8_t * buffer, uint8_t len) +{ + (void) rhport; + + if ( dir ) + { + _dcd.control.in_bytes = len; + control_ep_write(buffer, len); + }else + { + if ( _dcd.control.out_received ) + { + // Already received the DATA OUT packet + _dcd.control.out_received = false; + _dcd.control.out_buffer = NULL; + _dcd.control.out_bytes = 0; + + uint8_t received = control_ep_read(buffer, len); + dcd_event_xfer_complete(0, 0, received, XFER_RESULT_SUCCESS, true); + }else + { + _dcd.control.out_buffer = buffer; + _dcd.control.out_bytes = len; + } + } + + return true; +} + +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) +{ + // Control transfer is not DMA support, and must be done in slave mode + if ( edpt_number(ep_addr) == 0 ) + { + return control_xact(rhport, edpt_dir(ep_addr), buffer, (uint8_t) total_bytes); + } + else + { + uint8_t ep_id = ep_addr2idx(ep_addr); + dma_desc_t* dd = &_dcd.dd[ep_id]; + + // Prepare DMA descriptor + // Isochronous & max packet size must be preserved, Other fields of dd should be clear + uint16_t const ep_size = dd->max_packet_size; + uint8_t is_iso = dd->isochronous; + + tu_memclr(dd, sizeof(dma_desc_t)); + dd->isochronous = is_iso; + dd->max_packet_size = ep_size; + dd->buffer = (uint32_t) buffer; + dd->buflen = total_bytes; + + _dcd.udca[ep_id] = dd; + + if ( ep_id % 2 ) + { + // Clear EP interrupt before Enable DMA + LPC_USB->EpIntEn &= ~BIT_(ep_id); + LPC_USB->EpDMAEn = BIT_(ep_id); + + // endpoint IN need to actively raise DMA request + LPC_USB->DMARSet = BIT_(ep_id); + }else + { + // Enable DMA + LPC_USB->EpDMAEn = BIT_(ep_id); + } + + return true; + } +} + +//--------------------------------------------------------------------+ +// ISR +//--------------------------------------------------------------------+ + +// handle control xfer (slave mode) +static void control_xfer_isr(uint8_t rhport, uint32_t ep_int_status) +{ + // Control out complete + if ( ep_int_status & BIT_(0) ) + { + bool is_setup = sie_read(SIE_CMDCODE_ENDPOINT_SELECT+0) & SIE_SELECT_ENDPOINT_SETUP_RECEIVED_MASK; + + LPC_USB->EpIntClr = BIT_(0); + + if (is_setup) + { + uint8_t setup_packet[8]; + control_ep_read(setup_packet, 8); // TODO read before clear setup above + + dcd_event_setup_received(rhport, setup_packet, true); + } + else if ( _dcd.control.out_buffer ) + { + // software queued transfer previously + uint8_t received = control_ep_read(_dcd.control.out_buffer, _dcd.control.out_bytes); + + _dcd.control.out_buffer = NULL; + _dcd.control.out_bytes = 0; + + dcd_event_xfer_complete(rhport, 0, received, XFER_RESULT_SUCCESS, true); + }else + { + // hardware auto ack packet -> mark as received + _dcd.control.out_received = true; + } + } + + // Control In complete + if ( ep_int_status & BIT_(1) ) + { + LPC_USB->EpIntClr = BIT_(1); + dcd_event_xfer_complete(rhport, TUSB_DIR_IN_MASK, _dcd.control.in_bytes, XFER_RESULT_SUCCESS, true); + } +} + +// handle bus event signal +static void bus_event_isr(uint8_t rhport) +{ + uint8_t const dev_status = sie_read(SIE_CMDCODE_DEVICE_STATUS); + if (dev_status & SIE_DEV_STATUS_RESET_MASK) + { + bus_reset(); + dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); + } + + if (dev_status & SIE_DEV_STATUS_CONNECT_CHANGE_MASK) + { + // device is disconnected, require using VBUS (P1_30) + dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true); + } + + if (dev_status & SIE_DEV_STATUS_SUSPEND_CHANGE_MASK) + { + if (dev_status & SIE_DEV_STATUS_SUSPEND_MASK) + { + dcd_event_bus_signal(rhport, DCD_EVENT_SUSPENDED, true); + } + else + { + dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); + } + } +} + +// Helper to complete a DMA descriptor for non-control transfer +static void dd_complete_isr(uint8_t rhport, uint8_t ep_id) +{ + dma_desc_t* const dd = &_dcd.dd[ep_id]; + uint8_t result = (dd->status == DD_STATUS_NORMAL || dd->status == DD_STATUS_DATA_UNDERUN) ? XFER_RESULT_SUCCESS : XFER_RESULT_FAILED; + uint8_t const ep_addr = (ep_id / 2) | ((ep_id & 0x01) ? TUSB_DIR_IN_MASK : 0); + + dcd_event_xfer_complete(rhport, ep_addr, dd->present_count, result, true); +} + +// main USB IRQ handler +void hal_dcd_isr(uint8_t rhport) +{ + uint32_t const dev_int_status = LPC_USB->DevIntSt & LPC_USB->DevIntEn; + LPC_USB->DevIntClr = dev_int_status;// Acknowledge handled interrupt + + // Bus event + if (dev_int_status & DEV_INT_DEVICE_STATUS_MASK) + { + bus_event_isr(rhport); + } + + // Endpoint interrupt + uint32_t const ep_int_status = LPC_USB->EpIntSt & LPC_USB->EpIntEn; + + // Control Endpoint are fast + if (dev_int_status & DEV_INT_ENDPOINT_FAST_MASK) + { + // Note clear USBEpIntClr will also clear the setup received bit --> clear after handle setup packet + // Only clear USBEpIntClr 1 endpoint each, and should wait for CDFULL bit set + control_xfer_isr(rhport, ep_int_status); + } + + // non-control IN are slow + if (dev_int_status & DEV_INT_ENDPOINT_SLOW_MASK) + { + for ( uint8_t ep_id = 3; ep_id < DCD_ENDPOINT_MAX; ep_id += 2 ) + { + if ( BIT_TEST_(ep_int_status, ep_id) ) + { + LPC_USB->EpIntClr = BIT_(ep_id); + + // Clear Ep interrupt for next DMA + LPC_USB->EpIntEn &= ~BIT_(ep_id); + + dd_complete_isr(rhport, ep_id); + } + } + } + + // DMA transfer complete (RAM <-> EP) for Non-Control + // OUT: USB transfer is fully complete + // IN : UBS transfer is still on-going -> enable EpIntEn to know when it is complete + uint32_t const dma_int_status = LPC_USB->DMAIntSt & LPC_USB->DMAIntEn; + if (dma_int_status & DMA_INT_END_OF_XFER_MASK) + { + uint32_t const eot = LPC_USB->EoTIntSt; + LPC_USB->EoTIntClr = eot; // acknowledge interrupt source + + for ( uint8_t ep_id = 2; ep_id < DCD_ENDPOINT_MAX; ep_id++ ) + { + if ( BIT_TEST_(eot, ep_id) ) + { + if ( ep_id & 0x01 ) + { + // IN enable EpInt for end of usb transfer + LPC_USB->EpIntEn |= BIT_(ep_id); + }else + { + // OUT + dd_complete_isr(rhport, ep_id); + } + } + } + } + + // Errors + if ( (dev_int_status & DEV_INT_ERROR_MASK) || (dma_int_status & DMA_INT_ERROR_MASK) ) + { + uint32_t error_status = sie_read(SIE_CMDCODE_READ_ERROR_STATUS); + (void) error_status; + TU_BREAKPOINT(); + } +} + +#endif diff --git a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.h b/src/portable/nxp/lpc17_40/dcd_lpc17_40.h similarity index 100% rename from src/portable/nxp/lpc17xx/dcd_lpc175x_6x.h rename to src/portable/nxp/lpc17_40/dcd_lpc17_40.h diff --git a/src/portable/nxp/lpc17xx/hal_lpc175x_6x.c b/src/portable/nxp/lpc17_40/hal_lpc17_40.c similarity index 95% rename from src/portable/nxp/lpc17xx/hal_lpc175x_6x.c rename to src/portable/nxp/lpc17_40/hal_lpc17_40.c index bc61178d8..668cabd80 100644 --- a/src/portable/nxp/lpc17xx/hal_lpc175x_6x.c +++ b/src/portable/nxp/lpc17_40/hal_lpc17_40.c @@ -1,108 +1,108 @@ -/**************************************************************************/ -/*! - @file hal_lpc175x_6x.c - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, hathach (tinyusb.org) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. 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. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 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. - - This file is part of the tinyusb stack. -*/ -/**************************************************************************/ - -#include "common/tusb_common.h" - -#if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X - -#include "chip.h" - -void tusb_hal_int_enable(uint8_t rhport) -{ - (void) rhport; - NVIC_EnableIRQ(USB_IRQn); -} - -void tusb_hal_int_disable(uint8_t rhport) -{ - (void) rhport; - NVIC_DisableIRQ(USB_IRQn); -} - -//--------------------------------------------------------------------+ -// IMPLEMENTATION -//--------------------------------------------------------------------+ -bool tusb_hal_init(void) -{ - enum { - USBCLK_DEVCIE = 0x12, // AHB + Device - USBCLK_HOST = 0x19, // AHB + Host + OTG (!) - }; - - Chip_USB_Init(); - - /* Configure P0.29 as D+, P0.30 as D- */ - Chip_IOCON_PinMux(LPC_IOCON, 0, 29, IOCON_MODE_INACT, IOCON_FUNC1); - Chip_IOCON_PinMux(LPC_IOCON, 0, 30, IOCON_MODE_INACT, IOCON_FUNC1); - -#if MODE_HOST_SUPPORTED - PINSEL_ConfigPin( &(PINSEL_CFG_Type) { .Portnum = 1, .Pinnum = 22, .Funcnum = 2} ); // P1.22 as USB_PWRD - PINSEL_ConfigPin( &(PINSEL_CFG_Type) { .Portnum = 1, .Pinnum = 19, .Funcnum = 2} ); // P1.19 as USB_PPWR - - // Enable host - LPC_USB->USBClkCtrl = USBCLK_HOST; - while ((LPC_USB->USBClkSt & USBCLK_HOST) != USBCLK_HOST); - LPC_USB->OTGStCtrl = 0x3; -#endif - -#if TUSB_OPT_DEVICE_ENABLED - // P2_9 as USB Connect - Chip_IOCON_PinMux(LPC_IOCON, 2, 9, IOCON_MODE_INACT, IOCON_FUNC1); - - // Enable Device - LPC_USB->USBClkCtrl = USBCLK_DEVCIE; - while ((LPC_USB->USBClkSt & USBCLK_DEVCIE) != USBCLK_DEVCIE); -#endif - - return true; -} - -void USB_IRQHandler(void) -{ - extern void hal_dcd_isr(uint8_t rhport); - - #if MODE_HOST_SUPPORTED - hal_hcd_isr(0); - #endif - - #if TUSB_OPT_DEVICE_ENABLED - hal_dcd_isr(0); - #endif -} - -#endif +/**************************************************************************/ +/*! + @file hal_lpc175x_6x.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. 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. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 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. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "common/tusb_common.h" + +#if (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX) + +#include "chip.h" + +void tusb_hal_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USB_IRQn); +} + +void tusb_hal_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USB_IRQn); +} + +//--------------------------------------------------------------------+ +// IMPLEMENTATION +//--------------------------------------------------------------------+ +bool tusb_hal_init(void) +{ + enum { + USBCLK_DEVCIE = 0x12, // AHB + Device + USBCLK_HOST = 0x19, // AHB + Host + OTG (!) + }; + + Chip_USB_Init(); + + /* Configure P0.29 as D+, P0.30 as D- */ + Chip_IOCON_PinMux(LPC_IOCON, 0, 29, IOCON_MODE_INACT, IOCON_FUNC1); + Chip_IOCON_PinMux(LPC_IOCON, 0, 30, IOCON_MODE_INACT, IOCON_FUNC1); + +#if MODE_HOST_SUPPORTED + PINSEL_ConfigPin( &(PINSEL_CFG_Type) { .Portnum = 1, .Pinnum = 22, .Funcnum = 2} ); // P1.22 as USB_PWRD + PINSEL_ConfigPin( &(PINSEL_CFG_Type) { .Portnum = 1, .Pinnum = 19, .Funcnum = 2} ); // P1.19 as USB_PPWR + + // Enable host + LPC_USB->USBClkCtrl = USBCLK_HOST; + while ((LPC_USB->USBClkSt & USBCLK_HOST) != USBCLK_HOST); + LPC_USB->OTGStCtrl = 0x3; +#endif + +#if TUSB_OPT_DEVICE_ENABLED + // P2_9 as USB Connect + Chip_IOCON_PinMux(LPC_IOCON, 2, 9, IOCON_MODE_INACT, IOCON_FUNC1); + + // Enable Device + LPC_USB->USBClkCtrl = USBCLK_DEVCIE; + while ((LPC_USB->USBClkSt & USBCLK_DEVCIE) != USBCLK_DEVCIE); +#endif + + return true; +} + +void USB_IRQHandler(void) +{ + extern void hal_dcd_isr(uint8_t rhport); + + #if MODE_HOST_SUPPORTED + hal_hcd_isr(0); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + hal_dcd_isr(0); + #endif +} + +#endif diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index af1fa619c..8f5e3b457 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -54,9 +54,14 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ + +#define QHD_MAX 12 +#define QTD_NEXT_INVALID 0x01 + typedef struct { - dcd_qhd_t qhd[DCD_QHD_MAX] ATTR_ALIGNED(64); ///< Must be at 2K alignment - dcd_qtd_t qtd[DCD_QTD_MAX] ATTR_ALIGNED(32); + // Must be at 2K alignment + dcd_qhd_t qhd[QHD_MAX] ATTR_ALIGNED(64); + dcd_qtd_t qtd[QHD_MAX] ATTR_ALIGNED(32); }dcd_data_t; #if (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) @@ -229,7 +234,6 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) { - // TODO USB1 only has 4 non-control enpoint (USB0 has 5) // TODO not support ISO yet TU_VERIFY ( p_endpoint_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); @@ -237,6 +241,9 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) uint8_t const dir = edpt_dir(p_endpoint_desc->bEndpointAddress); uint8_t const ep_idx = 2*epnum + dir; + // USB0 has 5, USB1 has 3 non-control endpoints + TU_ASSERT( epnum <= (rhport ? 3 : 5) ); + //------------- Prepare Queue Head -------------// dcd_qhd_t * p_qhd = &dcd_data_ptr[rhport]->qhd[ep_idx]; tu_memclr(p_qhd, sizeof(dcd_qhd_t)); @@ -351,7 +358,7 @@ void hal_dcd_isr(uint8_t rhport) if ( edpt_complete ) { - for(uint8_t ep_idx = 0; ep_idx < DCD_QHD_MAX; ep_idx++) + for(uint8_t ep_idx = 0; ep_idx < QHD_MAX; ep_idx++) { if ( BIT_TEST_(edpt_complete, ep_idx2bit(ep_idx)) ) { diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.h b/src/portable/nxp/lpc18_43/dcd_lpc18_43.h index cd54cae7c..faf0e3b0f 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.h +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.h @@ -52,10 +52,6 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -#define DCD_QHD_MAX 12 -#define DCD_QTD_MAX 12 - -#define QTD_NEXT_INVALID 0x01 /*---------- ENDPTCTRL ----------*/ enum { diff --git a/src/tusb_option.h b/src/tusb_option.h index 1bcf6aa8d..d808a0518 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -53,8 +53,9 @@ #define OPT_MCU_LPC13XX 3 ///< NXP LPC13xx #define OPT_MCU_LPC175X_6X 4 ///< NXP LPC175x, LPC176x #define OPT_MCU_LPC177X_8X 5 ///< NXP LPC177x, LPC178x -#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx series -#define OPT_MCU_LPC43XX 7 ///< NXP LPC43xx series +#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx +#define OPT_MCU_LPC40XX 7 ///< NXP LPC40xx +#define OPT_MCU_LPC43XX 8 ///< NXP LPC43xx #define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series