Browse Source

init commit

Vladimir N. Shilov 2 years ago
commit
44e2539973
22 changed files with 3993 additions and 0 deletions
  1. 15 0
      .gitignore
  2. 39 0
      .vscode/c_cpp_properties.json
  3. 4 0
      .vscode/settings.json
  4. 200 0
      Makefile
  5. 69 0
      board/board.c
  6. 355 0
      board/board.h
  7. 9 0
      board/board.mk
  8. 127 0
      board/board_LGDP4532.h
  9. 27 0
      board/ginput_lld_toggle_board.h
  10. 87 0
      board/gmouse_lld_ADS7843_board.h
  11. 840 0
      cfg/chconf.h
  12. 76 0
      cfg/gfxconf.h
  13. 550 0
      cfg/halconf.h
  14. 222 0
      cfg/mcuconf.h
  15. 3 0
      flash.cmd
  16. 7 0
      flash.jlink
  17. 245 0
      inc/INA3221.h
  18. 44 0
      inc/buttons.h
  19. 29 0
      readme.txt
  20. 577 0
      src/INA3221.c
  21. 76 0
      src/buttons.c
  22. 392 0
      src/main.c

+ 15 - 0
.gitignore

@@ -0,0 +1,15 @@
+~*.*~
+*.layout
+build
+.dep
+*.log
+etc
+MDK-ARM/*.uvguix.*
+MDK-ARM/DebugConfig
+MDK-ARM/LST
+MDK-ARM/OUT
+MDK-ARM/RTE
+MDK-ARM/*.txt
+MDK-ARM/*.scvd
+MDK-ARM/JLinkSettings.ini
+.vscode/BROWSE.VC.DB*

+ 39 - 0
.vscode/c_cpp_properties.json

@@ -0,0 +1,39 @@
+{
+    "version": 4,
+    "configurations": [
+        {
+            "name": "Accum-Tester",
+            "defines": [
+                "STM32F103xx="
+            ],
+            "includePath": [
+                "${workspaceRoot}/inc",
+                "${workspaceRoot}/cfg",
+                "${workspaceRoot}/board",
+                "C:/MCU/gcc-arm/arm-none-eabi/include",
+                "C:/MCU/ChibiOS/os/**",
+                "C:/MCU/uGFX/**"
+            ],
+            "compilerPath": "C:/MCU/gcc-arm/bin/arm-none-eabi-gcc.exe",
+            "forcedInclude": [],
+            "cStandard": "gnu17",
+            "cppStandard": "c++17",
+            "intelliSenseMode": "windows-gcc-arm",
+            "configurationProvider": "ms-vscode.makefile-tools",
+            "browse": {
+                "path": [
+                    "${workspaceRoot}",
+                    "${workspaceRoot}/inc",
+                    "${workspaceRoot}/cfg",
+                    "${workspaceRoot}/board",
+                    "C:/MCU/gcc-arm/arm-none-eabi/include",
+                    "C:/MCU/gcc-arm/lib/gcc/arm-none-eabi/**",
+                    "C:/MCU/ChibiOS/os/**",
+                    "C:/MCU/uGFX/**"
+                ],
+                "limitSymbolsToIncludedHeaders": true,
+                "databaseFilename": "${workspaceRoot}/.vscode/browse.vc.db"
+            }
+        }
+    ]
+}

+ 4 - 0
.vscode/settings.json

@@ -0,0 +1,4 @@
+{
+  "makefile.extensionOutputFolder": "./.vscode",
+  "C_Cpp.errorSquiggles": "disabled"
+}

+ 200 - 0
Makefile

@@ -0,0 +1,200 @@
+##############################################################################
+# Build global options
+# NOTE: Can be overridden externally.
+#
+
+# Compiler options here.
+ifeq ($(USE_OPT),)
+  USE_OPT = -O2 -ggdb -fomit-frame-pointer -falign-functions=16
+endif
+
+# C specific options here (added to USE_OPT).
+ifeq ($(USE_COPT),)
+  USE_COPT = 
+endif
+
+# C++ specific options here (added to USE_OPT).
+ifeq ($(USE_CPPOPT),)
+  USE_CPPOPT = -fno-rtti
+endif
+
+# Enable this if you want the linker to remove unused code and data.
+ifeq ($(USE_LINK_GC),)
+  USE_LINK_GC = yes
+endif
+
+# Linker extra options here.
+ifeq ($(USE_LDOPT),)
+  USE_LDOPT = -lm
+endif
+
+# Enable this if you want link time optimizations (LTO).
+ifeq ($(USE_LTO),)
+  USE_LTO = yes
+endif
+
+# Enable this if you want to see the full log while compiling.
+ifeq ($(USE_VERBOSE_COMPILE),)
+  USE_VERBOSE_COMPILE = no
+endif
+
+# If enabled, this option makes the build process faster by not compiling
+# modules not used in the current configuration.
+ifeq ($(USE_SMART_BUILD),)
+  USE_SMART_BUILD = yes
+endif
+
+#
+# Build global options
+##############################################################################
+
+##############################################################################
+# Architecture or project specific options
+#
+
+# Stack size to be allocated to the Cortex-M process stack. This stack is
+# the stack used by the main() thread.
+ifeq ($(USE_PROCESS_STACKSIZE),)
+  USE_PROCESS_STACKSIZE = 0x400
+endif
+
+# Stack size to the allocated to the Cortex-M main/exceptions stack. This
+# stack is used for processing interrupts and exceptions.
+ifeq ($(USE_EXCEPTIONS_STACKSIZE),)
+  USE_EXCEPTIONS_STACKSIZE = 0x400
+endif
+
+# Enables the use of FPU (no, softfp, hard).
+ifeq ($(USE_FPU),)
+  USE_FPU = no
+endif
+
+# FPU-related options.
+ifeq ($(USE_FPU_OPT),)
+  USE_FPU_OPT = -mfloat-abi=$(USE_FPU) -mfpu=fpv4-sp-d16
+endif
+
+#
+# Architecture or project specific options
+##############################################################################
+
+##############################################################################
+# Project, target, sources and paths
+#
+
+# Define project name here
+PROJECT = acc-tst
+
+# Target settings.
+MCU  = cortex-m3
+
+# Imported source files and paths.
+CHIBIOS  := C:/MCU/ChibiOS
+CONFDIR  := ./cfg
+BUILDDIR := ./build
+DEPDIR   := ./.dep
+
+# Licensing files.
+include $(CHIBIOS)/os/license/license.mk
+# Startup files.
+include $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32f1xx.mk
+# HAL-OSAL files (optional).
+include $(CHIBIOS)/os/hal/hal.mk
+include $(CHIBIOS)/os/hal/ports/STM32/STM32F1xx/platform.mk
+#include $(CHIBIOS)/os/hal/boards/ST_NUCLEO64_F103RB/board.mk
+include board/board.mk
+include $(CHIBIOS)/os/hal/osal/rt-nil/osal.mk
+# RTOS files (optional).
+include $(CHIBIOS)/os/rt/rt.mk
+include $(CHIBIOS)/os/common/ports/ARMv7-M/compilers/GCC/mk/port.mk
+# Auto-build files in ./source recursively.
+include $(CHIBIOS)/tools/mk/autobuild.mk
+# Other files (optional).
+include $(CHIBIOS)/os/hal/lib/streams/streams.mk
+#include $(CHIBIOS)/os/various/shell/shell.mk
+
+# µGFX
+GFXLIB = C:/MCU/uGFX
+include $(GFXLIB)/gfx.mk
+include $(GFXLIB)/drivers/gdisp/LGDP4532/driver.mk       # your board
+include $(GFXLIB)/drivers/ginput/toggle/Pal/driver.mk    # your button keys
+include $(GFXLIB)/drivers/ginput/touch/ADS7843/driver.mk # your touch panel
+
+# Define linker script file here
+LDSCRIPT= $(STARTUPLD)/STM32F103xE.ld
+
+# C sources that can be compiled in ARM or THUMB mode depending on the global
+# setting.
+CSRC =	$(ALLCSRC) \
+	$(GFXSRC) \
+	src/INA3221.c \
+	src/buttons.c \
+	src/main.c
+
+# C++ sources that can be compiled in ARM or THUMB mode depending on the global
+# setting.
+CPPSRC = $(ALLCPPSRC) \
+
+# List ASM source files here.
+ASMSRC = $(ALLASMSRC)
+
+# List ASM with preprocessor source files here.
+ASMXSRC = $(ALLXASMSRC)
+
+# Inclusion directories.
+INCDIR = $(CONFDIR) $(ALLINC) $(GFXINC)
+
+# Define C warning options here.
+CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes
+
+# Define C++ warning options here.
+CPPWARN = -Wall -Wextra -Wundef
+
+#
+# Project, target, sources and paths
+##############################################################################
+
+##############################################################################
+# Start of user section
+#
+
+# List all user C define here, like -D_DEBUG=1
+UDEFS = 
+
+# Define ASM defines here
+UADEFS =
+
+# List all user directories here
+UINCDIR = inc
+
+# List the user directory to look for the libraries here
+ULIBDIR =
+
+# List all user libraries here
+ULIBS =
+
+#
+# End of user section
+##############################################################################
+
+##############################################################################
+# Common rules
+#
+
+RULESPATH = $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk
+include $(RULESPATH)/arm-none-eabi.mk
+include $(RULESPATH)/rules.mk
+
+#
+# Common rules
+##############################################################################
+
+##############################################################################
+# Custom rules
+#
+flash: all
+	@flash.cmd
+
+#
+# Custom rules
+##############################################################################

+ 69 - 0
board/board.c

@@ -0,0 +1,69 @@
+/*
+    ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+*/
+
+#include "hal.h"
+
+/**
+ * @brief   PAL setup.
+ * @details Digital I/O ports static configuration as defined in @p board.h.
+ *          This variable is used by the HAL when initializing the PAL driver.
+ */
+#if HAL_USE_PAL || defined(__DOXYGEN__)
+const PALConfig pal_default_config =
+{
+  {VAL_GPIOAODR, VAL_GPIOACRL, VAL_GPIOACRH},
+  {VAL_GPIOBODR, VAL_GPIOBCRL, VAL_GPIOBCRH},
+  {VAL_GPIOCODR, VAL_GPIOCCRL, VAL_GPIOCCRH},
+  {VAL_GPIODODR, VAL_GPIODCRL, VAL_GPIODCRH},
+  {VAL_GPIOEODR, VAL_GPIOECRL, VAL_GPIOECRH},
+  {VAL_GPIOFODR, VAL_GPIOFCRL, VAL_GPIOFCRH},
+  {VAL_GPIOGODR, VAL_GPIOGCRL, VAL_GPIOGCRH},
+};
+#endif
+
+/*
+ * Early initialization code.
+ * This initialization must be performed just after stack setup and before
+ * any other initialization.
+ */
+void __early_init(void) {
+  stm32_clock_init();
+}
+
+#if HAL_USE_MMC_SPI
+/* Board-related functions related to the MMC_SPI driver.*/
+bool mmc_lld_is_card_inserted(MMCDriver *mmcp) {
+  (void)mmcp;
+  return palReadPad(GPIOC, GPIOC_MMCCP);
+}
+
+bool mmc_lld_is_write_protected(MMCDriver *mmcp) {
+  (void)mmcp;
+  return !palReadPad(GPIOC, GPIOC_MMCWP);
+}
+#endif
+
+/*
+ * Board-specific initialization code.
+ */
+void boardInit(void) {
+  /*
+   * Pin remap, RM0008, 9.3, page 175.
+   * Îòêëþ÷èëè JTAG, SWD âêëþ÷åí (9.3.5/176)
+   * I2C to PB8/PB9 (9.3.9/181)
+   */
+  AFIO->MAPR |= (AFIO_MAPR_SWJ_CFG_JTAGDISABLE | AFIO_MAPR_I2C1_REMAP);
+}

+ 355 - 0
board/board.h

