From 8d9542865bd2fd0fa0e24ffc679b82c6520e4021 2019-08-31 12:57:05 From: fantawams Date: 2019-08-31 12:57:05 Subject: [PATCH] Updated Software repo --- diff --git a/Software/hoverboard-firmware-hack_modified20190825/Inc/config.h b/Software/hoverboard-firmware-hack_modified20190825/Inc/config.h new file mode 100644 index 0000000000000000000000000000000000000000..a6987e701d0aa4658be8f4be73174caac37ec450 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Inc/config.h @@ -0,0 +1,194 @@ +#pragma once +#include "stm32f1xx_hal.h" + +// ############################### DO-NOT-TOUCH SETTINGS ############################### + +#define PWM_FREQ 16000 // PWM frequency in Hz +#define DEAD_TIME 32 // PWM deadtime + +#define DELAY_IN_MAIN_LOOP 5 // in ms. default 5. it is independent of all the timing critical stuff. do not touch if you do not know what you are doing. + +#define TIMEOUT 5 // number of wrong / missing input commands before emergency off + +// ############################### GENERAL ############################### + +// How to calibrate: connect GND and RX of a 3.3v uart-usb adapter to the right sensor board cable (be careful not to use the red wire of the cable. 15v will destroy everything.). if you are using nunchuck, disable it temporarily. enable DEBUG_SERIAL_USART3 and DEBUG_SERIAL_ASCII use asearial terminal. + +// Battery voltage calibration: connect power source. see . write value nr 5 to BAT_CALIB_ADC. make and flash firmware. then you can verify voltage on value 6 (devide it by 100.0 to get calibrated voltage). +#define BAT_CALIB_REAL_VOLTAGE 43.0 // input voltage measured by multimeter +#define BAT_CALIB_ADC 1704 // adc-value measured by mainboard (value nr 5 on UART debug output) + +#define BAT_NUMBER_OF_CELLS 10 // normal Hoverboard battery: 10s +#define BAT_LOW_LVL1_ENABLE 0 // to beep or not to beep, 1 or 0 +#define BAT_LOW_LVL1 3.6 // gently beeps at this voltage level. [V/cell] +#define BAT_LOW_LVL2_ENABLE 1 // to beep or not to beep, 1 or 0 +#define BAT_LOW_LVL2 3.5 // your battery is almost empty. Charge now! [V/cell] +#define BAT_LOW_DEAD 3.37 // undervoltage poweroff. (while not driving) [V/cell] + +#define DC_CUR_LIMIT 15 // DC current limit in amps per motor. so 15 means it will draw 30A out of your battery. it does not disable motors, it is a soft current limit. + +// Board overheat detection: the sensor is inside the STM/GD chip. it is very inaccurate without calibration (up to 45°C). so only enable this funcion after calibration! let your board cool down. see . get the real temp of the chip by thermo cam or another temp-sensor taped on top of the chip and write it to TEMP_CAL_LOW_DEG_C. write debug value 8 to TEMP_CAL_LOW_ADC. drive around to warm up the board. it should be at least 20°C warmer. repeat it for the HIGH-values. enable warning and/or poweroff and make and flash firmware. +#define TEMP_CAL_LOW_ADC 1655 // temperature 1: ADC value +#define TEMP_CAL_LOW_DEG_C 35.8 // temperature 1: measured temperature [°C] +#define TEMP_CAL_HIGH_ADC 1588 // temperature 2: ADC value +#define TEMP_CAL_HIGH_DEG_C 48.9 // temperature 2: measured temperature [°C] +#define TEMP_WARNING_ENABLE 0 // to beep or not to beep, 1 or 0, DO NOT ACTIVITE WITHOUT CALIBRATION! +#define TEMP_WARNING 60 // annoying fast beeps [°C] +#define TEMP_POWEROFF_ENABLE 0 // to poweroff or not to poweroff, 1 or 0, DO NOT ACTIVITE WITHOUT CALIBRATION! +#define TEMP_POWEROFF 65 // overheat poweroff. (while not driving) [°C] + +#define INACTIVITY_TIMEOUT 8 // minutes of not driving until poweroff. it is not very precise. + +// ############################### LCD DEBUG ############################### + +//#define DEBUG_I2C_LCD // standard 16x2 or larger text-lcd via i2c-converter on right sensor board cable + +// ############################### SERIAL DEBUG ############################### + +#define DEBUG_SERIAL_USART3 // right sensor board cable, disable if I2C (nunchuck or lcd) is used! +#define DEBUG_BAUD 115200 // UART baud rate +//#define DEBUG_SERIAL_SERVOTERM // Software for plotting graphs: https://github.com/STMBL/Servoterm-app +#define DEBUG_SERIAL_ASCII // "1:345 2:1337 3:0 4:0 5:0 6:0 7:0 8:0\r\n" + +// ############################### INPUT ############################### + +// ###### CONTROL VIA UART (serial) ###### +//#define CONTROL_SERIAL_USART2 // left sensor board cable, disable if ADC or PPM is used! +//#define CONTROL_BAUD 19200 // control via usart from eg an Arduino or raspberry +// for Arduino, use void loop(void){ Serial.write((uint8_t *) &steer, sizeof(steer)); Serial.write((uint8_t *) &speed, sizeof(speed));delay(20); } + +// ###### CONTROL VIA RC REMOTE ###### +// left sensor board cable. Channel 1: steering, Channel 2: speed. Use a very short cable! +#define CONTROL_PPM // use PPM-Sum as input. disable CONTROL_SERIAL_USART2! +#define PPM_NUM_CHANNELS 6 // total number of PPM channels to receive, even if they are not used. + +// ###### CONTROL VIA TWO POTENTIOMETERS ###### +// ADC-calibration to cover the full poti-range: connect potis to left sensor board cable (0 to 3.3V) (do NOT use the red 15V wire in the cable!). see . turn the potis to minimum position, write value 1 to ADC1_MIN and value 2 to ADC2_MIN. turn to maximum position and repeat it for ADC?_MAX. make, flash and test it. +//#define CONTROL_ADC // use ADC as input. disable CONTROL_SERIAL_USART2! +//#define ADC1_MIN 0 // min ADC1-value while poti at minimum-position (0 - 4095) +//#define ADC1_MAX 4095 // max ADC1-value while poti at maximum-position (0 - 4095) +//#define ADC2_MIN 0 // min ADC2-value while poti at minimum-position (0 - 4095) +//#define ADC2_MAX 4095 // max ADC2-value while poti at maximum-position (0 - 4095) + +// ###### CONTROL VIA NINTENDO NUNCHUCK ###### +// left sensor board cable. keep cable short, use shielded cable, use ferrits, stabalize voltage in nunchuck, use the right one of the 2 types of nunchucks, add i2c pullups. use original nunchuck. most clones does not work very well. +//#define CONTROL_NUNCHUCK // use nunchuck as input. disable DEBUG_SERIAL_USART3! + +// ###### MOTOR TEST MODE ###### +// slowly move both wheels forward and backward, ignoring all inputs +#define CONTROL_MOTOR_TEST +#define CONTROL_MOTOR_TEST_MAX_SPEED 300 // sweep slowly from -MAX_SPEED to MAX_SPEED (0 - 1000) + +// ############################### DRIVING BEHAVIOR ############################### + +// inputs: +// - cmd1 and cmd2: analog normalized input values. -1000 to 1000 +// - button1 and button2: digital input values. 0 or 1 +// - adc_buffer.l_tx2 and adc_buffer.l_rx2: unfiltered ADC values (you do not need them). 0 to 4095 +// outputs: +// - speedR and speedL: normal driving -1000 to 1000 +// - weakr and weakl: field weakening for extra boost at high speed (speedR > 700 and speedL > 700). 0 to ~400 + +#define FILTER 0.1 // lower value == softer filter. do not use values <0.01, you will get float precision issues. +#define SPEED_COEFFICIENT 0.5 // higher value == stronger. 0.0 to ~2.0? +#define STEER_COEFFICIENT 0.5 // higher value == stronger. if you do not want any steering, set it to 0.0; 0.0 to 1.0 +#define INVERT_R_DIRECTION +#define INVERT_L_DIRECTION +#define BEEPS_BACKWARD 1 // 0 or 1 + +//Turbo boost at high speeds while button1 is pressed: +//#define ADDITIONAL_CODE \ +if (button1 && speedR > 700) { /* field weakening at high speeds */ \ + weakl = cmd1 - 700; /* weak should never exceed 400 or 450 MAX!! */ \ + weakr = cmd1 - 700; } \ +else { \ + weakl = 0; \ + weakr = 0; } + +// ###### SIMPLE BOBBYCAR ###### +// for better bobbycar code see: https://github.com/larsmm/hoverboard-firmware-hack-bbcar +// #define FILTER 0.1 +// #define SPEED_COEFFICIENT -1 +// #define STEER_COEFFICIENT 0 + +// #define ADDITIONAL_CODE \ +if (button1 && speedR < 300) { /* drive backwards */ \ + speedR = speedR * -0.2f; \ + speedL = speedL * -0.2f; } \ +else { \ + direction = 1; } \ +if (button1 && speedR > 700) { /* field weakening at high speeds */ \ + weakl = speedR - 600; /* weak should never exceed 400 or 450 MAX!! */ \ + weakr = speedR - 600; } \ +else { \ + weakl = 0; \ + weakr = 0; } + +// ###### ARMCHAIR ###### +// #define FILTER 0.05 +// #define SPEED_COEFFICIENT 0.5 +// #define STEER_COEFFICIENT -0.2 + +// #define ADDITIONAL_CODE if (button1 && scale > 0.8) { /* field weakening at high speeds */ \ + weakl = speedL - 600; /* weak should never exceed 400 or 450 MAX!! */ \ + weakr = speedR - 600; } \ +else {\ + weakl = 0;\ + weakr = 0; + +// ############################### VALIDATE SETTINGS ############################### + +#if defined CONTROL_SERIAL_USART2 && defined CONTROL_ADC + #error CONTROL_ADC and CONTROL_SERIAL_USART2 not allowed. it is on the same cable. +#endif + +#if defined CONTROL_SERIAL_USART2 && defined CONTROL_PPM + #error CONTROL_PPM and CONTROL_SERIAL_USART2 not allowed. it is on the same cable. +#endif + +#if defined DEBUG_SERIAL_USART3 && defined CONTROL_NUNCHUCK + #error CONTROL_NUNCHUCK and DEBUG_SERIAL_USART3 not allowed. it is on the same cable. +#endif + +#if defined DEBUG_SERIAL_USART3 && defined DEBUG_I2C_LCD + #error DEBUG_I2C_LCD and DEBUG_SERIAL_USART3 not allowed. it is on the same cable. +#endif + +#ifdef CONTROL_SERIAL_USART2 + #if defined CONTROL_DEFINED + #error select exactly 1 input method in config.h! + #endif + #define CONTROL_DEFINED +#endif + +#ifdef CONTROL_PPM + #if defined CONTROL_DEFINED + #error select exactly 1 input method in config.h! + #endif + #define CONTROL_DEFINED +#endif + +#ifdef CONTROL_ADC + #if defined CONTROL_DEFINED + #error select exactly 1 input method in config.h! + #endif + #define CONTROL_DEFINED +#endif + +#ifdef CONTROL_NUNCHUCK + #if defined CONTROL_DEFINED + #error select exactly 1 input method in config.h! + #endif + #define CONTROL_DEFINED +#endif + +#ifdef CONTROL_MOTOR_TEST + #if defined CONTROL_DEFINED + #error select exactly 1 input method in config.h! + #endif + #define CONTROL_DEFINED +#endif + +#ifndef CONTROL_DEFINED + #error select exactly 1 input method in config.h! +#endif diff --git a/Software/hoverboard-firmware-hack_modified20190825/Inc/defines.h b/Software/hoverboard-firmware-hack_modified20190825/Inc/defines.h new file mode 100644 index 0000000000000000000000000000000000000000..dc66f4f95bfc9049755d19897da1e54ec021cc7d --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Inc/defines.h @@ -0,0 +1,160 @@ +/* +* This file is part of the hoverboard-firmware-hack project. +* +* Copyright (C) 2017-2018 Rene Hopf +* Copyright (C) 2017-2018 Nico Stute +* Copyright (C) 2017-2018 Niklas Fauth +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +#pragma once +#include "stm32f1xx_hal.h" + +#define LEFT_HALL_U_PIN GPIO_PIN_5 +#define LEFT_HALL_V_PIN GPIO_PIN_6 +#define LEFT_HALL_W_PIN GPIO_PIN_7 + +#define LEFT_HALL_U_PORT GPIOB +#define LEFT_HALL_V_PORT GPIOB +#define LEFT_HALL_W_PORT GPIOB + +#define RIGHT_HALL_U_PIN GPIO_PIN_10 +#define RIGHT_HALL_V_PIN GPIO_PIN_11 +#define RIGHT_HALL_W_PIN GPIO_PIN_12 + +#define RIGHT_HALL_U_PORT GPIOC +#define RIGHT_HALL_V_PORT GPIOC +#define RIGHT_HALL_W_PORT GPIOC + +#define LEFT_TIM TIM8 +#define LEFT_TIM_U CCR1 +#define LEFT_TIM_UH_PIN GPIO_PIN_6 +#define LEFT_TIM_UH_PORT GPIOC +#define LEFT_TIM_UL_PIN GPIO_PIN_7 +#define LEFT_TIM_UL_PORT GPIOA +#define LEFT_TIM_V CCR2 +#define LEFT_TIM_VH_PIN GPIO_PIN_7 +#define LEFT_TIM_VH_PORT GPIOC +#define LEFT_TIM_VL_PIN GPIO_PIN_0 +#define LEFT_TIM_VL_PORT GPIOB +#define LEFT_TIM_W CCR3 +#define LEFT_TIM_WH_PIN GPIO_PIN_8 +#define LEFT_TIM_WH_PORT GPIOC +#define LEFT_TIM_WL_PIN GPIO_PIN_1 +#define LEFT_TIM_WL_PORT GPIOB + +#define RIGHT_TIM TIM1 +#define RIGHT_TIM_U CCR1 +#define RIGHT_TIM_UH_PIN GPIO_PIN_8 +#define RIGHT_TIM_UH_PORT GPIOA +#define RIGHT_TIM_UL_PIN GPIO_PIN_13 +#define RIGHT_TIM_UL_PORT GPIOB +#define RIGHT_TIM_V CCR2 +#define RIGHT_TIM_VH_PIN GPIO_PIN_9 +#define RIGHT_TIM_VH_PORT GPIOA +#define RIGHT_TIM_VL_PIN GPIO_PIN_14 +#define RIGHT_TIM_VL_PORT GPIOB +#define RIGHT_TIM_W CCR3 +#define RIGHT_TIM_WH_PIN GPIO_PIN_10 +#define RIGHT_TIM_WH_PORT GPIOA +#define RIGHT_TIM_WL_PIN GPIO_PIN_15 +#define RIGHT_TIM_WL_PORT GPIOB + +// #define LEFT_DC_CUR_ADC ADC1 +// #define LEFT_U_CUR_ADC ADC1 +// #define LEFT_V_CUR_ADC ADC1 + +#define LEFT_DC_CUR_PIN GPIO_PIN_0 +#define LEFT_U_CUR_PIN GPIO_PIN_0 +#define LEFT_V_CUR_PIN GPIO_PIN_3 + +#define LEFT_DC_CUR_PORT GPIOC +#define LEFT_U_CUR_PORT GPIOA +#define LEFT_V_CUR_PORT GPIOC + +// #define RIGHT_DC_CUR_ADC ADC2 +// #define RIGHT_U_CUR_ADC ADC2 +// #define RIGHT_V_CUR_ADC ADC2 + +#define RIGHT_DC_CUR_PIN GPIO_PIN_1 +#define RIGHT_U_CUR_PIN GPIO_PIN_4 +#define RIGHT_V_CUR_PIN GPIO_PIN_5 + +#define RIGHT_DC_CUR_PORT GPIOC +#define RIGHT_U_CUR_PORT GPIOC +#define RIGHT_V_CUR_PORT GPIOC + +// #define DCLINK_ADC ADC3 +// #define DCLINK_CHANNEL +#define DCLINK_PIN GPIO_PIN_2 +#define DCLINK_PORT GPIOC +// #define DCLINK_PULLUP 30000 +// #define DCLINK_PULLDOWN 1000 + +#define LED_PIN GPIO_PIN_2 +#define LED_PORT GPIOB + +#define BUZZER_PIN GPIO_PIN_4 +#define BUZZER_PORT GPIOA + +#define SWITCH_PIN GPIO_PIN_1 +#define SWITCH_PORT GPIOA + +#define OFF_PIN GPIO_PIN_5 +#define OFF_PORT GPIOA + +#define BUTTON_PIN GPIO_PIN_1 +#define BUTTON_PORT GPIOA + +#define CHARGER_PIN GPIO_PIN_12 +#define CHARGER_PORT GPIOA + +#define DELAY_TIM_FREQUENCY_US 1000000 + +#define MOTOR_AMP_CONV_DC_AMP 0.02 // A per bit (12) on ADC. + +#define MILLI_R (R * 1000) +#define MILLI_PSI (PSI * 1000) +#define MILLI_V (V * 1000) + +#define NO 0 +#define YES 1 +#define ABS(a) (((a) < 0.0) ? -(a) : (a)) +#define LIMIT(x, lowhigh) (((x) > (lowhigh)) ? (lowhigh) : (((x) < (-lowhigh)) ? (-lowhigh) : (x))) +#define SAT(x, lowhigh) (((x) > (lowhigh)) ? (1.0) : (((x) < (-lowhigh)) ? (-1.0) : (0.0))) +#define SAT2(x, low, high) (((x) > (high)) ? (1.0) : (((x) < (low)) ? (-1.0) : (0.0))) +#define STEP(from, to, step) (((from) < (to)) ? (MIN((from) + (step), (to))) : (MAX((from) - (step), (to)))) +#define DEG(a) ((a)*M_PI / 180.0) +#define RAD(a) ((a)*180.0 / M_PI) +#define SIGN(a) (((a) < 0.0) ? (-1.0) : (((a) > 0.0) ? (1.0) : (0.0))) +#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x))) +#define SCALE(value, high, max) MIN(MAX(((max) - (value)) / ((max) - (high)), 0.0), 1.0) +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MIN3(a, b, c) MIN(a, MIN(b, c)) +#define MAX3(a, b, c) MAX(a, MAX(b, c)) + +typedef struct { + uint16_t rr1; + uint16_t rr2; + uint16_t rl1; + uint16_t rl2; + uint16_t dcr; + uint16_t dcl; + uint16_t batt1; + uint16_t l_tx2; + uint16_t temp; + uint16_t l_rx2; +} adc_buf_t; diff --git a/Software/hoverboard-firmware-hack_modified20190825/Inc/setup.h b/Software/hoverboard-firmware-hack_modified20190825/Inc/setup.h new file mode 100644 index 0000000000000000000000000000000000000000..a024fe6b1df4f16a43acc120424fab61feebf6c7 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Inc/setup.h @@ -0,0 +1,30 @@ +/* +* This file is part of the hoverboard-firmware-hack project. +* +* Copyright (C) 2017-2018 Rene Hopf +* Copyright (C) 2017-2018 Nico Stute +* Copyright (C) 2017-2018 Niklas Fauth +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +#pragma once + +#include "stm32f1xx_hal.h" + +void MX_GPIO_Init(void); +void MX_TIM_Init(void); +void MX_ADC1_Init(void); +void MX_ADC2_Init(void); +void UART_Init(void); diff --git a/Software/hoverboard-firmware-hack_modified20190825/Inc/stm32f1xx_hal_conf.h b/Software/hoverboard-firmware-hack_modified20190825/Inc/stm32f1xx_hal_conf.h new file mode 100644 index 0000000000000000000000000000000000000000..ee93bd90795bdf276605de5991c84774d0717a71 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Inc/stm32f1xx_hal_conf.h @@ -0,0 +1,365 @@ +/** + ****************************************************************************** + * @file stm32f1xx_hal_conf.h + * @brief HAL configuration file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F1xx_HAL_CONF_H +#define __STM32F1xx_HAL_CONF_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ + +#define HAL_MODULE_ENABLED +#define HAL_ADC_MODULE_ENABLED +/*#define HAL_CRYP_MODULE_ENABLED */ +/*#define HAL_CAN_MODULE_ENABLED */ +/*#define HAL_CEC_MODULE_ENABLED */ +/*#define HAL_CORTEX_MODULE_ENABLED */ +/*#define HAL_CRC_MODULE_ENABLED */ +/*#define HAL_DAC_MODULE_ENABLED */ +#define HAL_DMA_MODULE_ENABLED +/*#define HAL_ETH_MODULE_ENABLED */ +/*#define HAL_FLASH_MODULE_ENABLED */ +#define HAL_GPIO_MODULE_ENABLED +#define HAL_I2C_MODULE_ENABLED +/*#define HAL_I2S_MODULE_ENABLED */ +/*#define HAL_IRDA_MODULE_ENABLED */ +/*#define HAL_IWDG_MODULE_ENABLED */ +/*#define HAL_NOR_MODULE_ENABLED */ +/*#define HAL_NAND_MODULE_ENABLED */ +/*#define HAL_PCCARD_MODULE_ENABLED */ +/*#define HAL_PCD_MODULE_ENABLED */ +/*#define HAL_HCD_MODULE_ENABLED */ +/*#define HAL_PWR_MODULE_ENABLED */ +/*#define HAL_RCC_MODULE_ENABLED */ +/*#define HAL_RTC_MODULE_ENABLED */ +/*#define HAL_SD_MODULE_ENABLED */ +/*#define HAL_MMC_MODULE_ENABLED */ +/*#define HAL_SDRAM_MODULE_ENABLED */ +/*#define HAL_SMARTCARD_MODULE_ENABLED */ +/*#define HAL_SPI_MODULE_ENABLED */ +/*#define HAL_SRAM_MODULE_ENABLED */ +#define HAL_TIM_MODULE_ENABLED +#define HAL_UART_MODULE_ENABLED +/*#define HAL_USART_MODULE_ENABLED */ +/*#define HAL_WWDG_MODULE_ENABLED */ + +#define HAL_CORTEX_MODULE_ENABLED +#define HAL_DMA_MODULE_ENABLED +#define HAL_FLASH_MODULE_ENABLED +#define HAL_GPIO_MODULE_ENABLED +#define HAL_PWR_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED + +/* ########################## Oscillator Values adaptation ####################*/ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined(HSE_VALUE) +#define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined(HSE_STARTUP_TIMEOUT) +#define HSE_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined(HSI_VALUE) +#define HSI_VALUE ((uint32_t)8000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined(LSI_VALUE) +#define LSI_VALUE 40000U /*!< LSI Typical Value in Hz */ +#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz \ + The real value may vary depending on the variations \ + in voltage and temperature. */ + +/** + * @brief External Low Speed oscillator (LSE) value. + * This value is used by the UART, RTC HAL module to compute the system frequency + */ +#if !defined(LSE_VALUE) +#define LSE_VALUE ((uint32_t)32768) /*!< Value of the External oscillator in Hz*/ +#endif /* LSE_VALUE */ + +#if !defined(LSE_STARTUP_TIMEOUT) +#define LSE_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for LSE start up, in ms */ +#endif /* LSE_STARTUP_TIMEOUT */ + +/* Tip: To avoid modifying this file each time you need to use different HSE, + === you can define the HSE value in your toolchain compiler preprocessor. */ + +/* ########################### System Configuration ######################### */ +/** + * @brief This is the HAL system configuration section + */ +#define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY ((uint32_t)0) /*!< tick interrupt priority (lowest by default) */ +#define USE_RTOS 0 +#define PREFETCH_ENABLE 1 + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1U */ + +/* ################## Ethernet peripheral configuration ##################### */ + +/* Section 1 : Ethernet peripheral configuration */ + +/* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ +#define MAC_ADDR0 2 +#define MAC_ADDR1 0 +#define MAC_ADDR2 0 +#define MAC_ADDR3 0 +#define MAC_ADDR4 0 +#define MAC_ADDR5 0 + +/* Definition of the Ethernet driver buffers size and count */ +#define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ +#define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ +#define ETH_RXBUFNB ((uint32_t)8) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ +#define ETH_TXBUFNB ((uint32_t)4) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ + +/* Section 2: PHY configuration section */ + +/* DP83848_PHY_ADDRESS Address*/ +#define DP83848_PHY_ADDRESS 0x01U +/* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ +#define PHY_RESET_DELAY ((uint32_t)0x000000FF) +/* PHY Configuration delay */ +#define PHY_CONFIG_DELAY ((uint32_t)0x00000FFF) + +#define PHY_READ_TO ((uint32_t)0x0000FFFF) +#define PHY_WRITE_TO ((uint32_t)0x0000FFFF) + +/* Section 3: Common PHY Registers */ + +#define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ +#define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ + +#define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ +#define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ +#define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */ +#define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */ +#define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */ +#define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */ +#define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */ +#define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */ +#define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */ +#define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */ + +#define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */ +#define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */ +#define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */ + +/* Section 4: Extended PHY Registers */ +#define PHY_SR ((uint16_t)0x10U) /*!< PHY status register Offset */ + +#define PHY_SPEED_STATUS ((uint16_t)0x0002U) /*!< PHY Speed mask */ +#define PHY_DUPLEX_STATUS ((uint16_t)0x0004U) /*!< PHY Duplex mask */ + +/* Includes ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED +#include "stm32f1xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED +#include "stm32f1xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED +#include "stm32f1xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_ETH_MODULE_ENABLED +#include "stm32f1xx_hal_eth.h" +#endif /* HAL_ETH_MODULE_ENABLED */ + +#ifdef HAL_CAN_MODULE_ENABLED +#include "stm32f1xx_hal_can.h" +#endif /* HAL_CAN_MODULE_ENABLED */ + +#ifdef HAL_CEC_MODULE_ENABLED +#include "stm32f1xx_hal_cec.h" +#endif /* HAL_CEC_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED +#include "stm32f1xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED +#include "stm32f1xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED +#include "stm32f1xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_DAC_MODULE_ENABLED +#include "stm32f1xx_hal_dac.h" +#endif /* HAL_DAC_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED +#include "stm32f1xx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_SRAM_MODULE_ENABLED +#include "stm32f1xx_hal_sram.h" +#endif /* HAL_SRAM_MODULE_ENABLED */ + +#ifdef HAL_NOR_MODULE_ENABLED +#include "stm32f1xx_hal_nor.h" +#endif /* HAL_NOR_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED +#include "stm32f1xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED +#include "stm32f1xx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED +#include "stm32f1xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED +#include "stm32f1xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED +#include "stm32f1xx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_PCCARD_MODULE_ENABLED +#include "stm32f1xx_hal_pccard.h" +#endif /* HAL_PCCARD_MODULE_ENABLED */ + +#ifdef HAL_SD_MODULE_ENABLED +#include "stm32f1xx_hal_sd.h" +#endif /* HAL_SD_MODULE_ENABLED */ + +#ifdef HAL_MMC_MODULE_ENABLED +#include "stm32f1xx_hal_mmc.h" +#endif /* HAL_MMC_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED +#include "stm32f1xx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED +#include "stm32f1xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED +#include "stm32f1xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED +#include "stm32f1xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED +#include "stm32f1xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED +#include "stm32f1xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED +#include "stm32f1xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED +#include "stm32f1xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED +#include "stm32f1xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_HCD_MODULE_ENABLED +#include "stm32f1xx_hal_hcd.h" +#endif /* HAL_HCD_MODULE_ENABLED */ + + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ +#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ +void assert_failed(uint8_t *file, uint32_t line); +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F1xx_HAL_CONF_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/Software/hoverboard-firmware-hack_modified20190825/Inc/stm32f1xx_it.h b/Software/hoverboard-firmware-hack_modified20190825/Inc/stm32f1xx_it.h new file mode 100644 index 0000000000000000000000000000000000000000..237a392e411ed4077349e4606e2d47f9c6830051 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Inc/stm32f1xx_it.h @@ -0,0 +1,67 @@ +/** + ****************************************************************************** + * @file stm32f1xx_it.h + * @brief This file contains the headers of the interrupt handlers. + ****************************************************************************** + * + * COPYRIGHT(c) 2017 STMicroelectronics + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F1xx_IT_H +#define __STM32F1xx_IT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f1xx_hal.h" +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions ------------------------------------------------------- */ + +void NMI_Handler(void); +void HardFault_Handler(void); +void MemManage_Handler(void); +void BusFault_Handler(void); +void UsageFault_Handler(void); +void SVC_Handler(void); +void DebugMon_Handler(void); +void PendSV_Handler(void); +void SysTick_Handler(void); +void DMA1_Channel1_IRQHandler(void); +void DMA2_Channel4_5_IRQHandler(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F1xx_IT_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/Software/hoverboard-firmware-hack_modified20190825/Src/bldc.c b/Software/hoverboard-firmware-hack_modified20190825/Src/bldc.c new file mode 100644 index 0000000000000000000000000000000000000000..e5c609cd02436e3d87017072b539f817b812cf06 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Src/bldc.c @@ -0,0 +1,279 @@ + +#include "stm32f1xx_hal.h" +#include "defines.h" +#include "setup.h" +#include "config.h" + + +volatile int posl = 0; +volatile int posr = 0; +volatile int pwml = 0; +volatile int pwmr = 0; +volatile int weakl = 0; +volatile int weakr = 0; + +extern volatile int speed; + +extern volatile adc_buf_t adc_buffer; + +extern volatile uint32_t timeout; + +uint32_t buzzerFreq = 0; +uint32_t buzzerPattern = 0; + +uint8_t enable = 0; + +const int pwm_res = 64000000 / 2 / PWM_FREQ; // = 2000 + +const uint8_t hall_to_pos[8] = { + 0, + 0, + 2, + 1, + 4, + 5, + 3, + 0, +}; + +inline void blockPWM(int pwm, int pos, int *u, int *v, int *w) { + switch(pos) { + case 0: + *u = 0; + *v = pwm; + *w = -pwm; + break; + case 1: + *u = -pwm; + *v = pwm; + *w = 0; + break; + case 2: + *u = -pwm; + *v = 0; + *w = pwm; + break; + case 3: + *u = 0; + *v = -pwm; + *w = pwm; + break; + case 4: + *u = pwm; + *v = -pwm; + *w = 0; + break; + case 5: + *u = pwm; + *v = 0; + *w = -pwm; + break; + default: + *u = 0; + *v = 0; + *w = 0; + } +} + +inline void blockPhaseCurrent(int pos, int u, int v, int *q) { + switch(pos) { + case 0: + *q = u - v; + // *u = 0; + // *v = pwm; + // *w = -pwm; + break; + case 1: + *q = u; + // *u = -pwm; + // *v = pwm; + // *w = 0; + break; + case 2: + *q = u; + // *u = -pwm; + // *v = 0; + // *w = pwm; + break; + case 3: + *q = v; + // *u = 0; + // *v = -pwm; + // *w = pwm; + break; + case 4: + *q = v; + // *u = pwm; + // *v = -pwm; + // *w = 0; + break; + case 5: + *q = -(u - v); + // *u = pwm; + // *v = 0; + // *w = -pwm; + break; + default: + *q = 0; + // *u = 0; + // *v = 0; + // *w = 0; + } +} + +uint32_t buzzerTimer = 0; + +int offsetcount = 0; +int offsetrl1 = 2000; +int offsetrl2 = 2000; +int offsetrr1 = 2000; +int offsetrr2 = 2000; +int offsetdcl = 2000; +int offsetdcr = 2000; + +float batteryVoltage = BAT_NUMBER_OF_CELLS * 4.0; + +int curl = 0; +// int errorl = 0; +// int kp = 5; +// volatile int cmdl = 0; + +int last_pos = 0; +int timer = 0; +const int max_time = PWM_FREQ / 10; +volatile int vel = 0; + +//scan 8 channels with 2ADCs @ 20 clk cycles per sample +//meaning ~80 ADC clock cycles @ 8MHz until new DMA interrupt =~ 100KHz +//=640 cpu cycles +void DMA1_Channel1_IRQHandler() { + DMA1->IFCR = DMA_IFCR_CTCIF1; + // HAL_GPIO_WritePin(LED_PORT, LED_PIN, 1); + + if(offsetcount < 1000) { // calibrate ADC offsets + offsetcount++; + offsetrl1 = (adc_buffer.rl1 + offsetrl1) / 2; + offsetrl2 = (adc_buffer.rl2 + offsetrl2) / 2; + offsetrr1 = (adc_buffer.rr1 + offsetrr1) / 2; + offsetrr2 = (adc_buffer.rr2 + offsetrr2) / 2; + offsetdcl = (adc_buffer.dcl + offsetdcl) / 2; + offsetdcr = (adc_buffer.dcr + offsetdcr) / 2; + return; + } + + if (buzzerTimer % 1000 == 0) { // because you get float rounding errors if it would run every time + batteryVoltage = batteryVoltage * 0.99 + ((float)adc_buffer.batt1 * ((float)BAT_CALIB_REAL_VOLTAGE / (float)BAT_CALIB_ADC)) * 0.01; + } + + //disable PWM when current limit is reached (current chopping) + if(ABS((adc_buffer.dcl - offsetdcl) * MOTOR_AMP_CONV_DC_AMP) > DC_CUR_LIMIT || timeout > TIMEOUT || enable == 0) { + LEFT_TIM->BDTR &= ~TIM_BDTR_MOE; + //HAL_GPIO_WritePin(LED_PORT, LED_PIN, 1); + } else { + LEFT_TIM->BDTR |= TIM_BDTR_MOE; + //HAL_GPIO_WritePin(LED_PORT, LED_PIN, 0); + } + + if(ABS((adc_buffer.dcr - offsetdcr) * MOTOR_AMP_CONV_DC_AMP) > DC_CUR_LIMIT || timeout > TIMEOUT || enable == 0) { + RIGHT_TIM->BDTR &= ~TIM_BDTR_MOE; + } else { + RIGHT_TIM->BDTR |= TIM_BDTR_MOE; + } + + int ul, vl, wl; + int ur, vr, wr; + + //determine next position based on hall sensors + uint8_t hall_ul = !(LEFT_HALL_U_PORT->IDR & LEFT_HALL_U_PIN); + uint8_t hall_vl = !(LEFT_HALL_V_PORT->IDR & LEFT_HALL_V_PIN); + uint8_t hall_wl = !(LEFT_HALL_W_PORT->IDR & LEFT_HALL_W_PIN); + + uint8_t hall_ur = !(RIGHT_HALL_U_PORT->IDR & RIGHT_HALL_U_PIN); + uint8_t hall_vr = !(RIGHT_HALL_V_PORT->IDR & RIGHT_HALL_V_PIN); + uint8_t hall_wr = !(RIGHT_HALL_W_PORT->IDR & RIGHT_HALL_W_PIN); + + uint8_t halll = hall_ul * 1 + hall_vl * 2 + hall_wl * 4; + posl = hall_to_pos[halll]; + posl += 2; + posl %= 6; + + uint8_t hallr = hall_ur * 1 + hall_vr * 2 + hall_wr * 4; + posr = hall_to_pos[hallr]; + posr += 2; + posr %= 6; + + blockPhaseCurrent(posl, adc_buffer.rl1 - offsetrl1, adc_buffer.rl2 - offsetrl2, &curl); + + //setScopeChannel(2, (adc_buffer.rl1 - offsetrl1) / 8); + //setScopeChannel(3, (adc_buffer.rl2 - offsetrl2) / 8); + + + // uint8_t buzz(uint16_t *notes, uint32_t len){ + // static uint32_t counter = 0; + // static uint32_t timer = 0; + // if(len == 0){ + // return(0); + // } + + // struct { + // uint16_t freq : 4; + // uint16_t volume : 4; + // uint16_t time : 8; + // } note = notes[counter]; + + // if(timer / 500 == note.time){ + // timer = 0; + // counter++; + // } + + // if(counter == len){ + // counter = 0; + // } + + // timer++; + // return(note.freq); + // } + + + //create square wave for buzzer + buzzerTimer++; + if (buzzerFreq != 0 && (buzzerTimer / 5000) % (buzzerPattern + 1) == 0) { + if (buzzerTimer % buzzerFreq == 0) { + HAL_GPIO_TogglePin(BUZZER_PORT, BUZZER_PIN); + } + } else { + HAL_GPIO_WritePin(BUZZER_PORT, BUZZER_PIN, 0); + } + + //update PWM channels based on position + blockPWM(pwml, posl, &ul, &vl, &wl); + blockPWM(pwmr, posr, &ur, &vr, &wr); + + int weakul, weakvl, weakwl; + if (pwml > 0) { + blockPWM(weakl, (posl+5) % 6, &weakul, &weakvl, &weakwl); + } else { + blockPWM(-weakl, (posl+1) % 6, &weakul, &weakvl, &weakwl); + } + ul += weakul; + vl += weakvl; + wl += weakwl; + + int weakur, weakvr, weakwr; + if (pwmr > 0) { + blockPWM(weakr, (posr+5) % 6, &weakur, &weakvr, &weakwr); + } else { + blockPWM(-weakr, (posr+1) % 6, &weakur, &weakvr, &weakwr); + } + ur += weakur; + vr += weakvr; + wr += weakwr; + + LEFT_TIM->LEFT_TIM_U = CLAMP(ul + pwm_res / 2, 10, pwm_res-10); + LEFT_TIM->LEFT_TIM_V = CLAMP(vl + pwm_res / 2, 10, pwm_res-10); + LEFT_TIM->LEFT_TIM_W = CLAMP(wl + pwm_res / 2, 10, pwm_res-10); + + RIGHT_TIM->RIGHT_TIM_U = CLAMP(ur + pwm_res / 2, 10, pwm_res-10); + RIGHT_TIM->RIGHT_TIM_V = CLAMP(vr + pwm_res / 2, 10, pwm_res-10); + RIGHT_TIM->RIGHT_TIM_W = CLAMP(wr + pwm_res / 2, 10, pwm_res-10); +} diff --git a/Software/hoverboard-firmware-hack_modified20190825/Src/comms.c b/Software/hoverboard-firmware-hack_modified20190825/Src/comms.c new file mode 100644 index 0000000000000000000000000000000000000000..5e437a185afff49ef73463a96a24f2dcf1ecdb08 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Src/comms.c @@ -0,0 +1,64 @@ +#include "stm32f1xx_hal.h" +#include "defines.h" +#include "setup.h" +#include "config.h" +#include "stdio.h" +#include "string.h" + +UART_HandleTypeDef huart2; + +#ifdef DEBUG_SERIAL_USART3 +#define UART_DMA_CHANNEL DMA1_Channel2 +#endif + +#ifdef DEBUG_SERIAL_USART2 +#define UART_DMA_CHANNEL DMA1_Channel7 +#endif + + +volatile uint8_t uart_buf[100]; +volatile int16_t ch_buf[8]; +//volatile char char_buf[300]; + +void setScopeChannel(uint8_t ch, int16_t val) { + ch_buf[ch] = val; +} + +void consoleScope() { + #if defined DEBUG_SERIAL_SERVOTERM && (defined DEBUG_SERIAL_USART2 || defined DEBUG_SERIAL_USART3) + uart_buf[0] = 0xff; + uart_buf[1] = CLAMP(ch_buf[0]+127, 0, 255); + uart_buf[2] = CLAMP(ch_buf[1]+127, 0, 255); + uart_buf[3] = CLAMP(ch_buf[2]+127, 0, 255); + uart_buf[4] = CLAMP(ch_buf[3]+127, 0, 255); + uart_buf[5] = CLAMP(ch_buf[4]+127, 0, 255); + uart_buf[6] = CLAMP(ch_buf[5]+127, 0, 255); + uart_buf[7] = CLAMP(ch_buf[6]+127, 0, 255); + uart_buf[8] = CLAMP(ch_buf[7]+127, 0, 255); + uart_buf[9] = '\n'; + + if(UART_DMA_CHANNEL->CNDTR == 0) { + UART_DMA_CHANNEL->CCR &= ~DMA_CCR_EN; + UART_DMA_CHANNEL->CNDTR = 10; + UART_DMA_CHANNEL->CMAR = (uint32_t)uart_buf; + UART_DMA_CHANNEL->CCR |= DMA_CCR_EN; + } + #endif + + #if defined DEBUG_SERIAL_ASCII && (defined DEBUG_SERIAL_USART2 || defined DEBUG_SERIAL_USART3) + memset(uart_buf, 0, sizeof(uart_buf)); + sprintf(uart_buf, "1:%i 2:%i 3:%i 4:%i 5:%i 6:%i 7:%i 8:%i\r\n", ch_buf[0], ch_buf[1], ch_buf[2], ch_buf[3], ch_buf[4], ch_buf[5], ch_buf[6], ch_buf[7]); + + if(UART_DMA_CHANNEL->CNDTR == 0) { + UART_DMA_CHANNEL->CCR &= ~DMA_CCR_EN; + UART_DMA_CHANNEL->CNDTR = strlen(uart_buf); + UART_DMA_CHANNEL->CMAR = (uint32_t)uart_buf; + UART_DMA_CHANNEL->CCR |= DMA_CCR_EN; + } + #endif +} + +void consoleLog(char *message) +{ + HAL_UART_Transmit_DMA(&huart2, (uint8_t *)message, strlen(message)); +} diff --git a/Software/hoverboard-firmware-hack_modified20190825/Src/control.c b/Software/hoverboard-firmware-hack_modified20190825/Src/control.c new file mode 100644 index 0000000000000000000000000000000000000000..9ffdfd2aa54a4404b6453501c531d2d705c490b5 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Src/control.c @@ -0,0 +1,119 @@ + +#include "stm32f1xx_hal.h" +#include "defines.h" +#include "setup.h" +#include "config.h" +#include +#include + +TIM_HandleTypeDef TimHandle; +uint8_t ppm_count = 0; +uint32_t timeout = 100; +uint8_t nunchuck_data[6] = {0}; + +uint8_t i2cBuffer[2]; + +extern I2C_HandleTypeDef hi2c2; +DMA_HandleTypeDef hdma_i2c2_rx; +DMA_HandleTypeDef hdma_i2c2_tx; + +#ifdef CONTROL_PPM +uint16_t ppm_captured_value[PPM_NUM_CHANNELS + 1] = {500, 500}; +uint16_t ppm_captured_value_buffer[PPM_NUM_CHANNELS+1] = {500, 500}; +uint32_t ppm_timeout = 0; + +bool ppm_valid = true; + +#define IN_RANGE(x, low, up) (((x) >= (low)) && ((x) <= (up))) + +void PPM_ISR_Callback() { + // Dummy loop with 16 bit count wrap around + uint16_t rc_delay = TIM2->CNT; + TIM2->CNT = 0; + + if (rc_delay > 3000) { + if (ppm_valid && ppm_count == PPM_NUM_CHANNELS) { + ppm_timeout = 0; + memcpy(ppm_captured_value, ppm_captured_value_buffer, sizeof(ppm_captured_value)); + } + ppm_valid = true; + ppm_count = 0; + } + else if (ppm_count < PPM_NUM_CHANNELS && IN_RANGE(rc_delay, 900, 2100)){ + timeout = 0; + ppm_captured_value_buffer[ppm_count++] = CLAMP(rc_delay, 1000, 2000) - 1000; + } else { + ppm_valid = false; + } +} + +// SysTick executes once each ms +void PPM_SysTick_Callback() { + ppm_timeout++; + // Stop after 500 ms without PPM signal + if(ppm_timeout > 500) { + int i; + for(i = 0; i < PPM_NUM_CHANNELS; i++) { + ppm_captured_value[i] = 500; + } + ppm_timeout = 0; + } +} + +void PPM_Init() { + GPIO_InitTypeDef GPIO_InitStruct; + /*Configure GPIO pin : PA3 */ + GPIO_InitStruct.Pin = GPIO_PIN_3; + GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Pull = GPIO_PULLDOWN; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + __HAL_RCC_TIM2_CLK_ENABLE(); + TimHandle.Instance = TIM2; + TimHandle.Init.Period = UINT16_MAX; + TimHandle.Init.Prescaler = (SystemCoreClock/DELAY_TIM_FREQUENCY_US)-1;; + TimHandle.Init.ClockDivision = 0; + TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; + HAL_TIM_Base_Init(&TimHandle); + + /* EXTI interrupt init*/ + HAL_NVIC_SetPriority(EXTI3_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(EXTI3_IRQn); + HAL_TIM_Base_Start(&TimHandle); +} +#endif + +void Nunchuck_Init() { + //-- START -- init WiiNunchuck + i2cBuffer[0] = 0xF0; + i2cBuffer[1] = 0x55; + + HAL_I2C_Master_Transmit(&hi2c2,0xA4,(uint8_t*)i2cBuffer, 2, 100); + HAL_Delay(10); + + i2cBuffer[0] = 0xFB; + i2cBuffer[1] = 0x00; + + HAL_I2C_Master_Transmit(&hi2c2,0xA4,(uint8_t*)i2cBuffer, 2, 100); + HAL_Delay(10); +} + +void Nunchuck_Read() { + i2cBuffer[0] = 0x00; + HAL_I2C_Master_Transmit(&hi2c2,0xA4,(uint8_t*)i2cBuffer, 1, 100); + HAL_Delay(5); + if (HAL_I2C_Master_Receive(&hi2c2,0xA4,(uint8_t*)nunchuck_data, 6, 100) == HAL_OK) { + timeout = 0; + } + + if (timeout > 3) { + HAL_Delay(50); + Nunchuck_Init(); + } + + //setScopeChannel(0, (int)nunchuck_data[0]); + //setScopeChannel(1, (int)nunchuck_data[1]); + //setScopeChannel(2, (int)nunchuck_data[5] & 1); + //setScopeChannel(3, ((int)nunchuck_data[5] >> 1) & 1); +} diff --git a/Software/hoverboard-firmware-hack_modified20190825/Src/main.c b/Software/hoverboard-firmware-hack_modified20190825/Src/main.c new file mode 100644 index 0000000000000000000000000000000000000000..4cc2624161a717bd2c2c281fbd3738f49a74e15c --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Src/main.c @@ -0,0 +1,374 @@ +/* +* This file is part of the hoverboard-firmware-hack project. +* +* Copyright (C) 2017-2018 Rene Hopf +* Copyright (C) 2017-2018 Nico Stute +* Copyright (C) 2017-2018 Niklas Fauth +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +#include "stm32f1xx_hal.h" +#include "defines.h" +#include "setup.h" +#include "config.h" +//#include "hd44780.h" + +void SystemClock_Config(void); + +extern TIM_HandleTypeDef htim_left; +extern TIM_HandleTypeDef htim_right; +extern ADC_HandleTypeDef hadc1; +extern ADC_HandleTypeDef hadc2; +extern volatile adc_buf_t adc_buffer; +//LCD_PCF8574_HandleTypeDef lcd; +extern I2C_HandleTypeDef hi2c2; +extern UART_HandleTypeDef huart2; + +int cmd1; // normalized input values. -1000 to 1000 +int cmd2; +int cmd3; + +typedef struct{ + int16_t steer; + int16_t speed; + //uint32_t crc; +} Serialcommand; + +volatile Serialcommand command; + +uint8_t button1, button2; + +int steer; // global variable for steering. -1000 to 1000 +int speed; // global variable for speed. -1000 to 1000 + +extern volatile int pwml; // global variable for pwm left. -1000 to 1000 +extern volatile int pwmr; // global variable for pwm right. -1000 to 1000 +extern volatile int weakl; // global variable for field weakening left. -1000 to 1000 +extern volatile int weakr; // global variable for field weakening right. -1000 to 1000 + +extern uint8_t buzzerFreq; // global variable for the buzzer pitch. can be 1, 2, 3, 4, 5, 6, 7... +extern uint8_t buzzerPattern; // global variable for the buzzer pattern. can be 1, 2, 3, 4, 5, 6, 7... + +extern uint8_t enable; // global variable for motor enable + +extern volatile uint32_t timeout; // global variable for timeout +extern float batteryVoltage; // global variable for battery voltage + +uint32_t inactivity_timeout_counter; +uint32_t main_loop_counter; + +int32_t motor_test_direction = 1; + +extern uint8_t nunchuck_data[6]; +#ifdef CONTROL_PPM +extern volatile uint16_t ppm_captured_value[PPM_NUM_CHANNELS+1]; +#endif + +int milli_vel_error_sum = 0; + + +void poweroff() { + #ifndef CONTROL_MOTOR_TEST + if (abs(speed) < 20) { + #endif + buzzerPattern = 0; + enable = 0; + for (int i = 0; i < 8; i++) { + buzzerFreq = i; + HAL_Delay(100); + } + HAL_GPIO_WritePin(OFF_PORT, OFF_PIN, 0); + while(1) {} + #ifndef CONTROL_MOTOR_TEST + } + #endif +} + + +int main(void) { + HAL_Init(); + __HAL_RCC_AFIO_CLK_ENABLE(); + HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); + /* System interrupt init*/ + /* MemoryManagement_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(MemoryManagement_IRQn, 0, 0); + /* BusFault_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(BusFault_IRQn, 0, 0); + /* UsageFault_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(UsageFault_IRQn, 0, 0); + /* SVCall_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SVCall_IRQn, 0, 0); + /* DebugMonitor_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DebugMonitor_IRQn, 0, 0); + /* PendSV_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(PendSV_IRQn, 0, 0); + /* SysTick_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); + + SystemClock_Config(); + + __HAL_RCC_DMA1_CLK_DISABLE(); + MX_GPIO_Init(); + MX_TIM_Init(); + MX_ADC1_Init(); + MX_ADC2_Init(); + + #if defined(DEBUG_SERIAL_USART2) || defined(DEBUG_SERIAL_USART3) + UART_Init(); + #endif + + HAL_GPIO_WritePin(OFF_PORT, OFF_PIN, 1); + + HAL_ADC_Start(&hadc1); + HAL_ADC_Start(&hadc2); + + for (int i = 8; i >= 0; i--) { + buzzerFreq = i; + HAL_Delay(100); + } + buzzerFreq = 0; + + HAL_GPIO_WritePin(LED_PORT, LED_PIN, 1); + + int lastSpeedL = 0, lastSpeedR = 0; + int speedL = 0, speedR = 0; + float direction = 1; + + #ifdef CONTROL_PPM + PPM_Init(); + #endif + + #ifdef CONTROL_NUNCHUCK + I2C_Init(); + Nunchuck_Init(); + #endif + + #ifdef CONTROL_SERIAL_USART2 + UART_Control_Init(); + HAL_UART_Receive_DMA(&huart2, (uint8_t *)&command, 4); + #endif + + #ifdef DEBUG_I2C_LCD + I2C_Init(); + HAL_Delay(50); + lcd.pcf8574.PCF_I2C_ADDRESS = 0x27; + lcd.pcf8574.PCF_I2C_TIMEOUT = 5; + lcd.pcf8574.i2c = hi2c2; + lcd.NUMBER_OF_LINES = NUMBER_OF_LINES_2; + lcd.type = TYPE0; + + if(LCD_Init(&lcd)!=LCD_OK){ + // error occured + //TODO while(1); + } + + LCD_ClearDisplay(&lcd); + HAL_Delay(5); + LCD_SetLocation(&lcd, 0, 0); + LCD_WriteString(&lcd, "Hover V2.0"); + LCD_SetLocation(&lcd, 0, 1); + LCD_WriteString(&lcd, "Initializing..."); + #endif + + float board_temp_adc_filtered = (float)adc_buffer.temp; + float board_temp_deg_c; + + enable = 1; // enable motors + + while(1) { + HAL_Delay(DELAY_IN_MAIN_LOOP); //delay in ms + + #ifdef CONTROL_NUNCHUCK + Nunchuck_Read(); + cmd1 = CLAMP((nunchuck_data[0] - 127) * 8, -1000, 1000); // x - axis. Nunchuck joystick readings range 30 - 230 + cmd2 = CLAMP((nunchuck_data[1] - 128) * 8, -1000, 1000); // y - axis + + button1 = (uint8_t)nunchuck_data[5] & 1; + button2 = (uint8_t)(nunchuck_data[5] >> 1) & 1; + #endif + + #ifdef CONTROL_PPM + cmd1 = CLAMP((ppm_captured_value[0] - 500) * 2, -1000, 1000); + cmd2 = CLAMP((ppm_captured_value[1] - 500) * 2, -1000, 1000); + button1 = ppm_captured_value[5] > 500; + float scale = ppm_captured_value[2] / 1000.0f; + #endif + + #ifdef CONTROL_ADC + // ADC values range: 0-4095, see ADC-calibration in config.h + cmd1 = CLAMP(adc_buffer.l_tx2 - ADC1_MIN, 0, ADC1_MAX) / (ADC1_MAX / 1000.0f); // ADC1 + cmd2 = CLAMP(adc_buffer.l_rx2 - ADC2_MIN, 0, ADC2_MAX) / (ADC2_MAX / 1000.0f); // ADC2 + + // use ADCs as button inputs: + button1 = (uint8_t)(adc_buffer.l_tx2 > 2000); // ADC1 + button2 = (uint8_t)(adc_buffer.l_rx2 > 2000); // ADC2 + + timeout = 0; + #endif + + #ifdef CONTROL_SERIAL_USART2 + cmd1 = CLAMP((int16_t)command.steer, -1000, 1000); + cmd2 = CLAMP((int16_t)command.speed, -1000, 1000); + + timeout = 0; + #endif + + #ifdef CONTROL_MOTOR_TEST + if (motor_test_direction == 1) cmd2 += 1; + else cmd2 -= 1; + if (abs(cmd2) > CONTROL_MOTOR_TEST_MAX_SPEED) motor_test_direction = -motor_test_direction; + + timeout = 0; + #endif + + // ####### LOW-PASS FILTER ####### + steer = steer * (1.0 - FILTER) + cmd1 * FILTER; + speed = speed * (1.0 - FILTER) + cmd2 * FILTER; + + + // ####### MIXER ####### + speedR = CLAMP(speed * SPEED_COEFFICIENT - steer * STEER_COEFFICIENT, -1000, 1000); + speedL = CLAMP(speed * SPEED_COEFFICIENT + steer * STEER_COEFFICIENT, -1000, 1000); + + + #ifdef ADDITIONAL_CODE + ADDITIONAL_CODE; + #endif + + + // ####### SET OUTPUTS ####### + if ((speedL < lastSpeedL + 50 && speedL > lastSpeedL - 50) && (speedR < lastSpeedR + 50 && speedR > lastSpeedR - 50) && timeout < TIMEOUT) { + #ifdef INVERT_R_DIRECTION + pwmr = speedR; + #else + pwmr = -speedR; + #endif + #ifdef INVERT_L_DIRECTION + pwml = -speedL; + #else + pwml = speedL; + #endif + } + + lastSpeedL = speedL; + lastSpeedR = speedR; + + + if (main_loop_counter % 25 == 0) { + // ####### CALC BOARD TEMPERATURE ####### + board_temp_adc_filtered = board_temp_adc_filtered * 0.99 + (float)adc_buffer.temp * 0.01; + board_temp_deg_c = ((float)TEMP_CAL_HIGH_DEG_C - (float)TEMP_CAL_LOW_DEG_C) / ((float)TEMP_CAL_HIGH_ADC - (float)TEMP_CAL_LOW_ADC) * (board_temp_adc_filtered - (float)TEMP_CAL_LOW_ADC) + (float)TEMP_CAL_LOW_DEG_C; + + // ####### DEBUG SERIAL OUT ####### + #ifdef CONTROL_ADC + setScopeChannel(0, (int)adc_buffer.l_tx2); // 1: ADC1 + setScopeChannel(1, (int)adc_buffer.l_rx2); // 2: ADC2 + #endif + setScopeChannel(2, (int)speedR); // 3: output speed: 0-1000 + setScopeChannel(3, (int)speedL); // 4: output speed: 0-1000 + setScopeChannel(4, (int)adc_buffer.batt1); // 5: for battery voltage calibration + setScopeChannel(5, (int)(batteryVoltage * 100.0f)); // 6: for verifying battery voltage calibration + setScopeChannel(6, (int)board_temp_adc_filtered); // 7: for board temperature calibration + setScopeChannel(7, (int)board_temp_deg_c); // 8: for verifying board temperature calibration + consoleScope(); + } + + + // ####### POWEROFF BY POWER-BUTTON ####### + if (HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN) && weakr == 0 && weakl == 0) { + enable = 0; + while (HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN)) {} + poweroff(); + } + + + // ####### BEEP AND EMERGENCY POWEROFF ####### + if ((TEMP_POWEROFF_ENABLE && board_temp_deg_c >= TEMP_POWEROFF && abs(speed) < 20) || (batteryVoltage < ((float)BAT_LOW_DEAD * (float)BAT_NUMBER_OF_CELLS) && abs(speed) < 20)) { // poweroff before mainboard burns OR low bat 3 + poweroff(); + } else if (TEMP_WARNING_ENABLE && board_temp_deg_c >= TEMP_WARNING) { // beep if mainboard gets hot + buzzerFreq = 4; + buzzerPattern = 1; + } else if (batteryVoltage < ((float)BAT_LOW_LVL1 * (float)BAT_NUMBER_OF_CELLS) && batteryVoltage > ((float)BAT_LOW_LVL2 * (float)BAT_NUMBER_OF_CELLS) && BAT_LOW_LVL1_ENABLE) { // low bat 1: slow beep + buzzerFreq = 5; + buzzerPattern = 42; + } else if (batteryVoltage < ((float)BAT_LOW_LVL2 * (float)BAT_NUMBER_OF_CELLS) && batteryVoltage > ((float)BAT_LOW_DEAD * (float)BAT_NUMBER_OF_CELLS) && BAT_LOW_LVL2_ENABLE) { // low bat 2: fast beep + buzzerFreq = 5; + buzzerPattern = 6; + } else if (BEEPS_BACKWARD && speed < -50) { // backward beep + buzzerFreq = 5; + buzzerPattern = 1; + } else { // do not beep + buzzerFreq = 0; + buzzerPattern = 0; + } + + + // ####### INACTIVITY TIMEOUT ####### + if (abs(speedL) > 50 || abs(speedR) > 50) { + inactivity_timeout_counter = 0; + } else { + inactivity_timeout_counter ++; + } + if (inactivity_timeout_counter > (INACTIVITY_TIMEOUT * 60 * 1000) / (DELAY_IN_MAIN_LOOP + 1)) { // rest of main loop needs maybe 1ms + poweroff(); + } + + main_loop_counter += 1; + timeout++; + } +} + +/** System Clock Configuration +*/ +void SystemClock_Config(void) { + RCC_OscInitTypeDef RCC_OscInitStruct; + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_PeriphCLKInitTypeDef PeriphClkInit; + + /**Initializes the CPU, AHB and APB busses clocks + */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; + RCC_OscInitStruct.HSIState = RCC_HSI_ON; + RCC_OscInitStruct.HSICalibrationValue = 16; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2; + RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /**Initializes the CPU, AHB and APB busses clocks + */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; + + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2); + + PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC; + PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV8; // 8 MHz + HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit); + + /**Configure the Systick interrupt time + */ + HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000); + + /**Configure the Systick + */ + HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); + + /* SysTick_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); +} diff --git a/Software/hoverboard-firmware-hack_modified20190825/Src/setup.c b/Software/hoverboard-firmware-hack_modified20190825/Src/setup.c new file mode 100644 index 0000000000000000000000000000000000000000..8de657a0c717aed6ed973ac99b7279809da4d37d --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Src/setup.c @@ -0,0 +1,643 @@ +/* +* This file is part of the hoverboard-firmware-hack project. +* +* Copyright (C) 2017-2018 Rene Hopf +* Copyright (C) 2017-2018 Nico Stute +* Copyright (C) 2017-2018 Niklas Fauth +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +/* +tim1 master, enable -> trgo +tim8, gated slave mode, trgo by tim1 trgo. overflow -> trgo +adc1,adc2 triggered by tim8 trgo +adc 1,2 dual mode + +ADC1 ADC2 +R_Blau PC4 CH14 R_Gelb PC5 CH15 +L_Grün PA0 CH01 L_Blau PC3 CH13 +R_DC PC1 CH11 L_DC PC0 CH10 +BAT PC2 CH12 L_TX PA2 CH02 +BAT PC2 CH12 L_RX PA3 CH03 + +pb10 usart3 dma1 channel2/3 +*/ + +#include "defines.h" +#include "config.h" + +TIM_HandleTypeDef htim_right; +TIM_HandleTypeDef htim_left; +ADC_HandleTypeDef hadc1; +ADC_HandleTypeDef hadc2; +I2C_HandleTypeDef hi2c2; +UART_HandleTypeDef huart2; + +DMA_HandleTypeDef hdma_usart2_rx; +DMA_HandleTypeDef hdma_usart2_tx; +volatile adc_buf_t adc_buffer; + + +#ifdef CONTROL_SERIAL_USART2 + + +void UART_Control_Init() { + GPIO_InitTypeDef GPIO_InitStruct; + __HAL_RCC_USART2_CLK_ENABLE(); + /* DMA1_Channel6_IRQn interrupt configuration */ + //HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 5, 6); + //HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn); + HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 5, 6); + HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn); + /* DMA1_Channel7_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Channel7_IRQn, 5, 7); + HAL_NVIC_EnableIRQ(DMA1_Channel7_IRQn); + + huart2.Instance = USART2; + huart2.Init.BaudRate = CONTROL_BAUD; + huart2.Init.WordLength = UART_WORDLENGTH_8B; + huart2.Init.StopBits = UART_STOPBITS_1; + huart2.Init.Parity = UART_PARITY_NONE; + huart2.Init.Mode = UART_MODE_TX_RX; + huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; + // huart2.Init.OverSampling = UART_OVERSAMPLING_16; + HAL_UART_Init(&huart2); + + + __HAL_RCC_DMA1_CLK_ENABLE(); + /* USER CODE BEGIN USART2_MspInit 0 */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + /* USER CODE END USART2_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_USART2_CLK_ENABLE(); + + GPIO_InitStruct.Pull = GPIO_PULLUP; //GPIO_NOPULL; + GPIO_InitStruct.Pin = GPIO_PIN_2; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = GPIO_PIN_3; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; //GPIO_MODE_AF_PP; +// GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* Peripheral DMA init*/ + + hdma_usart2_rx.Instance = DMA1_Channel6; + hdma_usart2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_usart2_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_usart2_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_usart2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_usart2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_usart2_rx.Init.Mode = DMA_CIRCULAR; //DMA_NORMAL; + hdma_usart2_rx.Init.Priority = DMA_PRIORITY_LOW; + HAL_DMA_Init(&hdma_usart2_rx); + + __HAL_LINKDMA(&huart2,hdmarx,hdma_usart2_rx); + + hdma_usart2_tx.Instance = DMA1_Channel7; + hdma_usart2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_usart2_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_usart2_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_usart2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_usart2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_usart2_tx.Init.Mode = DMA_NORMAL; + hdma_usart2_tx.Init.Priority = DMA_PRIORITY_LOW; +HAL_DMA_Init(&hdma_usart2_tx); + __HAL_LINKDMA(&huart2,hdmatx,hdma_usart2_tx); +} + +#endif + +#ifdef DEBUG_SERIAL_USART3 +void UART_Init() { + __HAL_RCC_USART3_CLK_ENABLE(); + __HAL_RCC_DMA1_CLK_ENABLE(); + + UART_HandleTypeDef huart3; + huart3.Instance = USART3; + huart3.Init.BaudRate = DEBUG_BAUD; + huart3.Init.WordLength = UART_WORDLENGTH_8B; + huart3.Init.StopBits = UART_STOPBITS_1; + huart3.Init.Parity = UART_PARITY_NONE; + huart3.Init.Mode = UART_MODE_TX; + huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart3.Init.OverSampling = UART_OVERSAMPLING_16; + HAL_UART_Init(&huart3); + + USART3->CR3 |= USART_CR3_DMAT; // | USART_CR3_DMAR | USART_CR3_OVRDIS; + + GPIO_InitTypeDef GPIO_InitStruct; + GPIO_InitStruct.Pin = GPIO_PIN_10; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + DMA1_Channel2->CCR = 0; + DMA1_Channel2->CPAR = (uint32_t) & (USART3->DR); + DMA1_Channel2->CNDTR = 0; + DMA1_Channel2->CCR = DMA_CCR_MINC | DMA_CCR_DIR; + DMA1->IFCR = DMA_IFCR_CTCIF2 | DMA_IFCR_CHTIF2 | DMA_IFCR_CGIF2; +} +#endif + +#ifdef DEBUG_SERIAL_USART2 +void UART_Init() { + __HAL_RCC_USART2_CLK_ENABLE(); + __HAL_RCC_DMA1_CLK_ENABLE(); + + UART_HandleTypeDef huart2; + huart2.Instance = USART2; + huart2.Init.BaudRate = DEBUG_BAUD; + huart2.Init.WordLength = UART_WORDLENGTH_8B; + huart2.Init.StopBits = UART_STOPBITS_1; + huart2.Init.Parity = UART_PARITY_NONE; + huart2.Init.Mode = UART_MODE_TX; + huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart2.Init.OverSampling = UART_OVERSAMPLING_16; + HAL_UART_Init(&huart2); + + USART2->CR3 |= USART_CR3_DMAT; // | USART_CR3_DMAR | USART_CR3_OVRDIS; + + GPIO_InitTypeDef GPIO_InitStruct; + GPIO_InitStruct.Pin = GPIO_PIN_2; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + DMA1_Channel7->CCR = 0; + DMA1_Channel7->CPAR = (uint32_t) & (USART2->DR); + DMA1_Channel7->CNDTR = 0; + DMA1_Channel7->CCR = DMA_CCR_MINC | DMA_CCR_DIR; + DMA1->IFCR = DMA_IFCR_CTCIF7 | DMA_IFCR_CHTIF7 | DMA_IFCR_CGIF7; +} +#endif + +/* +void UART_Init() { + __HAL_RCC_USART2_CLK_ENABLE(); + __HAL_RCC_DMA1_CLK_ENABLE(); + + UART_HandleTypeDef huart2; + huart2.Instance = USART2; + huart2.Init.BaudRate = 115200; + huart2.Init.WordLength = UART_WORDLENGTH_8B; + huart2.Init.StopBits = UART_STOPBITS_1; + huart2.Init.Parity = UART_PARITY_NONE; + huart2.Init.Mode = UART_MODE_TX; + huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart2.Init.OverSampling = UART_OVERSAMPLING_16; + HAL_UART_Init(&huart2); + + USART2->CR3 |= USART_CR3_DMAT; // | USART_CR3_DMAR | USART_CR3_OVRDIS; + + GPIO_InitTypeDef GPIO_InitStruct; + GPIO_InitStruct.Pin = GPIO_PIN_2; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + DMA1_Channel7->CCR = 0; + DMA1_Channel7->CPAR = (uint32_t) & (USART3->DR); + DMA1_Channel7->CNDTR = 0; + DMA1_Channel7->CCR = DMA_CCR_MINC | DMA_CCR_DIR; + DMA1->IFCR = DMA_IFCR_CTCIF7 | DMA_IFCR_CHTIF7 | DMA_IFCR_CGIF7; +} +*/ + +DMA_HandleTypeDef hdma_i2c2_rx; +DMA_HandleTypeDef hdma_i2c2_tx; + +void I2C_Init() +{ + + __HAL_RCC_I2C2_CLK_ENABLE(); + __HAL_RCC_DMA1_CLK_ENABLE(); + + /* DMA1_Channel4_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Channel4_IRQn, 1, 4); + HAL_NVIC_EnableIRQ(DMA1_Channel4_IRQn); + /* DMA1_Channel5_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Channel5_IRQn, 1, 3); + HAL_NVIC_EnableIRQ(DMA1_Channel5_IRQn); + + hi2c2.Instance = I2C2; + hi2c2.Init.ClockSpeed = 100000; + hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2; + hi2c2.Init.OwnAddress1 = 0; + hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; + hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; + hi2c2.Init.OwnAddress2 = 0; + hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; + hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; + HAL_I2C_Init(&hi2c2); + + GPIO_InitTypeDef GPIO_InitStruct; + + __HAL_RCC_DMA1_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + /* USER CODE BEGIN I2C2_MspInit 0 */ + + /* USER CODE END I2C2_MspInit 0 */ + + /**I2C2 GPIO Configuration + PB10 ------> I2C2_SCL + PB11 ------> I2C2_SDA + */ + GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* Peripheral clock enable */ + __HAL_RCC_I2C2_CLK_ENABLE(); + + /* Peripheral DMA init*/ + + hdma_i2c2_rx.Instance = DMA1_Channel5; + hdma_i2c2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_i2c2_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_i2c2_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_i2c2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_i2c2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_i2c2_rx.Init.Mode = DMA_NORMAL; + hdma_i2c2_rx.Init.Priority = DMA_PRIORITY_MEDIUM; + HAL_DMA_Init(&hdma_i2c2_rx); + + __HAL_LINKDMA(&hi2c2,hdmarx,hdma_i2c2_rx); + + hdma_i2c2_tx.Instance = DMA1_Channel4; + hdma_i2c2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_i2c2_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_i2c2_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_i2c2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_i2c2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_i2c2_tx.Init.Mode = DMA_NORMAL; + hdma_i2c2_tx.Init.Priority = DMA_PRIORITY_MEDIUM; + HAL_DMA_Init(&hdma_i2c2_tx); + + __HAL_LINKDMA(&hi2c2,hdmatx,hdma_i2c2_tx); + + /* Peripheral interrupt init */ + HAL_NVIC_SetPriority(I2C2_EV_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(I2C2_EV_IRQn); + HAL_NVIC_SetPriority(I2C2_ER_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(I2C2_ER_IRQn); + /* USER CODE BEGIN I2C2_MspInit 1 */ + + /* USER CODE END I2C2_MspInit 1 */ + + +} + +void MX_GPIO_Init(void) { + GPIO_InitTypeDef GPIO_InitStruct; + + /* GPIO Ports Clock Enable */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + + GPIO_InitStruct.Pin = LEFT_HALL_U_PIN; + HAL_GPIO_Init(LEFT_HALL_U_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_HALL_V_PIN; + HAL_GPIO_Init(LEFT_HALL_V_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_HALL_W_PIN; + HAL_GPIO_Init(LEFT_HALL_W_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_HALL_U_PIN; + HAL_GPIO_Init(RIGHT_HALL_U_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_HALL_V_PIN; + HAL_GPIO_Init(RIGHT_HALL_V_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_HALL_W_PIN; + HAL_GPIO_Init(RIGHT_HALL_W_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = CHARGER_PIN; + HAL_GPIO_Init(CHARGER_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = BUTTON_PIN; + HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); + + + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + + GPIO_InitStruct.Pin = LED_PIN; + HAL_GPIO_Init(LED_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = BUZZER_PIN; + HAL_GPIO_Init(BUZZER_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = OFF_PIN; + HAL_GPIO_Init(OFF_PORT, &GPIO_InitStruct); + + + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + + GPIO_InitStruct.Pin = LEFT_DC_CUR_PIN; + HAL_GPIO_Init(LEFT_DC_CUR_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_U_CUR_PIN; + HAL_GPIO_Init(LEFT_U_CUR_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_V_CUR_PIN; + HAL_GPIO_Init(LEFT_V_CUR_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_DC_CUR_PIN; + HAL_GPIO_Init(RIGHT_DC_CUR_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_U_CUR_PIN; + HAL_GPIO_Init(RIGHT_U_CUR_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_V_CUR_PIN; + HAL_GPIO_Init(RIGHT_V_CUR_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = DCLINK_PIN; + HAL_GPIO_Init(DCLINK_PORT, &GPIO_InitStruct); + + //Analog in + GPIO_InitStruct.Pin = GPIO_PIN_3; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + GPIO_InitStruct.Pin = GPIO_PIN_2; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + + GPIO_InitStruct.Pin = LEFT_TIM_UH_PIN; + HAL_GPIO_Init(LEFT_TIM_UH_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_TIM_VH_PIN; + HAL_GPIO_Init(LEFT_TIM_VH_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_TIM_WH_PIN; + HAL_GPIO_Init(LEFT_TIM_WH_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_TIM_UL_PIN; + HAL_GPIO_Init(LEFT_TIM_UL_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_TIM_VL_PIN; + HAL_GPIO_Init(LEFT_TIM_VL_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = LEFT_TIM_WL_PIN; + HAL_GPIO_Init(LEFT_TIM_WL_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_TIM_UH_PIN; + HAL_GPIO_Init(RIGHT_TIM_UH_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_TIM_VH_PIN; + HAL_GPIO_Init(RIGHT_TIM_VH_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_TIM_WH_PIN; + HAL_GPIO_Init(RIGHT_TIM_WH_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_TIM_UL_PIN; + HAL_GPIO_Init(RIGHT_TIM_UL_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_TIM_VL_PIN; + HAL_GPIO_Init(RIGHT_TIM_VL_PORT, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = RIGHT_TIM_WL_PIN; + HAL_GPIO_Init(RIGHT_TIM_WL_PORT, &GPIO_InitStruct); +} + +void MX_TIM_Init(void) { + __HAL_RCC_TIM1_CLK_ENABLE(); + __HAL_RCC_TIM8_CLK_ENABLE(); + + TIM_MasterConfigTypeDef sMasterConfig; + TIM_OC_InitTypeDef sConfigOC; + TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig; + TIM_SlaveConfigTypeDef sTimConfig; + + htim_right.Instance = RIGHT_TIM; + htim_right.Init.Prescaler = 0; + htim_right.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED1; + htim_right.Init.Period = 64000000 / 2 / PWM_FREQ; + htim_right.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim_right.Init.RepetitionCounter = 0; + htim_right.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + HAL_TIM_PWM_Init(&htim_right); + + sMasterConfig.MasterOutputTrigger = TIM_TRGO_ENABLE; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + HAL_TIMEx_MasterConfigSynchronization(&htim_right, &sMasterConfig); + + sConfigOC.OCMode = TIM_OCMODE_PWM1; + sConfigOC.Pulse = 0; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCNPolarity = TIM_OCNPOLARITY_LOW; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET; + sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_SET; + HAL_TIM_PWM_ConfigChannel(&htim_right, &sConfigOC, TIM_CHANNEL_1); + HAL_TIM_PWM_ConfigChannel(&htim_right, &sConfigOC, TIM_CHANNEL_2); + HAL_TIM_PWM_ConfigChannel(&htim_right, &sConfigOC, TIM_CHANNEL_3); + + sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_ENABLE; + sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_ENABLE; + sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF; + sBreakDeadTimeConfig.DeadTime = DEAD_TIME; + sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE; + sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_LOW; + sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; + HAL_TIMEx_ConfigBreakDeadTime(&htim_right, &sBreakDeadTimeConfig); + + htim_left.Instance = LEFT_TIM; + htim_left.Init.Prescaler = 0; + htim_left.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED1; + htim_left.Init.Period = 64000000 / 2 / PWM_FREQ; + htim_left.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim_left.Init.RepetitionCounter = 0; + htim_left.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + HAL_TIM_PWM_Init(&htim_left); + + sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_ENABLE; + HAL_TIMEx_MasterConfigSynchronization(&htim_left, &sMasterConfig); + + sTimConfig.InputTrigger = TIM_TS_ITR0; + sTimConfig.SlaveMode = TIM_SLAVEMODE_GATED; + HAL_TIM_SlaveConfigSynchronization(&htim_left, &sTimConfig); + + sConfigOC.OCMode = TIM_OCMODE_PWM1; + sConfigOC.Pulse = 0; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCNPolarity = TIM_OCNPOLARITY_LOW; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET; + sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_SET; + HAL_TIM_PWM_ConfigChannel(&htim_left, &sConfigOC, TIM_CHANNEL_1); + HAL_TIM_PWM_ConfigChannel(&htim_left, &sConfigOC, TIM_CHANNEL_2); + HAL_TIM_PWM_ConfigChannel(&htim_left, &sConfigOC, TIM_CHANNEL_3); + + sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_ENABLE; + sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_ENABLE; + sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF; + sBreakDeadTimeConfig.DeadTime = DEAD_TIME; + sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE; + sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_LOW; + sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; + HAL_TIMEx_ConfigBreakDeadTime(&htim_left, &sBreakDeadTimeConfig); + + LEFT_TIM->BDTR &= ~TIM_BDTR_MOE; + RIGHT_TIM->BDTR &= ~TIM_BDTR_MOE; + + HAL_TIM_PWM_Start(&htim_left, TIM_CHANNEL_1); + HAL_TIM_PWM_Start(&htim_left, TIM_CHANNEL_2); + HAL_TIM_PWM_Start(&htim_left, TIM_CHANNEL_3); + HAL_TIMEx_PWMN_Start(&htim_left, TIM_CHANNEL_1); + HAL_TIMEx_PWMN_Start(&htim_left, TIM_CHANNEL_2); + HAL_TIMEx_PWMN_Start(&htim_left, TIM_CHANNEL_3); + + HAL_TIM_PWM_Start(&htim_right, TIM_CHANNEL_1); + HAL_TIM_PWM_Start(&htim_right, TIM_CHANNEL_2); + HAL_TIM_PWM_Start(&htim_right, TIM_CHANNEL_3); + HAL_TIMEx_PWMN_Start(&htim_right, TIM_CHANNEL_1); + HAL_TIMEx_PWMN_Start(&htim_right, TIM_CHANNEL_2); + HAL_TIMEx_PWMN_Start(&htim_right, TIM_CHANNEL_3); + + htim_left.Instance->RCR = 1; + + __HAL_TIM_ENABLE(&htim_right); +} + +void MX_ADC1_Init(void) { + ADC_MultiModeTypeDef multimode; + ADC_ChannelConfTypeDef sConfig; + + __HAL_RCC_ADC1_CLK_ENABLE(); + + hadc1.Instance = ADC1; + hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE; + hadc1.Init.ContinuousConvMode = DISABLE; + hadc1.Init.DiscontinuousConvMode = DISABLE; + hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T8_TRGO; + hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc1.Init.NbrOfConversion = 5; + HAL_ADC_Init(&hadc1); + /**Enable or disable the remapping of ADC1_ETRGREG: + * ADC1 External Event regular conversion is connected to TIM8 TRG0 + */ + __HAL_AFIO_REMAP_ADC1_ETRGREG_ENABLE(); + + /**Configure the ADC multi-mode + */ + multimode.Mode = ADC_DUALMODE_REGSIMULT; + HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode); + + sConfig.SamplingTime = ADC_SAMPLETIME_7CYCLES_5; + + sConfig.Channel = ADC_CHANNEL_14; // pc4 left b + sConfig.Rank = 1; + HAL_ADC_ConfigChannel(&hadc1, &sConfig); + + sConfig.Channel = ADC_CHANNEL_0; // pa0 right a + sConfig.Rank = 2; + HAL_ADC_ConfigChannel(&hadc1, &sConfig); + + sConfig.SamplingTime = ADC_SAMPLETIME_13CYCLES_5; + + sConfig.Channel = ADC_CHANNEL_11; // pc1 left cur + sConfig.Rank = 3; + HAL_ADC_ConfigChannel(&hadc1, &sConfig); + + sConfig.Channel = ADC_CHANNEL_12; // pc2 vbat + sConfig.Rank = 4; + HAL_ADC_ConfigChannel(&hadc1, &sConfig); + + //temperature requires at least 17.1uS sampling time + sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5; + + sConfig.Channel = ADC_CHANNEL_TEMPSENSOR; // internal temp + sConfig.Rank = 5; + HAL_ADC_ConfigChannel(&hadc1, &sConfig); + + hadc1.Instance->CR2 |= ADC_CR2_DMA | ADC_CR2_TSVREFE; + + __HAL_ADC_ENABLE(&hadc1); + + __HAL_RCC_DMA1_CLK_ENABLE(); + + DMA1_Channel1->CCR = 0; + DMA1_Channel1->CNDTR = 5; + DMA1_Channel1->CPAR = (uint32_t) & (ADC1->DR); + DMA1_Channel1->CMAR = (uint32_t)&adc_buffer; + DMA1_Channel1->CCR = DMA_CCR_MSIZE_1 | DMA_CCR_PSIZE_1 | DMA_CCR_MINC | DMA_CCR_CIRC | DMA_CCR_TCIE; + DMA1_Channel1->CCR |= DMA_CCR_EN; + + HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn); +} + +/* ADC2 init function */ +void MX_ADC2_Init(void) { + ADC_ChannelConfTypeDef sConfig; + + __HAL_RCC_ADC2_CLK_ENABLE(); + + // HAL_ADC_DeInit(&hadc2); + // hadc2.Instance->CR2 = 0; + /**Common config + */ + hadc2.Instance = ADC2; + hadc2.Init.ScanConvMode = ADC_SCAN_ENABLE; + hadc2.Init.ContinuousConvMode = DISABLE; + hadc2.Init.DiscontinuousConvMode = DISABLE; + hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START; + hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc2.Init.NbrOfConversion = 5; + HAL_ADC_Init(&hadc2); + + sConfig.SamplingTime = ADC_SAMPLETIME_7CYCLES_5; + + sConfig.Channel = ADC_CHANNEL_15; // pc5 left c + sConfig.Rank = 1; + HAL_ADC_ConfigChannel(&hadc2, &sConfig); + + sConfig.Channel = ADC_CHANNEL_13; // pc3 right b + sConfig.Rank = 2; + HAL_ADC_ConfigChannel(&hadc2, &sConfig); + + sConfig.SamplingTime = ADC_SAMPLETIME_13CYCLES_5; + + sConfig.Channel = ADC_CHANNEL_10; // pc0 right cur + sConfig.Rank = 3; + HAL_ADC_ConfigChannel(&hadc2, &sConfig); + + sConfig.Channel = ADC_CHANNEL_2; // pa2 uart-l-tx + sConfig.Rank = 4; + HAL_ADC_ConfigChannel(&hadc2, &sConfig); + + sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5; + + sConfig.Channel = ADC_CHANNEL_3; // pa3 uart-l-rx + sConfig.Rank = 5; + HAL_ADC_ConfigChannel(&hadc2, &sConfig); + + hadc2.Instance->CR2 |= ADC_CR2_DMA; + __HAL_ADC_ENABLE(&hadc2); +} diff --git a/Software/hoverboard-firmware-hack_modified20190825/Src/stm32f1xx_it.c b/Software/hoverboard-firmware-hack_modified20190825/Src/stm32f1xx_it.c new file mode 100644 index 0000000000000000000000000000000000000000..8ca24ee5d5d8580294512fcf727693368af5513c --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Src/stm32f1xx_it.c @@ -0,0 +1,267 @@ +/** + ****************************************************************************** + * @file stm32f1xx_it.c + * @brief Interrupt Service Routines. + ****************************************************************************** + * + * COPYRIGHT(c) 2017 STMicroelectronics + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "stm32f1xx_hal.h" +#include "stm32f1xx.h" +#include "stm32f1xx_it.h" +#include "config.h" + +extern DMA_HandleTypeDef hdma_i2c2_rx; +extern DMA_HandleTypeDef hdma_i2c2_tx; +extern I2C_HandleTypeDef hi2c2; + +extern DMA_HandleTypeDef hdma_usart2_rx; +extern DMA_HandleTypeDef hdma_usart2_tx; + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/* External variables --------------------------------------------------------*/ + + +/******************************************************************************/ +/* Cortex-M3 Processor Interruption and Exception Handlers */ +/******************************************************************************/ + +/** +* @brief This function handles Non maskable interrupt. +*/ +void NMI_Handler(void) { + /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ + + /* USER CODE END NonMaskableInt_IRQn 0 */ + /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ + + /* USER CODE END NonMaskableInt_IRQn 1 */ +} + +/** +* @brief This function handles Hard fault interrupt. +*/ +void HardFault_Handler(void) { + /* USER CODE BEGIN HardFault_IRQn 0 */ + + /* USER CODE END HardFault_IRQn 0 */ + while(1) { + } + /* USER CODE BEGIN HardFault_IRQn 1 */ + + /* USER CODE END HardFault_IRQn 1 */ +} + +/** +* @brief This function handles Memory management fault. +*/ +void MemManage_Handler(void) { + /* USER CODE BEGIN MemoryManagement_IRQn 0 */ + + /* USER CODE END MemoryManagement_IRQn 0 */ + while(1) { + } + /* USER CODE BEGIN MemoryManagement_IRQn 1 */ + + /* USER CODE END MemoryManagement_IRQn 1 */ +} + +/** +* @brief This function handles Prefetch fault, memory access fault. +*/ +void BusFault_Handler(void) { + /* USER CODE BEGIN BusFault_IRQn 0 */ + + /* USER CODE END BusFault_IRQn 0 */ + while(1) { + } + /* USER CODE BEGIN BusFault_IRQn 1 */ + + /* USER CODE END BusFault_IRQn 1 */ +} + +/** +* @brief This function handles Undefined instruction or illegal state. +*/ +void UsageFault_Handler(void) { + /* USER CODE BEGIN UsageFault_IRQn 0 */ + + /* USER CODE END UsageFault_IRQn 0 */ + while(1) { + } + /* USER CODE BEGIN UsageFault_IRQn 1 */ + + /* USER CODE END UsageFault_IRQn 1 */ +} + +/** +* @brief This function handles System service call via SWI instruction. +*/ +void SVC_Handler(void) { + /* USER CODE BEGIN SVCall_IRQn 0 */ + + /* USER CODE END SVCall_IRQn 0 */ + /* USER CODE BEGIN SVCall_IRQn 1 */ + + /* USER CODE END SVCall_IRQn 1 */ +} + +/** +* @brief This function handles Debug monitor. +*/ +void DebugMon_Handler(void) { + /* USER CODE BEGIN DebugMonitor_IRQn 0 */ + + /* USER CODE END DebugMonitor_IRQn 0 */ + /* USER CODE BEGIN DebugMonitor_IRQn 1 */ + + /* USER CODE END DebugMonitor_IRQn 1 */ +} + +/** +* @brief This function handles Pendable request for system service. +*/ +void PendSV_Handler(void) { + /* USER CODE BEGIN PendSV_IRQn 0 */ + + /* USER CODE END PendSV_IRQn 0 */ + /* USER CODE BEGIN PendSV_IRQn 1 */ + + /* USER CODE END PendSV_IRQn 1 */ +} + +/** +* @brief This function handles System tick timer. +*/ +#ifdef CONTROL_PPM +void PPM_SysTick_Callback(void); +#endif +void SysTick_Handler(void) { + /* USER CODE BEGIN SysTick_IRQn 0 */ + + /* USER CODE END SysTick_IRQn 0 */ + HAL_IncTick(); + HAL_SYSTICK_IRQHandler(); + /* USER CODE BEGIN SysTick_IRQn 1 */ +#ifdef CONTROL_PPM + PPM_SysTick_Callback(); +#endif + /* USER CODE END SysTick_IRQn 1 */ +} + +#ifdef CONTROL_NUNCHUCK +extern I2C_HandleTypeDef hi2c2; +void I2C1_EV_IRQHandler(void) +{ + HAL_I2C_EV_IRQHandler(&hi2c2); +} + +void I2C1_ER_IRQHandler(void) +{ + HAL_I2C_ER_IRQHandler(&hi2c2); +} + +/** +* @brief This function handles DMA1 channel4 global interrupt. +*/ +void DMA1_Channel4_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */ + + /* USER CODE END DMA1_Channel4_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_i2c2_tx); + /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */ + + /* USER CODE END DMA1_Channel4_IRQn 1 */ +} + +/** +* @brief This function handles DMA1 channel5 global interrupt. +*/ +void DMA1_Channel5_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */ + + /* USER CODE END DMA1_Channel5_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_i2c2_rx); + /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */ + + /* USER CODE END DMA1_Channel5_IRQn 1 */ +} +#endif + +#ifdef CONTROL_PPM +void EXTI3_IRQHandler(void) +{ + PPM_ISR_Callback(); + __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_3); +} +#endif + +#ifdef CONTROL_SERIAL_USART2 +void DMA1_Channel6_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */ + + /* USER CODE END DMA1_Channel4_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_usart2_rx); + /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */ + + /* USER CODE END DMA1_Channel4_IRQn 1 */ +} + +/** +* @brief This function handles DMA1 channel5 global interrupt. +*/ +void DMA1_Channel7_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */ + + /* USER CODE END DMA1_Channel5_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_usart2_tx); + /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */ + + /* USER CODE END DMA1_Channel5_IRQn 1 */ +} +#endif + +/******************************************************************************/ +/* STM32F1xx Peripheral Interrupt Handlers */ +/* Add here the Interrupt Handlers for the used peripherals. */ +/* For the available peripheral interrupt handler names, */ +/* please refer to the startup file (startup_stm32f1xx.s). */ +/******************************************************************************/ + + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/Software/hoverboard-firmware-hack_modified20190825/Src/system_stm32f1xx.c b/Software/hoverboard-firmware-hack_modified20190825/Src/system_stm32f1xx.c new file mode 100644 index 0000000000000000000000000000000000000000..bb1a3abf2d0be76d2424640ad0813d48af5b1756 --- /dev/null +++ b/Software/hoverboard-firmware-hack_modified20190825/Src/system_stm32f1xx.c @@ -0,0 +1,429 @@ +/** + ****************************************************************************** + * @file system_stm32f1xx.c + * @author MCD Application Team + * @version V4.2.0 + * @date 31-March-2017 + * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File. + * + * 1. This file provides two functions and one global variable to be called from + * user application: + * - SystemInit(): Setups the system clock (System clock source, PLL Multiplier + * factors, AHB/APBx prescalers and Flash settings). + * This function is called at startup just after reset and + * before branch to main program. This call is made inside + * the "startup_stm32f1xx_xx.s" file. + * + * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used + * by the user application to setup the SysTick + * timer or configure other parameters. + * + * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must + * be called whenever the core clock is changed + * during program execution. + * + * 2. After each device reset the HSI (8 MHz) is used as system clock source. + * Then SystemInit() function is called, in "startup_stm32f1xx_xx.s" file, to + * configure the system clock before to branch to main program. + * + * 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depending on + * the product used), refer to "HSE_VALUE". + * When HSE is used as system clock source, directly or through PLL, and you + * are using different crystal you have to adapt the HSE value to your own + * configuration. + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32f1xx_system + * @{ + */ + +/** @addtogroup STM32F1xx_System_Private_Includes + * @{ + */ + +#include "stm32f1xx.h" + +/** + * @} + */ + +/** @addtogroup STM32F1xx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F1xx_System_Private_Defines + * @{ + */ + +#if !defined(HSE_VALUE) +#define HSE_VALUE 8000000U /*!< Default value of the External oscillator in Hz. \ + This value can be provided and adapted by the user application. */ +#endif /* HSE_VALUE */ + +#if !defined(HSI_VALUE) +#define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz. \ + This value can be provided and adapted by the user application. */ +#endif /* HSI_VALUE */ + +/*!< Uncomment the following line if you need to use external SRAM */ +#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) +/* #define DATA_IN_ExtSRAM */ +#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */ + +/*!< Uncomment the following line if you need to relocate your vector Table in + Internal SRAM. */ +/* #define VECT_TAB_SRAM */ +#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field. \ + This value must be a multiple of 0x200. */ + + +/** + * @} + */ + +/** @addtogroup STM32F1xx_System_Private_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F1xx_System_Private_Variables + * @{ + */ + +/******************************************************************************* +* Clock Definitions +*******************************************************************************/ +#if defined(STM32F100xB) || defined(STM32F100xE) +uint32_t SystemCoreClock = 24000000U; /*!< System Clock Frequency (Core Clock) */ +#else /*!< HSI Selected as System Clock source */ +uint32_t SystemCoreClock = 72000000U; /*!< System Clock Frequency (Core Clock) */ +#endif + +const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4}; + +/** + * @} + */ + +/** @addtogroup STM32F1xx_System_Private_FunctionPrototypes + * @{ + */ + +#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) +#ifdef DATA_IN_ExtSRAM +static void SystemInit_ExtMemCtl(void); +#endif /* DATA_IN_ExtSRAM */ +#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */ + +/** + * @} + */ + +/** @addtogroup STM32F1xx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system + * Initialize the Embedded Flash Interface, the PLL and update the + * SystemCoreClock variable. + * @note This function should be used only after reset. + * @param None + * @retval None + */ +void SystemInit(void) { + /* Reset the RCC clock configuration to the default reset state(for debug purpose) */ + /* Set HSION bit */ + RCC->CR |= 0x00000001U; + +/* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */ +#if !defined(STM32F105xC) && !defined(STM32F107xC) + RCC->CFGR &= 0xF8FF0000U; +#else + RCC->CFGR &= 0xF0FF0000U; +#endif /* STM32F105xC */ + + /* Reset HSEON, CSSON and PLLON bits */ + RCC->CR &= 0xFEF6FFFFU; + + /* Reset HSEBYP bit */ + RCC->CR &= 0xFFFBFFFFU; + + /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */ + RCC->CFGR &= 0xFF80FFFFU; + +#if defined(STM32F105xC) || defined(STM32F107xC) + /* Reset PLL2ON and PLL3ON bits */ + RCC->CR &= 0xEBFFFFFFU; + + /* Disable all interrupts and clear pending bits */ + RCC->CIR = 0x00FF0000U; + + /* Reset CFGR2 register */ + RCC->CFGR2 = 0x00000000U; +#elif defined(STM32F100xB) || defined(STM32F100xE) + /* Disable all interrupts and clear pending bits */ + RCC->CIR = 0x009F0000U; + + /* Reset CFGR2 register */ + RCC->CFGR2 = 0x00000000U; +#else + /* Disable all interrupts and clear pending bits */ + RCC->CIR = 0x009F0000U; +#endif /* STM32F105xC */ + +#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) +#ifdef DATA_IN_ExtSRAM + SystemInit_ExtMemCtl(); +#endif /* DATA_IN_ExtSRAM */ +#endif + +#ifdef VECT_TAB_SRAM + SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */ +#else + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */ +#endif +} + +/** + * @brief Update SystemCoreClock variable according to Clock Register Values. + * The SystemCoreClock variable contains the core clock (HCLK), it can + * be used by the user application to setup the SysTick timer or configure + * other parameters. + * + * @note Each time the core clock (HCLK) changes, this function must be called + * to update SystemCoreClock variable value. Otherwise, any configuration + * based on this variable will be incorrect. + * + * @note - The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * + * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) + * + * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) + * + * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) + * or HSI_VALUE(*) multiplied by the PLL factors. + * + * (*) HSI_VALUE is a constant defined in stm32f1xx.h file (default value + * 8 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (**) HSE_VALUE is a constant defined in stm32f1xx.h file (default value + * 8 MHz or 25 MHz, depending on the product used), user has to ensure + * that HSE_VALUE is same as the real frequency of the crystal used. + * Otherwise, this function may have wrong result. + * + * - The result of this function could be not correct when using fractional + * value for HSE crystal. + * @param None + * @retval None + */ +void SystemCoreClockUpdate(void) { + uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U; + +#if defined(STM32F105xC) || defined(STM32F107xC) + uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U; +#endif /* STM32F105xC */ + +#if defined(STM32F100xB) || defined(STM32F100xE) + uint32_t prediv1factor = 0U; +#endif /* STM32F100xB or STM32F100xE */ + + /* Get SYSCLK source -------------------------------------------------------*/ + tmp = RCC->CFGR & RCC_CFGR_SWS; + + switch(tmp) { + case 0x00U: /* HSI used as system clock */ + SystemCoreClock = HSI_VALUE; + break; + case 0x04U: /* HSE used as system clock */ + SystemCoreClock = HSE_VALUE; + break; + case 0x08U: /* PLL used as system clock */ + + /* Get PLL clock source and multiplication factor ----------------------*/ + pllmull = RCC->CFGR & RCC_CFGR_PLLMULL; + pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; + +#if !defined(STM32F105xC) && !defined(STM32F107xC) + pllmull = (pllmull >> 18U) + 2U; + + if(pllsource == 0x00U) { + /* HSI oscillator clock divided by 2 selected as PLL clock entry */ + SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + } else { +#if defined(STM32F100xB) || defined(STM32F100xE) + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + /* HSE oscillator clock selected as PREDIV1 clock entry */ + SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; +#else + /* HSE selected as PLL clock entry */ + if((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET) { /* HSE oscillator clock divided by 2 */ + SystemCoreClock = (HSE_VALUE >> 1U) * pllmull; + } else { + SystemCoreClock = HSE_VALUE * pllmull; + } +#endif + } +#else + pllmull = pllmull >> 18U; + + if(pllmull != 0x0DU) { + pllmull += 2U; + } else { /* PLL multiplication factor = PLL input clock * 6.5 */ + pllmull = 13U / 2U; + } + + if(pllsource == 0x00U) { + /* HSI oscillator clock divided by 2 selected as PLL clock entry */ + SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + } else { /* PREDIV1 selected as PLL clock entry */ + + /* Get PREDIV1 clock source and division factor */ + prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC; + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + + if(prediv1source == 0U) { + /* HSE oscillator clock selected as PREDIV1 clock entry */ + SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; + } else { /* PLL2 clock selected as PREDIV1 clock entry */ + + /* Get PREDIV2 division factor and PLL2 multiplication factor */ + prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U; + pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U; + SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull; + } + } +#endif /* STM32F105xC */ + break; + + default: + SystemCoreClock = HSI_VALUE; + break; + } + + /* Compute HCLK clock frequency ----------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)]; + /* HCLK clock frequency */ + SystemCoreClock >>= tmp; +} + +#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) +/** + * @brief Setup the external memory controller. Called in startup_stm32f1xx.s + * before jump to __main + * @param None + * @retval None + */ +#ifdef DATA_IN_ExtSRAM +/** + * @brief Setup the external memory controller. + * Called in startup_stm32f1xx_xx.s/.c before jump to main. + * This function configures the external SRAM mounted on STM3210E-EVAL + * board (STM32 High density devices). This SRAM will be used as program + * data memory (including heap and stack). + * @param None + * @retval None + */ +void SystemInit_ExtMemCtl(void) { + __IO uint32_t tmpreg; + /*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is + required, then adjust the Register Addresses */ + + /* Enable FSMC clock */ + RCC->AHBENR = 0x00000114U; + + /* Delay after an RCC peripheral clock enabling */ + tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN); + + /* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */ + RCC->APB2ENR = 0x000001E0U; + + /* Delay after an RCC peripheral clock enabling */ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN); + + (void)(tmpreg); + + /* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/ + /*---------------- SRAM Address lines configuration -------------------------*/ + /*---------------- NOE and NWE configuration --------------------------------*/ + /*---------------- NE3 configuration ----------------------------------------*/ + /*---------------- NBL0, NBL1 configuration ---------------------------------*/ + + GPIOD->CRL = 0x44BB44BBU; + GPIOD->CRH = 0xBBBBBBBBU; + + GPIOE->CRL = 0xB44444BBU; + GPIOE->CRH = 0xBBBBBBBBU; + + GPIOF->CRL = 0x44BBBBBBU; + GPIOF->CRH = 0xBBBB4444U; + + GPIOG->CRL = 0x44BBBBBBU; + GPIOG->CRH = 0x444B4B44U; + + /*---------------- FSMC Configuration ---------------------------------------*/ + /*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/ + + FSMC_Bank1->BTCR[4U] = 0x00001091U; + FSMC_Bank1->BTCR[5U] = 0x00110212U; +} +#endif /* DATA_IN_ExtSRAM */ +#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/