@@ -0,0 +1,355 @@
+/*
+    ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+*/
+
+#ifndef _BOARD_H_
+#define _BOARD_H_
+
+/*
+ * Setup for the ST INEMO-M1 Discovery board.
+ */
+
+/*
+ * Board identifier.
+ */
+#define BOARD_HY_STM32
+#define BOARD_NAME              "HY-STM32"
+
+/*
+ * Board frequencies.
+ */
+#define STM32_LSECLK            32768
+#define STM32_HSECLK            8000000
+
+/*
+ * MCU type, supported types are defined in ./os/hal/platforms/hal_lld.h.
+ */
+#define STM32F103xE
+
+/*
+ * IO pins assignments.
+ */
+#define GPIOC_USB_DISC              13U
+
+#define GPIOE_TFT_RST               1U
+
+#define GPIOE_BUTTON1               5U
+#define GPIOE_BUTTON2               4U
+#define GPIOE_BUTTON3               3U
+#define GPIOE_BUTTON4               2U
+#define LINE_BUTTON1                PAL_LINE(GPIOE, GPIOE_BUTTON1)
+#define LINE_BUTTON2                PAL_LINE(GPIOE, GPIOE_BUTTON2)
+#define LINE_BUTTON3                PAL_LINE(GPIOE, GPIOE_BUTTON3)
+#define LINE_BUTTON4                PAL_LINE(GPIOE, GPIOE_BUTTON4)
+#define BUTTON_PRESSED              PAL_LOW
+
+#define GPIOC_LED1                  6U
+#define GPIOC_LED2                  7U
+#define GPIOD_LED3                  13U
+#define GPIOD_LED4                  6U
+#define LINE_LED1                   PAL_LINE(GPIOC, GPIOC_LED1)
+#define LINE_LED2                   PAL_LINE(GPIOC, GPIOC_LED2)
+#define LINE_LED3                   PAL_LINE(GPIOD, GPIOD_LED3)
+#define LINE_LED4                   PAL_LINE(GPIOD, GPIOD_LED4)
+
+#define GPIOE_BUZZER                0U
+#define LINE_BUZZER                 PAL_LINE(GPIOE, GPIOE_BUZZER)
+
+#define LINE_RELAY1                 PAL_LINE(GPIOA, GPIOA_PIN8)
+#define LINE_RELAY2                 PAL_LINE(GPIOD, GPIOD_PIN12)
+
+
+#define GPIOA_PIN0                  0U
+#define GPIOA_PIN1                  1U
+#define GPIOA_PIN2                  2U
+#define GPIOA_PIN3                  3U
+#define GPIOA_PIN4                  4U
+#define GPIOA_PIN5                  5U
+#define GPIOA_PIN6                  6U
+#define GPIOA_PIN7                  7U
+#define GPIOA_PIN8                  8U
+#define GPIOA_PIN9                  9U
+#define GPIOA_PIN10                 10U
+#define GPIOA_PIN11                 11U
+#define GPIOA_PIN12                 12U
+#define GPIOA_SWDIO                 13U
+#define GPIOA_SWCLK                 14U
+#define GPIOA_PIN15                 15U
+
+#define GPIOB_PIN0                  0U
+#define GPIOB_PIN1                  1U
+#define GPIOB_PIN2                  2U
+#define GPIOB_PIN3                  3U
+#define GPIOB_PIN4                  4U
+#define GPIOB_PIN5                  5U
+#define GPIOB_PIN6                  6U
+#define GPIOB_PIN7                  7U
+#define GPIOB_PIN8                  8U
+#define GPIOB_PIN9                  9U
+#define GPIOB_PIN10                 10U
+#define GPIOB_PIN11                 11U
+#define GPIOB_PIN12                 12U
+#define GPIOB_PIN13                 13U
+#define GPIOB_PIN14                 14U
+#define GPIOB_PIN15                 15U
+
+#define GPIOC_PIN0                  0U
+#define GPIOC_PIN1                  1U
+#define GPIOC_PIN2                  2U
+#define GPIOC_PIN3                  3U
+#define GPIOC_PIN4                  4U
+#define GPIOC_PIN5                  5U
+#define GPIOC_PIN6                  6U
+#define GPIOC_PIN7                  7U
+#define GPIOC_PIN8                  8U
+#define GPIOC_PIN9                  9U
+#define GPIOC_PIN10                 10U
+#define GPIOC_PIN11                 11U
+#define GPIOC_PIN12                 12U
+#define GPIOC_PIN13                 13U
+#define GPIOC_PIN14                 14U
+#define GPIOC_PIN15                 15U
+
+#define GPIOD_PIN0                  0U
+#define GPIOD_PIN1                  1U
+#define GPIOD_PIN2                  2U
+#define GPIOD_PIN3                  3U
+#define GPIOD_PIN4                  4U
+#define GPIOD_PIN5                  5U
+#define GPIOD_PIN6                  6U
+#define GPIOD_PIN7                  7U
+#define GPIOD_PIN8                  8U
+#define GPIOD_PIN9                  9U
+#define GPIOD_PIN10                 10U
+#define GPIOD_PIN11                 11U
+#define GPIOD_PIN12                 12U
+#define GPIOD_PIN13                 13U
+#define GPIOD_PIN14                 14U
+#define GPIOD_PIN15                 15U
+
+#define GPIOE_PIN0                  0U
+#define GPIOE_PIN1                  1U
+#define GPIOE_PIN2                  2U
+#define GPIOE_PIN3                  3U
+#define GPIOE_PIN4                  4U
+#define GPIOE_PIN5                  5U
+#define GPIOE_PIN6                  6U
+#define GPIOE_PIN7                  7U
+#define GPIOE_PIN8                  8U
+#define GPIOE_PIN9                  9U
+#define GPIOE_PIN10                 10U
+#define GPIOE_PIN11                 11U
+#define GPIOE_PIN12                 12U
+#define GPIOE_PIN13                 13U
+#define GPIOE_PIN14                 14U
+#define GPIOE_PIN15                 15U
+
+#define GPIOF_PIN0                  0U
+#define GPIOF_PIN1                  1U
+#define GPIOF_PIN2                  2U
+#define GPIOF_PIN3                  3U
+#define GPIOF_PIN4                  4U
+#define GPIOF_PIN5                  5U
+#define GPIOF_PIN6                  6U
+#define GPIOF_PIN7                  7U
+#define GPIOF_PIN8                  8U
+#define GPIOF_PIN9                  9U
+#define GPIOF_PIN10                 10U
+#define GPIOF_PIN11                 11U
+#define GPIOF_PIN12                 12U
+#define GPIOF_PIN13                 13U
+#define GPIOF_PIN14                 14U
+#define GPIOF_PIN15                 15U
+/*
+ * I/O ports initial setup, this configuration is established soon after reset
+ * in the initialization code.
+ *
+ * The digits have the following meaning:
+ *   0 - Analog input.
+ *   1 - Push Pull output 10MHz.
+ *   2 - Push Pull output 2MHz.
+ *   3 - Push Pull output 50MHz.
+ *   4 - Digital input.
+ *   5 - Open Drain output 10MHz.
+ *   6 - Open Drain output 2MHz.
+ *   7 - Open Drain output 50MHz.
+ *   8 - Digital input with PullUp or PullDown resistor depending on ODR.
+ *   9 - Alternate Push Pull output 10MHz.
+ *   A - Alternate Push Pull output 2MHz.
+ *   B - Alternate Push Pull output 50MHz.
+ *   C - Reserved.
+ *   D - Alternate Open Drain output 10MHz.
+ *   E - Alternate Open Drain output 2MHz.
+ *   F - Alternate Open Drain output 50MHz.
+ * Please refer to the STM32 Reference Manual for details.
+ */
+
+/*
+ * Port A setup.
+ * Everything input with pull-up except:
+ * PA0  - GIOP J1.5
+ * PA1  - GIOP J1.6
+ * PA2  - Alternate output  (USART2 TX MAX3232). / GIOP J1.36
+ * PA3  - Normal input      (USART2 RX MAX3232). / GIOP J1.35
+ * PA4  - CS M25P16.1 / GIOP J1.3
+ * PA5  - TP_DCLK (TFT.40) / SD_SCK (TFT.22) / C M25P16.6
+ * PA6  - TP_DOUT (TFT.36) / SD_MISO (TFT.21) / Q M25P16.2
+ * PA7  - TP_DIN (TFT.38) / SD_MOSI (TFT.23) / D M25P15.5
+ * PA8  - Open Drain 50M  (RELAY1/PWR CON3.4)
+ * PA9  - Alternate output  (USART1 TX PL2303). / GIOP J1.32
+ * PA10 - Normal input      (USART1 RX PL2303). / GIOP J1.31
+ * PA11 - Normal input      (USB DM). / GIOP J1.33
+ * PA12 - Normal input      (USB DP). / GIOP J1.34
+ * PA13 - SWDIO / JTAG_TMS.7
+ * PA14 - SWCLK / JTAG_TCK.9
+ * PA15 - JTAG_TDI.5
+ */
+#define VAL_GPIOACRL            0x88884B88      /*  PA7...PA0 */
+#define VAL_GPIOACRH            0x888444B7      /* PA15...PA8 */
+#define VAL_GPIOAODR            0xFFFFFFFF
+
+/*
+ * Port B setup.
+ * Everything input with pull-up except:
+ * PB0  - GPIO J1.13
+ * PB1  - GPIO J1.16
+ * PB2  - GPIO J1.15 / BOOT1
+ * PB3  - JTAG_TDO.13
+ * PB4  - JTAG_nRTST.3
+ * PB5  - GPIO J1.18
+ * PB6  - TP_IRQ (TFT.35)
+ * PB7  - PP output 50M    TP_CS (TFT.39)
+ * PB8  - Alternate OD 50M (I2C1_SCL CON3.1)
+ * PB9  - Alternate OD 50M (I2C1_SDA CON3.2)
+ * PB10 - TFT.16
+ * PB11 - TFT.18
+ * PB12 - GPIO J1.24
+ * PB13 - GPIO J1.23
+ * PB14 - GPIO J1.26
+ * PB15 - GPIO J1.55
+ */
+#define VAL_GPIOBCRL            0x38888888      /*  PB7...PB0 */
+#define VAL_GPIOBCRH            0x888888FF      /* PB15...PB8 */
+#define VAL_GPIOBODR            0xFFFFFFFF
+
+/*
+ * Port C setup.
+ * Everything input with pull-up except:
+ * PC0  - Analog Input CON3.6 (ADC_IN10).
+ * PC1  - Analog Input CON3.5 (ADC_IN11).
+ * PC2  - GPIO J1.7        (ADC_IN12).
+ * PC3  - GPIO J1.8        (ADC_IN13).
+ * PC4  - TFT.25           (ADC_IN14).
+ * PC5  - TFT.26           (ADC_IN15).
+ * PC6  - Output PP 50M    (LED1)
+ * PC7  - Output PP 50M    (LED2)
+ * PC8  - Alternate PP 50M (SD_D0 / GPIO J1.30).
+ * PC9  - Alternate PP 50M (SD_D1 / GPIO J1.29).
+ * PC10 - Alternate PP 50M (SD_D2 / GPIO J1.21).
+ * PC11 - Alternate PP 50M (SD_D3 / GPIO J1.22).
+ * PC12 - Alternate PP 50M (SD_CLK / GPIO J1.19).
+ * PC13 - PP output 50M    (USB Pull-UP / TFT.3)
+ * PC14 - Normal input	   (XTAL).
+ * PC15 - Normal input	   (XTAL).
+ */
+#define VAL_GPIOCCRL            0x33880000      /*  PC7...PC0 */
+#define VAL_GPIOCCRH            0x443BBBBB      /* PC15...PC8 */
+#define VAL_GPIOCODR            0xFFFFFF3F
+
+/*
+ * Port D setup.
+ * Everything input with pull-up except:
+ * PD0  - Alternate PP 50M (FSMC_DB2)
+ * PD1  - Alternate PP 50M (FSMC_DB3)
+ * PD2  - Alternate PP 50M (SDIO_CMD / GPIO J1.20)
+ * PD3  - GPIO             (J1.17)
+ * PD4  - Alternate PP 50M (TFT_RD)
+ * PD5  - Alternate PP 50M (TFT_WR)
+ * PD6  - Output PP 50M    (SD_CS1, LED4)
+ * PD7  - Alternate PP 50M (TFT_CS)
+ * PD8  - Alternate PP 50M (FSMC_DB13)
+ * PD9  - Alternate PP 50M (FSMC_DB14)
+ * PD10 - Alternate PP 50M (FSMC_DB15)
+ * PD11 - Alternate PP 50M (TFT_RS - Data/Command)
+ * PD12 - Output OD 50M    (RELAY2 CON3.3)
+ * PD13 - Output PP 50M    (LED3)
+ * PD14 - Alternate PP 50M (FSMC_DB0)
+ * PD15 - Alternate PP 50M (FSMC_DB1)
+ */
+#define VAL_GPIODCRL            0xB3BB8BBB      /*  PD7...PD0 */
+#define VAL_GPIODCRH            0xBB37BBBB      /* PD15...PD8 */
+#define VAL_GPIODODR            0xFFFFDFBF
+
+/*
+ * Port E setup.
+ * Everything input with pull-up except:
+ * PE0  - Digital Output   (BUZZER J2 / GPIO J1.4)
+ * PE1  - Digital Output   (TFT_RESET)
+ * PE2  - Digital input    (KEY_S4 / GPIO J1.14)
+ * PE3  - Digital input    (KEY_S3 / GPIO J1.11)
+ * PE4  - Digital input    (KEY_S2 / GPIO J1.12)
+ * PE5  - Digital input    (KEY_S1 / GPIO J1.9)
+ * PE6  - GPIO             (J1.10)
+ * PE7  - Alternate PP 50M (FSMC_DB4)
+ * PE8  - Alternate PP 50M (FSMC_DB5)
+ * PE9  - Alternate PP 50M (FSMC_DB6)
+ * PE10 - Alternate PP 50M (FSMC_DB7)
+ * PE11 - Alternate PP 50M (FSMC_DB8)
+ * PE12 - Alternate PP 50M (FSMC_DB9)
+ * PE13 - Alternate PP 50M (FSMC_DB10)
+ * PE14 - Alternate PP 50M (FSMC_DB11)
+ * PE15 - Alternate PP 50M (FSMC_DB12)
+ */
+#define VAL_GPIOECRL            0xB8444433      /*  PE7...PE0 */
+#define VAL_GPIOECRH            0xBBBBBBBB      /* PE15...PE8 */
+#define VAL_GPIOEODR            0xFFFFFFFF
+
+/*
+ * Port F setup.
+ * Everything input with pull-up expect:
+ */
+#define VAL_GPIOFCRL            0x88888888      /*  PF7...PF0 */
+#define VAL_GPIOFCRH            0x88888888      /* PF15...PF8 */
+#define VAL_GPIOFODR            0xFFFFFFFF
+
+/*
+ * Port G setup.
+ * Everything input with pull-up expect:
+ */
+#define VAL_GPIOGCRL            0x88888888      /*  PG7...PG0 */
+#define VAL_GPIOGCRH            0x88888888      /* PG15...PG8 */
+#define VAL_GPIOGODR            0xFFFFFFFF
+
+/*
+ * USB bus activation macro, required by the USB driver.
+ */
+#define usb_lld_connect_bus(usbp) palClearPad(GPIOC, GPIOC_USB_DISC)
+
+/*
+ * USB bus de-activation macro, required by the USB driver.
+ */
+#define usb_lld_disconnect_bus(usbp) palSetPad(GPIOC, GPIOC_USB_DISC)
+
+#if !defined(_FROM_ASM_)
+#ifdef __cplusplus
+extern "C" {
+#endif
+  void boardInit(void);
+#ifdef __cplusplus
+}
+#endif
+#endif /* _FROM_ASM_ */
+
+#endif /* _BOARD_H_ */

+ 9 - 0
board/board.mk

@@ -0,0 +1,9 @@
+# List of all the board related files.
+BOARDSRC = board/board.c
+
+# Required include directories
+BOARDINC = board
+
+# Shared variables
+ALLCSRC += $(BOARDSRC)
+ALLINC  += $(BOARDINC)

+ 127 - 0
board/board_LGDP4532.h

@@ -0,0 +1,127 @@
+/*
+ * This file is subject to the terms of the GFX License. If a copy of
+ * the license was not distributed with this file, you can obtain one at:
+ *
+ *              http://ugfx.org/license.html
+ */
+
+/*
+	driver quickly hacked together from a chinese sourcecode that came
+	with the board and existing ili9320 code by Chris van Dongen (sjaak)
+	(sjaak2002 at msn.com)
+	
+	Also added rotation for 180 and 270 degrees and minor tweaks to
+	setcursor
+	
+	Added code comes without warranty and free bugs. Feel free to use 
+	or misuse the added code :D
+*/
+
+
+/**
+ * @file    boards/addons/gdisp/board_ILI9325_hy_stm32_100p.h
+ * @brief   GDISP Graphic Driver subsystem board SPI interface for the ILI9325 display.
+ *
+ * @note	This file contains a mix of hardware specific and operating system specific
+ *			code. You will need to change it for your CPU and/or operating system.
+ */
+
+#ifndef GDISP_LLD_BOARD_H
+#define GDISP_LLD_BOARD_H
+
+// For a multiple display configuration we would put all this in a structure and then
+//	set g->board to that structure.
+#define GDISP_REG              (*((volatile uint16_t *) 0x60000000)) /* RS = 0 */
+#define GDISP_RAM              (*((volatile uint16_t *) 0x60020000)) /* RS = 1 */
+
+static inline void init_board(GDisplay *g) {
+
+	(void) g;
+	// As we are not using multiple displays we set g->board to NULL as we don't use it.
+
+	/* FSMC setup for F1 */
+	rccEnableAHB(RCC_AHBENR_FSMCEN, 0);
+
+	/* set pin modes. by default sets in board files */
+/*	IOBus busD = {GPIOD, PAL_WHOLE_PORT, 0};
+	IOBus busE = {GPIOE, PAL_WHOLE_PORT, 0};
+	palSetBusMode(&busD, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
+	palSetBusMode(&busE, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
+	palSetPadMode(GPIOE, GPIOE_TFT_RST, PAL_MODE_OUTPUT_PUSHPULL);
+	palSetPadMode(GPIOD, GPIOD_TFT_LIGHT, PAL_MODE_OUTPUT_PUSHPULL);
+*/
+
+  const uint8_t FSMC_Bank = 0x0;
+
+  /* Bank1 NOR/SRAM control register configuration */ 
+  // FSMC_MemoryType_NOR | FSMC_MemoryDataWidth_16b | FSMC_WriteOperation_Enable
+  FSMC_Bank1->BTCR[FSMC_Bank] = (uint32_t)(0x8 | 0x10 | 0x1000);
+
+  // if FSMC_MemoryType_NOR
+  FSMC_Bank1->BTCR[FSMC_Bank] |= ((uint32_t)0x00000040);
+  
+  /* Bank1 NOR/SRAM timing register configuration */
+  // AddressSetupTime | DataSetupTime | FSMC_AccessMode_B
+  FSMC_Bank1->BTCR[FSMC_Bank+1] = (uint32_t)(0x2 | (0x5 << 8) | 0x10000000);
+
+  /* Bank1 NOR/SRAM timing register for write configuration, if extended mode is used */
+  FSMC_Bank1E->BWTR[FSMC_Bank] = 0x0FFFFFFF;
+
+  /* Enable FSMC Bank1_SRAM Bank */
+  FSMC_Bank1->BTCR[FSMC_Bank] |= 0x1;
+}
+
+static inline void post_init_board(GDisplay *g) {
+	(void) g;
+}
+
+static inline void setpin_reset(GDisplay *g, bool_t state) {
+	(void) g;
+	if(state)
+		palClearPad(GPIOE, GPIOE_TFT_RST);
+	else
+		palSetPad(GPIOE, GPIOE_TFT_RST);
+}
+
+static inline void set_backlight(GDisplay *g, uint8_t percent) {
+	(void) g;
+	(void)percent;
+}
+
+static inline void gdisp_lld_backlight(GDisplay *g, uint8_t percent) {
+	(void) g;
+	(void)percent;
+}
+
+static inline void acquire_bus(GDisplay *g) {
+	(void) g;
+}
+
+static inline void release_bus(GDisplay *g) {
+	(void) g;
+}
+
+static inline void write_index(GDisplay *g, uint16_t index) {
+	(void) g;
+	GDISP_REG = index;
+}
+
+static inline void write_data(GDisplay *g, uint16_t data) {
+	(void) g;
+	GDISP_RAM = data;
+}
+
+static inline void setreadmode(GDisplay *g) {
+	(void) g;
+}
+
+static inline void setwritemode(GDisplay *g) {
+	(void) g;
+}
+
+static inline uint16_t read_data(GDisplay *g) {
+	(void) g;
+	return GDISP_RAM;
+}
+
+#endif /* GDISP_LLD_BOARD_H */

+ 27 - 0
board/ginput_lld_toggle_board.h

@@ -0,0 +1,27 @@
+/*
+ * This file is subject to the terms of the GFX License. If a copy of
+ * the license was not distributed with this file, you can obtain one at:
+ *
+ *              http://ugfx.io/license.html
+ */
+
+#ifndef _GDISP_LLD_TOGGLE_BOARD_H
+#define _GDISP_LLD_TOGGLE_BOARD_H
+
+#define GINPUT_TOGGLE_NUM_PORTS       4  // The total number of toggle inputs
+#define GINPUT_TOGGLE_CONFIG_ENTRIES  1  // The total number of GToggleConfig entries
+
+#define GINPUT_TOGGLE_SW1      0  // Switch 1
+#define GINPUT_TOGGLE_SW2      1  // Switch 2
+#define GINPUT_TOGGLE_SW3      2  // Switch 3
+#define GINPUT_TOGGLE_SW4      3  // Switch 4
+
+#define GINPUT_TOGGLE_DECLARE_STRUCTURE() \
+  const GToggleConfig GInputToggleConfigTable[GINPUT_TOGGLE_CONFIG_ENTRIES] = { \
+    {GPIOE, /* Switch 1 - Switch 4 */ \
+      (1<<GPIOE_BUTTON1) | (1<<GPIOE_BUTTON2) | (1<<GPIOE_BUTTON3) | (1<<GPIOE_BUTTON4), \
+      (1<<GPIOE_BUTTON1) | (1<<GPIOE_BUTTON2) | (1<<GPIOE_BUTTON3) | (1<<GPIOE_BUTTON4), \
+      PAL_MODE_INPUT}, \
+  }
+
+#endif /* _GDISP_LLD_TOGGLE_BOARD_H */

+ 87 - 0
board/gmouse_lld_ADS7843_board.h

@@ -0,0 +1,87 @@
+/*
+ * This file is subject to the terms of the GFX License. If a copy of
+ * the license was not distributed with this file, you can obtain one at:
+ *
+ *              http://ugfx.io/license.html
+ */
+
+#ifndef _GINPUT_LLD_MOUSE_BOARD_H
+#define _GINPUT_LLD_MOUSE_BOARD_H
+
+// Resolution and Accuracy Settings
+#define GMOUSE_ADS7843_PEN_CALIBRATE_ERROR		2
+#define GMOUSE_ADS7843_PEN_CLICK_ERROR			2
+#define GMOUSE_ADS7843_PEN_MOVE_ERROR			2
+#define GMOUSE_ADS7843_FINGER_CALIBRATE_ERROR	20
+#define GMOUSE_ADS7843_FINGER_CLICK_ERROR		4
+#define GMOUSE_ADS7843_FINGER_MOVE_ERROR		4
+
+// How much extra data to allocate at the end of the GMouse structure for the board's use
+#define GMOUSE_ADS7843_BOARD_DATA_SIZE			0
+
+static const SPIConfig spicfg = { 
+    0,
+	GPIOB, 
+    7, // CS
+    /* SPI_CR1_BR_2 |*/ SPI_CR1_BR_1 | SPI_CR1_BR_0,
+};
+
+static gBool init_board(GMouse* m, unsigned driverinstance)
+{
+	(void)m;
+
+	// Only one touch interface on this board
+	if (driverinstance)
+		return gFalse;
+	
+	// Set the GPIO modes
+	palSetPadMode(GPIOB, 6, PAL_MODE_INPUT_PULLUP); // IRQ
+	palSetPadMode(GPIOC, 6, PAL_MODE_INPUT); // BUSY
+
+	// Start the SPI peripheral
+	spiStart(&SPID1, &spicfg);
+
+	return gTrue;
+}
+
+static GFXINLINE gBool getpin_pressed(GMouse* m)
+{
+	(void)	m;
+
+	return (!palReadPad(GPIOB, 6));
+}
+
+static GFXINLINE void aquire_bus(GMouse* m)
+{
+	(void)	m;
+
+	spiAcquireBus(&SPID1);
+    palClearPad(GPIOB, 7);
+}
+
+static GFXINLINE void release_bus(GMouse* m)
+{
+	(void)	m;
+
+	palSetPad(GPIOB, 7);
+	spiReleaseBus(&SPID1);
+}
+
+static GFXINLINE gU16 read_value(GMouse* m, gU16 port)
+{
+    static gU8 txbuf[3] = {0};
+    static gU8 rxbuf[3] = {0};
+    gU16 ret;
+	(void)	m;
+
+    txbuf[0] = port;
+
+    spiExchange(&SPID1, 3, txbuf, rxbuf);
+
+    ret = (rxbuf[1] << 5) | (rxbuf[2] >> 3); 
+    
+	return ret;
+}
+
+#endif /* _GINPUT_LLD_MOUSE_BOARD_H */
+

+ 840 - 0
cfg/chconf.h

@@ -0,0 +1,840 @@
+/*
+    ChibiOS - Copyright (C) 2006..2020 Giovanni Di Sirio
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+*/
+
+/**
+ * @file    rt/templates/chconf.h
+ * @brief   Configuration file template.
+ * @details A copy of this file must be placed in each project directory, it
+ *          contains the application specific kernel settings.
+ *
+ * @addtogroup config
+ * @details Kernel related settings and hooks.
+ * @{
+ */
+
+#ifndef CHCONF_H
+#define CHCONF_H
+
+#define _CHIBIOS_RT_CONF_
+#define _CHIBIOS_RT_CONF_VER_7_0_
+
+/*===========================================================================*/
+/**
+ * @name System settings
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   Handling of instances.
+ * @note    If enabled then threads assigned to various instances can
+ *          interact each other using the same synchronization objects.
+ *          If disabled then each OS instance is a separate world, no
+ *          direct interactions are handled by the OS.
+ */
+#if !defined(CH_CFG_SMP_MODE)
+#define CH_CFG_SMP_MODE                     FALSE
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name System timers settings
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   System time counter resolution.
+ * @note    Allowed values are 16, 32 or 64 bits.
+ */
+#if !defined(CH_CFG_ST_RESOLUTION)
+#define CH_CFG_ST_RESOLUTION                16
+#endif
+
+/**
+ * @brief   System tick frequency.
+ * @details Frequency of the system timer that drives the system ticks. This
+ *          setting also defines the system tick time unit.
+ */
+#if !defined(CH_CFG_ST_FREQUENCY)
+#define CH_CFG_ST_FREQUENCY                 2000
+#endif
+
+/**
+ * @brief   Time intervals data size.
+ * @note    Allowed values are 16, 32 or 64 bits.
+ */
+#if !defined(CH_CFG_INTERVALS_SIZE)
+#define CH_CFG_INTERVALS_SIZE               32
+#endif
+
+/**
+ * @brief   Time types data size.
+ * @note    Allowed values are 16 or 32 bits.
+ */
+#if !defined(CH_CFG_TIME_TYPES_SIZE)
+#define CH_CFG_TIME_TYPES_SIZE              32
+#endif
+
+/**
+ * @brief   Time delta constant for the tick-less mode.
+ * @note    If this value is zero then the system uses the classic
+ *          periodic tick. This value represents the minimum number
+ *          of ticks that is safe to specify in a timeout directive.
+ *          The value one is not valid, timeouts are rounded up to
+ *          this value.
+ */
+#if !defined(CH_CFG_ST_TIMEDELTA)
+#define CH_CFG_ST_TIMEDELTA                 2
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Kernel parameters and options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   Round robin interval.
+ * @details This constant is the number of system ticks allowed for the
+ *          threads before preemption occurs. Setting this value to zero
+ *          disables the preemption for threads with equal priority and the
+ *          round robin becomes cooperative. Note that higher priority
+ *          threads can still preempt, the kernel is always preemptive.
+ * @note    Disabling the round robin preemption makes the kernel more compact
+ *          and generally faster.
+ * @note    The round robin preemption is not supported in tickless mode and
+ *          must be set to zero in that case.
+ */
+#if !defined(CH_CFG_TIME_QUANTUM)
+#define CH_CFG_TIME_QUANTUM                 0
+#endif
+
+/**
+ * @brief   Idle thread automatic spawn suppression.
+ * @details When this option is activated the function @p chSysInit()
+ *          does not spawn the idle thread. The application @p main()
+ *          function becomes the idle thread and must implement an
+ *          infinite loop.
+ */
+#if !defined(CH_CFG_NO_IDLE_THREAD)
+#define CH_CFG_NO_IDLE_THREAD               FALSE
+#endif
+
+/**
+ * @brief   Kernel hardening level.
+ * @details This option is the level of functional-safety checks enabled
+ *          in the kerkel. The meaning is:
+ *          - 0: No checks, maximum performance.
+ *          - 1: Reasonable checks.
+ *          - 2: All checks.
+ *          .
+ */
+#if !defined(CH_CFG_HARDENING_LEVEL)
+#define CH_CFG_HARDENING_LEVEL              0
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Performance options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   OS optimization.
+ * @details If enabled then time efficient rather than space efficient code
+ *          is used when two possible implementations exist.
+ *
+ * @note    This is not related to the compiler optimization options.
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_OPTIMIZE_SPEED)
+#define CH_CFG_OPTIMIZE_SPEED               TRUE
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Subsystem options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   Time Measurement APIs.
+ * @details If enabled then the time measurement APIs are included in
+ *          the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_TM)
+#define CH_CFG_USE_TM                       TRUE
+#endif
+
+/**
+ * @brief   Time Stamps APIs.
+ * @details If enabled then the time stamps APIs are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_TIMESTAMP)
+#define CH_CFG_USE_TIMESTAMP                TRUE
+#endif
+
+/**
+ * @brief   Threads registry APIs.
+ * @details If enabled then the registry APIs are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_REGISTRY)
+#define CH_CFG_USE_REGISTRY                 TRUE
+#endif
+
+/**
+ * @brief   Threads synchronization APIs.
+ * @details If enabled then the @p chThdWait() function is included in
+ *          the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_WAITEXIT)
+#define CH_CFG_USE_WAITEXIT                 TRUE
+#endif
+
+/**
+ * @brief   Semaphores APIs.
+ * @details If enabled then the Semaphores APIs are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_SEMAPHORES)
+#define CH_CFG_USE_SEMAPHORES               TRUE
+#endif
+
+/**
+ * @brief   Semaphores queuing mode.
+ * @details If enabled then the threads are enqueued on semaphores by
+ *          priority rather than in FIFO order.
+ *
+ * @note    The default is @p FALSE. Enable this if you have special
+ *          requirements.
+ * @note    Requires @p CH_CFG_USE_SEMAPHORES.
+ */
+#if !defined(CH_CFG_USE_SEMAPHORES_PRIORITY)
+#define CH_CFG_USE_SEMAPHORES_PRIORITY      FALSE
+#endif
+
+/**
+ * @brief   Mutexes APIs.
+ * @details If enabled then the mutexes APIs are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_MUTEXES)
+#define CH_CFG_USE_MUTEXES                  TRUE
+#endif
+
+/**
+ * @brief   Enables recursive behavior on mutexes.
+ * @note    Recursive mutexes are heavier and have an increased
+ *          memory footprint.
+ *
+ * @note    The default is @p FALSE.
+ * @note    Requires @p CH_CFG_USE_MUTEXES.
+ */
+#if !defined(CH_CFG_USE_MUTEXES_RECURSIVE)
+#define CH_CFG_USE_MUTEXES_RECURSIVE        FALSE
+#endif
+
+/**
+ * @brief   Conditional Variables APIs.
+ * @details If enabled then the conditional variables APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ * @note    Requires @p CH_CFG_USE_MUTEXES.
+ */
+#if !defined(CH_CFG_USE_CONDVARS)
+#define CH_CFG_USE_CONDVARS                 TRUE
+#endif
+
+/**
+ * @brief   Conditional Variables APIs with timeout.
+ * @details If enabled then the conditional variables APIs with timeout
+ *          specification are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ * @note    Requires @p CH_CFG_USE_CONDVARS.
+ */
+#if !defined(CH_CFG_USE_CONDVARS_TIMEOUT)
+#define CH_CFG_USE_CONDVARS_TIMEOUT         TRUE
+#endif
+
+/**
+ * @brief   Events Flags APIs.
+ * @details If enabled then the event flags APIs are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_EVENTS)
+#define CH_CFG_USE_EVENTS                   TRUE
+#endif
+
+/**
+ * @brief   Events Flags APIs with timeout.
+ * @details If enabled then the events APIs with timeout specification
+ *          are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ * @note    Requires @p CH_CFG_USE_EVENTS.
+ */
+#if !defined(CH_CFG_USE_EVENTS_TIMEOUT)
+#define CH_CFG_USE_EVENTS_TIMEOUT           TRUE
+#endif
+
+/**
+ * @brief   Synchronous Messages APIs.
+ * @details If enabled then the synchronous messages APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_MESSAGES)
+#define CH_CFG_USE_MESSAGES                 TRUE
+#endif
+
+/**
+ * @brief   Synchronous Messages queuing mode.
+ * @details If enabled then messages are served by priority rather than in
+ *          FIFO order.
+ *
+ * @note    The default is @p FALSE. Enable this if you have special
+ *          requirements.
+ * @note    Requires @p CH_CFG_USE_MESSAGES.
+ */
+#if !defined(CH_CFG_USE_MESSAGES_PRIORITY)
+#define CH_CFG_USE_MESSAGES_PRIORITY        FALSE
+#endif
+
+/**
+ * @brief   Dynamic Threads APIs.
+ * @details If enabled then the dynamic threads creation APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ * @note    Requires @p CH_CFG_USE_WAITEXIT.
+ * @note    Requires @p CH_CFG_USE_HEAP and/or @p CH_CFG_USE_MEMPOOLS.
+ */
+#if !defined(CH_CFG_USE_DYNAMIC)
+#define CH_CFG_USE_DYNAMIC                  TRUE
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name OSLIB options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   Mailboxes APIs.
+ * @details If enabled then the asynchronous messages (mailboxes) APIs are
+ *          included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ * @note    Requires @p CH_CFG_USE_SEMAPHORES.
+ */
+#if !defined(CH_CFG_USE_MAILBOXES)
+#define CH_CFG_USE_MAILBOXES                TRUE
+#endif
+
+/**
+ * @brief   Memory checks APIs.
+ * @details If enabled then the memory checks APIs are included in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_MEMCHECKS)
+#define CH_CFG_USE_MEMCHECKS                TRUE
+#endif
+
+/**
+ * @brief   Core Memory Manager APIs.
+ * @details If enabled then the core memory manager APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_MEMCORE)
+#define CH_CFG_USE_MEMCORE                  TRUE
+#endif
+
+/**
+ * @brief   Managed RAM size.
+ * @details Size of the RAM area to be managed by the OS. If set to zero
+ *          then the whole available RAM is used. The core memory is made
+ *          available to the heap allocator and/or can be used directly through
+ *          the simplified core memory allocator.
+ *
+ * @note    In order to let the OS manage the whole RAM the linker script must
+ *          provide the @p __heap_base__ and @p __heap_end__ symbols.
+ * @note    Requires @p CH_CFG_USE_MEMCORE.
+ */
+#if !defined(CH_CFG_MEMCORE_SIZE)
+#define CH_CFG_MEMCORE_SIZE                 0
+#endif
+
+/**
+ * @brief   Heap Allocator APIs.
+ * @details If enabled then the memory heap allocator APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ * @note    Requires @p CH_CFG_USE_MEMCORE and either @p CH_CFG_USE_MUTEXES or
+ *          @p CH_CFG_USE_SEMAPHORES.
+ * @note    Mutexes are recommended.
+ */
+#if !defined(CH_CFG_USE_HEAP)
+#define CH_CFG_USE_HEAP                     TRUE
+#endif
+
+/**
+ * @brief   Memory Pools Allocator APIs.
+ * @details If enabled then the memory pools allocator APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_MEMPOOLS)
+#define CH_CFG_USE_MEMPOOLS                 TRUE
+#endif
+
+/**
+ * @brief   Objects FIFOs APIs.
+ * @details If enabled then the objects FIFOs APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_OBJ_FIFOS)
+#define CH_CFG_USE_OBJ_FIFOS                TRUE
+#endif
+
+/**
+ * @brief   Pipes APIs.
+ * @details If enabled then the pipes APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_PIPES)
+#define CH_CFG_USE_PIPES                    TRUE
+#endif
+
+/**
+ * @brief   Objects Caches APIs.
+ * @details If enabled then the objects caches APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_OBJ_CACHES)
+#define CH_CFG_USE_OBJ_CACHES               TRUE
+#endif
+
+/**
+ * @brief   Delegate threads APIs.
+ * @details If enabled then the delegate threads APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_DELEGATES)
+#define CH_CFG_USE_DELEGATES                TRUE
+#endif
+
+/**
+ * @brief   Jobs Queues APIs.
+ * @details If enabled then the jobs queues APIs are included
+ *          in the kernel.
+ *
+ * @note    The default is @p TRUE.
+ */
+#if !defined(CH_CFG_USE_JOBS)
+#define CH_CFG_USE_JOBS                     TRUE
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Objects factory options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   Objects Factory APIs.
+ * @details If enabled then the objects factory APIs are included in the
+ *          kernel.
+ *
+ * @note    The default is @p FALSE.
+ */
+#if !defined(CH_CFG_USE_FACTORY)
+#define CH_CFG_USE_FACTORY                  TRUE
+#endif
+
+/**
+ * @brief   Maximum length for object names.
+ * @details If the specified length is zero then the name is stored by
+ *          pointer but this could have unintended side effects.
+ */
+#if !defined(CH_CFG_FACTORY_MAX_NAMES_LENGTH)
+#define CH_CFG_FACTORY_MAX_NAMES_LENGTH     8
+#endif
+
+/**
+ * @brief   Enables the registry of generic objects.
+ */
+#if !defined(CH_CFG_FACTORY_OBJECTS_REGISTRY)
+#define CH_CFG_FACTORY_OBJECTS_REGISTRY     TRUE
+#endif
+
+/**
+ * @brief   Enables factory for generic buffers.
+ */
+#if !defined(CH_CFG_FACTORY_GENERIC_BUFFERS)
+#define CH_CFG_FACTORY_GENERIC_BUFFERS      TRUE
+#endif
+
+/**
+ * @brief   Enables factory for semaphores.
+ */
+#if !defined(CH_CFG_FACTORY_SEMAPHORES)
+#define CH_CFG_FACTORY_SEMAPHORES           TRUE
+#endif
+
+/**
+ * @brief   Enables factory for mailboxes.
+ */
+#if !defined(CH_CFG_FACTORY_MAILBOXES)
+#define CH_CFG_FACTORY_MAILBOXES            TRUE
+#endif
+
+/**
+ * @brief   Enables factory for objects FIFOs.
+ */
+#if !defined(CH_CFG_FACTORY_OBJ_FIFOS)
+#define CH_CFG_FACTORY_OBJ_FIFOS            TRUE
+#endif
+
+/**
+ * @brief   Enables factory for Pipes.
+ */
+#if !defined(CH_CFG_FACTORY_PIPES) || defined(__DOXYGEN__)
+#define CH_CFG_FACTORY_PIPES                TRUE
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Debug options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   Debug option, kernel statistics.
+ *
+ * @note    The default is @p FALSE.
+ */
+#if !defined(CH_DBG_STATISTICS)
+#define CH_DBG_STATISTICS                   FALSE
+#endif
+
+/**
+ * @brief   Debug option, system state check.
+ * @details If enabled the correct call protocol for system APIs is checked
+ *          at runtime.
+ *
+ * @note    The default is @p FALSE.
+ */
+#if !defined(CH_DBG_SYSTEM_STATE_CHECK)
+#define CH_DBG_SYSTEM_STATE_CHECK           TRUE
+#endif
+
+/**
+ * @brief   Debug option, parameters checks.
+ * @details If enabled then the checks on the API functions input
+ *          parameters are activated.
+ *
+ * @note    The default is @p FALSE.
+ */
+#if !defined(CH_DBG_ENABLE_CHECKS)
+#define CH_DBG_ENABLE_CHECKS                TRUE
+#endif
+
+/**
+ * @brief   Debug option, consistency checks.
+ * @details If enabled then all the assertions in the kernel code are
+ *          activated. This includes consistency checks inside the kernel,
+ *          runtime anomalies and port-defined checks.
+ *
+ * @note    The default is @p FALSE.
+ */
+#if !defined(CH_DBG_ENABLE_ASSERTS)
+#define CH_DBG_ENABLE_ASSERTS               FALSE
+#endif
+
+/**
+ * @brief   Debug option, trace buffer.
+ * @details If enabled then the trace buffer is activated.
+ *
+ * @note    The default is @p CH_DBG_TRACE_MASK_DISABLED.
+ */
+#if !defined(CH_DBG_TRACE_MASK)
+#define CH_DBG_TRACE_MASK                   CH_DBG_TRACE_MASK_DISABLED
+#endif
+
+/**
+ * @brief   Trace buffer entries.
+ * @note    The trace buffer is only allocated if @p CH_DBG_TRACE_MASK is
+ *          different from @p CH_DBG_TRACE_MASK_DISABLED.
+ */
+#if !defined(CH_DBG_TRACE_BUFFER_SIZE)
+#define CH_DBG_TRACE_BUFFER_SIZE            128
+#endif
+
+/**
+ * @brief   Debug option, stack checks.
+ * @details If enabled then a runtime stack check is performed.
+ *
+ * @note    The default is @p FALSE.
+ * @note    The stack check is performed in a architecture/port dependent way.
+ *          It may not be implemented or some ports.
+ * @note    The default failure mode is to halt the system with the global
+ *          @p panic_msg variable set to @p NULL.
+ */
+#if !defined(CH_DBG_ENABLE_STACK_CHECK)
+#define CH_DBG_ENABLE_STACK_CHECK           FALSE
+#endif
+
+/**
+ * @brief   Debug option, stacks initialization.
+ * @details If enabled then the threads working area is filled with a byte
+ *          value when a thread is created. This can be useful for the
+ *          runtime measurement of the used stack.
+ *
+ * @note    The default is @p FALSE.
+ */
+#if !defined(CH_DBG_FILL_THREADS)
+#define CH_DBG_FILL_THREADS                 FALSE
+#endif
+
+/**
+ * @brief   Debug option, threads profiling.
+ * @details If enabled then a field is added to the @p thread_t structure that
+ *          counts the system ticks occurred while executing the thread.
+ *
+ * @note    The default is @p FALSE.
+ * @note    This debug option is not currently compatible with the
+ *          tickless mode.
+ */
+#if !defined(CH_DBG_THREADS_PROFILING)
+#define CH_DBG_THREADS_PROFILING            FALSE
+#endif
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Kernel hooks
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief   System structure extension.
+ * @details User fields added to the end of the @p ch_system_t structure.
+ */
+#define CH_CFG_SYSTEM_EXTRA_FIELDS                                          \
+  /* Add system custom fields here.*/
+
+/**
+ * @brief   System initialization hook.
+ * @details User initialization code added to the @p chSysInit() function
+ *          just before interrupts are enabled globally.
+ */
+#define CH_CFG_SYSTEM_INIT_HOOK() {                                         \
+  /* Add system initialization code here.*/                                 \
+}
+
+/**
+ * @brief   OS instance structure extension.
+ * @details User fields added to the end of the @p os_instance_t structure.
+ */
+#define CH_CFG_OS_INSTANCE_EXTRA_FIELDS                                     \
+  /* Add OS instance custom fields here.*/
+
+/**
+ * @brief   OS instance initialization hook.
+ *
+ * @param[in] oip       pointer to the @p os_instance_t structure
+ */
+#define CH_CFG_OS_INSTANCE_INIT_HOOK(oip) {                                 \
+  /* Add OS instance initialization code here.*/                            \
+}
+
+/**
+ * @brief   Threads descriptor structure extension.
+ * @details User fields added to the end of the @p thread_t structure.
+ */
+#define CH_CFG_THREAD_EXTRA_FIELDS                                          \
+  /* Add threads custom fields here.*/
+
+/**
+ * @brief   Threads initialization hook.
+ * @details User initialization code added to the @p _thread_init() function.
+ *
+ * @note    It is invoked from within @p _thread_init() and implicitly from all
+ *          the threads creation APIs.
+ *
+ * @param[in] tp        pointer to the @p thread_t structure
+ */
+#define CH_CFG_THREAD_INIT_HOOK(tp) {                                       \
+  /* Add threads initialization code here.*/                                \
+}
+
+/**
+ * @brief   Threads finalization hook.
+ * @details User finalization code added to the @p chThdExit() API.
+ *
+ * @param[in] tp        pointer to the @p thread_t structure
+ */
+#define CH_CFG_THREAD_EXIT_HOOK(tp) {                                       \
+  /* Add threads finalization code here.*/                                  \
+}
+
+/**
+ * @brief   Context switch hook.
+ * @details This hook is invoked just before switching between threads.
+ *
+ * @param[in] ntp       thread being switched in
+ * @param[in] otp       thread being switched out
+ */
+#define CH_CFG_CONTEXT_SWITCH_HOOK(ntp, otp) {                              \
+  /* Context switch code here.*/                                            \
+}
+
+/**
+ * @brief   ISR enter hook.
+ */
+#define CH_CFG_IRQ_PROLOGUE_HOOK() {                                        \
+  /* IRQ prologue code here.*/                                              \
+}
+
+/**
+ * @brief   ISR exit hook.
+ */
+#define CH_CFG_IRQ_EPILOGUE_HOOK() {                                        \
+  /* IRQ epilogue code here.*/                                              \
+}
+
+/**
+ * @brief   Idle thread enter hook.
+ * @note    This hook is invoked within a critical zone, no OS functions
+ *          should be invoked from here.
+ * @note    This macro can be used to activate a power saving mode.
+ */
+#define CH_CFG_IDLE_ENTER_HOOK() {                                          \
+  /* Idle-enter code here.*/                                                \
+}
+
+/**
+ * @brief   Idle thread leave hook.
+ * @note    This hook is invoked within a critical zone, no OS functions
+ *          should be invoked from here.
+ * @note    This macro can be used to deactivate a power saving mode.
+ */
+#define CH_CFG_IDLE_LEAVE_HOOK() {                                          \
+  /* Idle-leave code here.*/                                                \
+}
+
+/**
+ * @brief   Idle Loop hook.
+ * @details This hook is continuously invoked by the idle thread loop.
+ */
+#define CH_CFG_IDLE_LOOP_HOOK() {                                           \
+  /* Idle loop code here.*/                                                 \
+}
+
+/**
+ * @brief   System tick event hook.
+ * @details This hook is invoked in the system tick handler immediately
+ *          after processing the virtual timers queue.
+ */
+#define CH_CFG_SYSTEM_TICK_HOOK() {                                         \
+  /* System tick event code here.*/                                         \
+}
+
+/**
+ * @brief   System halt hook.
+ * @details This hook is invoked in case to a system halting error before
+ *          the system is halted.
+ */
+#define CH_CFG_SYSTEM_HALT_HOOK(reason) {                                   \
+  /* System halt code here.*/                                               \
+}
+
+/**
+ * @brief   Trace hook.
+ * @details This hook is invoked each time a new record is written in the
+ *          trace buffer.
+ */
+#define CH_CFG_TRACE_HOOK(tep) {                                            \
+  /* Trace code here.*/                                                     \
+}
+
+/**
+ * @brief   Runtime Faults Collection Unit hook.
+ * @details This hook is invoked each time new faults are collected and stored.
+ */
+#define CH_CFG_RUNTIME_FAULTS_HOOK(mask) {                                  \
+  /* Faults handling code here.*/                                           \
+}
+
+/** @} */
+
+/*===========================================================================*/
+/* Port-specific settings (override port settings defaulted in chcore.h).    */
+/*===========================================================================*/
+
+#endif  /* CHCONF_H */
+
+/** @} */

+ 76 - 0
cfg/gfxconf.h

@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2012, 2013, Joel Bodenmann aka Tectu <joel@unormal.org>
+ * Copyright (c) 2012, 2013, Andrew Hannam aka inmarket
+ *
+ * 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 the <organization> 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 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.
+ */
+
+#ifndef _GFXCONF_H
+#define _GFXCONF_H
+
+/* The operating system to use. One of these must be defined - preferably in your Makefile */
+#define GFX_USE_OS_CHIBIOS		GFXON
+    #define GFX_MEM_LT64K		GFXOFF
+#define GOS_NEED_X_HEAP 		GFXOFF
+#define GOS_NEED_X_THREADS		GFXOFF
+
+/* GFX sub-systems to turn on */
+#define GFX_USE_GDISP			GFXON
+#define GFX_USE_GWIN			GFXON
+#define GFX_USE_GMISC			GFXON
+#define GFX_USE_GTIMER			GFXON
+#define GFX_USE_GQUEUE			GFXON
+#define GDISP_NEED_CONTROL		GFXON
+#define GDISP_DEFAULT_ORIENTATION       gOrientationLandscape
+
+/* Features for the GDISP sub-system. */
+#define GDISP_NEED_VALIDATION	    GFXON
+#define GDISP_NEED_CLIP			    GFXON
+#define GDISP_NEED_MULTITHREAD	    GFXON
+#define GDISP_NEED_TEXT			    GFXON
+
+/* GDISP fonts to include */
+#define GDISP_INCLUDE_FONT_DEJAVUSANS12 GFXON
+#define GDISP_INCLUDE_FONT_DEJAVUSANS24 GFXON
+
+/* Features for the GWIN subsystem. */
+#define GWIN_NEED_WINDOWMANAGER	    GFXON
+#define GWIN_NEED_CONSOLE		    GFXON
+#define GWIN_CONSOLE_ESCSEQ		    GFXON
+#define GWIN_CONSOLE_USE_HISTORY	GFXOFF
+//#define GWIN_CONSOLE_HISTORY_AVERAGING	GFXON
+//#define GWIN_CONSOLE_HISTORY_ATCREATE	GFXON
+#define GWIN_NEED_GRAPH			    GFXON
+
+/* Features for the GQUEUE subsystem. */
+#define GQUEUE_NEED_ASYNC           GFXON
+
+/* Features for the GMISC subsystem. */
+#define GMISC_NEED_FASTTRIG		    GFXON
+#define GMISC_NEED_MATRIXFLOAT2D    GFXOFF
+#define GMISC_NEED_MATRIXFIXED2D    GFXOFF
+
+#endif /* _GFXCONF_H */
+

+ 550 - 0
cfg/halconf.h

@@ -0,0 +1,550 @@
+/*
+    ChibiOS - Copyright (C) 2006..2020 Giovanni Di Sirio
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+*/
+
+/**
+ * @file    templates/halconf.h
+ * @brief   HAL configuration header.
+ * @details HAL configuration file, this file allows to enable or disable the
+ *          various device drivers from your application. You may also use
+ *          this file in order to override the device drivers default settings.
+ *
+ * @addtogroup HAL_CONF
+ * @{
+ */
+
+#ifndef HALCONF_H
+#define HALCONF_H
+
+#define _CHIBIOS_HAL_CONF_
+#define _CHIBIOS_HAL_CONF_VER_8_0_
+
+#include "mcuconf.h"
+
+/**
+ * @brief   Enables the PAL subsystem.
+ */
+#if !defined(HAL_USE_PAL) || defined(__DOXYGEN__)
+#define HAL_USE_PAL                         TRUE
+#endif
+
+/**
+ * @brief   Enables the ADC subsystem.
+ */
+#if !defined(HAL_USE_ADC) || defined(__DOXYGEN__)
+#define HAL_USE_ADC                         FALSE
+#endif
+
+/**
+ * @brief   Enables the CAN subsystem.
+ */
+#if !defined(HAL_USE_CAN) || defined(__DOXYGEN__)
+#define HAL_USE_CAN                         FALSE
+#endif
+
+/**
+ * @brief   Enables the cryptographic subsystem.
+ */
+#if !defined(HAL_USE_CRY) || defined(__DOXYGEN__)
+#define HAL_USE_CRY                         FALSE
+#endif
+
+/**
+ * @brief   Enables the DAC subsystem.
+ */
+#if !defined(HAL_USE_DAC) || defined(__DOXYGEN__)
+#define HAL_USE_DAC                         FALSE
+#endif
+
+/**
+ * @brief   Enables the EFlash subsystem.
+ */
+#if !defined(HAL_USE_EFL) || defined(__DOXYGEN__)
+#define HAL_USE_EFL                         FALSE
+#endif
+
+/**
+ * @brief   Enables the GPT subsystem.
+ */
+#if !defined(HAL_USE_GPT) || defined(__DOXYGEN__)
+#define HAL_USE_GPT                         TRUE
+#endif
+
+/**
+ * @brief   Enables the I2C subsystem.
+ */
+#if !defined(HAL_USE_I2C) || defined(__DOXYGEN__)
+#define HAL_USE_I2C                         TRUE
+#endif
+
+/**
+ * @brief   Enables the I2S subsystem.
+ */
+#if !defined(HAL_USE_I2S) || defined(__DOXYGEN__)
+#define HAL_USE_I2S                         FALSE
+#endif
+
+/**
+ * @brief   Enables the ICU subsystem.
+ */
+#if !defined(HAL_USE_ICU) || defined(__DOXYGEN__)
+#define HAL_USE_ICU                         FALSE
+#endif
+
+/**
+ * @brief   Enables the MAC subsystem.
+ */
+#if !defined(HAL_USE_MAC) || defined(__DOXYGEN__)
+#define HAL_USE_MAC                         FALSE
+#endif
+
+/**
+ * @brief   Enables the MMC_SPI subsystem.
+ */
+#if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__)
+#define HAL_USE_MMC_SPI                     FALSE
+#endif
+
+/**
+ * @brief   Enables the PWM subsystem.
+ */
+#if !defined(HAL_USE_PWM) || defined(__DOXYGEN__)
+#define HAL_USE_PWM                         FALSE
+#endif
+
+/**
+ * @brief   Enables the RTC subsystem.
+ */
+#if !defined(HAL_USE_RTC) || defined(__DOXYGEN__)
+#define HAL_USE_RTC                         FALSE
+#endif
+
+/**
+ * @brief   Enables the SDC subsystem.
+ */
+#if !defined(HAL_USE_SDC) || defined(__DOXYGEN__)
+#define HAL_USE_SDC                         FALSE
+#endif
+
+/**
+ * @brief   Enables the SERIAL subsystem.
+ */
+#if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__)
+#define HAL_USE_SERIAL                      TRUE
+#endif
+
+/**
+ * @brief   Enables the SERIAL over USB subsystem.
+ */
+#if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__)
+#define HAL_USE_SERIAL_USB                  FALSE
+#endif
+
+/**
+ * @brief   Enables the SIO subsystem.
+ */
+#if !defined(HAL_USE_SIO) || defined(__DOXYGEN__)
+#define HAL_USE_SIO                         FALSE
+#endif
+
+/**
+ * @brief   Enables the SPI subsystem.
+ */
+#if !defined(HAL_USE_SPI) || defined(__DOXYGEN__)
+#define HAL_USE_SPI                         FALSE
+#endif
+
+/**
+ * @brief   Enables the TRNG subsystem.
+ */
+#if !defined(HAL_USE_TRNG) || defined(__DOXYGEN__)
+#define HAL_USE_TRNG                        FALSE
+#endif
+
+/**
+ * @brief   Enables the UART subsystem.
+ */
+#if !defined(HAL_USE_UART) || defined(__DOXYGEN__)
+#define HAL_USE_UART                        FALSE
+#endif
+
+/**
+ * @brief   Enables the USB subsystem.
+ */
+#if !defined(HAL_USE_USB) || defined(__DOXYGEN__)
+#define HAL_USE_USB                         FALSE
+#endif
+
+/**
+ * @brief   Enables the WDG subsystem.
+ */
+#if !defined(HAL_USE_WDG) || defined(__DOXYGEN__)
+#define HAL_USE_WDG                         FALSE
+#endif
+
+/**
+ * @brief   Enables the WSPI subsystem.
+ */
+#if !defined(HAL_USE_WSPI) || defined(__DOXYGEN__)
+#define HAL_USE_WSPI                        FALSE
+#endif
+
+/*===========================================================================*/
+/* PAL driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(PAL_USE_CALLBACKS) || defined(__DOXYGEN__)
+#define PAL_USE_CALLBACKS                   FALSE
+#endif
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(PAL_USE_WAIT) || defined(__DOXYGEN__)
+#define PAL_USE_WAIT                        FALSE
+#endif
+
+/*===========================================================================*/
+/* ADC driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(ADC_USE_WAIT) || defined(__DOXYGEN__)
+#define ADC_USE_WAIT                        TRUE
+#endif
+
+/**
+ * @brief   Enables the @p adcAcquireBus() and @p adcReleaseBus() APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(ADC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
+#define ADC_USE_MUTUAL_EXCLUSION            TRUE
+#endif
+
+/*===========================================================================*/
+/* CAN driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Sleep mode related APIs inclusion switch.
+ */
+#if !defined(CAN_USE_SLEEP_MODE) || defined(__DOXYGEN__)
+#define CAN_USE_SLEEP_MODE                  TRUE
+#endif
+
+/**
+ * @brief   Enforces the driver to use direct callbacks rather than OSAL events.
+ */
+#if !defined(CAN_ENFORCE_USE_CALLBACKS) || defined(__DOXYGEN__)
+#define CAN_ENFORCE_USE_CALLBACKS           FALSE
+#endif
+
+/*===========================================================================*/
+/* CRY driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables the SW fall-back of the cryptographic driver.
+ * @details When enabled, this option, activates a fall-back software
+ *          implementation for algorithms not supported by the underlying
+ *          hardware.
+ * @note    Fall-back implementations may not be present for all algorithms.
+ */
+#if !defined(HAL_CRY_USE_FALLBACK) || defined(__DOXYGEN__)
+#define HAL_CRY_USE_FALLBACK                FALSE
+#endif
+
+/**
+ * @brief   Makes the driver forcibly use the fall-back implementations.
+ */
+#if !defined(HAL_CRY_ENFORCE_FALLBACK) || defined(__DOXYGEN__)
+#define HAL_CRY_ENFORCE_FALLBACK            FALSE
+#endif
+
+/*===========================================================================*/
+/* DAC driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(DAC_USE_WAIT) || defined(__DOXYGEN__)
+#define DAC_USE_WAIT                        TRUE
+#endif
+
+/**
+ * @brief   Enables the @p dacAcquireBus() and @p dacReleaseBus() APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(DAC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
+#define DAC_USE_MUTUAL_EXCLUSION            TRUE
+#endif
+
+/*===========================================================================*/
+/* I2C driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables the mutual exclusion APIs on the I2C bus.
+ */
+#if !defined(I2C_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
+#define I2C_USE_MUTUAL_EXCLUSION            TRUE
+#endif
+
+/*===========================================================================*/
+/* MAC driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables the zero-copy API.
+ */
+#if !defined(MAC_USE_ZERO_COPY) || defined(__DOXYGEN__)
+#define MAC_USE_ZERO_COPY                   FALSE
+#endif
+
+/**
+ * @brief   Enables an event sources for incoming packets.
+ */
+#if !defined(MAC_USE_EVENTS) || defined(__DOXYGEN__)
+#define MAC_USE_EVENTS                      TRUE
+#endif
+
+/*===========================================================================*/
+/* MMC_SPI driver related settings.                                          */
+/*===========================================================================*/
+
+/**
+ * @brief   Delays insertions.
+ * @details If enabled this options inserts delays into the MMC waiting
+ *          routines releasing some extra CPU time for the threads with
+ *          lower priority, this may slow down the driver a bit however.
+ *          This option is recommended also if the SPI driver does not
+ *          use a DMA channel and heavily loads the CPU.
+ */
+#if !defined(MMC_NICE_WAITING) || defined(__DOXYGEN__)
+#define MMC_NICE_WAITING                    TRUE
+#endif
+
+/*===========================================================================*/
+/* SDC driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Number of initialization attempts before rejecting the card.
+ * @note    Attempts are performed at 10mS intervals.
+ */
+#if !defined(SDC_INIT_RETRY) || defined(__DOXYGEN__)
+#define SDC_INIT_RETRY                      100
+#endif
+
+/**
+ * @brief   Include support for MMC cards.
+ * @note    MMC support is not yet implemented so this option must be kept
+ *          at @p FALSE.
+ */
+#if !defined(SDC_MMC_SUPPORT) || defined(__DOXYGEN__)
+#define SDC_MMC_SUPPORT                     FALSE
+#endif
+
+/**
+ * @brief   Delays insertions.
+ * @details If enabled this options inserts delays into the MMC waiting
+ *          routines releasing some extra CPU time for the threads with
+ *          lower priority, this may slow down the driver a bit however.
+ */
+#if !defined(SDC_NICE_WAITING) || defined(__DOXYGEN__)
+#define SDC_NICE_WAITING                    TRUE
+#endif
+
+/**
+ * @brief   OCR initialization constant for V20 cards.
+ */
+#if !defined(SDC_INIT_OCR_V20) || defined(__DOXYGEN__)
+#define SDC_INIT_OCR_V20                    0x50FF8000U
+#endif
+
+/**
+ * @brief   OCR initialization constant for non-V20 cards.
+ */
+#if !defined(SDC_INIT_OCR) || defined(__DOXYGEN__)
+#define SDC_INIT_OCR                        0x80100000U
+#endif
+
+/*===========================================================================*/
+/* SERIAL driver related settings.                                           */
+/*===========================================================================*/
+
+/**
+ * @brief   Default bit rate.
+ * @details Configuration parameter, this is the baud rate selected for the
+ *          default configuration.
+ */
+#if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__)
+#define SERIAL_DEFAULT_BITRATE              115200
+#endif
+
+/**
+ * @brief   Serial buffers size.
+ * @details Configuration parameter, you can change the depth of the queue
+ *          buffers depending on the requirements of your application.
+ * @note    The default is 16 bytes for both the transmission and receive
+ *          buffers.
+ */
+#if !defined(SERIAL_BUFFERS_SIZE) || defined(__DOXYGEN__)
+#define SERIAL_BUFFERS_SIZE                 16
+#endif
+
+/*===========================================================================*/
+/* SIO driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Default bit rate.
+ * @details Configuration parameter, this is the baud rate selected for the
+ *          default configuration.
+ */
+#if !defined(SIO_DEFAULT_BITRATE) || defined(__DOXYGEN__)
+#define SIO_DEFAULT_BITRATE                 38400
+#endif
+
+/**
+ * @brief   Support for thread synchronization API.
+ */
+#if !defined(SIO_USE_SYNCHRONIZATION) || defined(__DOXYGEN__)
+#define SIO_USE_SYNCHRONIZATION             TRUE
+#endif
+
+/*===========================================================================*/
+/* SERIAL_USB driver related setting.                                        */
+/*===========================================================================*/
+
+/**
+ * @brief   Serial over USB buffers size.
+ * @details Configuration parameter, the buffer size must be a multiple of
+ *          the USB data endpoint maximum packet size.
+ * @note    The default is 256 bytes for both the transmission and receive
+ *          buffers.
+ */
+#if !defined(SERIAL_USB_BUFFERS_SIZE) || defined(__DOXYGEN__)
+#define SERIAL_USB_BUFFERS_SIZE             256
+#endif
+
+/**
+ * @brief   Serial over USB number of buffers.
+ * @note    The default is 2 buffers.
+ */
+#if !defined(SERIAL_USB_BUFFERS_NUMBER) || defined(__DOXYGEN__)
+#define SERIAL_USB_BUFFERS_NUMBER           2
+#endif
+
+/*===========================================================================*/
+/* SPI driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(SPI_USE_WAIT) || defined(__DOXYGEN__)
+#define SPI_USE_WAIT                        TRUE
+#endif
+
+/**
+ * @brief   Inserts an assertion on function errors before returning.
+ */
+#if !defined(SPI_USE_ASSERT_ON_ERROR) || defined(__DOXYGEN__)
+#define SPI_USE_ASSERT_ON_ERROR             TRUE
+#endif
+
+/**
+ * @brief   Enables the @p spiAcquireBus() and @p spiReleaseBus() APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(SPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
+#define SPI_USE_MUTUAL_EXCLUSION            TRUE
+#endif
+
+/**
+ * @brief   Handling method for SPI CS line.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(SPI_SELECT_MODE) || defined(__DOXYGEN__)
+#define SPI_SELECT_MODE                     SPI_SELECT_MODE_PAD
+#endif
+
+/*===========================================================================*/
+/* UART driver related settings.                                             */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(UART_USE_WAIT) || defined(__DOXYGEN__)
+#define UART_USE_WAIT                       FALSE
+#endif
+
+/**
+ * @brief   Enables the @p uartAcquireBus() and @p uartReleaseBus() APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(UART_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
+#define UART_USE_MUTUAL_EXCLUSION           FALSE
+#endif
+
+/*===========================================================================*/
+/* USB driver related settings.                                              */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(USB_USE_WAIT) || defined(__DOXYGEN__)
+#define USB_USE_WAIT                        FALSE
+#endif
+
+/*===========================================================================*/
+/* WSPI driver related settings.                                             */
+/*===========================================================================*/
+
+/**
+ * @brief   Enables synchronous APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(WSPI_USE_WAIT) || defined(__DOXYGEN__)
+#define WSPI_USE_WAIT                       TRUE
+#endif
+
+/**
+ * @brief   Enables the @p wspiAcquireBus() and @p wspiReleaseBus() APIs.
+ * @note    Disabling this option saves both code and data space.
+ */
+#if !defined(WSPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
+#define WSPI_USE_MUTUAL_EXCLUSION           TRUE
+#endif
+
+#endif /* HALCONF_H */
+
+/** @} */

+ 222 - 0
cfg/mcuconf.h

@@ -0,0 +1,222 @@
+/*
+    ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+*/
+
+#ifndef MCUCONF_H
+#define MCUCONF_H
+
+#define STM32F103_MCUCONF
+
+/*
+ * STM32F103 drivers configuration.
+ * The following settings override the default settings present in
+ * the various device driver implementation headers.
+ * Note that the settings for each driver only have effect if the whole
+ * driver is enabled in halconf.h.
+ *
+ * IRQ priorities:
+ * 15...0       Lowest...Highest.
+ *
+ * DMA priorities:
+ * 0...3        Lowest...Highest.
+ */
+
+/*
+ * HAL driver system settings.
+ */
+#define STM32_NO_INIT                       FALSE
+#define STM32_HSI_ENABLED                   TRUE
+#define STM32_LSI_ENABLED                   FALSE
+#define STM32_HSE_ENABLED                   TRUE
+#define STM32_LSE_ENABLED                   FALSE
+#define STM32_SW                            STM32_SW_PLL
+#define STM32_PLLSRC                        STM32_PLLSRC_HSE
+#define STM32_PLLXTPRE                      STM32_PLLXTPRE_DIV1
+#define STM32_PLLMUL_VALUE                  9
+#define STM32_HPRE                          STM32_HPRE_DIV1
+#define STM32_PPRE1                         STM32_PPRE1_DIV2
+#define STM32_PPRE2                         STM32_PPRE2_DIV1
+#define STM32_ADCPRE                        STM32_ADCPRE_DIV6
+#define STM32_USB_CLOCK_REQUIRED            TRUE
+#define STM32_USBPRE                        STM32_USBPRE_DIV1P5
+#define STM32_MCOSEL                        STM32_MCOSEL_NOCLOCK
+#define STM32_RTCSEL                        STM32_RTCSEL_NOCLOCK
+#define STM32_PVD_ENABLE                    FALSE
+#define STM32_PLS                           STM32_PLS_LEV0
+
+/*
+ * IRQ system settings.
+ */
+#define STM32_IRQ_EXTI0_PRIORITY            6
+#define STM32_IRQ_EXTI1_PRIORITY            6
+#define STM32_IRQ_EXTI2_PRIORITY            6
+#define STM32_IRQ_EXTI3_PRIORITY            6
+#define STM32_IRQ_EXTI4_PRIORITY            6
+#define STM32_IRQ_EXTI5_9_PRIORITY          6
+#define STM32_IRQ_EXTI10_15_PRIORITY        6
+#define STM32_IRQ_EXTI16_PRIORITY           6
+#define STM32_IRQ_EXTI17_PRIORITY           6
+#define STM32_IRQ_EXTI18_PRIORITY           6
+#define STM32_IRQ_EXTI19_PRIORITY           6
+
+/*
+ * ADC driver system settings.
+ */
+#define STM32_ADC_USE_ADC1                  FALSE
+#define STM32_ADC_ADC1_DMA_PRIORITY         2
+#define STM32_ADC_ADC1_IRQ_PRIORITY         6
+
+/*
+ * CAN driver system settings.
+ */
+#define STM32_CAN_USE_CAN1                  FALSE
+#define STM32_CAN_CAN1_IRQ_PRIORITY         11
+
+/*
+ * GPT driver system settings.
+ */
+#define STM32_GPT_USE_TIM1                  FALSE
+#define STM32_GPT_USE_TIM2                  FALSE
+#define STM32_GPT_USE_TIM3                  FALSE
+#define STM32_GPT_USE_TIM4                  FALSE
+#define STM32_GPT_USE_TIM5                  TRUE
+#define STM32_GPT_USE_TIM6                  FALSE
+#define STM32_GPT_USE_TIM7                  FALSE
+#define STM32_GPT_USE_TIM8                  FALSE
+#define STM32_GPT_USE_TIM9                  FALSE
+#define STM32_GPT_USE_TIM10                 FALSE
+#define STM32_GPT_USE_TIM11                 FALSE
+#define STM32_GPT_USE_TIM12                 FALSE
+#define STM32_GPT_USE_TIM13                 FALSE
+#define STM32_GPT_USE_TIM14                 FALSE
+#define STM32_GPT_TIM1_IRQ_PRIORITY         7
+#define STM32_GPT_TIM2_IRQ_PRIORITY         7
+#define STM32_GPT_TIM3_IRQ_PRIORITY         7
+#define STM32_GPT_TIM4_IRQ_PRIORITY         7
+#define STM32_GPT_TIM5_IRQ_PRIORITY         7
+#define STM32_GPT_TIM8_IRQ_PRIORITY         7
+
+/*
+ * I2C driver system settings.
+ */
+#define STM32_I2C_USE_I2C1                  TRUE
+#define STM32_I2C_USE_I2C2                  FALSE
+#define STM32_I2C_BUSY_TIMEOUT              50
+#define STM32_I2C_I2C1_IRQ_PRIORITY         5
+#define STM32_I2C_I2C2_IRQ_PRIORITY         5
+#define STM32_I2C_I2C1_DMA_PRIORITY         3
+#define STM32_I2C_I2C2_DMA_PRIORITY         3
+#define STM32_I2C_DMA_ERROR_HOOK(i2cp)      osalSysHalt("DMA failure")
+
+/*
+ * ICU driver system settings.
+ */
+#define STM32_ICU_USE_TIM1                  FALSE
+#define STM32_ICU_USE_TIM2                  FALSE
+#define STM32_ICU_USE_TIM3                  FALSE
+#define STM32_ICU_USE_TIM4                  FALSE
+#define STM32_ICU_USE_TIM5                  FALSE
+#define STM32_ICU_USE_TIM8                  FALSE
+#define STM32_ICU_TIM1_IRQ_PRIORITY         7
+#define STM32_ICU_TIM2_IRQ_PRIORITY         7
+#define STM32_ICU_TIM3_IRQ_PRIORITY         7
+#define STM32_ICU_TIM4_IRQ_PRIORITY         7
+#define STM32_ICU_TIM5_IRQ_PRIORITY         7
+#define STM32_ICU_TIM8_IRQ_PRIORITY         7
+
+/*
+ * PWM driver system settings.
+ */
+#define STM32_PWM_USE_ADVANCED              FALSE
+#define STM32_PWM_USE_TIM1                  FALSE
+#define STM32_PWM_USE_TIM2                  FALSE
+#define STM32_PWM_USE_TIM3                  FALSE
+#define STM32_PWM_USE_TIM4                  FALSE
+#define STM32_PWM_USE_TIM5                  FALSE
+#define STM32_PWM_USE_TIM8                  FALSE
+#define STM32_PWM_TIM1_IRQ_PRIORITY         7
+#define STM32_PWM_TIM2_IRQ_PRIORITY         7
+#define STM32_PWM_TIM3_IRQ_PRIORITY         7
+#define STM32_PWM_TIM4_IRQ_PRIORITY         7
+#define STM32_PWM_TIM5_IRQ_PRIORITY         7
+#define STM32_PWM_TIM8_IRQ_PRIORITY         7
+
+/*
+ * RTC driver system settings.
+ */
+#define STM32_RTC_IRQ_PRIORITY              15
+
+/*
+ * SERIAL driver system settings.
+ */
+#define STM32_SERIAL_USE_USART1             TRUE
+#define STM32_SERIAL_USE_USART2             FALSE
+#define STM32_SERIAL_USE_USART3             FALSE
+#define STM32_SERIAL_USE_UART4              FALSE
+#define STM32_SERIAL_USE_UART5              FALSE
+#define STM32_SERIAL_USART1_PRIORITY        12
+#define STM32_SERIAL_USART2_PRIORITY        12
+#define STM32_SERIAL_USART3_PRIORITY        12
+#define STM32_SERIAL_UART4_PRIORITY         12
+#define STM32_SERIAL_UART5_PRIORITY         12
+
+/*
+ * SPI driver system settings.
+ */
+#define STM32_SPI_USE_SPI1                  FALSE
+#define STM32_SPI_USE_SPI2                  FALSE
+#define STM32_SPI_USE_SPI3                  FALSE
+#define STM32_SPI_SPI1_DMA_PRIORITY         1
+#define STM32_SPI_SPI2_DMA_PRIORITY         1
+#define STM32_SPI_SPI3_DMA_PRIORITY         1
+#define STM32_SPI_SPI1_IRQ_PRIORITY         10
+#define STM32_SPI_SPI2_IRQ_PRIORITY         10
+#define STM32_SPI_SPI3_IRQ_PRIORITY         10
+#define STM32_SPI_DMA_ERROR_HOOK(spip)      osalSysHalt("DMA failure")
+
+/*
+ * ST driver system settings.
+ */
+#define STM32_ST_IRQ_PRIORITY               8
+#define STM32_ST_USE_TIMER                  2
+
+/*
+ * UART driver system settings.
+ */
+#define STM32_UART_USE_USART1               FALSE
+#define STM32_UART_USE_USART2               FALSE
+#define STM32_UART_USE_USART3               FALSE
+#define STM32_UART_USART1_IRQ_PRIORITY      12
+#define STM32_UART_USART2_IRQ_PRIORITY      12
+#define STM32_UART_USART3_IRQ_PRIORITY      12
+#define STM32_UART_USART1_DMA_PRIORITY      0
+#define STM32_UART_USART2_DMA_PRIORITY      0
+#define STM32_UART_USART3_DMA_PRIORITY      0
+#define STM32_UART_DMA_ERROR_HOOK(uartp)    osalSysHalt("DMA failure")
+
+/*
+ * USB driver system settings.
+ */
+#define STM32_USB_USE_USB1                  FALSE
+#define STM32_USB_LOW_POWER_ON_SUSPEND      FALSE
+#define STM32_USB_USB1_HP_IRQ_PRIORITY      13
+#define STM32_USB_USB1_LP_IRQ_PRIORITY      14
+
+/*
+ * WDG driver system settings.
+ */
+#define STM32_WDG_USE_IWDG                  FALSE
+
+#endif /* MCUCONF_H */

+ 3 - 0
flash.cmd

@@ -0,0 +1,3 @@
+@echo off
+
+c:\MCU\SEGGER\JLink\JLink.exe -CommanderScript flash.jlink

+ 7 - 0
flash.jlink

@@ -0,0 +1,7 @@
+if swd
+speed 4000
+device stm32f103ve
+loadfile build\acc-tst.hex
+r
+g
+q

+ 245 - 0
inc/INA3221.h

@@ -0,0 +1,245 @@
+/*
+
+	Arduino library for INA3221 current and voltage sensor.
+
+	MIT License
+
+	Copyright (c) 2020 Beast Devices, Andrejs Bondarevs
+
+	Permission is hereby granted, free of charge, to any person obtaining a copy
+	of this software and associated documentation files (the "Software"), to deal
+	in the Software without restriction, including without limitation the rights
+	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+	copies of the Software, and to permit persons to whom the Software is
+	furnished to do so, subject to the following conditions:
+
+	The above copyright notice and this permission notice shall be included in all
+	copies or substantial portions of the Software.
+
+	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+	SOFTWARE.
+
+*/
+
+#ifndef BEASTDEVICES_INA3221_H
+#define BEASTDEVICES_INA3221_H
+
+#include <ch.h>
+#include <hal.h>
+
+typedef enum {
+    INA3221_ADDR40_GND = 0b1000000, // A0 pin -> GND
+    INA3221_ADDR41_VCC = 0b1000001, // A0 pin -> VCC
+    INA3221_ADDR42_SDA = 0b1000010, // A0 pin -> SDA
+    INA3221_ADDR43_SCL = 0b1000011  // A0 pin -> SCL
+} ina3221_addr_t;
+
+// Channels
+typedef enum {
+    INA3221_CH1 = 0,
+    INA3221_CH2 = 1,
+    INA3221_CH3 = 2,
+    INA3221_CH_NUM = 3
+} ina3221_ch_t;
+
+// Registers
+typedef enum {
+    INA3221_REG_CONF = 0,
+    INA3221_REG_CH1_SHUNTV,
+    INA3221_REG_CH1_BUSV,
+    INA3221_REG_CH2_SHUNTV,
+    INA3221_REG_CH2_BUSV,
+    INA3221_REG_CH3_SHUNTV,
+    INA3221_REG_CH3_BUSV,
+    INA3221_REG_CH1_CRIT_ALERT_LIM,
+    INA3221_REG_CH1_WARNING_ALERT_LIM,
+    INA3221_REG_CH2_CRIT_ALERT_LIM,
+    INA3221_REG_CH2_WARNING_ALERT_LIM,
+    INA3221_REG_CH3_CRIT_ALERT_LIM,
+    INA3221_REG_CH3_WARNING_ALERT_LIM,
+    INA3221_REG_SHUNTV_SUM,
+    INA3221_REG_SHUNTV_SUM_LIM,
+    INA3221_REG_MASK_ENABLE,
+    INA3221_REG_PWR_VALID_HI_LIM,
+    INA3221_REG_PWR_VALID_LO_LIM,
+    INA3221_REG_MANUF_ID = 0xFE,
+    INA3221_REG_DIE_ID = 0xFF
+} ina3221_reg_t;
+
+// Conversion times
+typedef enum {
+    INA3221_REG_CONF_CT_140US = 0,
+    INA3221_REG_CONF_CT_204US,
+    INA3221_REG_CONF_CT_332US,
+    INA3221_REG_CONF_CT_588US,
+    INA3221_REG_CONF_CT_1100US,
+    INA3221_REG_CONF_CT_2116US,
+    INA3221_REG_CONF_CT_4156US,
+    INA3221_REG_CONF_CT_8244US
+} ina3221_conv_time_t;
+
+// Averaging modes
+typedef enum {
+    INA3221_REG_CONF_AVG_1 = 0,
+    INA3221_REG_CONF_AVG_4,
+    INA3221_REG_CONF_AVG_16,
+    INA3221_REG_CONF_AVG_64,
+    INA3221_REG_CONF_AVG_128,
+    INA3221_REG_CONF_AVG_256,
+    INA3221_REG_CONF_AVG_512,
+    INA3221_REG_CONF_AVG_1024
+} ina3221_avg_mode_t;
+
+typedef struct Beastdevices_INA3221 {
+    ina3221_addr_t i2c_addr; /**< I2C address */
+    I2CDriver *i2cd; /**< I2C driver */
+    uint32_t shuntRes[INA3221_CH_NUM]; /**< Shunt resistance in mOhm */
+    uint32_t filterRes[INA3221_CH_NUM]; /**< Series filter resistance in Ohm */
+} ina3221_t;
+
+// Gets a register value.
+uint16_t INA3221_getReg(ina3221_t * ina, const ina3221_reg_t reg);
+
+// Resets INA3221
+void INA3221_reset(ina3221_t * ina);
+
+// Sets operating mode to power-down
+void INA3221_setModePowerDown(ina3221_t * ina);
+
+// Sets operating mode to continious
+void INA3221_setModeContinious(ina3221_t * ina);
+
+// Sets operating mode to triggered (single-shot)
+void INA3221_setModeTriggered(ina3221_t * ina);
+
+// Enables shunt-voltage measurement
+void INA3221_setShuntMeasEnable(ina3221_t * ina);
+
+// Disables shunt-voltage mesurement
+void INA3221_setShuntMeasDisable(ina3221_t * ina);
+
+// Enables bus-voltage measurement
+void INA3221_setBusMeasEnable(ina3221_t * ina);
+
+// Disables bus-voltage measureement
+void INA3221_setBusMeasDisable(ina3221_t * ina);
+
+// Sets averaging mode. Sets number of samples that are collected
+// and averaged togehter.
+void INA3221_setAveragingMode(ina3221_t * ina, ina3221_avg_mode_t mode);
+
+// Sets bus-voltage conversion time.
+void INA3221_setBusConversionTime(ina3221_t * ina, ina3221_conv_time_t convTime);
+
+// Sets shunt-voltage conversion time.
+void INA3221_setShuntConversionTime(ina3221_t * ina, ina3221_conv_time_t convTime);
+
+// Sets power-valid upper-limit voltage. The power-valid condition
+// is reached when all bus-voltage channels exceed the value set.
+// When the powervalid condition is met, the PV alert pin asserts high.
+void INA3221_setPwrValidUpLimit(ina3221_t * ina, int16_t voltagemV);
+
+// Sets power-valid lower-limit voltage. If any bus-voltage channel drops
+// below the power-valid lower-limit, the PV alert pin pulls low.
+void INA3221_setPwrValidLowLimit(ina3221_t * ina, int16_t voltagemV);
+
+// Sets the value that is compared to the Shunt-Voltage Sum register value
+// following each completed cycle of all selected channels to detect
+// for system overcurrent events.
+void INA3221_setShuntSumAlertLimit(ina3221_t * ina, int32_t voltagemV);
+
+// Sets the current value that is compared to the sum all currents.
+// This function is a helper for setShuntSumAlertLim(). It onverts current
+// value to shunt voltage value.
+void INA3221_setCurrentSumAlertLimit(ina3221_t * ina, int32_t currentmA);
+
+// Enables warning alert latch.
+void INA3221_setWarnAlertLatchEnable(ina3221_t * ina);
+
+// Disables warning alert latch.
+void INA3221_setWarnAlertLatchDisable(ina3221_t * ina);
+
+// Enables critical alert latch.
+void INA3221_setCritAlertLatchEnable(ina3221_t * ina);
+
+// Disables critical alert latch.
+void INA3221_setCritAlertLatchDisable(ina3221_t * ina);
+
+// Reads flags from Mask/Enable register.
+// When Mask/Enable register is read, flags are cleared.
+// Use getTimingCtrlAlertFlag(), getPwrValidAlertFlag(),
+// getCurrentSumAlertFlag() and getConvReadyFlag() to get flags after
+// readFlags() is called.
+void INA3221_readFlags(ina3221_t * ina);
+
+// Gets timing-control-alert flag indicator.
+bool INA3221_getTimingCtrlAlertFlag(void);
+
+// Gets power-valid-alert flag indicator.
+bool INA3221_getPwrValidAlertFlag(void);
+
+// Gets summation-alert flag indicator.
+bool INA3221_getCurrentSumAlertFlag(void);
+
+// Gets Conversion-ready flag.
+bool INA3221_getConversionReadyFlag(void);
+
+// Gets manufacturer ID.
+// Should read 0x5449.
+uint16_t INA3221_getManufID(ina3221_t * ina);
+
+// Gets die ID.
+// Should read 0x3220.
+uint16_t INA3221_getDieID(ina3221_t * ina);
+
+// Enables channel measurements
+void INA3221_setChannelEnable(ina3221_t * ina, ina3221_ch_t channel);
+
+// Disables channel measurements
+void INA3221_setChannelDisable(ina3221_t * ina, ina3221_ch_t channel);
+
+// Sets warning alert shunt voltage limit
+void INA3221_setWarnAlertShuntLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t voltageuV);
+
+// Sets critical alert shunt voltage limit
+void INA3221_setCritAlertShuntLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t voltageuV);
+
+// Sets warning alert current limit
+void INA3221_setWarnAlertCurrentLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t currentmA);
+
+// Sets critical alert current limit
+void INA3221_setCritAlertCurrentLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t currentmA);
+
+// Includes channel to fill Shunt-Voltage Sum register.
+void INA3221_setCurrentSumEnable(ina3221_t * ina, ina3221_ch_t channel);
+
+// Excludes channel from filling Shunt-Voltage Sum register.
+void INA3221_setCurrentSumDisable(ina3221_t * ina, ina3221_ch_t channel);
+
+// Gets shunt voltage in uV.
+int32_t INA3221_getShuntVoltage(ina3221_t * ina, ina3221_ch_t channel);
+
+// Gets warning alert flag.
+bool INA3221_getWarnAlertFlag(ina3221_t * ina, ina3221_ch_t channel);
+
+// Gets critical alert flag.
+bool INA3221_getCritAlertFlag(ina3221_t * ina, ina3221_ch_t channel);
+
+// Estimates offset voltage added by the series filter resitors
+int32_t INA3221_estimateOffsetVoltage(ina3221_t * ina, ina3221_ch_t channel, uint32_t busVoltage);
+
+// Gets current in A.
+int32_t INA3221_getCurrent(ina3221_t * ina, ina3221_ch_t channel);
+
+// Gets current compensated with calculated offset voltage.
+int32_t INA3221_getCurrentCompensated(ina3221_t * ina, ina3221_ch_t channel);
+
+// Gets bus voltage in V.
+uint32_t INA3221_getVoltage(ina3221_t * ina, ina3221_ch_t channel);
+
+#endif

+ 44 - 0
inc/buttons.h

@@ -0,0 +1,44 @@
+#pragma once
+#ifndef _BUTTONS_H_
+#define _BUTTONS_H_
+
+/* Events */
+#define EVT_BTN1_PRS EVENT_MASK(0)
+#define EVT_BTN2_PRS EVENT_MASK(1)
+#define EVT_BTN3_PRS EVENT_MASK(2)
+#define EVT_BTN4_PRS EVENT_MASK(3)
+
+/* time constant in ms */
+#define BTN_SCAN_PERIOD     10
+#define BTN_SCAN_PAUSE      200
+#define BTN_TIME_PRESSED    30
+#define BTN_TIME_HOLDED     500
+#define BTN_TIME_REPEATED   50
+#define BUTTON_NUMS         4
+
+/* type defs */
+typedef enum btn_num {
+  Button1 = 0,
+  Button2 = 1,
+  Button3 = 2,
+  Button4 = 3
+} button_num_t;
+
+typedef enum btn_state {
+  BTN_st_Clear = 0,
+  BTN_st_Pressed,
+  BTN_st_Holded,
+  BTN_st_Released
+} button_state_t;
+
+/* function prototypes */
+#ifdef __cplusplus
+extern "C" {
+#endif
+  void buttons_Init(thread_t * thread);
+  button_state_t buttons_GetState(const button_num_t btn);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _BUTTONS_H_ */

+ 29 - 0
readme.txt

@@ -0,0 +1,29 @@
+Accumulator Tester/Charger/Decharger
+
+Hardware:
+HY-STM32 Board
+INA3221 Triple-Channel Module
+2 Channel 5V Relay Module
+
+Board Pins usage:
+PB8	I2C1_SCL
+PB9	I2C1_SDA
+PA8	RELAY1 (Power)
+PD12	RELAY2 (Load)
+
+Soft:
+ChibiOS 21.11.x (trunk)
+uGFX 29 (trunk)
+
+Tasks:
+ - выбор аккума вручную из списка (1-4S LiIon / SLA 12v)
+ - выбор режима (заряд, тест - заряд/разряд/заряд)
+ - определение наличия аккумулятора
+ - подключение внешнего питания (RELAY1)
+ - подключение нагрузки (RELAY2)
+ - подсчёт времени каждого процесса
+ - контроль напряжения, тока, ёмкости
+ - сохранение настроек, состояния в EEPROM
+ - сохранение лога в файл на MicroSD
+ - вывод лога в COM-порт (возможно в формате для LogView/iMax B6)
+ - отображение на экран текущего режима, текущих данных, графика...

+ 577 - 0
src/INA3221.c

@@ -0,0 +1,577 @@
+/*
+
+	Arduino library for INA3221 current and voltage sensor.
+
+	MIT License
+
+	Copyright (c) 2020 Beast Devices, Andrejs Bondarevs
+
+	Permission is hereby granted, free of charge, to any person obtaining a copy
+	of this software and associated documentation files (the "Software"), to deal
+	in the Software without restriction, including without limitation the rights
+	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+	copies of the Software, and to permit persons to whom the Software is
+	furnished to do so, subject to the following conditions:
+
+	The above copyright notice and this permission notice shall be included in all
+	copies or substantial portions of the Software.
+
+	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+	SOFTWARE.
+
+*/
+
+#include "INA3221.h"
+
+// Configuration register
+typedef struct {
+    uint16_t mode_shunt_en:1;
+    uint16_t mode_bus_en:1;
+    uint16_t mode_continious_en:1;
+    uint16_t shunt_conv_time:3;
+    uint16_t bus_conv_time:3;
+    uint16_t avg_mode:3;
+    uint16_t ch3_en:1;
+    uint16_t ch2_en:1;
+    uint16_t ch1_en:1;
+    uint16_t reset:1;
+} conf_reg_t;
+
+// Mask/Enable register
+typedef struct {
+    uint16_t conv_ready:1;
+    uint16_t timing_ctrl_alert:1;
+    uint16_t pwr_valid_alert:1;
+    uint16_t warn_alert_ch3:1;
+    uint16_t warn_alert_ch2:1;
+    uint16_t warn_alert_ch1:1;
+    uint16_t shunt_sum_alert:1;
+    uint16_t crit_alert_ch3:1;
+    uint16_t crit_alert_ch2:1;
+    uint16_t crit_alert_ch1:1;
+    uint16_t crit_alert_latch_en:1;
+    uint16_t warn_alert_latch_en:1;
+    uint16_t shunt_sum_en_ch3:1;
+    uint16_t shunt_sum_en_ch2:1;
+    uint16_t shunt_sum_en_ch1:1;
+    uint16_t reserved:1;
+} masken_reg_t;
+
+// I2C buffers
+static uint8_t rx_data[4];
+static uint8_t tx_data[4];
+// Value of Mask/Enable register.
+static masken_reg_t _masken_reg;
+
+// Reads 16 bytes from a register.
+static void _read(ina3221_t * ina, const ina3221_reg_t reg, uint16_t *val);
+// Writes 16 bytes to a register.
+static void _write(ina3221_t * ina, const ina3221_reg_t reg, uint16_t *val);
+
+static void _read(ina3221_t * ina, ina3221_reg_t reg, uint16_t *val) {
+    msg_t status = MSG_OK;
+    sysinterval_t tmo = TIME_MS2I(4);
+
+    /* read in burst mode */
+    tx_data[0] = (uint8_t)reg;
+    i2cAcquireBus(ina->i2cd);
+    status = i2cMasterTransmitTimeout(ina->i2cd, ina->i2c_addr, tx_data, 1, rx_data, 2, tmo);
+    i2cReleaseBus(ina->i2cd);
+    
+    if (status != MSG_OK) {
+        *val = 0xFFFF;
+    }
+
+    // data in rx_data[]
+    *val = rx_data[0] << 8;
+    *val |= rx_data[1];
+}
+
+static void _write(ina3221_t * ina, ina3221_reg_t reg, uint16_t *val) {
+    msg_t status = MSG_OK;
+    sysinterval_t tmo = TIME_MS2I(4);
+
+    tx_data[0] = (uint8_t)reg;
+    tx_data[1] = (uint8_t)(*val >> 8);
+    tx_data[2] = (uint8_t)(*val & 0xff);
+
+    /* sending */
+    i2cAcquireBus(ina->i2cd);
+    status = i2cMasterTransmitTimeout(ina->i2cd, ina->i2c_addr, tx_data, 3, NULL, 0, tmo);
+    i2cReleaseBus(ina->i2cd);
+
+    if (status != MSG_OK) {
+        *val = 0xFFFE;
+    }
+}
+
+uint16_t INA3221_getReg(ina3221_t * ina, ina3221_reg_t reg) {
+    uint16_t val = 0;
+    _read(ina, reg, &val);
+    return val;
+}
+
+void INA3221_reset(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.reset = 1;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setModePowerDown(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.mode_bus_en = 0;
+    conf_reg.mode_continious_en =0 ;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setModeContinious(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.mode_continious_en =1;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setModeTriggered(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.mode_continious_en = 0;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setShuntMeasEnable(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.mode_shunt_en = 1;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setShuntMeasDisable(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.mode_shunt_en = 0;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setBusMeasEnable(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.mode_bus_en = 1;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setBusMeasDisable(ina3221_t * ina) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.mode_bus_en = 0;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setAveragingMode(ina3221_t * ina, ina3221_avg_mode_t mode) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.avg_mode = mode;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setBusConversionTime(ina3221_t * ina, ina3221_conv_time_t convTime) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.bus_conv_time = convTime;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setShuntConversionTime(ina3221_t * ina, ina3221_conv_time_t convTime) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+    conf_reg.shunt_conv_time = convTime;
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setPwrValidUpLimit(ina3221_t * ina, int16_t voltagemV) {
+    _write(ina, INA3221_REG_PWR_VALID_HI_LIM, (uint16_t*)&voltagemV);
+}
+
+void INA3221_setPwrValidLowLimit(ina3221_t * ina, int16_t voltagemV) {
+    _write(ina, INA3221_REG_PWR_VALID_LO_LIM, (uint16_t*)&voltagemV);
+}
+
+void INA3221_setShuntSumAlertLimit(ina3221_t * ina, int32_t voltageuV) {
+    int16_t val = voltageuV / 20;
+    _write(ina, INA3221_REG_SHUNTV_SUM_LIM, (uint16_t*)&val);
+}
+
+void INA3221_setCurrentSumAlertLimit(ina3221_t * ina, int32_t currentmA) {
+    int16_t shuntuV = currentmA * (int32_t)ina->shuntRes[INA3221_CH1];
+    INA3221_setShuntSumAlertLimit(ina, shuntuV);
+}
+
+void INA3221_setWarnAlertLatchEnable(ina3221_t * ina) {
+    masken_reg_t masken_reg;
+
+    _read(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    masken_reg.warn_alert_latch_en = 1;
+    _write(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    _masken_reg = masken_reg;
+}
+
+void INA3221_setWarnAlertLatchDisable(ina3221_t * ina) {
+    masken_reg_t masken_reg;
+
+    _read(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    masken_reg.warn_alert_latch_en = 1;
+    _write(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    _masken_reg = masken_reg;
+}
+
+void INA3221_setCritAlertLatchEnable(ina3221_t * ina) {
+    masken_reg_t masken_reg;
+
+    _read(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    masken_reg.crit_alert_latch_en = 1;
+    _write(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    _masken_reg = masken_reg;
+}
+
+void INA3221_setCritAlertLatchDisable(ina3221_t * ina) {
+    masken_reg_t masken_reg;
+
+    _read(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    masken_reg.crit_alert_latch_en = 1;
+    _write(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    _masken_reg = masken_reg;
+}
+
+void INA3221_readFlags(ina3221_t * ina) {
+    _read(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&_masken_reg);
+}
+
+bool INA3221_getTimingCtrlAlertFlag(void) {
+    return _masken_reg.timing_ctrl_alert;
+}
+
+bool INA3221_getPwrValidAlertFlag(void) {
+    return _masken_reg.pwr_valid_alert;
+}
+
+bool INA3221_getCurrentSumAlertFlag(void) {
+    return _masken_reg.shunt_sum_alert;
+}
+
+bool INA3221_getConversionReadyFlag(void) {
+    return _masken_reg.conv_ready;
+}
+
+uint16_t INA3221_getManufID(ina3221_t * ina) {
+    uint16_t id = 0;
+    _read(ina, INA3221_REG_MANUF_ID, &id);
+    return id;
+}
+
+uint16_t INA3221_getDieID(ina3221_t * ina) {
+    uint16_t id = 0;
+    _read(ina, INA3221_REG_DIE_ID, &id);
+    return id;
+}
+
+void INA3221_setChannelEnable(ina3221_t * ina, ina3221_ch_t channel) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+
+    switch(channel){
+        case INA3221_CH1:
+            conf_reg.ch1_en = 1;
+            break;
+        case INA3221_CH2:
+            conf_reg.ch2_en = 1;
+            break;
+        case INA3221_CH3:
+            conf_reg.ch3_en = 1;
+            break;
+        default:
+            break;
+    }
+
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setChannelDisable(ina3221_t * ina, ina3221_ch_t channel) {
+    conf_reg_t conf_reg;
+
+    _read(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+
+    switch(channel){
+        case INA3221_CH1:
+            conf_reg.ch1_en = 0;
+            break;
+        case INA3221_CH2:
+            conf_reg.ch2_en = 0;
+            break;
+        case INA3221_CH3:
+            conf_reg.ch3_en = 0;
+            break;
+        default:
+            break;
+    }
+
+    _write(ina, INA3221_REG_CONF, (uint16_t*)&conf_reg);
+}
+
+void INA3221_setWarnAlertShuntLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t voltageuV) {
+    ina3221_reg_t reg;
+    int16_t val = 0;
+
+    switch(channel){
+        case INA3221_CH1:
+            reg = INA3221_REG_CH1_WARNING_ALERT_LIM;
+            break;
+        case INA3221_CH2:
+            reg = INA3221_REG_CH2_WARNING_ALERT_LIM;
+            break;
+        case INA3221_CH3:
+            reg = INA3221_REG_CH3_WARNING_ALERT_LIM;
+            break;
+        default:
+            break;
+    }
+
+    val = voltageuV / 5;
+    _write(ina, reg, (uint16_t*)&val);
+}
+
+void INA3221_setCritAlertShuntLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t voltageuV) {
+    ina3221_reg_t reg;
+    int16_t val = 0;
+
+    switch(channel){
+        case INA3221_CH1:
+            reg = INA3221_REG_CH1_CRIT_ALERT_LIM;
+            break;
+        case INA3221_CH2:
+            reg = INA3221_REG_CH2_CRIT_ALERT_LIM;
+            break;
+        case INA3221_CH3:
+            reg = INA3221_REG_CH3_CRIT_ALERT_LIM;
+            break;
+        default:
+            break;
+    }
+
+    val = voltageuV / 5;
+    _write(ina, reg, (uint16_t*)&val);
+}
+
+void INA3221_setWarnAlertCurrentLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t currentmA) {
+    int32_t shuntuV = 0;
+    shuntuV = currentmA * (int32_t)ina->shuntRes[channel];
+    INA3221_setWarnAlertShuntLimit(ina, channel, shuntuV);
+}
+
+void INA3221_setCritAlertCurrentLimit(ina3221_t * ina, ina3221_ch_t channel, int32_t currentmA) {
+    int32_t shuntuV = 0;
+    shuntuV = currentmA * (int32_t)ina->shuntRes[channel];
+    INA3221_setCritAlertShuntLimit(ina, channel, shuntuV);
+}
+
+void INA3221_setCurrentSumEnable(ina3221_t * ina, ina3221_ch_t channel) {
+    masken_reg_t masken_reg;
+
+    _read(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+
+    switch(channel){
+        case INA3221_CH1:
+            masken_reg.shunt_sum_en_ch1 = 1;
+            break;
+        case INA3221_CH2:
+            masken_reg.shunt_sum_en_ch2 = 1;
+            break;
+        case INA3221_CH3:
+            masken_reg.shunt_sum_en_ch3 = 1;
+            break;
+        default:
+            break;
+    }
+
+    _write(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    _masken_reg = masken_reg;
+}
+
+void INA3221_setCurrentSumDisable(ina3221_t * ina, ina3221_ch_t channel) {
+    masken_reg_t masken_reg;
+
+    _read(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+
+    switch(channel){
+        case INA3221_CH1:
+            masken_reg.shunt_sum_en_ch1 = 0;
+            break;
+        case INA3221_CH2:
+            masken_reg.shunt_sum_en_ch2 = 0;
+            break;
+        case INA3221_CH3:
+            masken_reg.shunt_sum_en_ch3 = 0;
+            break;
+        default:
+            break;
+    }
+
+    _write(ina, INA3221_REG_MASK_ENABLE, (uint16_t*)&masken_reg);
+    _masken_reg = masken_reg;
+}
+
+int32_t INA3221_getShuntVoltage(ina3221_t * ina, ina3221_ch_t channel) {
+    int32_t res;
+    ina3221_reg_t reg;
+    uint16_t val_raw = 0;
+
+    switch(channel){
+        case INA3221_CH1:
+            reg = INA3221_REG_CH1_SHUNTV;
+            break;
+        case INA3221_CH2:
+            reg = INA3221_REG_CH2_SHUNTV;
+            break;
+        case INA3221_CH3:
+            reg = INA3221_REG_CH3_SHUNTV;
+            break;
+        default:
+            break;
+    }
+
+    _read(ina, reg, &val_raw);
+
+    res = (int16_t)val_raw;
+    res *= 5; // 1 LSB = 5uV
+
+    return res;
+}
+
+bool INA3221_getWarnAlertFlag(ina3221_t * ina, ina3221_ch_t channel) {
+    (void)ina;
+    bool ret;
+    switch(channel) {
+    case INA3221_CH1:
+        return _masken_reg.warn_alert_ch1;
+        break;
+    case INA3221_CH2:
+        return _masken_reg.warn_alert_ch2;
+        break;
+    case INA3221_CH3:
+        return _masken_reg.warn_alert_ch3;
+        break;
+    default:
+        break;
+    }
+    return ret;
+}
+
+bool INA3221_getCritAlertFlag(ina3221_t * ina, ina3221_ch_t channel) {
+    (void)ina;
+    bool ret;
+    switch(channel) {
+    case INA3221_CH1:
+        ret = _masken_reg.crit_alert_ch1;
+        break;
+    case INA3221_CH2:
+        ret = _masken_reg.crit_alert_ch2;
+        break;
+    case INA3221_CH3:
+        ret = _masken_reg.crit_alert_ch3;
+        break;
+    default:
+        break;
+    }
+    return ret;
+}
+
+int32_t INA3221_estimateOffsetVoltage(ina3221_t * ina, ina3221_ch_t channel, uint32_t busV) {
+    uint32_t bias_in = 10;  // Input bias current at IN– in uA
+    uint32_t r_in = 670;    // Input resistance at IN– in KOhm
+    int32_t adc_step = 40;  // smallest shunt ADC step in uV
+    uint32_t shunt_res = ina->shuntRes[channel];
+    uint32_t filter_res = ina->filterRes[channel];
+    int32_t offset = 0;
+    int32_t reminder;
+
+    offset = (shunt_res + (filter_res * 1000) + 500) / 1000; // resistance in Ohm
+    offset *= (((busV * 1000) + (r_in/2)) / r_in) + bias_in; // cuurent in uA
+    offset -= bias_in * filter_res; // offset in uV
+
+    // Round the offset to the closest shunt ADC value
+    reminder = offset % adc_step;
+    if (reminder < adc_step/2) {
+        offset -= reminder;
+    } else {
+        offset += adc_step - reminder;
+    }
+
+    return offset;
+}
+
+int32_t INA3221_getCurrent(ina3221_t * ina, ina3221_ch_t channel) {
+    int32_t shunt_uV = 0;
+    int32_t current_A = 0;
+
+    shunt_uV = INA3221_getShuntVoltage(ina, channel);
+    current_A = shunt_uV / (int32_t)ina->shuntRes[channel];
+    return current_A;
+}
+
+int32_t INA3221_getCurrentCompensated(ina3221_t * ina, ina3221_ch_t channel) {
+    int32_t shunt_uV = 0;
+    int32_t bus_V = 0;
+    uint32_t current_A = 0;
+    int32_t offset_uV = 0;
+
+    shunt_uV = INA3221_getShuntVoltage(ina, channel);
+    bus_V = INA3221_getVoltage(ina, channel);
+    offset_uV = INA3221_estimateOffsetVoltage(ina, channel, bus_V);
+
+    current_A = (shunt_uV - offset_uV) / (int32_t)ina->shuntRes[channel];
+
+    return current_A;
+}
+
+uint32_t INA3221_getVoltage(ina3221_t * ina, ina3221_ch_t channel) {
+    uint32_t voltage_V = 0;
+    ina3221_reg_t reg;
+    uint16_t val_raw = 0;
+
+    switch(channel) {
+        case INA3221_CH1:
+            reg = INA3221_REG_CH1_BUSV;
+            break;
+        case INA3221_CH2:
+            reg = INA3221_REG_CH2_BUSV;
+            break;
+        case INA3221_CH3:
+            reg = INA3221_REG_CH3_BUSV;
+            break;
+        default:
+            break;
+    }
+
+    _read(ina, reg, &val_raw);
+
+    voltage_V = val_raw;
+
+    return voltage_V;
+}

+ 76 - 0
src/buttons.c

@@ -0,0 +1,76 @@
+#include <ch.h>
+#include <hal.h>
+#include "buttons.h"
+
+/* Constants */
+static const ioline_t button_Lines[BUTTON_NUMS] = {
+  LINE_BUTTON1, LINE_BUTTON2, LINE_BUTTON3, LINE_BUTTON4
+};
+static const eventmask_t button_Events[BUTTON_NUMS] = {
+  EVT_BTN1_PRS, EVT_BTN2_PRS, EVT_BTN3_PRS, EVT_BTN4_PRS
+};
+
+/* Variables */
+static thread_t * evt_thread;
+static virtual_timer_t button_vt;
+static button_state_t button_States[BUTTON_NUMS] = {
+  BTN_st_Clear, BTN_st_Clear, BTN_st_Clear, BTN_st_Clear
+};
+static uint8_t button_Time[BUTTON_NUMS] = {0, 0, 0, 0};
+
+/* Functions */
+static void button_Process(virtual_timer_t *vtp, void *p) {
+  (void)vtp;
+  (void)p;
+  eventmask_t events = 0;
+  static int pause = 0;
+
+  if (pause != 0) {
+    pause --;
+  } else {
+
+    int i;
+    for (i=0; i<BUTTON_NUMS; i++) {
+
+      if (palReadLine(button_Lines[(button_num_t)i]) == BUTTON_PRESSED) {
+      /* button pressed */
+        button_Time[i] ++;
+        if (button_Time[i] >= (BTN_TIME_HOLDED/BTN_SCAN_PERIOD)) {
+          /* process long press */
+          button_Time[i] -= (BTN_TIME_REPEATED/BTN_SCAN_PERIOD);
+          button_States[i] = BTN_st_Holded;
+          events |= button_Events[i]; // autorepeat
+        }
+
+      } else if (button_Time[i] != 0) {
+      /* button released */
+        if (button_Time[i] >= (BTN_TIME_PRESSED/BTN_SCAN_PERIOD)) {
+          /* process short press */
+          button_States[i] = BTN_st_Pressed;
+          events |= button_Events[i];
+        }
+        button_Time[i] = 0;
+        button_States[i] = BTN_st_Released;
+        pause = (BTN_SCAN_PAUSE/BTN_SCAN_PERIOD);
+      }
+
+      /* Segnaling events to the thread, if any. */
+      if (events) {
+        chSysLockFromISR();
+        chEvtSignalI(evt_thread, events);
+        chSysUnlockFromISR();
+        events = 0;
+      }
+    } /* end FOR */
+
+  } /* end Pause check */
+}
+
+void buttons_Init(thread_t * thread) {
+  evt_thread = thread;
+  chVTSetContinuous(&button_vt, TIME_MS2I(BTN_SCAN_PERIOD), button_Process, NULL);
+}
+
+button_state_t buttons_GetState(const button_num_t btn) {
+  return button_States[btn];
+}

+ 392 - 0
src/main.c

@@ -0,0 +1,392 @@
+/*
+    ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+*/
+
+#include <ch.h>
+#include <hal.h>
+#include <gfx.h>
+#include <chprintf.h>
+#include "buttons.h"
+#include "INA3221.h"
+
+/* Type definitions */
+typedef enum chrgr_state {
+  Stop = 0,
+  Charge1,
+  Pause1,
+  Decharge,
+  Pause2,
+  Charge2,
+  Error
+} charger_state_t;
+
+typedef struct {
+  uint8_t hh;
+  uint8_t mm;
+  uint8_t ss;
+} time_cnt_t;
+
+// types and description of accums - SLA, LiIon
+
+// variants and description of voltaged accroding to cemistry type - 6/12V, 1-4S
+// and db of min and max voltages for each
+
+// some set of amperage or capacitance - range of current for charge/decharge stop condition
+
+typedef struct chrgr_channel {
+  int16_t shunt;        /**< resistance in milliOhms. */
+  int16_t max_current;  /**< max channel current in milliAmpers. */
+} charger_channel_t;
+
+/*
+ * I2C1 config.
+ */
+static const I2CConfig i2cfg1 = {
+    OPMODE_I2C,
+    400000,
+    FAST_DUTY_CYCLE_2,
+};
+/*
+ * 
+ */
+static void gpt_cb(GPTDriver *gptp);
+static GPTConfig gpt_cfg = {
+  1000,   /* Timer clock.    */
+  gpt_cb, /* Timer callback. */
+  0, 0
+};
+
+/* Private constants */
+static const charger_channel_t charger_Channels[INA3221_CH_NUM] = {
+  {20, 8190}, {50, 3276}, {10, 16380}
+};
+
+/* Private variables */
+static charger_state_t charger_State;
+static uint8_t current_Channel;
+static int32_t Current, sumCurrent=0;
+static uint32_t Voltage, sumVoltage=0;
+static int INA_Present = 0;
+static BaseSequentialStream * chp = (BaseSequentialStream*) &SD1;
+GHandle GW1;  // The handle for our console
+ina3221_t ina3221;
+static gFont font1;
+static gFont font2;
+static time_cnt_t Timer = {0};
+
+/* Privae functions */
+static void prepareScreen(void);
+static void btn1_handler(void);
+static void btn2_handler(void);
+static void btn3_handler(void);
+static void btn4_handler(void);
+
+/*
+ * Read Voltage, Current, update screen info.
+ */
+static THD_WORKING_AREA(waInaThread, 128);
+static THD_FUNCTION(InaThread, arg) {
+  (void)arg;
+  systime_t time;
+  int32_t tmp1, tmp2;
+  char buf[12];
+
+  while (true) {
+    time = chVTGetSystemTimeX();
+
+    if (INA_Present != 0) {
+      Current = INA3221_getCurrent(&ina3221, (ina3221_ch_t)current_Channel);
+      Voltage = INA3221_getVoltage(&ina3221, (ina3221_ch_t)current_Channel);
+
+      tmp1 = Voltage / 1000;
+      tmp2 = Voltage % 1000;
+      chsnprintf(buf, 10, "V:%2d.%03u", tmp1, tmp2);
+      gdispFillStringBox(1, 123, 106, 29, buf, font2, Red, Gray, gJustifyCenter);
+
+      if (Current < 0) {
+        Current = 1 - Current;
+      }
+      tmp1 = Current / 1000;
+      tmp2 = Current % 1000;
+      chsnprintf(buf, 10, "I:%2d.%03u", tmp1, tmp2);
+      gdispFillStringBox(160, 123, 106, 29, buf, font2, Red, Gray, gJustifyCenter);
+
+      if (charger_State != Stop) {
+        sumCurrent += Current;
+        sumVoltage += Voltage;
+      }
+    }
+
+    chThdSleepUntil(time += TIME_MS2I(100));
+  }
+}
+
+/*
+ * Green LED blinker thread, times are in milliseconds.
+ */
+static THD_WORKING_AREA(waThread1, 128);
+static THD_FUNCTION(Thread1, arg) {
+  (void)arg;
+  chRegSetThreadName("blinker");
+  while (true) {
+    palSetLine(LINE_LED4);
+    chThdSleepMilliseconds(500);
+    palClearLine(LINE_LED4);
+    chThdSleepMilliseconds(500);
+  }
+}
+
+/*
+ * Pointer to the Buton handler thread.
+ */
+thread_t * btn_thread;
+
+static THD_WORKING_AREA(waBTNThread, 128);
+static THD_FUNCTION(BTNThread, arg) {
+  (void)arg;
+
+  /* Thread activity.*/
+  while (true) {
+    /* Waiting for any event.*/
+    eventmask_t evt = chEvtWaitAny(ALL_EVENTS);
+    palToggleLine(LINE_LED2);
+ 
+    /* Serving events.*/
+    if (evt & EVT_BTN1_PRS) {
+      /* BTN1 event.*/
+      btn1_handler();
+    }
+    if (evt & EVT_BTN2_PRS) {
+      /* BTN2 event.*/
+      btn2_handler();
+    }
+    if (evt & EVT_BTN3_PRS) {
+      /* BTN3 event.*/
+      btn3_handler();
+    }
+    if (evt & EVT_BTN4_PRS) {
+      /* BTN4 event.*/
+      btn4_handler();
+    }
+  }
+}
+
+/*
+ * Application entry point.
+ */
+int main(void) {
+  /*
+   * System initializations.
+   * - HAL initialization, this also initializes the configured device drivers
+   *   and performs the board-specific initializations.
+   * - Kernel initialization, the main() function becomes a thread and the
+   *   RTOS is active.
+   */
+  halInit();
+  chSysInit();
+
+  /*
+   * This initialization requires the OS already active because it uses delay
+   * APIs inside.
+   *
+   * Initialize uGFX and the underlying system
+   */
+  gfxInit();
+  prepareScreen();
+
+  gptStart(&GPTD5, &gpt_cfg);
+
+  /*
+   * Activates the I2C driver 1.
+   */
+  i2cStart(&I2CD1, &i2cfg1);
+
+  /*
+   * Activates the serial driver 1 using the driver default configuration.
+   */
+  sdStart(&SD1, NULL);
+  chprintf(chp, "\033[2J\033[1;1H"); // clear screen
+  chprintf(chp, "Started\r\n");
+
+  /*
+   * Starting the button handle thread.
+   */
+  btn_thread = chThdCreateStatic(waBTNThread, sizeof(waBTNThread),
+                                  NORMALPRIO+1, BTNThread, NULL);
+  buttons_Init(btn_thread);
+
+  /*
+   * Creates the INA thread.
+   */
+  chThdCreateStatic(waInaThread, sizeof(waInaThread), NORMALPRIO, InaThread, NULL);
+
+  gwinPrintf(GW1, "Try to init INA3221....\n");
+  ina3221.i2c_addr = INA3221_ADDR40_GND;
+  ina3221.i2cd = &I2CD1;
+  ina3221.shuntRes[INA3221_CH1] = charger_Channels[INA3221_CH1].shunt;
+  ina3221.shuntRes[INA3221_CH2] = charger_Channels[INA3221_CH2].shunt;
+  ina3221.shuntRes[INA3221_CH3] = charger_Channels[INA3221_CH3].shunt;
+
+  if (INA3221_getManufID(&ina3221) == 0x5449) {
+    if (INA3221_getDieID(&ina3221) == 0x3220) {
+      INA_Present = 1;
+      gwinPrintf(GW1, "INA3221 present!\n");
+
+      INA3221_reset(&ina3221);
+      INA3221_setBusConversionTime(&ina3221, INA3221_REG_CONF_CT_8244US);
+    }
+  } else {
+    gwinPrintf(GW1, "Sensor INA3221 not give proper IDs.\n", Voltage);
+  }
+
+  /*
+   * Creates the blinker thread.
+   */
+  chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO-1, Thread1, NULL);
+
+  /* Init charger module */
+  charger_State = Stop;
+  current_Channel = INA3221_CH1;
+  gptStartContinuous(&GPTD5, 10000);
+  char buf[16];
+  /*
+   * Normal main() thread activity, in this demo it does nothing except
+   * sleeping in a loop and check the button state.
+   */
+  while (true) {
+    chThdSleepMilliseconds(500);
+
+    if (charger_State != Stop) {
+      chsnprintf(buf, 12, "T:%02u:%02u:%02u", Timer.hh, Timer.mm, Timer.ss);
+    } else {
+      chsnprintf(buf, 12, "T:00:00:00");
+    }
+    gdispFillStringBox(1, 153, 158, 29, buf, font2, Red, Gray, gJustifyCenter);
+
+  }
+}
+
+static void prepareScreen(void) {
+  /* Set some fonts */
+  font1 = gdispOpenFont("DejaVu Sans Book 12");
+  font2 = gdispOpenFont("DejaVu Sans Book 24");
+  gwinSetDefaultFont(font1);
+
+  /* draw screen frame */
+  const coord_t width = 320;
+  const coord_t height = 240;
+
+  gdispDrawBox(0, 0, width-1, height-1, Green); // all screen
+  gdispDrawLine(0, 122, width-1, 122, Green); // h line
+  gdispDrawLine(79, 0, 79, 122, Green); // v line, text | console
+  gdispFillArea(1, 1, 78, 121, Blue); // text area
+
+  /* print text to top-left area */
+  gdispDrawStringBox(1, 1, 78, 15,  "[1] ch.1 ", font1, Yellow, gJustifyLeft);
+  gdispDrawStringBox(1, 16, 78, 15, "   -  A ", font1, Yellow, gJustifyLeft);
+  gdispDrawStringBox(1, 31, 78, 15, "[2] SLA", font1, Yellow, gJustifyLeft);
+  gdispDrawStringBox(1, 46, 78, 15, "   - 12V", font1, Yellow, gJustifyLeft);
+  gdispDrawStringBox(1, 61, 78, 15, "[3] current", font1, Yellow, gJustifyLeft);
+  gdispDrawStringBox(1, 76, 78, 15, "   - 1A", font1, Yellow, gJustifyLeft);
+  gdispDrawStringBox(1, 91, 78, 15, "[4] start", font1, Yellow, gJustifyLeft);
+//  gdispDrawStringBox(1, 106, 78, 15, "        ", font1, Yellow, gJustifyLeft);
+
+  /* print text to bootom area */
+  gdispFillStringBox(1, 123, 158, 115, " ", font2, Red, Gray, gJustifyCenter);
+  gdispFillStringBox(159, 123, 158, 115, " ", font2, Red, Silver, gJustifyCenter);
+
+  /* create the console window */
+  {
+    GWindowInit wi;
+
+    gwinClearInit(&wi);
+    wi.show = gTrue;
+    wi.x = 82; wi.y = 2; wi.width = 239; wi.height = 120;
+    GW1 = gwinConsoleCreate(0, &wi);
+  }
+
+  /* Set the fore- and background colors for each console */
+  gwinSetColor(GW1, GFX_WHITE);
+  gwinSetBgColor(GW1, GFX_BLACK);
+
+  /* clear all console windows - to set background */
+  gwinClear(GW1);
+
+  /* Output some data on the console */
+  gwinPrintf(GW1, "\033bConsole\033B started sucessful.\n");
+}
+
+static void btn1_handler(void) {
+  gwinPrintf(GW1, "Button 1 pressed\n");
+
+  current_Channel ++;
+  if (current_Channel >= INA3221_CH_NUM) {
+    current_Channel = INA3221_CH1;
+  }
+  int tmp = current_Channel + 1;
+  gwinPrintf(GW1, "Channel #%u selected.\n", tmp);
+
+  char buf[16];
+  chsnprintf(buf, 10, "[1] ch.%u", tmp);
+  gdispFillStringBox(1, 1, 78, 15,  buf, font1, Yellow, Blue, gJustifyLeft);
+
+  chsnprintf(buf, 12, "   - %2uA ", charger_Channels[current_Channel].max_current/1000);
+  gdispFillStringBox(1, 16, 78, 15, buf, font1, Yellow, Blue, gJustifyLeft);
+}
+
+static void btn2_handler(void) {
+  gwinPrintf(GW1, "Button 2 pressed\n");
+}
+
+static void btn3_handler(void) {
+  gwinPrintf(GW1, "Button 3 pressed\n");
+}
+
+static void btn4_handler(void) {
+  gwinPrintf(GW1, "Button 4 pressed\n");
+
+  switch(charger_State) {
+  case Stop:
+    charger_State = Charge1;
+    gwinPrintf(GW1, "Change state to Charge#1\n");
+    gdispFillStringBox(1, 91, 78, 15, "[4] Stop", font1, Yellow, Blue, gJustifyLeft);
+    break;
+  default:
+    charger_State = Stop;
+    gwinPrintf(GW1, "Change state to Stop\n");
+    gdispFillStringBox(1, 91, 78, 15, "[4] Start", font1, Yellow, Blue, gJustifyLeft);
+    break;
+  }
+}
+
+/*
+ * GPT callback.
+ */
+static void gpt_cb(GPTDriver *gptp) {
+  (void)gptp;
+
+  palToggleLine(LINE_LED1);
+  if (Timer.ss < 59) {
+    Timer.ss ++;
+  } else {
+    Timer.ss = 0;
+    if (Timer.mm < 59) {
+      Timer.mm ++;
+    } else {
+      Timer.mm = 0;
+      Timer.hh ++;
+    }
+  }
+}