├── .gitignore
├── LICENSE
├── README.md
├── ebike-g4
├── .cproject
├── .gitignore
├── .project
├── .settings
│ ├── .gitignore
│ └── org.eclipse.cdt.codan.core.prefs
├── include
│ ├── adc.h
│ ├── cordic_sin_cos.h
│ ├── crc.h
│ ├── data_commands.h
│ ├── data_packet.h
│ ├── delay.h
│ ├── drv8353.h
│ ├── eeprom_emulation.h
│ ├── foc_lib.h
│ ├── gpio.h
│ ├── hall_sensor.h
│ ├── hbd_data_comm.h
│ ├── live_data.h
│ ├── main.h
│ ├── main_data_types.h
│ ├── motor_loop.h
│ ├── periphconfig.h
│ ├── pinconfig.h
│ ├── power_calcs.h
│ ├── project_parameters.h
│ ├── pwm.h
│ ├── ram_commands.h
│ ├── throttle.h
│ ├── uart.h
│ ├── usb.h
│ ├── usb_cdc.h
│ ├── usb_data_comm.h
│ └── wdt.h
├── ldscripts
│ ├── libs.ld
│ ├── mem.ld
│ └── sections.ld
├── src
│ ├── _write.c
│ ├── adc.c
│ ├── cordic_sin_cos.c
│ ├── crc.c
│ ├── data_commands.c
│ ├── data_packet.c
│ ├── delay.c
│ ├── drv8353.c
│ ├── eeprom_emulation.c
│ ├── foc_lib.c
│ ├── gpio.c
│ ├── hall_sensor.c
│ ├── hbd_data_comm.c
│ ├── interrupts.c
│ ├── live_data.c
│ ├── main.c
│ ├── motor_loop.c
│ ├── power_calcs.c
│ ├── pwm.c
│ ├── throttle.c
│ ├── uart.c
│ ├── usb.c
│ ├── usb_cdc.c
│ ├── usb_data_comm.c
│ └── wdt.c
└── system
│ ├── include
│ ├── DEVICE
│ │ └── README_DRIVERS.txt
│ ├── arm
│ │ └── semihosting.h
│ ├── cmsis
│ │ ├── DEVICE.h
│ │ ├── README_DEVICE.txt
│ │ ├── arm_common_tables.h
│ │ ├── arm_const_structs.h
│ │ ├── arm_math.h
│ │ ├── cmsis_armcc.h
│ │ ├── cmsis_armcc_V6.h
│ │ ├── cmsis_device.h
│ │ ├── cmsis_gcc.h
│ │ ├── core_cm0.h
│ │ ├── core_cm0plus.h
│ │ ├── core_cm3.h
│ │ ├── core_cm4.h
│ │ ├── core_cm7.h
│ │ ├── core_cmFunc.h
│ │ ├── core_cmInstr.h
│ │ ├── core_cmSimd.h
│ │ ├── core_sc000.h
│ │ ├── core_sc300.h
│ │ ├── stm32g473xx.h
│ │ ├── stm32g4xx.h
│ │ ├── system_DEVICE.h
│ │ └── system_stm32g4xx.h
│ ├── cortexm
│ │ └── ExceptionHandlers.h
│ └── diag
│ │ └── Trace.h
│ └── src
│ ├── DEVICE
│ └── README_DRIVERS.txt
│ ├── cmsis
│ ├── README_DEVICE.txt
│ ├── arm_common_tables.c
│ ├── arm_sin_cos_f32.c
│ ├── system_DEVICE.c
│ ├── system_stm32g4xx.c
│ ├── vectors_DEVICE.c
│ └── vectors_stm32g473xx.c
│ ├── cortexm
│ ├── _initialize_hardware.c
│ ├── _reset_hardware.c
│ └── exception_handlers.c
│ ├── diag
│ ├── Trace.c
│ └── trace_impl.c
│ └── newlib
│ ├── README.txt
│ ├── _cxx.cpp
│ ├── _exit.c
│ ├── _sbrk.c
│ ├── _startup.c
│ ├── _syscalls.c
│ └── assert.c
└── scripts
├── comm_commands.xml
├── config_vars.py
├── datavar_codegen.py
├── datavars.xml
├── live_data_ids.py
├── plotMotorData
├── ebike_controller_packet.py
├── params.py
├── params.ui
├── plotMotorData.py
├── plotwin.py
└── plotwin.ui
├── project_configuration_variables.h
└── project_live_data_ids.h
/.gitignore:
--------------------------------------------------------------------------------
1 | /.vscode/
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 David Miller
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ebike-G4
2 | A brushless DC motor controller based on the STM32G4 microcontroller. Designed for electric bicycles.
3 | Hardware design files at: https://github.com/GyrocopterLLC/flatmcu/
4 |
5 | ## Build steps
6 | - Install GNU MCU Eclipse (https://gnu-mcu-eclipse.github.io/)
7 | - Import this project using the import wizard. File>Import..., select "Projects from GIT", then "Clone URI", and type in this repository's URI (https://github.com/GyrocopterLLC/ebike-g4/)
8 | ***
9 | #### License: MIT
10 | ***
11 |
--------------------------------------------------------------------------------
/ebike-g4/.gitignore:
--------------------------------------------------------------------------------
1 | /Debug/
2 | /Release/
3 |
--------------------------------------------------------------------------------
/ebike-g4/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | ebike-g4
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.cdt.managedbuilder.core.genmakebuilder
10 | clean,full,incremental,
11 |
12 |
13 |
14 |
15 | org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder
16 | full,incremental,
17 |
18 |
19 |
20 |
21 |
22 | org.eclipse.cdt.core.cnature
23 | org.eclipse.cdt.managedbuilder.core.managedBuildNature
24 | org.eclipse.cdt.managedbuilder.core.ScannerConfigNature
25 | org.eclipse.cdt.core.ccnature
26 |
27 |
28 |
--------------------------------------------------------------------------------
/ebike-g4/.settings/.gitignore:
--------------------------------------------------------------------------------
1 | /language.settings.xml
2 |
--------------------------------------------------------------------------------
/ebike-g4/include/adc.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: adc.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef ADC_H_
27 | #define ADC_H_
28 |
29 | #define MAXCOUNT (4095)
30 | #define MAXCOUNTF (4095.0f)
31 |
32 | #define NUM_ADC_CH 10
33 | #define NUM_CUR_CH 3
34 |
35 | // DMA settings
36 | #define ADC1_DMAMUX_REQ 5
37 | #define ADC2_DMAMUX_REQ 36
38 | #define ADC3_DMAMUX_REQ 37
39 | #define ADC4_DMAMUX_REQ 38
40 | #define ADC1_DMACHANNEL DMA1_Channel1
41 | #define ADC2_DMACHANNEL DMA1_Channel2
42 | #define ADC3_DMACHANNEL DMA1_Channel3
43 | #define ADC4_DMACHANNEL DMA1_Channel4
44 | #define ADC1_DMAMUXCHANNEL DMAMUX1_Channel0
45 | #define ADC2_DMAMUXCHANNEL DMAMUX1_Channel1
46 | #define ADC3_DMAMUXCHANNEL DMAMUX1_Channel2
47 | #define ADC4_DMAMUXCHANNEL DMAMUX1_Channel3
48 |
49 | // Channel definitions
50 | // Two versions are given -
51 | // Version A only uses ADC1 and ADC2, this is compatible with the STM32G4x1 series
52 | // Version B uses all ADC1 through ADC4, this is compatible with STM32G4x3 and x4
53 |
54 | #if defined(USE_ADC_1_2_ONLY)
55 | #define ADC_MTEMP_ADC ADC1
56 | #define ADC_MTEMP_CH 10
57 | #define ADC_FTEMP_ADC ADC2
58 | #define ADC_FTEMP_CH 10
59 | #define ADC_IA_ADC ADC1
60 | #define ADC_IA_CH 15
61 | #define ADC_IB_ADC ADC2
62 | #define ADC_IB_CH 2
63 | #define ADC_IC_ADC ADC1
64 | #define ADC_IC_CH 1
65 | #define ADC_VA_ADC ADC2
66 | #define ADC_VA_CH 3
67 | #define ADC_VB_ADC ADC2
68 | #define ADC_VB_CH 4
69 | #define ADC_VC_ADC ADC1
70 | #define ADC_VC_CH 12
71 | #define ADC_THR_ADC ADC2
72 | #define ADC_THR_CH 12
73 | #define ADC_VBUS_ADC ADC1
74 | #define ADC_VBUS_CH 11
75 |
76 | #else
77 |
78 | #define ADC_MTEMP_ADC ADC1
79 | #define ADC_MTEMP_CH 10
80 | #define ADC_FTEMP_ADC ADC2
81 | #define ADC_FTEMP_CH 10
82 | #define ADC_IA_ADC ADC3
83 | #define ADC_IA_CH 12
84 | #define ADC_IB_ADC ADC2
85 | #define ADC_IB_CH 2
86 | #define ADC_IC_ADC ADC1
87 | #define ADC_IC_CH 1
88 | #define ADC_VA_ADC ADC2
89 | #define ADC_VA_CH 3
90 | #define ADC_VB_ADC ADC2
91 | #define ADC_VB_CH 4
92 | #define ADC_VC_ADC ADC3
93 | #define ADC_VC_CH 1
94 | #define ADC_THR_ADC ADC2
95 | #define ADC_THR_CH 12
96 | #define ADC_VBUS_ADC ADC4
97 | #define ADC_VBUS_CH 3
98 |
99 | #endif
100 |
101 | // Common for all ADCs
102 | #define ADC_VTS_CH 16
103 | #define ADC_VBAT_CH 17
104 | #define ADC_VREFINT_CH 18
105 |
106 |
107 | #define VREFINTDEFAULT (1.212f) // From the STM32G4 spec sheet
108 | #define VREFINTCAL_MIN (1570) // Approximately 1.15V. Spec sheet minimum is 1.182V
109 | #define VREFINTCAL_MAX (1734) // Approximately 1.27V. Spec sheet maximum is 1.232V
110 | #define ADC_FACTORY_CAL_VOLTAGE (3.0f) // Calibration is done at 3.0V
111 | #define ADC_VREG_STARTUP_DELAY (1) // Only needs 20us
112 | #define ADC_STARTUP_DELAY_MS (50) // Wait this long for any startup spikes in analog values to die down
113 | #define ADC_NUM_INTEG_SAMPLES (128) // Number of samples to integrate when measuring at startup
114 |
115 | typedef struct _config_adc {
116 | float Shunt_Resistance;
117 | float Inverse_TIA_Gain;
118 | float Vbus_Ratio;
119 | float Vphase_Ratio;
120 | float Thermistor_Fixed_R;
121 | float Thermistor_R25;
122 | float Thermistor_Beta;
123 | } Config_ADC;
124 |
125 | typedef enum {
126 | ADC_IA = 0,
127 | ADC_IB,
128 | ADC_IC,
129 | ADC_VA,
130 | ADC_VB,
131 | ADC_VC,
132 | ADC_VBUS,
133 | ADC_FTEMP,
134 | ADC_MTEMP,
135 | ADC_THR,
136 | } ADC_OutputTypeDef;
137 |
138 |
139 | void ADC_InjSeqComplete(void);
140 | void ADC_RegSeqComplete(void);
141 | void ADC_Init(void);
142 | float ADC_GetCurrent(uint8_t which_cur);
143 | uint16_t ADC_Raw(uint8_t which_cur);
144 | float ADC_ConvertToAmps(int32_t rawCurrentReading);
145 | float ADC_GetThrottle(void);
146 | float ADC_GetVbus(void);
147 | float ADC_GetVref(void);
148 | float ADC_GetPhaseVoltage(uint8_t which_phase);
149 | void ADC_SetNull(uint8_t which_cur, uint16_t nullVal);
150 | float ADC_GetFetTempDegC(void);
151 |
152 | uint8_t ADC_SetRShunt(float new_rshunt);
153 | float ADC_GetRShunt(void);
154 | uint8_t ADC_SetVbusRatio(float new_ratio);
155 | float ADC_GetVbusRatio(void);
156 | uint8_t ADC_SetVphaseRatio(float new_ratio);
157 | float ADC_GetVphaseRatio(void);
158 | uint8_t ADC_SetThermFixedR(float new_fixed_r);
159 | float ADC_GetThermFixedR(void);
160 | uint8_t ADC_SetThermR25(float new_r25);
161 | float ADC_GetThermR25(void);
162 | uint8_t ADC_SetThermBeta(float new_beta);
163 | float ADC_GetThermBeta(void);
164 |
165 | void ADC_SaveVariables(void);
166 | void ADC_LoadVariables(void);
167 |
168 | uint8_t uiADC_SetRShunt(uint8_t* valptr);
169 | uint8_t uiADC_GetRShunt(uint8_t* valptr);
170 | uint8_t uiADC_SetVbusRatio(uint8_t* valptr);
171 | uint8_t uiADC_GetVbusRatio(uint8_t* valptr);
172 | uint8_t uiADC_SetVphaseRatio(uint8_t* valptr);
173 | uint8_t uiADC_GetVphaseRatio(uint8_t* valptr);
174 | uint8_t uiADC_SetThermFixedR(uint8_t* valptr);
175 | uint8_t uiADC_GetThermFixedR(uint8_t* valptr);
176 | uint8_t uiADC_SetThermR25(uint8_t* valptr);
177 | uint8_t uiADC_GetThermR25(uint8_t* valptr);
178 | uint8_t uiADC_SetThermBeta(uint8_t* valptr);
179 | uint8_t uiADC_GetThermBeta(uint8_t* valptr);
180 |
181 | #endif /* ADC_H_ */
182 |
--------------------------------------------------------------------------------
/ebike-g4/include/cordic_sin_cos.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: cordic_sin_cos.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2019 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef _CORDIC_SIN_COS_H
27 | #define _CORDIC_SIN_COS_H
28 |
29 | #define USE_DEFINE_CONVERSIONS 1
30 |
31 | #define float_to_q31_def(float_input, q31_output) \
32 | do{ \
33 | asm( "VCVT.S32.F32 %1, %1, #31\n\t" \
34 | "VMOV %0, %1" \
35 | :"=r" (q31_output) \
36 | :"t" (float_input) \
37 | :); \
38 | }while(0)
39 |
40 | #define q31_to_float_def(q31_input, float_output) \
41 | do{ \
42 | asm( "VMOV %0, %1\n\t" \
43 | "VCVT.F32.S32 %0, %0, #31" \
44 | :"=t" (float_output) \
45 | :"r" (q31_input) \
46 | :); \
47 | }while(0)
48 |
49 | #define CORDIC_CalcSinCosDeferred_Def(theta) \
50 | do{ \
51 | int32_t fxd_input; \
52 | float_to_q31_def(theta, fxd_input); \
53 | CORDIC->WDATA = fxd_input; \
54 | }while(0)
55 |
56 | #define CORDIC_GetResults_Def(sin, cos) \
57 | do{ \
58 | int32_t fxd_sin, fxd_cos; \
59 | fxd_sin = CORDIC->RDATA; \
60 | fxd_cos = CORDIC->RDATA; \
61 | q31_to_float_def(fxd_sin, sin); \
62 | q31_to_float_def(fxd_cos, cos); \
63 | }while(0)
64 |
65 | void CORDIC_Init(void);
66 | void CORDIC_CalcSinCos(float theta, float* sin, float* cos) ;
67 | void CORDIC_CalcSinCosDeferred(float theta);
68 | void CORDIC_GetResults(float* sin, float* cos);
69 |
70 | #endif
71 |
--------------------------------------------------------------------------------
/ebike-g4/include/crc.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: crc.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 |
27 | #ifndef _CRC32_H_
28 | #define _CRC32_H_
29 |
30 | void CRC_Init(void);
31 | uint32_t CRC_Generate_CRC32(uint8_t *buf, uint16_t len);
32 |
33 | #endif // _CRC32_H_
34 |
--------------------------------------------------------------------------------
/ebike-g4/include/data_commands.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: data_commands.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef _DATA_COMMANDS_H_
27 | #define _DATA_COMMANDS_H_
28 |
29 | #include "data_packet.h"
30 |
31 | #define RESULT_IS_8B (2)
32 | #define RESULT_IS_16B (3)
33 | #define RESULT_IS_32B (4)
34 | #define RESULT_IS_FLOAT (5)
35 |
36 | uint16_t data_process_command(Data_Packet_Type* pkt);
37 | uint16_t command_get_ram(uint8_t* pktdata, uint8_t* retval);
38 | uint16_t command_set_ram(uint8_t* pktdata);
39 | uint16_t command_get_eeprom(uint8_t* pktdata, uint8_t* retval);
40 | uint16_t command_set_eeprom(uint8_t* pktdata);
41 | uint16_t command_enable_feature(uint8_t* pktdata);
42 | uint16_t command_disable_feature(uint8_t* pktdata);
43 | uint16_t command_run_routine(uint8_t* pktdata);
44 |
45 | #endif //_DATA_COMMANDS_H_
46 |
--------------------------------------------------------------------------------
/ebike-g4/include/delay.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: delay.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef __DELAY_H
27 | #define __DELAY_H
28 |
29 | void DelayInit(void);
30 | void Delay(__IO uint32_t Delay);
31 | uint32_t GetTick(void);
32 | void SYSTICK_IRQHandler(void);
33 |
34 |
35 | #endif //__DELAY_H
36 |
--------------------------------------------------------------------------------
/ebike-g4/include/eeprom_emulation.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: eeprom_emulation.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef EEPROM_EMULATION_H_
27 | #define EEPROM_EMULATION_H_
28 |
29 | #include "main.h"
30 |
31 | typedef enum {
32 | FLASH_BUSY = 1,
33 | FLASH_ERROR_WRP,
34 | FLASH_ERROR_PROGRAM,
35 | FLASH_ERROR_OPERATION,
36 | FLASH_COMPLETE
37 | } FLASH_Status;
38 |
39 | /*
40 | * Note about Flash on the STM32G4 microcontroller:
41 | * Flash can be configured either in single bank (128 pages of 4KB)
42 | * or dual bank (two banks of 128 pages of 2KB)
43 | *
44 | * The setting can be read from the options register to figure
45 | * out what the current page sizes should be.
46 | */
47 |
48 | // Define the size of the pages to be used
49 | #define PAGE_SIZE_DUAL (uint32_t)0x0800 // Page size = 2KByte for dual bank mode
50 | #define PAGE_SIZE_SINGLE (uint32_t)0x1000 // Page size = 4KByte for single bank mode
51 |
52 | // Flash address definitions
53 | #define FLASH_START_ADDRESS (uint32_t)0x08000000
54 | #define BANK1_START_ADDRESS (uint32_t)0x08000000 // same as start of Flash
55 | #define BANK2_START_ADDRESS (uint32_t)0x08040000 // 256K past the start
56 |
57 | #define PAGE0_PAGE_NUM 126 // Second-to-last page
58 | #define PAGE1_PAGE_NUM 127 // Last page
59 |
60 | // EEPROM start address in Flash - last two pages
61 | #define EEPROM_START_ADDRESS_DUAL ((uint32_t)BANK2_START_ADDRESS + PAGE0_PAGE_NUM*PAGE_SIZE_DUAL)
62 | #define EEPROM_START_ADDRESS_SINGLE ((uint32_t)FLASH_START_ADDRESS + PAGE0_PAGE_NUM*PAGE_SIZE_SINGLE)
63 |
64 | // Pages 0 and 1 base and end addresses
65 | #define PAGE0_BASE_ADDRESS_DUAL ((uint32_t)EEPROM_START_ADDRESS_DUAL)
66 | #define PAGE0_BASE_ADDRESS_SINGLE ((uint32_t)EEPROM_START_ADDRESS_SINGLE)
67 | #define PAGE0_END_ADDRESS_DUAL ((uint32_t)(PAGE0_BASE_ADDRESS_DUAL + (PAGE_SIZE_DUAL - 1)))
68 | #define PAGE0_END_ADDRESS_SINGLE ((uint32_t)(PAGE0_BASE_ADDRESS_SINGLE + (PAGE_SIZE_SINGLE - 1)))
69 |
70 | #define PAGE1_BASE_ADDRESS_DUAL ((uint32_t)(EEPROM_START_ADDRESS_DUAL + PAGE_SIZE_DUAL))
71 | #define PAGE1_BASE_ADDRESS_SINGLE ((uint32_t)(EEPROM_START_ADDRESS_SINGLE + PAGE_SIZE_SINGLE))
72 | #define PAGE1_END_ADDRESS_DUAL ((uint32_t)(PAGE1_BASE_ADDRESS_DUAL + (PAGE_SIZE_DUAL - 1)))
73 | #define PAGE1_END_ADDRESS_SINGLE ((uint32_t)(PAGE1_BASE_ADDRESS_SINGLE + (PAGE_SIZE_SINGLE - 1)))
74 |
75 | // Used Flash pages for EEPROM emulation
76 | #define PAGE0 ((uint16_t)0x0000)
77 | #define PAGE1 ((uint16_t)0x0001)
78 |
79 | // No valid page define
80 | #define NO_VALID_PAGE ((uint16_t)0x00AB)
81 |
82 | // Page status definitions
83 | typedef enum _EE_Page_Status {
84 | EE_Page_Erased, // Page is empty
85 | EE_Page_Receive, // Page is receiving data from the other page
86 | EE_Page_Active, // Page is writing new data
87 | EE_Page_Invalid // The status flags were incorrectly set
88 | } EE_Page_Status;
89 |
90 | // Status flags
91 | #define FLASH_ERASED ((uint32_t)0xFFFFFFFFu)
92 | #define FLASH_FLAGGED ((uint32_t)0x5A5A5A5Au)
93 | #define FLASH_ZEROED ((uint32_t)0x00000000u)
94 |
95 | // Valid pages in read and write defines
96 | #define READ_FROM_VALID_PAGE ((uint8_t)0x00)
97 | #define WRITE_IN_VALID_PAGE ((uint8_t)0x01)
98 |
99 | // Page full define
100 | #define PAGE_FULL ((uint8_t)0x80)
101 |
102 | uint16_t EE_Init(uint16_t* addrTab);
103 | void EE_Config_Addr_Table(uint16_t* addrTab);
104 | uint16_t EE_ReadVariable(uint16_t VirtAddress, uint32_t* Data);
105 | uint16_t EE_WriteVariable(uint16_t VirtAddress, uint32_t Data);
106 | uint16_t EE_SaveInt16(uint16_t VirtAddress, int16_t Data);
107 | uint16_t EE_SaveInt32(uint16_t VirtAddress, int32_t Data);
108 | uint16_t EE_SaveFloat(uint16_t VirtAddress, float Data);
109 | int16_t EE_ReadInt16WithDefault(uint16_t VirtAddress, int16_t defalt);
110 | int32_t EE_ReadInt32WithDefault(uint16_t VirtAddress, int32_t defalt);
111 | float EE_ReadFloatWithDefault(uint16_t VirtAddress, float defalt);
112 |
113 | #endif /* EEPROM_EMULATION_H_ */
114 |
115 | /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
116 |
117 |
--------------------------------------------------------------------------------
/ebike-g4/include/foc_lib.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: foc_lib.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef _FOC_LIB_H
27 | #define _FOC_LIB_H
28 |
29 | #ifndef PI
30 | #define PI 3.14159265358979f
31 | #endif
32 |
33 | #ifndef SQRT3_OVER_2
34 | #define SQRT3_OVER_2 0.86602650378444f
35 |
36 | #endif
37 |
38 | #ifndef ONE_HALF
39 | #define ONE_HALF 0.5f
40 | #endif
41 |
42 | #ifndef INV_SQRT3
43 | #define INV_SQRT3 0.57735026918963f
44 | #endif
45 |
46 | typedef struct _PID_Type {
47 | float Err; // Input: Error term (Reference - feedback)
48 | float Ui; // Output: Integral output
49 | float Kp; // Param: Proportional gain
50 | float Ki; // Param: Integral gain
51 | float Kd; // Param: Derivative gain
52 | float Kc; // Param: Saturation gain
53 | float OutMin; // Param: Minimum output value
54 | float OutMax; // Param: Maximum output value
55 | float SatErr; // Output: Saturation error
56 | float Out; // Output: PID output term
57 | float Up1; // Previous proportional output
58 | } PID_Type;
59 |
60 | typedef struct _Biquad_Type {
61 | float A1; // Param: A1 gain (output at one delay)
62 | float A2; // Param: A2 gain (output at two delays)
63 | float B0; // Param: B0 gain (input, no delay)
64 | float B1; // Param: B1 gain (input, one delay)
65 | float B2; // Param: B2 gain (input, two delays)
66 | float U1; // State: First delay register
67 | float U2; // State: Second delay register
68 | float X; // Input: variable to be filtered
69 | float Y; // Output: filtered result
70 | } Biquad_Type;
71 |
72 | void FOC_SVM(float alpha, float beta, float* tA, float* tB, float* tC);
73 |
74 | void FOC_Ipark(float D, float Q, float sin, float cos, float* alpha, float* beta);
75 | void FOC_Clarke(float A, float B, float* Alpha, float* Beta);
76 | void FOC_Park(float alpha, float beta, float sin, float cos, float* D, float* Q);
77 |
78 | void FOC_BiquadCalc(Biquad_Type* biq);
79 | void FOC_BiquadLPF(Biquad_Type* biq, float Fs, float f0, float Q);
80 |
81 | void FOC_PIDdefaults(PID_Type* pid);
82 | void FOC_PIDreset(PID_Type* pid);
83 | void FOC_PIDcalc(PID_Type* pid);
84 | void FOC_PIcalc(PID_Type* pid);
85 |
86 | void FOC_RampGen(float* rampAngle, float rampInc);
87 | float FOC_RampCtrl(float callingFreq, float rampFreq);
88 |
89 | #endif
90 |
--------------------------------------------------------------------------------
/ebike-g4/include/gpio.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: gpio.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef GPIO_H_
27 | #define GPIO_H_
28 |
29 | #include "stm32g4xx.h"
30 |
31 | #define EXTI_None ((uint8_t)0x00)
32 | #define EXTI_Rising ((uint8_t)0x01)
33 | #define EXTI_Falling ((uint8_t)0x02)
34 | #define EXTI_Rising_Falling (EXTI_Rising | EXTI_Falling)
35 |
36 | typedef enum _PuPd_Type {
37 | PuPd_NoPull,
38 | PuPd_PullUp,
39 | PuPd_PullDown
40 | } PuPd_Type;
41 |
42 | #define GPIO_High(gpio, pin) ((gpio->BSRR) = (0x01U << pin))
43 | #define GPIO_Low(gpio, pin) ((gpio->BRR) = (0x01U << pin))
44 |
45 | void GPIO_Clk(GPIO_TypeDef* gpio);
46 | void GPIO_Output(GPIO_TypeDef* gpio, uint8_t pin);
47 | void GPIO_Input(GPIO_TypeDef* gpio, uint8_t pin);
48 | void GPIO_InputPD(GPIO_TypeDef* gpio, uint8_t pin);
49 | void GPIO_InputPU(GPIO_TypeDef* gpio, uint8_t pin);
50 | void GPIO_Analog(GPIO_TypeDef* gpio, uint8_t pin);
51 | void GPIO_AF(GPIO_TypeDef* gpio, uint8_t pin, uint8_t af);
52 | void GPIO_SetPUPD(GPIO_TypeDef* gpio, uint8_t pin, PuPd_Type pullupdn);
53 | void GPIO_EXTI_Config(GPIO_TypeDef* gpio, uint8_t pin,
54 | uint8_t rise_fall_select);
55 |
56 | #endif /* GPIO_H_ */
57 |
--------------------------------------------------------------------------------
/ebike-g4/include/hall_sensor.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: hall_sensor.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef __HALL_SENSOR_H
27 | #define __HALL_SENSOR_H
28 |
29 | #define HALL_PSC_MIN 15 // 84MHz clock / 16 = 5.25MHz -> 12.5millisec total period
30 | #define HALL_PSC_MAX 127 // 84MHz clock / 128 = 656.25kHz -> .0998sec total period
31 | #define HALL_PSC_CHG_AMT 16
32 | #define HALL_MIN_CAPTURE 16384 // First 1/4 of the period
33 | #define HALL_MAX_OVERFLOWS 3
34 |
35 | #define HALL_PSC_CHANGED_UP 1
36 | #define HALL_PSC_CHANGED_DOWN 2
37 | #define HALL_PSC_CHANGED (HALL_PSC_CHANGED_UP | HALL_PSC_CHANGED_DOWN)
38 | #define HALL_STOPPED 4
39 |
40 | #define HALL_ROT_UNKNOWN 0
41 | #define HALL_ROT_FORWARD 1
42 | #define HALL_ROT_REVERSE 2
43 |
44 | #define NUM_ACCEL_SAMPLES 4 // Number of speed samples for rolling average
45 |
46 | // Error checking
47 | #define HALL_MAX_SPEED_CHANGE (3.0f)
48 | #define HALL_MIN_STEADY_ROTATION_COUNT (6) // One full electrical rotation
49 |
50 | typedef struct _hallsensor{
51 | float Speed;
52 | float PreviousSpeed;
53 | float Accel;
54 | float AccelSamples[NUM_ACCEL_SAMPLES];
55 | uint32_t CallingFrequency;
56 | float AngleIncrement;
57 | float Angle;
58 | uint32_t CaptureValue;
59 | uint32_t CaptureForState[8];
60 | uint16_t Prescaler;
61 | uint16_t PrescalerForState[8];
62 | uint8_t CurrentAccelSample;
63 | uint8_t Status;
64 | uint8_t OverflowCount;
65 | uint8_t SteadyRotationCount;
66 | uint8_t RotationDirection;
67 | uint8_t PreviousRotationDirection;
68 | uint8_t CurrentState;
69 | uint8_t PreviousState;
70 | uint8_t Valid;
71 |
72 | } HallSensor_HandleTypeDef;
73 |
74 | typedef struct _hallsensorpll{
75 | float Alpha; // Gain for phase difference
76 | float Beta; // Gain for frequency (fixed at alpha^2/2)
77 | float dt; // Timestep
78 | float Frequency; // Output frequency
79 | float Phase; // Output angle
80 | uint8_t Valid; // Is phase locked?
81 | uint16_t ValidCounter; // Increments to saturation while locked
82 |
83 | } HallSensorPLL_HandleTypeDef;
84 |
85 | #define PLL_LOCKED_PHASE_ERROR (0.2f)
86 | #define PLL_LOCKED_COUNTS (1000)
87 |
88 | #define PLL_UNLOCKED (0)
89 | #define PLL_LOCKED (1)
90 |
91 | #define ANGLE_INVALID (0)
92 | #define ANGLE_VALID (1)
93 |
94 | void HALL_Init(uint32_t callingFrequency);
95 | uint8_t HALL_GenFwdOrder(float* angleTab, uint8_t* fwdOrderTab);
96 | uint8_t HALL_GenRevOrder(float* angleTab, uint8_t* revOrderTab);
97 | uint8_t HALL_GenFwdTable(uint8_t* orderTab, uint8_t* fwdTab);
98 | uint8_t HALL_GenFwdInvTable(uint8_t* fwdTab, uint8_t* fwdInvTab);
99 | uint8_t HALL_GenRevTable(uint8_t* revOrderTab, uint8_t* revTab);
100 | uint8_t HALL_GenRevInvTable(uint8_t* revTab, uint8_t* revInvTab);
101 |
102 | uint8_t HALL_GetState(void);
103 | void HALL_IncAngle(void);
104 | uint8_t HALL_IsStopped(void);
105 | uint16_t HALL_GetAngle(void);
106 | float HALL_GetAngleF(void);
107 |
108 | uint32_t HALL_GetSpeed(void);
109 | float HALL_GetSpeedF(void);
110 | uint32_t HALL_GetAcceleration(void);
111 | float HALL_GetAccelerationF(void);
112 | uint8_t HALL_GetDirection(void);
113 | uint8_t HALL_IsValid(void);
114 |
115 | void HALL_PLLUpdate(void);
116 | uint16_t HALL_GetPLLAngle(void);
117 | float HALL_GetPLLAngleF(void);
118 | uint32_t HALL_GetPLLSpeed(void);
119 | float HALL_GetPLLSpeedF(void);
120 | uint8_t HALL_PLLIsValid(void);
121 |
122 | uint8_t HALL_SetAngle(uint8_t state, float newAngle);
123 | uint8_t HALL_SetAngleTable(float* angleTab);
124 | float* HALL_GetAngleTable(void);
125 | float HALL_GetAngleFromTable(uint8_t state);
126 | float HALL_GetStateMidpoint(uint8_t state);
127 | void HALL_ChangeFrequency(uint32_t newfreq);
128 | void HALL_EnableHallDetection(float* angleTable, uint8_t tableLength);
129 | void HALL_DisableHallDetection(void);
130 | void HALL_UpdateCallback(void);
131 | void HALL_CaptureCallback(void);
132 |
133 | void HALL_SaveVariables(void);
134 | void HALL_LoadVariables(void);
135 |
136 | uint8_t uiMOTOR_GetHall1(uint8_t* valptr);
137 | uint8_t uiMOTOR_SetHall1(uint8_t* valptr);
138 | uint8_t uiMOTOR_GetHall2(uint8_t* valptr);
139 | uint8_t uiMOTOR_SetHall2(uint8_t* valptr);
140 | uint8_t uiMOTOR_GetHall3(uint8_t* valptr);
141 | uint8_t uiMOTOR_SetHall3(uint8_t* valptr);
142 | uint8_t uiMOTOR_GetHall4(uint8_t* valptr);
143 | uint8_t uiMOTOR_SetHall4(uint8_t* valptr);
144 | uint8_t uiMOTOR_GetHall5(uint8_t* valptr);
145 | uint8_t uiMOTOR_SetHall5(uint8_t* valptr);
146 | uint8_t uiMOTOR_GetHall6(uint8_t* valptr);
147 | uint8_t uiMOTOR_SetHall6(uint8_t* valptr);
148 |
149 | #endif // __HALL_SENSOR_H
150 |
--------------------------------------------------------------------------------
/ebike-g4/include/hbd_data_comm.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: hbd_data_comm.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2021 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef _HBD_DATA_COMM_H_
27 | #define _HBD_DATA_COMM_H_
28 |
29 | void HBD_Data_Comm_Init(void);
30 | void HBD_OneByte_Check(void);
31 |
32 | #endif //_HBD_DATA_COMM_H_
33 |
--------------------------------------------------------------------------------
/ebike-g4/include/live_data.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: live_data.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef __LIVE_DATA_H
27 | #define __LIVE_DATA_H
28 |
29 | #include "project_parameters.h"
30 |
31 | typedef enum _live_datarate_type {
32 | DataRate_50Hz = 0,
33 | DataRate_100Hz = 1,
34 | DataRate_200Hz = 2,
35 | DataRate_500Hz = 3,
36 | DataRate_1kHz = 4,
37 | DataRate_5kHz = 5
38 | } Live_DataRate;
39 |
40 | typedef struct _live_config_type {
41 | uint16_t Num_Outputs;
42 | uint16_t Speed;
43 | uint16_t Choices[MAX_LIVE_OUTPUTS];
44 | } Live_Config;
45 |
46 | void LIVE_Init(uint32_t calling_freq);
47 | void LIVE_AssemblePacket(Main_Variables* mvar);
48 | void LIVE_SendPacket(void);
49 |
50 | // Command interaction functions
51 | uint8_t LIVE_TurnOnData(void);
52 | uint8_t LIVE_TurnOffData(void);
53 | uint8_t LIVE_SetSpeed(uint16_t newSpeed);
54 | uint16_t LIVE_GetSpeed(void);
55 | uint8_t LIVE_SetNumOutputs(uint16_t numOutputs);
56 | uint16_t LIVE_GetNumOutputs(void);
57 | uint8_t LIVE_SetOutput(uint8_t whichOutput, uint16_t newSetting);
58 | uint16_t LIVE_GetOutput(uint8_t whichOutput);
59 |
60 | #endif
61 |
--------------------------------------------------------------------------------
/ebike-g4/include/main_data_types.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: main_data_types.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 |
27 | #ifndef __MAIN_DATA_TYPES_H
28 | #define __MAIN_DATA_TYPES_H
29 |
30 | #include "foc_lib.h"
31 |
32 | // Variable type definitions
33 |
34 | typedef enum _main_limit_type {
35 | Main_Limit_PhaseCurrent,
36 | Main_Limit_PhaseRegenCurrent,
37 | Main_Limit_BattCurrent,
38 | Main_Limit_BattRegenCurrent,
39 | Main_Limit_SoftVoltage,
40 | Main_Limit_HardVoltage,
41 | Main_Limit_SoftFetTemp,
42 | Main_Limit_HardFetTemp,
43 | Main_Limit_SoftMotorTemp,
44 | Main_Limit_HardMotorTemp,
45 | Main_Limit_MinVoltFault,
46 | Main_Limit_MaxVoltFault,
47 | Main_Limit_CurrentFault
48 | } Main_Limit_Type;
49 |
50 | typedef enum _main_control_methods {
51 | Control_None, // invalid
52 | Control_BLDC, // six-step (trapezoidal) control
53 | Control_Sine, // Sinusoidal outputs, no current feedback
54 | Control_FOC, // Field oriented control
55 | Control_Debug // all three PWMs simply follow the throttle
56 | } Main_Control_Methods;
57 |
58 | typedef enum _motor_run_state {
59 | Motor_Off, // All switching disabled.
60 | Motor_SixStep, // Running in trapezoidal mode
61 | Motor_Sine, // Ruuning in sinewave (open loop current, continuously updating angle)
62 | Motor_FOC, // Switched to FOC full control
63 | Motor_OpenLoop, // Open-loop with fixed frequency rotation
64 | Motor_Debug, // All three PWMs follow the throttle
65 | Motor_Fault // Something screwed up
66 | } Motor_Run_State;
67 |
68 | typedef struct _main_config {
69 | // ----- Settings editable by user -----
70 | float RampSpeed;
71 | uint32_t CountsToFOC;
72 | float SpeedToFOC;
73 | float SwitchEpsilon;
74 | uint16_t MotorPolePairs;
75 | float WheelSizeMM;
76 | float GearRatio;
77 | float MotorKv;
78 | int32_t PWMFrequency;
79 | int32_t PWMDeadTime;
80 | float MaxPhaseCurrent;
81 | float MaxPhaseRegenCurrent;
82 | float MaxBatteryCurrent;
83 | float MaxBatteryRegenCurrent;
84 | float VoltageSoftCap;
85 | float VoltageHardCap;
86 | float FetTempSoftCap;
87 | float FetTempHardCap;
88 | float MotorTempSoftCap;
89 | float MotorTempHardCap;
90 | float MinVoltFault;
91 | float MaxVoltFault;
92 | float CurrentFault;
93 | // ----- Generated constants -----
94 | float inv_max_phase_current;
95 | float inv_pole_pairs;
96 | float kv_volts_per_ehz;
97 | // ----- Local variables -----
98 | float throttle_limit_scale;
99 | } Config_Main;
100 |
101 | typedef struct _Motor_Controls {
102 | Main_Control_Methods ControlMethod;
103 | Motor_Run_State state;
104 | float RawThrottle;
105 | float ThrottleCommand;
106 | } Motor_Controls;
107 |
108 | typedef struct _Motor_Observations {
109 | float iA;
110 | float iB;
111 | float iC;
112 | float iAlpha;
113 | float iBeta;
114 | float vA;
115 | float vB;
116 | float vC;
117 | float BusVoltage;
118 | float RotorAngle;
119 | float RotorSpeed_eHz;
120 | float RotorAccel_eHzps;
121 | float FetTemperature;
122 | uint8_t HallState;
123 | } Motor_Observations;
124 |
125 | typedef struct _Motor_PWMDuties {
126 | float tA;
127 | float tB;
128 | float tC;
129 | } Motor_PWMDuties;
130 |
131 | typedef struct _Motor_Settings {
132 | float inv_max_phase_current;
133 | float kv_volts_per_ehz;
134 | } Motor_Settings;
135 |
136 | typedef struct _FOC_StateVariables {
137 | float Sin; // sin(motorangle)
138 | float Cos; // cos(motorangle)
139 | float Clarke_Alpha; // Stationary 2-phase current, aligned on 0 degrees
140 | float Clarke_Beta; // Stationary 2-phase current, aligned on 90 degrees
141 | float Park_D; // Rotational current, aligned with rotor
142 | float Park_Q; // Rotational current, aligned 90 degrees ahead of rotor
143 | float T_Alpha; // Commanded voltage (as percent of battery), aligned on 0 degrees
144 | float T_Beta; // Commanded voltage (as percent of battery), aligned on 90 degrees
145 | PID_Type* Id_PID; // Controller for rotor aligned current
146 | PID_Type* Iq_PID; // Controller for 90 degree ahead aligned current
147 | } FOC_StateVariables;
148 |
149 | typedef struct _main_variables_type {
150 | uint32_t Timestamp;
151 | Motor_Controls* Ctrl;
152 | Motor_Observations* Obv;
153 | Motor_PWMDuties* Pwm;
154 | FOC_StateVariables* Foc;
155 | Config_Main* Cfg;
156 | } Main_Variables;
157 |
158 |
159 |
160 | #endif
161 |
--------------------------------------------------------------------------------
/ebike-g4/include/motor_loop.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: motor_loop.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef __MOTOR_LOOP_H
27 | #define __MOTOR_LOOP_H
28 |
29 | #include "main_data_types.h"
30 |
31 | void Motor_Loop(Main_Variables* mvar);
32 |
33 | #endif
34 |
--------------------------------------------------------------------------------
/ebike-g4/include/periphconfig.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: periphconfig.h
3 | * Description: Settings for MCU peripherals.
4 | ******************************************************************************
5 |
6 | Copyright (c) 2020 David Miller
7 |
8 | Permission is hereby granted, free of charge, to any person obtaining a copy
9 | of this software and associated documentation files (the "Software"), to deal
10 | in the Software without restriction, including without limitation the rights
11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 | copies of the Software, and to permit persons to whom the Software is
13 | furnished to do so, subject to the following conditions:
14 |
15 | The above copyright notice and this permission notice shall be included in all
16 | copies or substantial portions of the Software.
17 |
18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 | SOFTWARE.
25 | */
26 |
27 | #ifndef __PERIPHCONFIG_H
28 | #define __PERIPHCONFIG_H
29 |
30 | /* Peripheral usage:
31 | *
32 | * *** TIMERS ***
33 | * --- Advanced motor control ---
34 | * TIM1 - 3phase bridge PWM output
35 | * TIM8 -
36 | * TIM20 -
37 | * --- General purpose, 32bit ---
38 | * TIM2 -
39 | * TIM5 - Pedal Assist (PAS) timer for Thr
40 | * --- General purpose, 16bit ---
41 | * TIM3 -
42 | * TIM4 - Hall sensors
43 | * TIM15 -
44 | * TIM16 -
45 | * TIM17 -
46 | * --- Basic ---
47 | * TIM6 - Basic timer for application scheduling
48 | * TIM7 -
49 | * --- Other ---
50 | * LPTIM1 -
51 | * IDWG - Safety reset
52 | * WWDG -
53 | * SysTick - Additional basic scheduling, delays
54 | * RTC - Temporary save variables into BKPSRAM to command bootloader resets
55 | *
56 | * *** ANALOG ***
57 | * ADC1,2,3,4 - Measure motor current, battery voltage, and throttle
58 | * ADC5 -
59 | * DAC1 - Debugging analog outputs for viewing with an oscilloscope
60 | * DAC2 -
61 | * COMP -
62 | * OPAMP -
63 | *
64 | * *** COMMUNICATION INTERFACES ***
65 | * USART1 -
66 | * USART2 - Handle bar display (HBD)
67 | * USART3 - Battery management system (BMS)
68 | * LPUART1 -
69 | * SPI1 - Communication with 3-phase bridge driver (DRV8353RS)
70 | * SPI2/I2S2 -
71 | * SPI3/I2S3 -
72 | * I2C1,2,3,4 -
73 | * FDCAN1,2,3 -
74 | * SAI -
75 | * USB Device - Debugging communications
76 | * UCPD -
77 | *
78 | * *** OTHER STUFF ***
79 | * CRS - Correct USB clock source to host SOF
80 | * FSMC -
81 | * QUADSPI -
82 | * DMA1 -
83 | * DMA2 -
84 | * CRC - Generate CRC-32 for packet data interface
85 | * RNG -
86 | * HASH -
87 | * CRYP -
88 | * CORDIC - sin/cos calculations in FOC
89 | * FMAC - biquad filter calculations
90 | */
91 |
92 | // Clocks and timing
93 | #if !defined (HSI_VALUE)
94 | #define HSI_VALUE 16000000U // High speed internal oscillator = 16MHz
95 | #endif
96 |
97 | #if !defined (LSI_VALUE)
98 | #define LSI_VALUE 32000U // Low speed internal oscillator = 32kHz
99 | #endif
100 |
101 | #define PLL_M 4U
102 | #define PLL_N 85U
103 | #define VCO_CLK 340000000U // VCO = HSI * PLL_N / PLL_M
104 | #define PLL_R 2U
105 | #define SYS_CLK 170000000U // Sysclk = VCO / PLL_R
106 | #define AHB_DIV 1U
107 | #define HCLKC 170000000U // HCLK = Sysclk / AHB_DIV
108 | #define APB1_DIV 1U
109 | #define APB1_CLK 170000000U
110 | #define APB2_DIV 1U
111 | #define APB2_CLK 170000000U
112 | #define PLL_Q 2U
113 | #define PLLQ_CLK 170000000U
114 | #define PLL_P 8U
115 | #define PLLP_CLK 42500000U
116 | #define ADC_CLK PLLP_CLK // Max is 52MHz in voltage range 1, all ADCs operational
117 | #define IWDG_CLK LSI_VALUE
118 |
119 | // PWM
120 | #define PWM_TIM TIM1
121 | #define PWM_CLK APB2_CLK
122 | #define PWM_TIM_CLK_ENABLE() RCC->APB2ENR |= RCC_APB2ENR_TIM1EN
123 | #define PWM_IRQn TIM1_UP_TIM16_IRQn
124 |
125 | // Hall Sensors
126 | #define HALL_TIM TIM4
127 | #define HALL_CLK APB1_CLK
128 | #define HALL_TIM_CLK_ENABLE() RCC->APB1ENR1 |= RCC_APB1ENR1_TIM4EN
129 | #define HALL_IRQn TIM4_IRQn
130 |
131 | // Pedal Assist Throttle (PAS) Timer
132 | #define PAS_TIM TIM5
133 | #define PAS_CLK APB1_CLK
134 | #define PAS_TIM_CLK_ENABLE() RCC->APB1ENR1 |= RCC_APB1ENR1_TIM5EN
135 | #define PAS_IRQn TIM5_IRQn
136 |
137 | // Application timer
138 | #define APP_TIM TIM6
139 | #define APP_CLK APB1_CLK
140 | #define APP_TIMER_CLK_ENABLE() RCC->APB1ENR1 |= RCC_APB1ENR1_TIM6EN
141 | #define APP_IRQn TIM6_DAC_IRQn
142 |
143 | // HBD
144 | #define HBD_UART USART2
145 | #define HBD_CLK APB1_CLK
146 | #define HBD_UART_CLK_ENABLE() RCC->APB1ENR1 |= RCC_APB1ENR1_USART2EN
147 | #define HBD_IRQn USART2_IRQn
148 |
149 | // BMS
150 | #define BMS_UART USART3
151 | #define BMS_CLK APB1_CLK
152 | #define BMS_UART_CLK_ENABLE() RCC->APB1ENR1 |= RCC_APB1ENR1_USART3EN
153 | #define BMS_IRQn USART3_IRQn
154 |
155 | // DRV8353 Control
156 | #define DRV_SPI SPI1
157 | #define DRV_CLK APB2_CLK
158 | #define DRV_SPI_CLK_ENABLE() RCC->APB2ENR |= RCC_APB2ENR_SPI1EN
159 | #define DRV_IRQn SPI1_IRQn
160 |
161 |
162 | // Interrupt priority settings
163 | // Lowest number takes precedence
164 | // Multiple interrupt sources can use the same priority level,
165 | // but only a lower number interrupt will override a currently
166 | // responding IRQ function.
167 | #define PRIO_PWM (0)
168 | #define PRIO_HALL (1)
169 | #define PRIO_ADC (2)
170 | #define PRIO_PAS (3)
171 | #define PRIO_APPTIMER (3)
172 | #define PRIO_SYSTICK (3)
173 | #define PRIO_HBD_UART (4)
174 | #define PRIO_BMS_UART (4)
175 | #define PRIO_DRV_SPI (4)
176 | #define PRIO_USB (5)
177 |
178 | #endif //__PERIPHCONFIG_H
179 |
--------------------------------------------------------------------------------
/ebike-g4/include/pinconfig.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: pinconfig.h
3 | * Description: Settings for MCU pins.
4 | ******************************************************************************
5 |
6 | Copyright (c) 2020 David Miller
7 |
8 | Permission is hereby granted, free of charge, to any person obtaining a copy
9 | of this software and associated documentation files (the "Software"), to deal
10 | in the Software without restriction, including without limitation the rights
11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 | copies of the Software, and to permit persons to whom the Software is
13 | furnished to do so, subject to the following conditions:
14 |
15 | The above copyright notice and this permission notice shall be included in all
16 | copies or substantial portions of the Software.
17 |
18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 | SOFTWARE.
25 | */
26 |
27 | #ifndef __PINCONFIG_H
28 | #define __PINCONFIG_H
29 |
30 | // GPIOs
31 | #define PIN(i) (1 << i)
32 |
33 | // User I/O
34 | #define DRV_EN_PORT GPIOC
35 | #define DRV_EN_PIN 13
36 | #define LED_PORT GPIOC
37 | #define GLED_PIN 15
38 | #define RLED_PIN 14
39 |
40 | // SPI
41 | #define SPI_PORT GPIOB
42 | #define SPI_MOSI_PIN 5
43 | #define SPI_MISO_PIN 4
44 | #define SPI_SCK_PIN 3
45 | #define SPI_CS_PIN 9
46 | #define SPI_AF (5U) // SPI1_MISO/MOSI/SCK
47 |
48 | // Hall Sensor
49 | #define HALL_PORT GPIOB
50 | #define HALL_A_PIN 6
51 | #define HALL_B_PIN 7
52 | #define HALL_C_PIN 8 // Note: PB8 is shared with BOOT0. This feature must be
53 | // disabled otherwise the MCU may randomly start up in
54 | // bootloader mode.
55 | #define HALL_AF (2U) // TIM4 Alternate Function
56 |
57 | // PWM
58 | #define PWM_HI_PORT GPIOA
59 | #define PWM_LO_PORT GPIOB
60 | #define PWM_BKIN_PORT GPIOA
61 | #define PWM_AHI_PIN 8
62 | #define PWM_BHI_PIN 9
63 | #define PWM_CHI_PIN 10
64 | #define PWM_ALO_PIN 13
65 | #define PWM_BLO_PIN 14
66 | #define PWM_CLO_PIN 15
67 | #define PWM_BKIN_PIN 15
68 | #define PWM_AHI_AF (6U) // TIM1_CH1
69 | #define PWM_BHI_AF (6U) // TIM1_CH2
70 | #define PWM_CHI_AF (6U) // TIM1_CH3
71 | #define PWM_ALO_AF (6U) // TIM1_CH1N
72 | #define PWM_BLO_AF (6U) // TIM1_CH2N
73 | #define PWM_CLO_AF (4U) // TIM1_CH3N
74 | #define PWM_BKIN_AF (9U) // TIM1_BKIN
75 |
76 | // UART
77 | #define HBD_UART_PORT GPIOA
78 | #define HBD_UART_TX_PIN 2
79 | #define HBD_UART_RX_PIN 3
80 | #define HBD_UART_AF (7U) // USART2_TX/RX
81 | #define BMS_UART_PORT GPIOB
82 | #define BMS_UART_TX_PIN 10
83 | #define BMS_UART_RX_PIN 11
84 | #define BMS_UART_AF (7U) // USART3_TX/RX
85 |
86 | // ADC
87 | #define ADC_MTEMP_PORT GPIOF
88 | #define ADC_MTEMP_PIN 0
89 | #define ADC_FTEMP_PORT GPIOF
90 | #define ADC_FTEMP_PIN 1
91 | #define ADC_IA_PORT GPIOB
92 | #define ADC_IA_PIN 0
93 | #define ADC_IB_PORT GPIOA
94 | #define ADC_IB_PIN 1
95 | #define ADC_IC_PORT GPIOA
96 | #define ADC_IC_PIN 0
97 | #define ADC_VA_PORT GPIOA
98 | #define ADC_VA_PIN 6
99 | #define ADC_VB_PORT GPIOA
100 | #define ADC_VB_PIN 7
101 | #define ADC_VC_PORT GPIOB
102 | #define ADC_VC_PIN 1
103 | #define ADC_THR_PORT GPIOB
104 | #define ADC_THR_PIN 2
105 | #define ADC_VBUS_PORT GPIOB
106 | #define ADC_VBUS_PIN 12
107 |
108 | // DAC
109 | #define DAC_PORT GPIOA
110 | #define DAC1_PIN 4
111 | #define DAC2_PIN 5
112 |
113 | // USB
114 | #define USB_PORT GPIOA
115 | #define USB_DM_PIN 11
116 | #define USB_DP_PIN 12
117 |
118 | // Unused Pins
119 | // None!
120 |
121 | #endif //__PINCONFIG_H
122 |
--------------------------------------------------------------------------------
/ebike-g4/include/power_calcs.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: power_calcs.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2021 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef _POWER_CALCS_H_
27 | #define _POWER_CALCS_H_
28 |
29 | #define ONE_OVER_SQRT3_F (0.57735026918962576451f)
30 | // Needs some filtering on the magnitude of power and current
31 | // Using a simple low-pass filter, about 20Hz bandwidth
32 | #define POWER_CALCS_LPF_MULTIPLIER (0.07f)
33 |
34 | typedef struct _PowerCalcs {
35 | // Inputs
36 | float Ta;
37 | float Tb;
38 | float Tc;
39 | float Vbus;
40 | float Ialpha;
41 | float Ibeta;
42 | // Outputs
43 | float TotalPower;
44 | float PhaseCurrent;
45 | float BatteryCurrent;
46 | } PowerCalcs;
47 |
48 | void power_calc(PowerCalcs* pc);
49 |
50 | #endif
51 |
--------------------------------------------------------------------------------
/ebike-g4/include/pwm.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: pwm.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef PWM_H_
27 | #define PWM_H_
28 |
29 | /********** Timer defines ***********/
30 |
31 | #define PWM_MIN_FREQ (5000)
32 | #define PWM_MAX_FREQ (40000)
33 |
34 | #define PWM_PERIOD (4249) // 170MHz / (4249+1) = 40kHz -> 20kHz due to up/down counting
35 | #define PWM_PERIOD_F (4249.0f)
36 |
37 | /** Deadtime register settings **
38 | * DTG[7:5]=0xx => DT=DTG[7:0]x Tdtg with tdtg=Tdts.
39 | * DTG[7:5]=10x => DT=(64+DTG[5:0])xTdtg with Tdtg=2xTdts.
40 | * DTG[7:5]=110 => DT=(32+DTG[4:0])xTdtg with Tdtg=8xTdts.
41 | * DTG[7:5]=111 => DT=(32+DTG[4:0])xTdtg with Tdtg=16xTdts.
42 | *
43 | * Tdts = 1/170MHz, since TIM_CR1_CKD = 2'b00 (Tdts = Ttim_ker_clk = 170MHz)
44 | *
45 | * If Tdts = 1/170MHz, then:
46 | * DTG[7:5]=0xx => DT=DTG[7:0]x 5.882ns (range: 0 -> 747.1ns)
47 | * DTG[7:5]=10x => DT=(64+DTG[5:0])x 11.765ns (range: 752.9 -> 1494.1ns)
48 | * DTG[7:5]=110 => DT=(32+DTG[4:0])x 47.059ns (range: 1505.9 -> 2964.7ns)
49 | * DTG[7:5]=111 => DT=(32+DTG[4:0])x 94.118ns (range: 3011.8 -> 5929.4ns)
50 | */
51 |
52 |
53 |
54 | #define DT_RANGE1_MAX 747
55 | #define DT_RANGE2_MAX 1494
56 | #define DT_RANGE3_MAX 2964
57 | #define DT_RANGE4_MAX 5929
58 |
59 | #define PWM_DEFAULT_DT_NS 500
60 | // Default setting is 500ns ... 170MHz / 85 = 2MHz -> 0.5us
61 | // Setting is therefore 85 -> DTG[7:0] = '01010101' (bits 6, 4, 2, and 0)
62 | #define PWM_DEFAULT_DT_REG (TIM_BDTR_DTG_6 | TIM_BDTR_DTG_4 | TIM_BDTR_DTG_2 | TIM_BDTR_DTG_0)
63 | #define PWM_MIN_DT_NS 10
64 | #define PWM_MAX_DT_NS DT_RANGE4_MAX
65 |
66 | /********** Functions **************/
67 |
68 | void PWM_Init(int32_t freq);
69 | void PWM_SetDuty(uint16_t tA, uint16_t tB, uint16_t tC);
70 | void PWM_SetDutyF(float tA, float tB, float tC);
71 | uint8_t PWM_SetDeadTime(int32_t newDT);
72 | int32_t PWM_GetDeadTime(void);
73 | uint8_t PWM_SetFreq(int32_t freq);
74 | int32_t PWM_GetFreq(void);
75 |
76 | /* Defines for directly changing PWM outputs */
77 |
78 | #define PWM_MotorON() PWM_TIM->BDTR |= (TIM_BDTR_MOE)
79 | #define PWM_MotorOFF() PWM_TIM->BDTR &= ~(TIM_BDTR_MOE)
80 |
81 | // PWM: OC mode is "PWM Mode 1", outputs enabled
82 | inline void PHASE_C_PWM(void) {
83 | PWM_TIM->CCMR1 &= ~(TIM_CCMR1_OC1M);
84 | PWM_TIM->CCMR1 |= (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1);
85 | PWM_TIM->CCER |= (TIM_CCER_CC1E | TIM_CCER_CC1NE);
86 | }
87 | // Low side on: OC mode is "Force inactive level", outputs enabled
88 | inline void PHASE_C_LOW(void) {
89 | PWM_TIM->CCMR1 &= ~(TIM_CCMR1_OC1M);
90 | PWM_TIM->CCMR1 |= (TIM_CCMR1_OC1M_2);
91 | PWM_TIM->CCER |= (TIM_CCER_CC1E | TIM_CCER_CC1NE);
92 | }
93 | // Phase off: OC mode is "Force inactive", high-side output disabled, low-side enabled (will be outputting low)
94 | inline void PHASE_C_OFF(void) {
95 | PWM_TIM->CCMR1 &= ~(TIM_CCMR1_OC1M);
96 | PWM_TIM->CCMR1 |= (TIM_CCMR1_OC1M_2);
97 | PWM_TIM->CCER &= ~(TIM_CCER_CC1E);
98 | PWM_TIM->CCER |= (TIM_CCER_CC1NE);
99 | }
100 |
101 | inline void PHASE_B_PWM(void) {
102 | PWM_TIM->CCMR1 &= ~(TIM_CCMR1_OC2M);
103 | PWM_TIM->CCMR1 |= (TIM_CCMR1_OC2M_2 | TIM_CCMR1_OC2M_1);
104 | PWM_TIM->CCER |= (TIM_CCER_CC2E | TIM_CCER_CC2NE);
105 | }
106 | inline void PHASE_B_LOW(void) {
107 | PWM_TIM->CCMR1 &= ~(TIM_CCMR1_OC2M);
108 | PWM_TIM->CCMR1 |= (TIM_CCMR1_OC2M_2);
109 | PWM_TIM->CCER |= (TIM_CCER_CC2E | TIM_CCER_CC2NE);
110 | }
111 |
112 | inline void PHASE_B_OFF(void) {
113 | PWM_TIM->CCMR1 &= ~(TIM_CCMR1_OC2M);
114 | PWM_TIM->CCMR1 |= (TIM_CCMR1_OC2M_2);
115 | PWM_TIM->CCER &= ~(TIM_CCER_CC2E);
116 | PWM_TIM->CCER |= (TIM_CCER_CC2NE);
117 | }
118 |
119 | inline void PHASE_A_PWM(void) {
120 | PWM_TIM->CCMR2 &= ~(TIM_CCMR2_OC3M);
121 | PWM_TIM->CCMR2 |= (TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1);
122 | PWM_TIM->CCER |= (TIM_CCER_CC3E | TIM_CCER_CC3NE);
123 | }
124 |
125 | inline void PHASE_A_LOW(void) {
126 | PWM_TIM->CCMR2 &= ~(TIM_CCMR2_OC3M);
127 | PWM_TIM->CCMR2 |= (TIM_CCMR2_OC3M_2);
128 | PWM_TIM->CCER |= (TIM_CCER_CC3E | TIM_CCER_CC3NE);
129 | }
130 |
131 | inline void PHASE_A_OFF(void) {
132 | PWM_TIM->CCMR2 &= ~(TIM_CCMR2_OC3M);
133 | PWM_TIM->CCMR2 |= (TIM_CCMR2_OC3M_2);
134 | PWM_TIM->CCER &= ~(TIM_CCER_CC3E);
135 | PWM_TIM->CCER |= (TIM_CCER_CC3NE);
136 | }
137 |
138 | #endif /* PWM_H_ */
139 |
--------------------------------------------------------------------------------
/ebike-g4/include/throttle.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: throttle.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef _THROTTLE_H_
27 | #define _THROTTLE_H_
28 |
29 | typedef struct _throttle_type {
30 | uint8_t state;
31 | float raw_voltage;
32 | float throttle_command;
33 | float prev_output;
34 | float hyst;
35 | float filt;
36 | float rise;
37 | float resistor_ratio;
38 | } Throttle_Type;
39 |
40 | typedef struct _throttle_analog {
41 | uint16_t flags;
42 | uint16_t startup_counter;
43 | float min;
44 | float max;
45 | float scale_factor;
46 | } Throttle_Analog_Type;
47 |
48 | // Definition of flags for analog throttle
49 | #define THR_FLAG_STARTUP_COMPLETE (0x0001)
50 | // Duration of time (in throttle ticks - usually 1ms) to wait for throttle to steady out
51 | #define THR_STARTUP_TIMER_DURATION (300)
52 |
53 | #define THROTTLE_DEFAULTS { 0, 0.0f, 0.0f, 0.0f, \
54 | DFLT_THRT_HYST, DFLT_THRT_FILT, \
55 | DFLT_THRT_RISE, DFLT_THRT_RATIO}
56 | #define THROTTLE_ANALOG_DEFAULTS {0, 0, 0.0f, 0.0f, 1.0f}
57 | // Biquad filter: Fs = 1kHz, f0 = 2Hz, Q = 0.45
58 | // Little bit sluggish response. Maybe feels safer?
59 | #define THROTTLE_LPF_DEFAULTS { \
60 | -1.972304f, \
61 | 0.9724600f, \
62 | 0.00003893429f, \
63 | 0.00007786857f, \
64 | 0.00003893429f, \
65 | 0.0f, \
66 | 0.0f, \
67 | 0.0f, \
68 | 0.0f }
69 |
70 | #define THROTTLE_OUTPUT_MIN (0.00f)
71 | #define THROTTLE_OUTPUT_MAX (0.99f)
72 | #define THROTTLE_HYST_MIN (0.005f)
73 | #define THROTTLE_HYST_MAX (0.1f)
74 | #define THROTTLE_FILT_MIN (0.1f)
75 | #define THROTTLE_FILT_MAX (499.9f)
76 | #define THROTTLE_FILT_Q_DEFAULT (0.707f)
77 | #define THROTTLE_SAMPLING_RATE (1000.0f)
78 | #define THROTTLE_RISE_MIN (0.00005f) // Minimum of 5% / sec
79 | #define THROTTLE_RISE_MAX (0.01f) // Maximum of 1000% / sec
80 | #define THROTTLE_RATIO_MIN (1.0f) // Minimum of 1.0 - a resistor divider cannot increase the voltage
81 | #define THROTTLE_RATIO_MAX (6.0f) // I don't know what kind of crazy throttle needs to have range up to 20V, but whatever.
82 |
83 | void THROTTLE_Init(void);
84 | void THROTTLE_Process(void);
85 | float THROTTLE_GetCommand(void);
86 | float THROTTLE_GetRaw(void);
87 |
88 | uint8_t THROTTLE_SetMin(float thrmin);
89 | float THROTTLE_GetMin(void);
90 | uint8_t THROTTLE_SetMax(float thrmax);
91 | float THROTTLE_GetMax(void);
92 | uint8_t THROTTLE_SetHyst(float thrhyst);
93 | float THROTTLE_GetHyst(void);
94 | uint8_t THROTTLE_SetFilt(float thrfilt);
95 | float THROTTLE_GetFilt(void);
96 | uint8_t THROTTLE_SetRise(float thrrise);
97 | float THROTTLE_GetRise(void);
98 | uint8_t THROTTLE_SetRatio(float thrratio);
99 | float THROTTLE_GetRatio(void);
100 |
101 | uint8_t uiTHRT_GetMin(uint8_t* valptr);
102 | uint8_t uiTHRT_SetMin(uint8_t* valptr);
103 | uint8_t uiTHRT_GetMax(uint8_t* valptr);
104 | uint8_t uiTHRT_SetMax(uint8_t* valptr);
105 | uint8_t uiTHRT_GetHyst(uint8_t* valptr);
106 | uint8_t uiTHRT_SetHyst(uint8_t* valptr);
107 | uint8_t uiTHRT_GetFilt(uint8_t* valptr);
108 | uint8_t uiTHRT_SetFilt(uint8_t* valptr);
109 | uint8_t uiTHRT_GetRise(uint8_t* valptr);
110 | uint8_t uiTHRT_SetRise(uint8_t* valptr);
111 | uint8_t uiTHRT_GetRatio(uint8_t* valptr);
112 | uint8_t uiTHRT_SetRatio(uint8_t* valptr);
113 |
114 | void THROTTLE_SaveVariables(void);
115 | void THROTTLE_LoadVariables(void);
116 |
117 | #endif /* _THROTTLE_H_ */
118 |
119 |
--------------------------------------------------------------------------------
/ebike-g4/include/uart.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: uart.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | // Used resources:
27 | // USART2, USART3
28 | #ifndef UART_H_
29 | #define UART_H_
30 |
31 | #define HBD_BAUDRATE (38400)
32 | #define HBD_USARTDIV (4427) // about 0.002% error (170MHz / 4427 = 38.4007kHz)
33 | #define HBD_OVER8 (0)
34 | #define HBD_BRR (4427)
35 |
36 | #define BMS_BAUDRATE 115200
37 | #define BMS_USARTDIV (1476) // about 0.02% error (170MHz / 1476 = 115.176kHz)
38 | #define BMS_OVER8 (0)
39 | #define BMS_BRR (1476)
40 |
41 | #define HBD_BUFFER_LENGTH 128
42 | #define HBD_TXMT_TIMEOUT 3 // ms
43 |
44 | #define BMS_BUFFER_LENGTH 128
45 | #define BMS_TXMT_TIMEOUT 3 // ms
46 |
47 | typedef enum _uart_sel{
48 | SELECT_HBD_UART,
49 | SELECT_BMS_UART
50 | } UART_Sel;
51 |
52 | typedef struct _uart_buffer{
53 | uint8_t Buffer[HBD_BUFFER_LENGTH];
54 | uint8_t RdPos, WrPos;
55 | uint8_t Done;
56 | } UARTBuffer_Type;
57 |
58 |
59 | uint16_t UART_CalcBRR(uint32_t fck, uint32_t baud, uint8_t over8);
60 |
61 | void UART_Init(void);
62 | int32_t UART_InWaiting(UART_Sel uart);
63 | uint8_t UART_IsFinishedTx(UART_Sel uart);
64 | int32_t UART_Read(UART_Sel uart, void* buf, uint32_t count);
65 | int32_t UART_Write(UART_Sel uart, void* buf, uint32_t count);
66 |
67 | void UART_IRQ(UART_Sel uart);
68 |
69 | #endif // UART_H_
70 |
--------------------------------------------------------------------------------
/ebike-g4/include/usb_cdc.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: usb_cdc.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef USB_CDC_H_
27 | #define USB_CDC_H_
28 |
29 | #include "usb.h"
30 |
31 | #define DATA_OUT_EP 1
32 | #define DATA_IN_EP 1
33 | #define CMD_IN_EP 2
34 |
35 | #define DATA_ENDPOINT_FIFO_SIZE 64
36 | #define CMD_ENDPOINT_FIFO_SIZE 8
37 |
38 | #define DEVICE_ID1 (0x1FFF7590)
39 | #define DEVICE_ID2 (0x1FFF7594)
40 | #define DEVICE_ID3 (0x1FFF7598)
41 |
42 | #define USB_SIZ_STRING_SERIAL 0x1A
43 |
44 | #define USB_VID 0x0483
45 | #define USB_PID 0x5740
46 | #define USB_LANGID_STRING 0x409
47 | #define USB_MANUFACTURER_STRING "STMicroelectronics"
48 | #define USB_PRODUCT_HS_STRING "STM32 Virtual ComPort in HS Mode"
49 | #define USB_PRODUCT_FS_STRING "STM32 Virtual ComPort in FS Mode"
50 | #define USB_CONFIGURATION_HS_STRING "VCP Config"
51 | #define USB_INTERFACE_HS_STRING "VCP Interface"
52 | #define USB_CONFIGURATION_FS_STRING "VCP Config"
53 | #define USB_INTERFACE_FS_STRING "VCP Interface"
54 | #define USB_MAX_NUM_INTERFACES 1
55 | #define USB_MAX_NUM_CONFIGURATION 1
56 | #define USB_MAX_STR_DESC_SIZ 0x100
57 |
58 | #define CDC_SEND_ENCAPSULATED_COMMAND 0x00
59 | #define CDC_GET_ENCAPSULATED_RESPONSE 0x01
60 | #define CDC_SET_COMM_FEATURE 0x02
61 | #define CDC_GET_COMM_FEATURE 0x03
62 | #define CDC_CLEAR_COMM_FEATURE 0x04
63 | #define CDC_SET_LINE_CODING 0x20
64 | #define CDC_GET_LINE_CODING 0x21
65 | #define CDC_SET_CONTROL_LINE_STATE 0x22
66 | #define CDC_SEND_BREAK 0x23
67 |
68 | typedef struct _usbd_cdc_handle {
69 | uint32_t data[CDC_CMD_PACKET_SIZE * 2]; // Buffer for control transfers
70 | uint8_t CmdOpCode;
71 | uint8_t CmdLength;
72 | uint8_t *RxBuffer;
73 | uint8_t *TxBuffer;
74 | uint32_t RxLength;
75 | uint32_t TxLength;
76 |
77 | volatile uint32_t TxState;
78 | volatile uint32_t RxState;
79 |
80 | void (*App_TxCompleteCallback)(void);
81 | } USBD_CDC_HandleTypeDef;
82 |
83 | typedef struct _usbd_cdc_linecoding {
84 | uint32_t bitrate;
85 | uint8_t format;
86 | uint8_t paritytype;
87 | uint8_t datatype;
88 | } USBD_CDC_LineCodingTypeDef;
89 |
90 | typedef struct _usbd_cdc_rxbuffer {
91 | uint8_t Buffer[DATA_ENDPOINT_FIFO_SIZE];
92 | int Position, Size;
93 | char ReadDone;
94 | } USB_CDC_RxBufferTypedef;
95 |
96 | extern USB_ClassDescTypedef USB_CDC_ClassDesc;
97 | extern USB_ClassCallbackTypedef USB_CDC_ClassCallbacks;
98 |
99 | uint8_t* CDC_DeviceDescriptor(uint16_t* len);
100 | uint8_t* CDC_ConfigDescriptor(uint16_t* len);
101 | uint8_t* CDC_LangIDStrDescriptor(uint16_t* len);
102 | uint8_t* CDC_ManufacturerStrDescriptor(uint16_t* len);
103 | uint8_t* CDC_ProductStrDescriptor(uint16_t* len);
104 | uint8_t* CDC_SerialStrDescriptor(uint16_t* len);
105 | uint8_t* CDC_ConfigurationStrDescriptor(uint16_t* len);
106 | uint8_t* CDC_InterfaceStrDescriptor(uint16_t* len);
107 |
108 | void CDC_Init(uint8_t configNum);
109 | void CDC_DeInit(void);
110 | void CDC_Connect(void);
111 | void CDC_Disconnect(void);
112 | void CDC_Reset(void);
113 | void CDC_Setup(USB_SetupReqTypedef* stp);
114 | void CDC_EP0_RxReady(void);
115 | void CDC_DataIn(uint8_t epnum);
116 | void CDC_DataOut(uint8_t epnum);
117 | void CDC_Itf_Control(uint8_t cmd, uint8_t* pbuf, uint16_t length);
118 | void CDC_SetTxCompleteCallback(void (*Callback)(void));
119 |
120 | int32_t VCP_InWaiting(void);
121 | int32_t VCP_Read(void* data, int32_t len);
122 | int32_t VCP_Write(const void* data, int32_t len);
123 |
124 | #endif /* USB_CDC_H_ */
125 |
--------------------------------------------------------------------------------
/ebike-g4/include/usb_data_comm.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: usb_data_comm.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | #ifndef _USB_DATA_COMM_H_
27 | #define _USB_DATA_COMM_H_
28 |
29 | void USB_Data_Comm_Init(void);
30 | void USB_Data_Comm_OneByte_Check(void);
31 | void USB_Data_Comm_Periodic_Check(void);
32 |
33 | #endif //_USB_DATA_COMM_H_
34 |
--------------------------------------------------------------------------------
/ebike-g4/include/wdt.h:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: wdt.h
3 | ******************************************************************************
4 |
5 | Copyright (c) 2020 David Miller
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 | */
25 |
26 | // Used resources:
27 | // IWDG
28 | #ifndef WDT_H_
29 | #define WDT_H_
30 |
31 | #define IWDG_RELOAD ((uint32_t)0x0000AAAAu)
32 | #define IWDG_KEY ((uint32_t)0x00005555u)
33 | #define IWDG_START ((uint32_t)0x0000CCCCu)
34 |
35 | #define IWDG_PSC ((uint32_t)0x00000000u) // For about 125usec granularity (32kHz/4)
36 | #define IWDG_REL_VAL ((uint32_t)400) // 125usec * 400 = 50msec
37 |
38 | void WDT_Init(void);
39 | void WDT_Feed(void);
40 |
41 | #endif //WDT_H_
42 |
--------------------------------------------------------------------------------
/ebike-g4/ldscripts/libs.ld:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * Placeholder to list other libraries required by the application.
4 |
5 | GROUP(
6 | )
7 |
8 | */
9 |
--------------------------------------------------------------------------------
/ebike-g4/ldscripts/mem.ld:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | /*
29 | * Memory Spaces Definitions.
30 | *
31 | * Need modifying for a specific board.
32 | * FLASH.ORIGIN: starting address of flash
33 | * FLASH.LENGTH: length of flash
34 | * RAM.ORIGIN: starting address of RAM bank 0
35 | * RAM.LENGTH: length of RAM bank 0
36 | *
37 | * The values below can be addressed in further linker scripts
38 | * using functions like 'ORIGIN(RAM)' or 'LENGTH(RAM)'.
39 | */
40 |
41 | MEMORY
42 | {
43 | FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
44 | RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 96K
45 | CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 32K
46 |
47 | /*
48 | * Optional sections; define the origin and length to match
49 | * the the specific requirements of your hardware. The zero
50 | * length prevents inadvertent allocation.
51 | */
52 |
53 | FLASHB1 (rx) : ORIGIN = 0x00000000, LENGTH = 0
54 | EXTMEMB0 (rx) : ORIGIN = 0x00000000, LENGTH = 0
55 | EXTMEMB1 (rx) : ORIGIN = 0x00000000, LENGTH = 0
56 | EXTMEMB2 (rx) : ORIGIN = 0x00000000, LENGTH = 0
57 | EXTMEMB3 (rx) : ORIGIN = 0x00000000, LENGTH = 0
58 | }
59 |
60 | /*
61 | * For external ram use something like:
62 | * RAM (xrw) : ORIGIN = 0x64000000, LENGTH = 2048K
63 | *
64 | * For special RAM areas use something like:
65 | * MEMORY_ARRAY (xrw) : ORIGIN = 0x20002000, LENGTH = 32
66 | */
67 |
--------------------------------------------------------------------------------
/ebike-g4/src/_write.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // Do not include on semihosting and when freestanding
29 | #if !defined(OS_USE_SEMIHOSTING) && !(__STDC_HOSTED__ == 0)
30 |
31 | // ----------------------------------------------------------------------------
32 |
33 | #include
34 | #include "diag/Trace.h"
35 |
36 | // ----------------------------------------------------------------------------
37 |
38 | // When using retargetted configurations, the standard write() system call,
39 | // after a long way inside newlib, finally calls this implementation function.
40 |
41 | // Based on the file descriptor, it can send arrays of characters to
42 | // different physical devices.
43 |
44 | // Currently only the output and error file descriptors are tested,
45 | // and the characters are forwarded to the trace device, mainly
46 | // for demonstration purposes. Adjust it for your specific needs.
47 |
48 | // For freestanding applications this file is not used and can be safely
49 | // ignored.
50 |
51 | ssize_t
52 | _write (int fd, const char* buf, size_t nbyte);
53 |
54 | ssize_t
55 | _write (int fd __attribute__((unused)), const char* buf __attribute__((unused)),
56 | size_t nbyte __attribute__((unused)))
57 | {
58 | #if defined(TRACE)
59 | // STDOUT and STDERR are routed to the trace device
60 | if (fd == 1 || fd == 2)
61 | {
62 | return trace_write (buf, nbyte);
63 | }
64 | #endif // TRACE
65 |
66 | errno = ENOSYS;
67 | return -1;
68 | }
69 |
70 | // ----------------------------------------------------------------------------
71 |
72 | #endif // !defined(OS_USE_SEMIHOSTING) && !(__STDC_HOSTED__ == 0)
73 |
--------------------------------------------------------------------------------
/ebike-g4/src/cordic_sin_cos.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: crc32.c
3 | * Description: Uses the STM32 built-in CORDIC co-processor to calculate sin
4 | * and cos of an input angle.
5 | ******************************************************************************
6 |
7 | Copyright (c) 2020 David Miller
8 |
9 | Permission is hereby granted, free of charge, to any person obtaining a copy
10 | of this software and associated documentation files (the "Software"), to deal
11 | in the Software without restriction, including without limitation the rights
12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | copies of the Software, and to permit persons to whom the Software is
14 | furnished to do so, subject to the following conditions:
15 |
16 | The above copyright notice and this permission notice shall be included in all
17 | copies or substantial portions of the Software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 | SOFTWARE.
26 | */
27 |
28 | #include "main.h"
29 | /**
30 | * @brief Initializes the CORDIC peripheral. Sin/Cos mode is used.
31 | */
32 | void CORDIC_Init(void) {
33 | volatile uint32_t dummy;
34 | // Turn on the clock
35 | RCC->AHB1ENR |= RCC_AHB1ENR_CORDICEN;
36 |
37 | // Initialize the needed function (sin/cos)
38 | // Also pump in one dummy calculation to set the second input variable (modulus m)
39 | // to one, which won't be changed in later calculations
40 | CORDIC->CSR = CORDIC_CSR_NARGS // 2 input arguments
41 | | CORDIC_CSR_NRES // 2 output arguments
42 | | CORDIC_CSR_PRECISION_0 | CORDIC_CSR_PRECISION_2 // 5 cycles, 20 iterations, error < 2^-18
43 | | CORDIC_CSR_FUNC_0; // Function 1 - sine
44 |
45 |
46 | // Enter in the dummy calculation
47 | CORDIC->WDATA = 0x80000000u; // Arg 1 = angle, about 0.5, which means pi/2
48 | CORDIC->WDATA = 0x7FFFFFFFu; // Arg 2 = modulus, 1. This won't be changed again later.
49 |
50 | // Read out the results.
51 | dummy = CORDIC->RDATA;
52 | (void)dummy; // So compiler doesn't complain about "set but not used"
53 | dummy = CORDIC->RDATA;
54 | (void)dummy;
55 | // Can change to single input argument now.
56 | CORDIC->CSR &= ~(CORDIC_CSR_NARGS);
57 |
58 | }
59 |
60 | #if(USE_DEFINE_CONVERSIONS == 0)
61 | int32_t float_to_q31(float input) {
62 | int32_t retval;
63 | asm( "VCVT.S32.F32 %1, %1, #31\n\t"
64 | "VMOV %0, %1"
65 | :"=r" (retval)
66 | :"t" (input)
67 | :);
68 | return retval;
69 | }
70 |
71 | float q31_to_float(int32_t input) {
72 | float retval;
73 | asm( "VMOV %0, %1\n\t"
74 | "VCVT.F32.S32 %0, %0, #31"
75 | :"=t"(retval)
76 | :"r"(input)
77 | :);
78 | return retval;
79 | }
80 | #endif
81 |
82 | /**
83 | * @brief Calculates sin(theta) and cos(theta) using the CORDIC peripheral.
84 | * @param theta: input angle in range [-1,1), which is scaled to [-pi, pi)
85 | * @param sin: pointer to sin(theta) result
86 | * @param cos: pointer to cos(theta) result
87 | * @retval None
88 | */
89 | void CORDIC_CalcSinCos(float theta, float* sin, float* cos) {
90 | int32_t fxd_input, fxd_sin, fxd_cos;
91 | // fxd_input = (int32_t) (theta * 2147483648.0f); // Multiply by 0x80000000 = 2147483648
92 | #if(USE_DEFINE_CONVERSIONS == 1)
93 | float_to_q31_def(theta, fxd_input);
94 | #else
95 | fxd_input = float_to_q31(theta);
96 | #endif
97 |
98 | CORDIC->WDATA = fxd_input;
99 |
100 | // Get the results
101 | fxd_sin = CORDIC->RDATA; // Inserts wait states until result is ready
102 | fxd_cos = CORDIC->RDATA;
103 |
104 | // *sin = ((float)fxd_sin) / (2147483648.0f);
105 | // *cos = ((float)fxd_cos) / (2147483648.0f);
106 | #if(USE_DEFINE_CONVERSIONS == 1)
107 | q31_to_float_def(fxd_sin, sin);
108 | q31_to_float_def(fxd_cos, cos);
109 | #else
110 | *sin = q31_to_float(fxd_sin);
111 | *cos = q31_to_float(fxd_cos);
112 | #endif
113 | }
114 |
115 | /**
116 | * @brief Launches sin(theta) and cos(theta) calculation, result read later with CORDIC_GetResult.
117 | * @param theta: input angle in range [-1,1), which is scaled to [-pi, pi)
118 | * @retval None
119 | */
120 | void CORDIC_CalcSinCosDeferred(float theta) {
121 | int32_t fxd_input;
122 | #if(USE_DEFINE_CONVERSIONS == 1)
123 | float_to_q31_def(theta, fxd_input);
124 | #else
125 | fxd_input = float_to_q31(theta);
126 | #endif
127 | // fxd_input = (int32_t) (theta * 1073741824.0f); // Multiply by 0x80000000
128 | CORDIC->WDATA = fxd_input;
129 | }
130 |
131 | /**
132 | * @brief Gets the results of a previous CORDIC_CalcSinCosDeferred function call.
133 | * @param sin: pointer to sin(theta) result
134 | * @param cos: pointer to cos(theta) result
135 | * @retval None
136 | */
137 | void CORDIC_GetResults(float* sin, float* cos) {
138 | int32_t fxd_sin, fxd_cos;
139 | fxd_sin = CORDIC->RDATA; // Inserts wait states until result is ready
140 | fxd_cos = CORDIC->RDATA;
141 |
142 | #if(USE_DEFINE_CONVERSIONS == 1)
143 | q31_to_float_def(fxd_sin, sin);
144 | q31_to_float_def(fxd_cos, cos);
145 | #else
146 | *sin = q31_to_float(fxd_sin);
147 | *cos = q31_to_float(fxd_cos);
148 | #endif
149 |
150 | // *sin = ((float)fxd_sin) / (1073741824.0f);
151 | // *cos = ((float)fxd_cos) / (1073741824.0f);
152 | }
153 |
--------------------------------------------------------------------------------
/ebike-g4/src/crc.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: crc32.c
3 | * Description: Uses the STM32 built-in CRC generator, but makes it compliant
4 | * with the CRC-32 used in Ethernet generation. A couple of
5 | * changes are needed. The bits need to be in reverse order for
6 | * each byte, the result is bit-flipped, and the result is
7 | * xor'd with 1's.
8 | * When making a matching function to interface with this
9 | * controller, make sure to pad all input data with 0's so that
10 | * the number of bytes is divisible by 4. Put the extra 0's at
11 | * the end.
12 | * Check with:
13 | * http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
14 | ******************************************************************************
15 |
16 | Copyright (c) 2020 David Miller
17 |
18 | Permission is hereby granted, free of charge, to any person obtaining a copy
19 | of this software and associated documentation files (the "Software"), to deal
20 | in the Software without restriction, including without limitation the rights
21 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22 | copies of the Software, and to permit persons to whom the Software is
23 | furnished to do so, subject to the following conditions:
24 |
25 | The above copyright notice and this permission notice shall be included in all
26 | copies or substantial portions of the Software.
27 |
28 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34 | SOFTWARE.
35 | */
36 |
37 | #include "main.h"
38 |
39 | void CRC_Init(void) {
40 | // Turns on the hardware
41 | RCC->AHB1ENR |= RCC_AHB1ENR_CRCEN;
42 | }
43 |
44 | /**
45 | * @brief Generates a CRC-32 using the Ethernet standard.
46 | *
47 | * Uses bit reversal on input and output, initial
48 | * value is all 1's, and output value is xor'd with
49 | * all 1's. The polynomial is fixed to 0x04C1.1DB7
50 | * @param buf: The input buffer of unsigned bytes
51 | * @param len: Length of input buffer (number of bytes)
52 | * @retval The generated CRC-32 value.
53 | */
54 | uint32_t CRC_Generate_CRC32(uint8_t *buf, uint16_t len) {
55 | uint32_t crc_input;
56 |
57 | // Enable the bit reversals for CRC-32
58 | CRC->CR = CRC_CR_REV_IN | CRC_CR_REV_OUT;
59 | // Set the polynomial
60 | CRC->POL = 0x04C11DB7u;
61 | // Set initial (reset) value
62 | CRC->INIT = 0xFFFFFFFFu;
63 | // Reset the CRC to all 1's
64 | CRC->CR |= CRC_CR_RESET;
65 |
66 |
67 | // Push data in blocks of 4 bytes
68 | while (len >= 4) {
69 | crc_input = ((uint32_t) buf[0]) + (((uint32_t) buf[1]) << 8u)
70 | + (((uint32_t) buf[2]) << 16u) + (((uint32_t) buf[3]) << 24u);
71 | CRC->DR = crc_input;
72 | len -= 4;
73 | buf += 4;
74 | }
75 | switch (len) {
76 | case 0:
77 | // No more to send
78 | return 0xFFFFFFFF ^ (CRC->DR);
79 | case 1:
80 | crc_input = ((uint32_t) buf[0]);
81 | CRC->DR = crc_input;
82 | return 0xFFFFFFFF ^ (CRC->DR);
83 | case 2:
84 | crc_input = ((uint32_t) buf[0]) + (((uint32_t) buf[1]) << 8);
85 | CRC->DR = crc_input;
86 | return 0xFFFFFFFF ^ (CRC->DR);
87 | case 3:
88 | crc_input = ((uint32_t) buf[0]) + (((uint32_t) buf[1]) << 8)
89 | + (((uint32_t) buf[2]) << 16);
90 | CRC->DR = crc_input;
91 | return 0xFFFFFFFF ^ (CRC->DR);
92 | default:
93 | // This shouldn't happen. So no special error fixing, just return what
94 | // we got at this point.
95 | return 0xFFFFFFFF ^ (CRC->DR);
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/ebike-g4/src/delay.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: delay.c
3 | * Description: Provides an easy millisecond delay routine. Also includes a
4 | * tick counter of milliseconds elapsed since power on, or since
5 | * the last 32-bit counter rollover (about 4.3 million seconds,
6 | * or 1,193 hours)
7 | ******************************************************************************
8 |
9 | Copyright (c) 2020 David Miller
10 |
11 | Permission is hereby granted, free of charge, to any person obtaining a copy
12 | of this software and associated documentation files (the "Software"), to deal
13 | in the Software without restriction, including without limitation the rights
14 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 | copies of the Software, and to permit persons to whom the Software is
16 | furnished to do so, subject to the following conditions:
17 |
18 | The above copyright notice and this permission notice shall be included in all
19 | copies or substantial portions of the Software.
20 |
21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 | SOFTWARE.
28 | */
29 |
30 | #include "main.h"
31 |
32 | volatile uint32_t g_SysTick;
33 |
34 | void DelayInit(void) {
35 | g_SysTick = 0;
36 | SysTick_Config(SYS_CLK / 1000u);
37 | NVIC_SetPriority(SysTick_IRQn, PRIO_SYSTICK);
38 | }
39 |
40 | void Delay(__IO uint32_t Delay) {
41 | volatile uint32_t tickstart = 0;
42 | tickstart = g_SysTick;
43 | while ((g_SysTick - tickstart) < Delay) {
44 | }
45 | }
46 |
47 | uint32_t GetTick(void) {
48 | return g_SysTick;
49 | }
50 |
51 | void SYSTICK_IRQHandler(void) {
52 | g_SysTick++;
53 | }
54 |
--------------------------------------------------------------------------------
/ebike-g4/src/hbd_data_comm.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: hbd_data_comm.c
3 | * Description: Conducts data packet communication between this motor
4 | * controller and the Handle Bar Display (hbd). The hbd is connected
5 | * via UART. The intended device is an Android phone using a Bluetooth
6 | * module (HC-05 serial bluetooth module), but any device with a UART
7 | * connection could work.
8 | *
9 | ******************************************************************************
10 |
11 | Copyright (c) 2021 David Miller
12 |
13 | Permission is hereby granted, free of charge, to any person obtaining a copy
14 | of this software and associated documentation files (the "Software"), to deal
15 | in the Software without restriction, including without limitation the rights
16 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 | copies of the Software, and to permit persons to whom the Software is
18 | furnished to do so, subject to the following conditions:
19 |
20 | The above copyright notice and this permission notice shall be included in all
21 | copies or substantial portions of the Software.
22 |
23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 | SOFTWARE.
30 | */
31 |
32 | #include "main.h"
33 | #include "hbd_data_comm.h"
34 | #include "data_packet.h"
35 | #include "data_commands.h"
36 |
37 | uint8_t HBD_Data_Comm_TxBuffer[PACKET_MAX_LENGTH];
38 | uint8_t HBD_Data_Comm_DataBuffer[PACKET_MAX_DATA_LENGTH];
39 | Data_Packet_Type HBD_Data_Comm_Packet;
40 |
41 | static void HBD_Data_Comm_Process_Command(void);
42 |
43 | /**
44 | * @brief HBD Data Communications Initialization
45 | * Sets packet data to default values.
46 | * @param None
47 | * @retval None
48 | */
49 | void HBD_Data_Comm_Init(void) {
50 | HBD_Data_Comm_Packet.State = DATA_COMM_IDLE;
51 | HBD_Data_Comm_Packet.Data = HBD_Data_Comm_DataBuffer;
52 | HBD_Data_Comm_Packet.TxBuffer = HBD_Data_Comm_TxBuffer;
53 | HBD_Data_Comm_Packet.TxReady = 0;
54 | HBD_Data_Comm_Packet.RxReady = 0;
55 | }
56 |
57 | /**
58 | * @brief HBD Data Communications One Byte Check
59 | * Handles the HBD serial port incoming data. Determines
60 | * if a properly encoded packet has been received, and
61 | * sends to the appropriate handler if it has. Operates
62 | * one byte at a time using an internal state machine.
63 | * @param None
64 | * @retval None
65 | */
66 | void HBD_OneByte_Check(void) {
67 | // Loop through each incoming byte
68 | int32_t numbytes = UART_InWaiting(SELECT_HBD_UART);
69 | uint8_t this_byte;
70 | while(numbytes > 0) {
71 | // Load one new byte
72 | if(UART_Read(SELECT_HBD_UART, &this_byte, 1) != 1) {
73 | // Check that a byte was really received
74 | return;
75 | }
76 | numbytes--;
77 | if(data_packet_extract_one_byte(&HBD_Data_Comm_Packet, this_byte) == DATA_PACKET_SUCCESS) {
78 | if(HBD_Data_Comm_Packet.RxReady == 1) {
79 | // Double checked and good to go
80 | HBD_Data_Comm_Process_Command();
81 | }
82 | }
83 | }
84 | }
85 |
86 | /**
87 | * @brief HBD Data Communications Process Command
88 | * Calls the command processor when a packet has been successfully
89 | * decoded. If a response is generated, it is sent back over the
90 | * HBD serial port.
91 | * @param None
92 | * @retval None
93 | */
94 | static void HBD_Data_Comm_Process_Command(void) {
95 | uint16_t errCode = data_process_command(&HBD_Data_Comm_Packet);
96 | if ((errCode == DATA_PACKET_SUCCESS) && HBD_Data_Comm_Packet.TxReady) {
97 | uint8_t* send_buffer = HBD_Data_Comm_Packet.TxBuffer;
98 | uint16_t len_to_send = HBD_Data_Comm_Packet.TxLength;
99 | uint16_t actually_sent = 0;
100 | while (len_to_send > 0) {
101 | actually_sent = UART_Write(SELECT_HBD_UART, send_buffer, len_to_send);
102 | len_to_send -= actually_sent;
103 | send_buffer += actually_sent;
104 | }
105 | HBD_Data_Comm_Packet.TxReady = 0;
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/ebike-g4/src/interrupts.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: interrupts.c
3 | * Description: Interrupt request handlers, aka interrupt service routines
4 | * (ISRs). When a processor interrupt is triggered, code execution
5 | * immediately jumps to the associated handler where software
6 | * clears the interrupt source, preventing the handler from being
7 | * re-triggered, and performs any necessary tasks.
8 | ******************************************************************************
9 |
10 | Copyright (c) 2020 David Miller
11 |
12 | Permission is hereby granted, free of charge, to any person obtaining a copy
13 | of this software and associated documentation files (the "Software"), to deal
14 | in the Software without restriction, including without limitation the rights
15 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 | copies of the Software, and to permit persons to whom the Software is
17 | furnished to do so, subject to the following conditions:
18 |
19 | The above copyright notice and this permission notice shall be included in all
20 | copies or substantial portions of the Software.
21 |
22 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 | SOFTWARE.
29 | */
30 |
31 | #include "main.h"
32 |
33 | /**
34 | * Handlers for System events
35 | * Most of the default handlers are used for things like hard fault, etc
36 | * Only SysTick handler is customized.
37 | */
38 |
39 | void SysTick_Handler (void) {
40 | // No flags to clear. Jump straight to the handler in delay.c
41 | SYSTICK_IRQHandler();
42 | }
43 |
44 | /**
45 | * Handlers for ADC.
46 | * The active interrupts are:
47 | * - ADC1 injected end of sequence (JEOS)
48 | * - ADC3 injected end of sequence (JEOS)
49 | * - DMA1 Channel 1 end of transfer (TCIF)
50 | * - DMA1 Channel 2 end of transfer (TCIF)
51 | */
52 |
53 | void ADC1_2_IRQHandler(void) {
54 | if((ADC1->ISR & ADC_ISR_JEOS) != 0) {
55 | // Injected end of conversion
56 | ADC1->ISR |= ADC_ISR_JEOS; // Clear the flag by writing 1 to it
57 |
58 | // Call the motor control loop
59 | MAIN_MotorISR();
60 | }
61 | }
62 |
63 | void ADC3_IRQHandler(void) {
64 | if((ADC3->ISR & ADC_ISR_JEOS) != 0) {
65 | // Injected end of conversion
66 | ADC3->ISR |= ADC_ISR_JEOS; // Clear the flag by writing 1 to it
67 | }
68 | }
69 |
70 | void DMA1_Channel1_IRQHandler(void) {
71 | if((DMA1->ISR & DMA_ISR_TCIF1) != 0) {
72 | // Transfer complete channel 1
73 | DMA1->IFCR |= DMA_IFCR_CTCIF1; // Clear the flag by writing 1
74 | }
75 | }
76 |
77 | void DMA1_Channel2_IRQHandler(void) {
78 | if((DMA1->ISR & DMA_ISR_TCIF2) != 0) {
79 | // Transfer complete channel 2
80 | DMA1->IFCR |= DMA_IFCR_CTCIF2; // Clear the flag by writing 1
81 | }
82 | }
83 |
84 | void DMA1_Channel3_IRQHandler(void) {
85 | if((DMA1->ISR & DMA_ISR_TCIF3) != 0) {
86 | // Transfer complete channel 3
87 | DMA1->IFCR |= DMA_IFCR_CTCIF3; // Clear the flag by writing 1
88 | }
89 | }
90 |
91 | void DMA1_Channel4_IRQHandler(void) {
92 | if((DMA1->ISR & DMA_ISR_TCIF4) != 0) {
93 | // Transfer complete channel 4
94 | DMA1->IFCR |= DMA_IFCR_CTCIF4; // Clear the flag by writing 1
95 | }
96 | }
97 |
98 | /**
99 | * Handlers for Hall sensor timer.
100 | * Two interrupts are used:
101 | * - TIM4 Update (UIF)
102 | * - TIM4 Channel 1 Capture (CC1F)
103 | */
104 |
105 | void TIM4_IRQHandler(void) {
106 | if((TIM4->SR & TIM_SR_UIF) != 0) {
107 | // Update (timer rollover)
108 | TIM4->SR &= ~(TIM_SR_UIF); // Clear the flag by writing 0
109 | HALL_UpdateCallback();
110 | }
111 | if((TIM4->SR & TIM_SR_CC1IF) != 0) {
112 | // Capture (Hall state change)
113 | TIM4->SR &= ~(TIM_SR_CC1IF); // Clear the flag by writing 0
114 | HALL_CaptureCallback();
115 | }
116 |
117 | }
118 |
119 | /**
120 | * Handler for application timer.
121 | * One interrupt:
122 | * - TIM6 Update (UIF)
123 | */
124 | void TIM6_DAC_IRQHandler(void) {
125 | if((TIM6->SR & TIM_SR_UIF) != 0) {
126 | // Update (timer rollover)
127 | TIM6->SR &= ~(TIM_SR_UIF); // Clear by writing 0
128 | MAIN_AppTimerISR(); // Call the application timer ISR in main
129 | }
130 | }
131 |
132 | /**
133 | * Handlers for PWM timer
134 | * Two interrupts used:
135 | * - TIM1 Update (UIF)
136 | * - TIM1 Break input (BIF)
137 | */
138 |
139 | void TIM1_UP_TIM16_IRQHandler(void) {
140 | if((TIM1->SR & TIM_SR_UIF) != 0) {
141 | // Update (timer rollover)
142 | TIM1->SR &= ~(TIM_SR_UIF); // Clear the flag by writing 0
143 | }
144 | }
145 |
146 | void TIM1_BRK_TIM15_IRQHandler(void) {
147 | if((TIM1->SR & TIM_SR_BIF) != 0) {
148 | // Break interrupt
149 | TIM1->SR &= ~(TIM_SR_BIF); // Clear the flag by writing 0
150 | }
151 | }
152 |
153 | /**
154 | * Handlers for UART
155 | * Two interrupts used:
156 | * - USART2 (HBD UART) receiver not empty (RXNE), transmitter empty (TXE)
157 | * - USART3 (BMS UART) receiver not empty (RXNE), transmitter empty (TXE)
158 | */
159 |
160 | void USART2_IRQHandler(void) {
161 | // RXNE is cleared automatically when the data register is read
162 | // TXE is cleared automatically when the data register is written
163 | UART_IRQ(SELECT_HBD_UART);
164 | }
165 |
166 | void USART3_IRQHandler(void) {
167 | // RXNE is cleared automatically when the data register is read
168 | // TXE is cleared automatically when the data register is written
169 | UART_IRQ(SELECT_BMS_UART);
170 | }
171 |
172 |
173 | /**
174 | * Handlers for USB
175 | * One interrupt handler, but many sources are activated:
176 | * - Correct Transfer (CTRM)
177 | * - Wakeup (WKUPM)
178 | * - Suspend (SUSPM)
179 | * - Error (ERRM)
180 | * - Start of Frame (SOFM)
181 | * - Expected Start of Frame (ESOFM)
182 | * - Reset (RESETM)
183 | * - Low power request (L1REQM)
184 | */
185 | void USB_LP_IRQHandler(void) {
186 | // Simply call the USB driver function.
187 | // It takes care of all the flag clearing and handling.
188 | USB_IRQ();
189 | }
190 |
191 | void USB_HP_IRQHandler(void) {
192 | // Not sure why there are two IRQ handlers for USB.
193 | // It isn't mentioned in the datasheet.
194 | USB_IRQ();
195 | }
196 |
--------------------------------------------------------------------------------
/ebike-g4/src/power_calcs.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: power_calcs.c
3 | * Description: Performs calculations on the three-phase voltage, current, and
4 | * power. Takes in measured quantities (bus voltage, phase
5 | * current, duty cycle) and determines phase voltage and bus
6 | * current, as well as total power.
7 | ******************************************************************************
8 |
9 | Copyright (c) 2021 David Miller
10 |
11 | Permission is hereby granted, free of charge, to any person obtaining a copy
12 | of this software and associated documentation files (the "Software"), to deal
13 | in the Software without restriction, including without limitation the rights
14 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 | copies of the Software, and to permit persons to whom the Software is
16 | furnished to do so, subject to the following conditions:
17 |
18 | The above copyright notice and this permission notice shall be included in all
19 | copies or substantial portions of the Software.
20 |
21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 | SOFTWARE.
28 | */
29 |
30 | #include "stm32g4xx.h"
31 | #include "arm_math.h"
32 | #include "power_calcs.h"
33 |
34 | void power_calc(PowerCalcs* pc) {
35 | // From "Permanent Magnet Synchronous and Brushless DC Motors" by Ramu Krishnan
36 | // Chapter 3.5, Power Equivalence
37 | // Power in = Power out
38 | // For the three-phase motor, power out = Van*Ia + Vbn*Ib + Vcn*Ic
39 | // For a two-phase equivalent, power out = (3/2) * (Valpha*Ialpha + Vbeta*Ibeta)
40 | // The (3/2) comes from the three-to-two-phase conversion.
41 |
42 | // Calculate the voltages for each phase to neutral
43 | // Vx = Tx * Vbus, x = a,b,c
44 | // Vn = (Va + Vb + Vc)/3
45 | // Van = Va - Vn = (2*Va - Vb - Vc) / 3
46 | // ...similar for Vbn, Vcn
47 | // But we don't need Vcn for the balanced Clarke transform, so it's skipped
48 | float Van, Vbn, Valpha, Vbeta;
49 | Van = pc->Vbus * ((2.0f * pc->Ta) - (pc->Tb) - (pc->Tc)) / 3.0f;
50 | Vbn = pc->Vbus * ((2.0f * pc->Tb) - (pc->Ta) - (pc->Tc)) / 3.0f;
51 |
52 | // Clarke transform from 3-phase to 2-phase
53 | Valpha = Van;
54 | Vbeta = (2.0f * Vbn + Van) * (ONE_OVER_SQRT3_F);
55 |
56 | // Calculate total power
57 | // Low pass filtering applied
58 | pc->TotalPower = (1.0f - POWER_CALCS_LPF_MULTIPLIER) * (pc->TotalPower) +
59 | POWER_CALCS_LPF_MULTIPLIER * ( (1.5f)*((pc->Ialpha)*Valpha + (pc->Ibeta)*Vbeta) );
60 |
61 | // Calculate battery current using Pin = Pout, and Pin = Vbattery*Ibattery
62 | if(pc->Vbus > 0.01f) {
63 | // Avoid divide by zero errors
64 | pc->BatteryCurrent = pc->TotalPower / pc->Vbus;
65 | } else {
66 | pc->BatteryCurrent = 0.0f;
67 | }
68 |
69 | // Also calculate the phase current using the magnitude of Ialpha & Ibeta
70 | pc->PhaseCurrent = (1.0f - POWER_CALCS_LPF_MULTIPLIER) * (pc->PhaseCurrent) +
71 | POWER_CALCS_LPF_MULTIPLIER * sqrtf(((pc->Ialpha) * (pc->Ialpha)) + ((pc->Ibeta) * (pc->Ibeta)));
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/ebike-g4/src/usb_data_comm.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: usb_data_comm.c
3 | * Description: Conducts data packet communication over the USB serial port.
4 | *
5 | ******************************************************************************
6 |
7 | Copyright (c) 2020 David Miller
8 |
9 | Permission is hereby granted, free of charge, to any person obtaining a copy
10 | of this software and associated documentation files (the "Software"), to deal
11 | in the Software without restriction, including without limitation the rights
12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | copies of the Software, and to permit persons to whom the Software is
14 | furnished to do so, subject to the following conditions:
15 |
16 | The above copyright notice and this permission notice shall be included in all
17 | copies or substantial portions of the Software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 | SOFTWARE.
26 | */
27 |
28 | #include "main.h"
29 |
30 | // Private variables
31 | uint8_t USB_Data_Comm_TxBuffer[PACKET_MAX_LENGTH];
32 | #if 0
33 | uint8_t USB_Data_Comm_RxBuffer[PACKET_MAX_LENGTH];
34 | int32_t USB_Data_Comm_RxBuffer_WrPlace;
35 | #endif
36 | uint8_t USB_Data_Comm_DataBuffer[PACKET_MAX_DATA_LENGTH];
37 | Data_Packet_Type USB_Data_Comm_Packet;
38 |
39 | // Private functions
40 | static void USB_Data_Comm_Process_Command(void);
41 |
42 | // Public functions
43 |
44 | /**
45 | * @brief USB Data Communications Initialization
46 | * Sets packet data to default values.
47 | * @param None
48 | * @retval None
49 | */
50 | void USB_Data_Comm_Init(void) {
51 | USB_Data_Comm_Packet.State = DATA_COMM_IDLE;
52 | USB_Data_Comm_Packet.Data = USB_Data_Comm_DataBuffer;
53 | USB_Data_Comm_Packet.TxBuffer = USB_Data_Comm_TxBuffer;
54 | USB_Data_Comm_Packet.TxReady = 0;
55 | USB_Data_Comm_Packet.RxReady = 0;
56 | #if 0
57 | USB_Data_Comm_RxBuffer_WrPlace = 0;
58 | #endif
59 |
60 | }
61 |
62 | /**
63 | * @brief USB Data Communications One Byte Check
64 | * Handles the USB serial port incoming data. Determines
65 | * if a properly encoded packet has been received, and
66 | * sends to the appropriate handler if it has. Operates
67 | * one byte at a time using an internal state machine.
68 | * @param None
69 | * @retval None
70 | */
71 | void USB_Data_Comm_OneByte_Check(void) {
72 | // Loop through each incoming byte
73 | int32_t numbytes = VCP_InWaiting();
74 | uint8_t this_byte;
75 | while(numbytes > 0) {
76 | // Load one new byte
77 | if(VCP_Read(&this_byte, 1) != 1) {
78 | // Check that a byte was really received
79 | return;
80 | }
81 | numbytes--;
82 | if(data_packet_extract_one_byte(&USB_Data_Comm_Packet, this_byte) == DATA_PACKET_SUCCESS) {
83 | if(USB_Data_Comm_Packet.RxReady == 1) {
84 | // Double checked and good to go
85 | USB_Data_Comm_Process_Command();
86 | }
87 | }
88 | }
89 | }
90 |
91 | /**
92 | * @brief USB Data Communications Process Command
93 | * Calls the command processor when a packet has been successfully
94 | * decoded. If a response is generated, it is sent back over the
95 | * USB serial port.
96 | * @param None
97 | * @retval None
98 | */
99 | static void USB_Data_Comm_Process_Command(void) {
100 | uint16_t errCode = data_process_command(&USB_Data_Comm_Packet);
101 | if ((errCode == DATA_PACKET_SUCCESS) && USB_Data_Comm_Packet.TxReady) {
102 | uint8_t* send_buffer = USB_Data_Comm_Packet.TxBuffer;
103 | uint16_t len_to_send = USB_Data_Comm_Packet.TxLength;
104 | uint16_t actually_sent = 0;
105 | while (len_to_send > 0) {
106 | actually_sent = VCP_Write(send_buffer, len_to_send);
107 | len_to_send -= actually_sent;
108 | send_buffer += actually_sent;
109 | }
110 | USB_Data_Comm_Packet.TxReady = 0;
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/ebike-g4/src/wdt.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | * Filename: wdt.c
3 | * Description: Functions for the STM32G4 watchdog timer.
4 | * The independent watchdog (IWDG) is used, which has its clock
5 | * input fixed to the internal low speed oscillator. Using the
6 | * prescaler and auto-reload registers, the reset timeout is set
7 | * to approximately 50ms. If this time duration passes without
8 | * the KEY register being written with the reload command, the
9 | * MCU resets.
10 | * Once started, the watchdog cannot be stopped.
11 | * Feed the watchdog!
12 | ******************************************************************************
13 |
14 | Copyright (c) 2020 David Miller
15 |
16 | Permission is hereby granted, free of charge, to any person obtaining a copy
17 | of this software and associated documentation files (the "Software"), to deal
18 | in the Software without restriction, including without limitation the rights
19 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20 | copies of the Software, and to permit persons to whom the Software is
21 | furnished to do so, subject to the following conditions:
22 |
23 | The above copyright notice and this permission notice shall be included in all
24 | copies or substantial portions of the Software.
25 |
26 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32 | SOFTWARE.
33 | */
34 |
35 | #include "main.h"
36 |
37 | void WDT_Init(void) {
38 | // Timer is stopped in debug (e.g. breakpoints)
39 | DBGMCU->APB1FZR1 |= DBGMCU_APB1FZR1_DBG_IWDG_STOP;
40 | // Start/enable the countdown timer
41 | IWDG->KR = IWDG_START;
42 | // Unlock registers
43 | IWDG->KR = IWDG_KEY;
44 | // Set prescaler
45 | IWDG->PR = IWDG_PSC;
46 | // Set reload value
47 | IWDG->RLR = IWDG_REL_VAL;
48 | // Wait for it all to take effect
49 | // This gets stuck. I think it needs to get a reload before it updates?
50 | // I don't really care about waiting for it to take effect.
51 | // If the reload register ends up being stuck at default, the IWDG will still work
52 | // but will reset after ~510 msec instead of 50 msec.
53 | // while((IWDG->SR) != ((uint32_t)0)) {
54 | // pass
55 | // }
56 |
57 | }
58 |
59 | void WDT_Feed(void) {
60 | IWDG->KR = IWDG_RELOAD;
61 | }
62 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/DEVICE/README_DRIVERS.txt:
--------------------------------------------------------------------------------
1 | This folder is a placeholder where to add vendor provided header files
2 | from the peripheral drivers library.
3 |
4 | Study the vendor drivers library and identify the drivers include files.
5 | Copy the files you need in your project to this folder.
6 |
7 | It should have been automatically added to the include paths.
8 |
9 | If you rename this folder, be sure you also update the include path.
10 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/arm/semihosting.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | #ifndef ARM_SEMIHOSTING_H_
29 | #define ARM_SEMIHOSTING_H_
30 |
31 | // ----------------------------------------------------------------------------
32 |
33 | // Semihosting operations.
34 | enum OperationNumber
35 | {
36 | // Regular operations
37 | SEMIHOSTING_EnterSVC = 0x17,
38 | SEMIHOSTING_ReportException = 0x18,
39 | SEMIHOSTING_SYS_CLOSE = 0x02,
40 | SEMIHOSTING_SYS_CLOCK = 0x10,
41 | SEMIHOSTING_SYS_ELAPSED = 0x30,
42 | SEMIHOSTING_SYS_ERRNO = 0x13,
43 | SEMIHOSTING_SYS_FLEN = 0x0C,
44 | SEMIHOSTING_SYS_GET_CMDLINE = 0x15,
45 | SEMIHOSTING_SYS_HEAPINFO = 0x16,
46 | SEMIHOSTING_SYS_ISERROR = 0x08,
47 | SEMIHOSTING_SYS_ISTTY = 0x09,
48 | SEMIHOSTING_SYS_OPEN = 0x01,
49 | SEMIHOSTING_SYS_READ = 0x06,
50 | SEMIHOSTING_SYS_READC = 0x07,
51 | SEMIHOSTING_SYS_REMOVE = 0x0E,
52 | SEMIHOSTING_SYS_RENAME = 0x0F,
53 | SEMIHOSTING_SYS_SEEK = 0x0A,
54 | SEMIHOSTING_SYS_SYSTEM = 0x12,
55 | SEMIHOSTING_SYS_TICKFREQ = 0x31,
56 | SEMIHOSTING_SYS_TIME = 0x11,
57 | SEMIHOSTING_SYS_TMPNAM = 0x0D,
58 | SEMIHOSTING_SYS_WRITE = 0x05,
59 | SEMIHOSTING_SYS_WRITEC = 0x03,
60 | SEMIHOSTING_SYS_WRITE0 = 0x04,
61 |
62 | // Codes returned by SEMIHOSTING_ReportException
63 | ADP_Stopped_ApplicationExit = ((2 << 16) + 38),
64 | ADP_Stopped_RunTimeError = ((2 << 16) + 35),
65 |
66 | };
67 |
68 | // ----------------------------------------------------------------------------
69 |
70 | // SWI numbers and reason codes for RDI (Angel) monitors.
71 | #define AngelSWI_ARM 0x123456
72 | #ifdef __thumb__
73 | #define AngelSWI 0xAB
74 | #else
75 | #define AngelSWI AngelSWI_ARM
76 | #endif
77 | // For thumb only architectures use the BKPT instruction instead of SWI.
78 | #if defined(__ARM_ARCH_7M__) \
79 | || defined(__ARM_ARCH_7EM__) \
80 | || defined(__ARM_ARCH_6M__)
81 | #define AngelSWIInsn "bkpt"
82 | #define AngelSWIAsm bkpt
83 | #else
84 | #define AngelSWIInsn "swi"
85 | #define AngelSWIAsm swi
86 | #endif
87 |
88 | #if defined(OS_DEBUG_SEMIHOSTING_FAULTS)
89 | // Testing the local semihosting handler cannot use another BKPT, since this
90 | // configuration cannot trigger HaedFault exceptions while the debugger is
91 | // connected, so we use an illegal op code, that will trigger an
92 | // UsageFault exception.
93 | #define AngelSWITestFault "setend be"
94 | #define AngelSWITestFaultOpCode (0xB658)
95 | #endif
96 |
97 | static inline int
98 | __attribute__ ((always_inline))
99 | call_host (int reason, void* arg)
100 | {
101 | int value;
102 | asm volatile (
103 |
104 | " mov r0, %[rsn] \n"
105 | " mov r1, %[arg] \n"
106 | #if defined(OS_DEBUG_SEMIHOSTING_FAULTS)
107 | " " AngelSWITestFault " \n"
108 | #else
109 | " " AngelSWIInsn " %[swi] \n"
110 | #endif
111 | " mov %[val], r0"
112 |
113 | : [val] "=r" (value) /* Outputs */
114 | : [rsn] "r" (reason), [arg] "r" (arg), [swi] "i" (AngelSWI) /* Inputs */
115 | : "r0", "r1", "r2", "r3", "ip", "lr", "memory", "cc"
116 | // Clobbers r0 and r1, and lr if in supervisor mode
117 | );
118 |
119 | // Accordingly to page 13-77 of ARM DUI 0040D other registers
120 | // can also be clobbered. Some memory positions may also be
121 | // changed by a system call, so they should not be kept in
122 | // registers. Note: we are assuming the manual is right and
123 | // Angel is respecting the APCS.
124 | return value;
125 | }
126 |
127 | // ----------------------------------------------------------------------------
128 |
129 | // Function used in _exit() to return the status code as Angel exception.
130 | static inline void
131 | __attribute__ ((always_inline,noreturn))
132 | report_exception (int reason)
133 | {
134 | call_host (SEMIHOSTING_ReportException, (void*) reason);
135 |
136 | for (;;)
137 | ;
138 | }
139 |
140 | // ----------------------------------------------------------------------------
141 |
142 | #endif // ARM_SEMIHOSTING_H_
143 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/README_DEVICE.txt:
--------------------------------------------------------------------------------
1 | The "DEVICE.h" and "system_DEVICE.h" files are provided
2 | only as a functional sample.
3 |
4 | For real applications they must be replaced by the vendor provided files.
5 |
6 | Extensions to the ARM CMSIS files:
7 |
8 | - the file "cmsis_device.h" was added, as a portable method to include the
9 | vendor device header file in library sources.
10 |
11 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/arm_const_structs.h:
--------------------------------------------------------------------------------
1 | /* ----------------------------------------------------------------------
2 | * Copyright (C) 2010-2014 ARM Limited. All rights reserved.
3 | *
4 | * $Date: 19. March 2015
5 | * $Revision: V.1.4.5
6 | *
7 | * Project: CMSIS DSP Library
8 | * Title: arm_const_structs.h
9 | *
10 | * Description: This file has constant structs that are initialized for
11 | * user convenience. For example, some can be given as
12 | * arguments to the arm_cfft_f32() function.
13 | *
14 | * Target Processor: Cortex-M4/Cortex-M3
15 | *
16 | * Redistribution and use in source and binary forms, with or without
17 | * modification, are permitted provided that the following conditions
18 | * are met:
19 | * - Redistributions of source code must retain the above copyright
20 | * notice, this list of conditions and the following disclaimer.
21 | * - Redistributions in binary form must reproduce the above copyright
22 | * notice, this list of conditions and the following disclaimer in
23 | * the documentation and/or other materials provided with the
24 | * distribution.
25 | * - Neither the name of ARM LIMITED nor the names of its contributors
26 | * may be used to endorse or promote products derived from this
27 | * software without specific prior written permission.
28 | *
29 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
32 | * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
33 | * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
36 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
37 | * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
39 | * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 | * POSSIBILITY OF SUCH DAMAGE.
41 | * -------------------------------------------------------------------- */
42 |
43 | #ifndef _ARM_CONST_STRUCTS_H
44 | #define _ARM_CONST_STRUCTS_H
45 |
46 | #include "arm_math.h"
47 | #include "arm_common_tables.h"
48 |
49 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len16;
50 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len32;
51 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len64;
52 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len128;
53 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len256;
54 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len512;
55 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len1024;
56 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len2048;
57 | extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len4096;
58 |
59 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len16;
60 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len32;
61 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len64;
62 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len128;
63 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len256;
64 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len512;
65 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len1024;
66 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len2048;
67 | extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len4096;
68 |
69 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len16;
70 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len32;
71 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len64;
72 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len128;
73 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len256;
74 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len512;
75 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len1024;
76 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len2048;
77 | extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len4096;
78 |
79 | #endif
80 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/cmsis_device.h:
--------------------------------------------------------------------------------
1 | #ifndef _CMSIS_H_
2 | #define _CMSIS_H_
3 |
4 | #include "stm32g473xx.h"
5 |
6 | #endif // _CMSIS_H_
7 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/core_cmFunc.h:
--------------------------------------------------------------------------------
1 | /**************************************************************************//**
2 | * @file core_cmFunc.h
3 | * @brief CMSIS Cortex-M Core Function Access Header File
4 | * @version V4.30
5 | * @date 20. October 2015
6 | ******************************************************************************/
7 | /* Copyright (c) 2009 - 2015 ARM LIMITED
8 |
9 | All rights reserved.
10 | Redistribution and use in source and binary forms, with or without
11 | modification, are permitted provided that the following conditions are met:
12 | - Redistributions of source code must retain the above copyright
13 | notice, this list of conditions and the following disclaimer.
14 | - Redistributions in binary form must reproduce the above copyright
15 | notice, this list of conditions and the following disclaimer in the
16 | documentation and/or other materials provided with the distribution.
17 | - Neither the name of ARM nor the names of its contributors may be used
18 | to endorse or promote products derived from this software without
19 | specific prior written permission.
20 | *
21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 | ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
25 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 | POSSIBILITY OF SUCH DAMAGE.
32 | ---------------------------------------------------------------------------*/
33 |
34 |
35 | #if defined ( __ICCARM__ )
36 | #pragma system_include /* treat file as system include file for MISRA check */
37 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
38 | #pragma clang system_header /* treat file as system include file */
39 | #endif
40 |
41 | #ifndef __CORE_CMFUNC_H
42 | #define __CORE_CMFUNC_H
43 |
44 |
45 | /* ########################### Core Function Access ########################### */
46 | /** \ingroup CMSIS_Core_FunctionInterface
47 | \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
48 | @{
49 | */
50 |
51 | /*------------------ RealView Compiler -----------------*/
52 | #if defined ( __CC_ARM )
53 | #include "cmsis_armcc.h"
54 |
55 | /*------------------ ARM Compiler V6 -------------------*/
56 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
57 | #include "cmsis_armcc_V6.h"
58 |
59 | /*------------------ GNU Compiler ----------------------*/
60 | #elif defined ( __GNUC__ )
61 | #include "cmsis_gcc.h"
62 |
63 | /*------------------ ICC Compiler ----------------------*/
64 | #elif defined ( __ICCARM__ )
65 | #include
66 |
67 | /*------------------ TI CCS Compiler -------------------*/
68 | #elif defined ( __TMS470__ )
69 | #include
70 |
71 | /*------------------ TASKING Compiler ------------------*/
72 | #elif defined ( __TASKING__ )
73 | /*
74 | * The CMSIS functions have been implemented as intrinsics in the compiler.
75 | * Please use "carm -?i" to get an up to date list of all intrinsics,
76 | * Including the CMSIS ones.
77 | */
78 |
79 | /*------------------ COSMIC Compiler -------------------*/
80 | #elif defined ( __CSMC__ )
81 | #include
82 |
83 | #endif
84 |
85 | /*@} end of CMSIS_Core_RegAccFunctions */
86 |
87 | #endif /* __CORE_CMFUNC_H */
88 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/core_cmInstr.h:
--------------------------------------------------------------------------------
1 | /**************************************************************************//**
2 | * @file core_cmInstr.h
3 | * @brief CMSIS Cortex-M Core Instruction Access Header File
4 | * @version V4.30
5 | * @date 20. October 2015
6 | ******************************************************************************/
7 | /* Copyright (c) 2009 - 2015 ARM LIMITED
8 |
9 | All rights reserved.
10 | Redistribution and use in source and binary forms, with or without
11 | modification, are permitted provided that the following conditions are met:
12 | - Redistributions of source code must retain the above copyright
13 | notice, this list of conditions and the following disclaimer.
14 | - Redistributions in binary form must reproduce the above copyright
15 | notice, this list of conditions and the following disclaimer in the
16 | documentation and/or other materials provided with the distribution.
17 | - Neither the name of ARM nor the names of its contributors may be used
18 | to endorse or promote products derived from this software without
19 | specific prior written permission.
20 | *
21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 | ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
25 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 | POSSIBILITY OF SUCH DAMAGE.
32 | ---------------------------------------------------------------------------*/
33 |
34 |
35 | #if defined ( __ICCARM__ )
36 | #pragma system_include /* treat file as system include file for MISRA check */
37 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
38 | #pragma clang system_header /* treat file as system include file */
39 | #endif
40 |
41 | #ifndef __CORE_CMINSTR_H
42 | #define __CORE_CMINSTR_H
43 |
44 |
45 | /* ########################## Core Instruction Access ######################### */
46 | /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface
47 | Access to dedicated instructions
48 | @{
49 | */
50 |
51 | /*------------------ RealView Compiler -----------------*/
52 | #if defined ( __CC_ARM )
53 | #include "cmsis_armcc.h"
54 |
55 | /*------------------ ARM Compiler V6 -------------------*/
56 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
57 | #include "cmsis_armcc_V6.h"
58 |
59 | /*------------------ GNU Compiler ----------------------*/
60 | #elif defined ( __GNUC__ )
61 | #include "cmsis_gcc.h"
62 |
63 | /*------------------ ICC Compiler ----------------------*/
64 | #elif defined ( __ICCARM__ )
65 | #include
66 |
67 | /*------------------ TI CCS Compiler -------------------*/
68 | #elif defined ( __TMS470__ )
69 | #include
70 |
71 | /*------------------ TASKING Compiler ------------------*/
72 | #elif defined ( __TASKING__ )
73 | /*
74 | * The CMSIS functions have been implemented as intrinsics in the compiler.
75 | * Please use "carm -?i" to get an up to date list of all intrinsics,
76 | * Including the CMSIS ones.
77 | */
78 |
79 | /*------------------ COSMIC Compiler -------------------*/
80 | #elif defined ( __CSMC__ )
81 | #include
82 |
83 | #endif
84 |
85 | /*@}*/ /* end of group CMSIS_Core_InstructionInterface */
86 |
87 | #endif /* __CORE_CMINSTR_H */
88 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/core_cmSimd.h:
--------------------------------------------------------------------------------
1 | /**************************************************************************//**
2 | * @file core_cmSimd.h
3 | * @brief CMSIS Cortex-M SIMD Header File
4 | * @version V4.30
5 | * @date 20. October 2015
6 | ******************************************************************************/
7 | /* Copyright (c) 2009 - 2015 ARM LIMITED
8 |
9 | All rights reserved.
10 | Redistribution and use in source and binary forms, with or without
11 | modification, are permitted provided that the following conditions are met:
12 | - Redistributions of source code must retain the above copyright
13 | notice, this list of conditions and the following disclaimer.
14 | - Redistributions in binary form must reproduce the above copyright
15 | notice, this list of conditions and the following disclaimer in the
16 | documentation and/or other materials provided with the distribution.
17 | - Neither the name of ARM nor the names of its contributors may be used
18 | to endorse or promote products derived from this software without
19 | specific prior written permission.
20 | *
21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 | ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
25 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 | POSSIBILITY OF SUCH DAMAGE.
32 | ---------------------------------------------------------------------------*/
33 |
34 |
35 | #if defined ( __ICCARM__ )
36 | #pragma system_include /* treat file as system include file for MISRA check */
37 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
38 | #pragma clang system_header /* treat file as system include file */
39 | #endif
40 |
41 | #ifndef __CORE_CMSIMD_H
42 | #define __CORE_CMSIMD_H
43 |
44 | #ifdef __cplusplus
45 | extern "C" {
46 | #endif
47 |
48 |
49 | /* ################### Compiler specific Intrinsics ########################### */
50 | /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics
51 | Access to dedicated SIMD instructions
52 | @{
53 | */
54 |
55 | /*------------------ RealView Compiler -----------------*/
56 | #if defined ( __CC_ARM )
57 | #include "cmsis_armcc.h"
58 |
59 | /*------------------ ARM Compiler V6 -------------------*/
60 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
61 | #include "cmsis_armcc_V6.h"
62 |
63 | /*------------------ GNU Compiler ----------------------*/
64 | #elif defined ( __GNUC__ )
65 | #include "cmsis_gcc.h"
66 |
67 | /*------------------ ICC Compiler ----------------------*/
68 | #elif defined ( __ICCARM__ )
69 | #include
70 |
71 | /*------------------ TI CCS Compiler -------------------*/
72 | #elif defined ( __TMS470__ )
73 | #include
74 |
75 | /*------------------ TASKING Compiler ------------------*/
76 | #elif defined ( __TASKING__ )
77 | /*
78 | * The CMSIS functions have been implemented as intrinsics in the compiler.
79 | * Please use "carm -?i" to get an up to date list of all intrinsics,
80 | * Including the CMSIS ones.
81 | */
82 |
83 | /*------------------ COSMIC Compiler -------------------*/
84 | #elif defined ( __CSMC__ )
85 | #include
86 |
87 | #endif
88 |
89 | /*@} end of group CMSIS_SIMD_intrinsics */
90 |
91 |
92 | #ifdef __cplusplus
93 | }
94 | #endif
95 |
96 | #endif /* __CORE_CMSIMD_H */
97 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/stm32g4xx.h:
--------------------------------------------------------------------------------
1 | /**
2 | ******************************************************************************
3 | * @file stm32g4xx.h
4 | * @author MCD Application Team
5 | * @brief CMSIS STM32G4xx Device Peripheral Access Layer Header File.
6 | *
7 | * The file is the unique include file that the application programmer
8 | * is using in the C source code, usually in main.c. This file contains:
9 | * - Configuration section that allows to select:
10 | * - The STM32G4xx device used in the target application
11 | * - To use or not the peripherals drivers in application code(i.e.
12 | * code will be based on direct access to peripherals registers
13 | * rather than drivers API), this option is controlled by
14 | * "#define USE_HAL_DRIVER"
15 | *
16 | ******************************************************************************
17 | * @attention
18 | *
19 | * © Copyright (c) 2019 STMicroelectronics.
20 | * All rights reserved.
21 | *
22 | * This software component is licensed by ST under BSD 3-Clause license,
23 | * the "License"; You may not use this file except in compliance with the
24 | * License. You may obtain a copy of the License at:
25 | * opensource.org/licenses/BSD-3-Clause
26 | *
27 | ******************************************************************************
28 | */
29 |
30 | /** @addtogroup CMSIS
31 | * @{
32 | */
33 |
34 | /** @addtogroup stm32g4xx
35 | * @{
36 | */
37 |
38 | #ifndef __STM32G4xx_H
39 | #define __STM32G4xx_H
40 |
41 | #ifdef __cplusplus
42 | extern "C" {
43 | #endif /* __cplusplus */
44 |
45 | /** @addtogroup Library_configuration_section
46 | * @{
47 | */
48 |
49 | /**
50 | * @brief STM32 Family
51 | */
52 | #if !defined (STM32G4)
53 | #define STM32G4
54 | #endif /* STM32G4 */
55 |
56 | /* Uncomment the line below according to the target STM32G4 device used in your
57 | application
58 | */
59 |
60 | #if !defined (STM32G431xx) && !defined (STM32G441xx) && \
61 | !defined (STM32G471xx) && !defined (STM32G473xx) && !defined (STM32G474xx) && !defined (STM32G484xx) && !defined (STM32GBK1CB)
62 | /* #define STM32G431xx */ /*!< STM32G431xx Devices */
63 | /* #define STM32G441xx */ /*!< STM32G441xx Devices */
64 | /* #define STM32G471xx */ /*!< STM32G471xx Devices */
65 | /* #define STM32G473xx */ /*!< STM32G473xx Devices */
66 | /* #define STM32G483xx */ /*!< STM32G483xx Devices */
67 | /* #define STM32G474xx */ /*!< STM32G474xx Devices */
68 | /* #define STM32G484xx */ /*!< STM32G484xx Devices */
69 | /* #define STM32GBK1CB */ /*!< STM32GBK1CB Devices */
70 | #endif
71 |
72 | /* Tip: To avoid modifying this file each time you need to switch between these
73 | devices, you can define the device in your toolchain compiler preprocessor.
74 | */
75 | #if !defined (USE_HAL_DRIVER)
76 | /**
77 | * @brief Comment the line below if you will not use the peripherals drivers.
78 | In this case, these drivers will not be included and the application code will
79 | be based on direct access to peripherals registers
80 | */
81 | /*#define USE_HAL_DRIVER */
82 | #endif /* USE_HAL_DRIVER */
83 |
84 | /**
85 | * @brief CMSIS Device version number V1.1.1
86 | */
87 | #define __STM32G4_CMSIS_VERSION_MAIN (0x01U) /*!< [31:24] main version */
88 | #define __STM32G4_CMSIS_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */
89 | #define __STM32G4_CMSIS_VERSION_SUB2 (0x01U) /*!< [15:8] sub2 version */
90 | #define __STM32G4_CMSIS_VERSION_RC (0x00U) /*!< [7:0] release candidate */
91 | #define __STM32G4_CMSIS_VERSION ((__STM32G4_CMSIS_VERSION_MAIN << 24)\
92 | |(__STM32G4_CMSIS_VERSION_SUB1 << 16)\
93 | |(__STM32G4_CMSIS_VERSION_SUB2 << 8 )\
94 | |(__STM32G4_CMSIS_VERSION_RC))
95 |
96 | /**
97 | * @}
98 | */
99 |
100 | /** @addtogroup Device_Included
101 | * @{
102 | */
103 |
104 | #if defined(STM32G431xx)
105 | #include "stm32g431xx.h"
106 | #elif defined(STM32G441xx)
107 | #include "stm32g441xx.h"
108 | #elif defined(STM32G471xx)
109 | #include "stm32g471xx.h"
110 | #elif defined(STM32G473xx)
111 | #include "stm32g473xx.h"
112 | #elif defined(STM32G483xx)
113 | #include "stm32g483xx.h"
114 | #elif defined(STM32G474xx)
115 | #include "stm32g474xx.h"
116 | #elif defined(STM32G484xx)
117 | #include "stm32g484xx.h"
118 | #elif defined(STM32GBK1CB)
119 | #include "stm32gbk1cb.h"
120 | #else
121 | #error "Please select first the target STM32G4xx device used in your application (in stm32g4xx.h file)"
122 | #endif
123 |
124 | /**
125 | * @}
126 | */
127 |
128 | /** @addtogroup Exported_types
129 | * @{
130 | */
131 | typedef enum
132 | {
133 | RESET = 0,
134 | SET = !RESET
135 | } FlagStatus, ITStatus;
136 |
137 | typedef enum
138 | {
139 | DISABLE = 0,
140 | ENABLE = !DISABLE
141 | } FunctionalState;
142 | #define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE))
143 |
144 | typedef enum
145 | {
146 | SUCCESS = 0,
147 | ERROR = !SUCCESS
148 | } ErrorStatus;
149 |
150 | /**
151 | * @}
152 | */
153 |
154 |
155 | /** @addtogroup Exported_macros
156 | * @{
157 | */
158 | #define SET_BIT(REG, BIT) ((REG) |= (BIT))
159 |
160 | #define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT))
161 |
162 | #define READ_BIT(REG, BIT) ((REG) & (BIT))
163 |
164 | #define CLEAR_REG(REG) ((REG) = (0x0))
165 |
166 | #define WRITE_REG(REG, VAL) ((REG) = (VAL))
167 |
168 | #define READ_REG(REG) ((REG))
169 |
170 | #define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK)))
171 |
172 | #define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL)))
173 |
174 |
175 | /**
176 | * @}
177 | */
178 |
179 | #if defined (USE_HAL_DRIVER)
180 | #include "stm32g4xx_hal.h"
181 | #endif /* USE_HAL_DRIVER */
182 |
183 | #ifdef __cplusplus
184 | }
185 | #endif /* __cplusplus */
186 |
187 | #endif /* __STM32G4xx_H */
188 | /**
189 | * @}
190 | */
191 |
192 | /**
193 | * @}
194 | */
195 |
196 |
197 |
198 |
199 | /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
200 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/system_DEVICE.h:
--------------------------------------------------------------------------------
1 | /**************************************************************************//**
2 | * @file system_.h
3 | * @brief CMSIS Cortex-M# Device Peripheral Access Layer Header File for
4 | * Device
5 | * @version V3.10
6 | * @date 23. November 2012
7 | *
8 | * @note
9 | *
10 | ******************************************************************************/
11 | /* Copyright (c) 2012 ARM LIMITED
12 |
13 | All rights reserved.
14 | Redistribution and use in source and binary forms, with or without
15 | modification, are permitted provided that the following conditions are met:
16 | - Redistributions of source code must retain the above copyright
17 | notice, this list of conditions and the following disclaimer.
18 | - Redistributions in binary form must reproduce the above copyright
19 | notice, this list of conditions and the following disclaimer in the
20 | documentation and/or other materials provided with the distribution.
21 | - Neither the name of ARM nor the names of its contributors may be used
22 | to endorse or promote products derived from this software without
23 | specific prior written permission.
24 | *
25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 | ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
29 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 | POSSIBILITY OF SUCH DAMAGE.
36 | ---------------------------------------------------------------------------*/
37 |
38 |
39 | #ifndef SYSTEM_Device_H /* ToDo: replace '' with your device name */
40 | #define SYSTEM_Device_H
41 |
42 | #ifdef __cplusplus
43 | extern "C" {
44 | #endif
45 |
46 | #include
47 |
48 | extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */
49 |
50 |
51 | /**
52 | * Initialize the system
53 | *
54 | * @param none
55 | * @return none
56 | *
57 | * @brief Setup the microcontroller system.
58 | * Initialize the System and update the SystemCoreClock variable.
59 | */
60 | extern void SystemInit (void);
61 |
62 | /**
63 | * Update SystemCoreClock variable
64 | *
65 | * @param none
66 | * @return none
67 | *
68 | * @brief Updates the SystemCoreClock with current core Clock
69 | * retrieved from cpu registers.
70 | */
71 | extern void SystemCoreClockUpdate (void);
72 |
73 | #ifdef __cplusplus
74 | }
75 | #endif
76 |
77 | #endif /* SYSTEM__H */
78 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cmsis/system_stm32g4xx.h:
--------------------------------------------------------------------------------
1 | /**
2 | ******************************************************************************
3 | * @file system_stm32g4xx.h
4 | * @author MCD Application Team
5 | * @brief CMSIS Cortex-M4 Device System Source File for STM32G4xx devices.
6 | ******************************************************************************
7 | * @attention
8 | *
9 | * © Copyright (c) 2019 STMicroelectronics.
10 | * All rights reserved.
11 | *
12 | * This software component is licensed by ST under BSD 3-Clause license,
13 | * the "License"; You may not use this file except in compliance with the
14 | * License. You may obtain a copy of the License at:
15 | * opensource.org/licenses/BSD-3-Clause
16 | *
17 | ******************************************************************************
18 | */
19 |
20 | /** @addtogroup CMSIS
21 | * @{
22 | */
23 |
24 | /** @addtogroup stm32g4xx_system
25 | * @{
26 | */
27 |
28 | /**
29 | * @brief Define to prevent recursive inclusion
30 | */
31 | #ifndef __SYSTEM_STM32G4XX_H
32 | #define __SYSTEM_STM32G4XX_H
33 |
34 | #ifdef __cplusplus
35 | extern "C" {
36 | #endif
37 |
38 | /** @addtogroup STM32G4xx_System_Includes
39 | * @{
40 | */
41 |
42 | /**
43 | * @}
44 | */
45 |
46 |
47 | /** @addtogroup STM32G4xx_System_Exported_Variables
48 | * @{
49 | */
50 | /* The SystemCoreClock variable is updated in three ways:
51 | 1) by calling CMSIS function SystemCoreClockUpdate()
52 | 2) by calling HAL API function HAL_RCC_GetSysClockFreq()
53 | 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
54 | Note: If you use this function to configure the system clock; then there
55 | is no need to call the 2 first functions listed above, since SystemCoreClock
56 | variable is updated automatically.
57 | */
58 | extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */
59 |
60 | extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */
61 | extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */
62 |
63 | /**
64 | * @}
65 | */
66 |
67 | /** @addtogroup STM32G4xx_System_Exported_Constants
68 | * @{
69 | */
70 |
71 | /**
72 | * @}
73 | */
74 |
75 | /** @addtogroup STM32G4xx_System_Exported_Macros
76 | * @{
77 | */
78 |
79 | /**
80 | * @}
81 | */
82 |
83 | /** @addtogroup STM32G4xx_System_Exported_Functions
84 | * @{
85 | */
86 |
87 | extern void SystemInit(void);
88 | extern void SystemCoreClockUpdate(void);
89 | /**
90 | * @}
91 | */
92 |
93 | #ifdef __cplusplus
94 | }
95 | #endif
96 |
97 | #endif /*__SYSTEM_STM32G4XX_H */
98 |
99 | /**
100 | * @}
101 | */
102 |
103 | /**
104 | * @}
105 | */
106 | /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
107 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/cortexm/ExceptionHandlers.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | #ifndef CORTEXM_EXCEPTION_HANDLERS_H_
29 | #define CORTEXM_EXCEPTION_HANDLERS_H_
30 |
31 | #include
32 |
33 | #if defined(DEBUG)
34 | #define __DEBUG_BKPT() asm volatile ("bkpt 0")
35 | #endif
36 |
37 | // ----------------------------------------------------------------------------
38 |
39 | #if defined(__cplusplus)
40 | extern "C"
41 | {
42 | #endif
43 |
44 | // External references to cortexm_handlers.c
45 |
46 | extern void
47 | Reset_Handler (void);
48 | extern void
49 | NMI_Handler (void);
50 | extern void
51 | HardFault_Handler (void);
52 |
53 | #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
54 | extern void
55 | MemManage_Handler (void);
56 | extern void
57 | BusFault_Handler (void);
58 | extern void
59 | UsageFault_Handler (void);
60 | extern void
61 | DebugMon_Handler (void);
62 | #endif
63 |
64 | extern void
65 | SVC_Handler (void);
66 |
67 | extern void
68 | PendSV_Handler (void);
69 | extern void
70 | SysTick_Handler (void);
71 |
72 | // Exception Stack Frame of the Cortex-M3 or Cortex-M4 processor.
73 | typedef struct
74 | {
75 | uint32_t r0;
76 | uint32_t r1;
77 | uint32_t r2;
78 | uint32_t r3;
79 | uint32_t r12;
80 | uint32_t lr;
81 | uint32_t pc;
82 | uint32_t psr;
83 | #if defined(__ARM_ARCH_7EM__)
84 | uint32_t s[16];
85 | #endif
86 | } ExceptionStackFrame;
87 |
88 | #if defined(TRACE)
89 | #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
90 | void
91 | dumpExceptionStack (ExceptionStackFrame* frame, uint32_t cfsr, uint32_t mmfar,
92 | uint32_t bfar, uint32_t lr);
93 | #endif // defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
94 | #if defined(__ARM_ARCH_6M__)
95 | void
96 | dumpExceptionStack (ExceptionStackFrame* frame, uint32_t lr);
97 | #endif // defined(__ARM_ARCH_6M__)
98 | #endif // defined(TRACE)
99 |
100 | void
101 | HardFault_Handler_C (ExceptionStackFrame* frame, uint32_t lr);
102 |
103 | #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
104 | void
105 | UsageFault_Handler_C (ExceptionStackFrame* frame, uint32_t lr);
106 | void
107 | BusFault_Handler_C (ExceptionStackFrame* frame, uint32_t lr);
108 | #endif // defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
109 |
110 | #if defined(__cplusplus)
111 | }
112 | #endif
113 |
114 | // ----------------------------------------------------------------------------
115 |
116 | #endif // CORTEXM_EXCEPTION_HANDLERS_H_
117 |
--------------------------------------------------------------------------------
/ebike-g4/system/include/diag/Trace.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | #ifndef DIAG_TRACE_H_
29 | #define DIAG_TRACE_H_
30 |
31 | // ----------------------------------------------------------------------------
32 |
33 | #include
34 |
35 | // ----------------------------------------------------------------------------
36 |
37 | // The trace device is an independent output channel, intended for debug
38 | // purposes.
39 | //
40 | // The API is simple, and mimics the standard output calls:
41 | // - trace_printf()
42 | // - trace_puts()
43 | // - trace_putchar();
44 | //
45 | // The implementation is done in
46 | // - trace_write()
47 | //
48 | // Trace support is enabled by adding the TRACE definition.
49 | // By default the trace messages are forwarded to the ITM output,
50 | // but can be rerouted via any device or completely suppressed by
51 | // changing the definitions required in system/src/diag/trace_impl.c
52 | // (currently OS_USE_TRACE_ITM, OS_USE_TRACE_SEMIHOSTING_DEBUG/_STDOUT).
53 | //
54 | // When TRACE is not defined, all functions are inlined to empty bodies.
55 | // This has the advantage that the trace call do not need to be conditionally
56 | // compiled with #ifdef TRACE/#endif
57 |
58 |
59 | #if defined(TRACE)
60 |
61 | #if defined(__cplusplus)
62 | extern "C"
63 | {
64 | #endif
65 |
66 | void
67 | trace_initialize(void);
68 |
69 | // Implementation dependent
70 | ssize_t
71 | trace_write(const char* buf, size_t nbyte);
72 |
73 | // ----- Portable -----
74 |
75 | int
76 | trace_printf(const char* format, ...);
77 |
78 | int
79 | trace_puts(const char *s);
80 |
81 | int
82 | trace_putchar(int c);
83 |
84 | void
85 | trace_dump_args(int argc, char* argv[]);
86 |
87 | #if defined(__cplusplus)
88 | }
89 | #endif
90 |
91 | #else // !defined(TRACE)
92 |
93 | #if defined(__cplusplus)
94 | extern "C"
95 | {
96 | #endif
97 |
98 | inline void
99 | trace_initialize(void);
100 |
101 | // Implementation dependent
102 | inline ssize_t
103 | trace_write(const char* buf, size_t nbyte);
104 |
105 | inline int
106 | trace_printf(const char* format, ...);
107 |
108 | inline int
109 | trace_puts(const char *s);
110 |
111 | inline int
112 | trace_putchar(int c);
113 |
114 | inline void
115 | trace_dump_args(int argc, char* argv[]);
116 |
117 | #if defined(__cplusplus)
118 | }
119 | #endif
120 |
121 | inline void
122 | __attribute__((always_inline))
123 | trace_initialize(void)
124 | {
125 | }
126 |
127 | // Empty definitions when trace is not defined
128 | inline ssize_t
129 | __attribute__((always_inline))
130 | trace_write(const char* buf __attribute__((unused)),
131 | size_t nbyte __attribute__((unused)))
132 | {
133 | return 0;
134 | }
135 |
136 | inline int
137 | __attribute__((always_inline))
138 | trace_printf(const char* format __attribute__((unused)), ...)
139 | {
140 | return 0;
141 | }
142 |
143 | inline int
144 | __attribute__((always_inline))
145 | trace_puts(const char *s __attribute__((unused)))
146 | {
147 | return 0;
148 | }
149 |
150 | inline int
151 | __attribute__((always_inline))
152 | trace_putchar(int c)
153 | {
154 | return c;
155 | }
156 |
157 | inline void
158 | __attribute__((always_inline))
159 | trace_dump_args(int argc __attribute__((unused)),
160 | char* argv[] __attribute__((unused)))
161 | {
162 | }
163 |
164 | #endif // defined(TRACE)
165 |
166 | // ----------------------------------------------------------------------------
167 |
168 | #endif // DIAG_TRACE_H_
169 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/DEVICE/README_DRIVERS.txt:
--------------------------------------------------------------------------------
1 | This folder is a placeholder where to add vendor provided source files
2 | from the peripheral drivers library.
3 |
4 | Study the vendor drivers library and identify the drivers source files.
5 | Copy the files you need in your project to this folder.
6 |
7 | Be sure you include the corresponding header files in the include folder.
--------------------------------------------------------------------------------
/ebike-g4/system/src/cmsis/README_DEVICE.txt:
--------------------------------------------------------------------------------
1 | These files are provided only as a functional sample.
2 |
3 | For real applications they must be replaced with the files
4 | provided by the vendor.
5 |
6 | Extensions to the ARM CMSIS files:
7 |
8 | - the assembly startup file was reimplemented in C, and split into
9 | multiple files, portable for the entire Cortex-M family:
10 |
11 | src/newlib/_startup.c
12 | src/cortexm/exception_handlers.c
13 |
14 | - the chip interrupt handlers must be added to the file
15 |
16 | src/cmsis/vectors_DEVICE.c
17 |
18 |
19 | Use of assembly files
20 | ---------------------
21 |
22 | The current version of the Eclipse managed build plug-in does not
23 | process .s, but only .S. If you want to use the assembly startup_Device.s,
24 | you must exclude the _startup.c and exception_handlers.c from build, and
25 | rename the vendor provided assembly file to startup_XXX.S, where XXX is the
26 | actual device name.
27 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/cmsis/arm_sin_cos_f32.c:
--------------------------------------------------------------------------------
1 | /* ----------------------------------------------------------------------
2 | * Copyright (C) 2010-2014 ARM Limited. All rights reserved.
3 | *
4 | * $Date: 12. March 2014
5 | * $Revision: V1.4.4
6 | *
7 | * Project: CMSIS DSP Library
8 | * Title: arm_sin_cos_f32.c
9 | *
10 | * Description: Sine and Cosine calculation for floating-point values.
11 | *
12 | * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
13 | *
14 | * Redistribution and use in source and binary forms, with or without
15 | * modification, are permitted provided that the following conditions
16 | * are met:
17 | * - Redistributions of source code must retain the above copyright
18 | * notice, this list of conditions and the following disclaimer.
19 | * - Redistributions in binary form must reproduce the above copyright
20 | * notice, this list of conditions and the following disclaimer in
21 | * the documentation and/or other materials provided with the
22 | * distribution.
23 | * - Neither the name of ARM LIMITED nor the names of its contributors
24 | * may be used to endorse or promote products derived from this
25 | * software without specific prior written permission.
26 | *
27 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
30 | * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
31 | * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
34 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
35 | * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
37 | * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38 | * POSSIBILITY OF SUCH DAMAGE.
39 | * -------------------------------------------------------------------- */
40 | #include "stm32g4xx.h"
41 | #include "arm_math.h"
42 | #include "arm_common_tables.h"
43 |
44 | /**
45 | * @ingroup groupController
46 | */
47 |
48 | /**
49 | * @defgroup SinCos Sine Cosine
50 | *
51 | * Computes the trigonometric sine and cosine values using a combination of table lookup
52 | * and linear interpolation.
53 | * There are separate functions for Q31 and floating-point data types.
54 | * The input to the floating-point version is in degrees while the
55 | * fixed-point Q31 have a scaled input with the range
56 | * [-1 0.9999] mapping to [-180 +180] degrees.
57 | *
58 | * The floating point function also allows values that are out of the usual range. When this happens, the function will
59 | * take extra time to adjust the input value to the range of [-180 180].
60 | *
61 | * The implementation is based on table lookup using 360 values together with linear interpolation.
62 | * The steps used are:
63 | * -# Calculation of the nearest integer table index.
64 | * -# Compute the fractional portion (fract) of the input.
65 | * -# Fetch the value corresponding to \c index from sine table to \c y0 and also value from \c index+1 to \c y1.
66 | * -# Sine value is computed as *psinVal = y0 + (fract * (y1 - y0))
.
67 | * -# Fetch the value corresponding to \c index from cosine table to \c y0 and also value from \c index+1 to \c y1.
68 | * -# Cosine value is computed as *pcosVal = y0 + (fract * (y1 - y0))
.
69 | */
70 |
71 | /**
72 | * @addtogroup SinCos
73 | * @{
74 | */
75 |
76 | /**
77 | * @brief Floating-point sin_cos function.
78 | * @param[in] theta input value in degrees
79 | * @param[out] *pSinVal points to the processed sine output.
80 | * @param[out] *pCosVal points to the processed cos output.
81 | * @return none.
82 | */
83 |
84 | void arm_sin_cos_f32(
85 | float32_t theta,
86 | float32_t * pSinVal,
87 | float32_t * pCosVal)
88 | {
89 | float32_t fract, in; /* Temporary variables for input, output */
90 | uint16_t indexS, indexC; /* Index variable */
91 | float32_t f1, f2, d1, d2; /* Two nearest output values */
92 | int32_t n;
93 | float32_t findex, Dn, Df, temp;
94 |
95 | /* input x is in degrees */
96 | /* Scale the input, divide input by 360, for cosine add 0.25 (pi/2) to read sine table */
97 | in = theta * 0.00277777777778f;
98 |
99 | /* Calculation of floor value of input */
100 | n = (int32_t) in;
101 |
102 | /* Make negative values towards -infinity */
103 | if(in < 0.0f)
104 | {
105 | n--;
106 | }
107 | /* Map input value to [0 1] */
108 | in = in - (float32_t) n;
109 |
110 | /* Calculation of index of the table */
111 | findex = (float32_t) FAST_MATH_TABLE_SIZE * in;
112 | indexS = ((uint16_t)findex) & 0x1ff;
113 | indexC = (indexS + (FAST_MATH_TABLE_SIZE / 4)) & 0x1ff;
114 |
115 | /* fractional value calculation */
116 | fract = findex - (float32_t) indexS;
117 |
118 | /* Read two nearest values of input value from the cos & sin tables */
119 | f1 = sinTable_f32[indexC+0];
120 | f2 = sinTable_f32[indexC+1];
121 | d1 = -sinTable_f32[indexS+0];
122 | d2 = -sinTable_f32[indexS+1];
123 |
124 | Dn = 0.0122718463030f; // delta between the two points (fixed), in this case 2*pi/FAST_MATH_TABLE_SIZE
125 | Df = f2 - f1; // delta between the values of the functions
126 | temp = Dn*(d1 + d2) - 2*Df;
127 | temp = fract*temp + (3*Df - (d2 + 2*d1)*Dn);
128 | temp = fract*temp + d1*Dn;
129 |
130 | /* Calculation of cosine value */
131 | *pCosVal = fract*temp + f1;
132 |
133 | /* Read two nearest values of input value from the cos & sin tables */
134 | f1 = sinTable_f32[indexS+0];
135 | f2 = sinTable_f32[indexS+1];
136 | d1 = sinTable_f32[indexC+0];
137 | d2 = sinTable_f32[indexC+1];
138 |
139 | Df = f2 - f1; // delta between the values of the functions
140 | temp = Dn*(d1 + d2) - 2*Df;
141 | temp = fract*temp + (3*Df - (d2 + 2*d1)*Dn);
142 | temp = fract*temp + d1*Dn;
143 |
144 | /* Calculation of sine value */
145 | *pSinVal = fract*temp + f1;
146 | }
147 | /**
148 | * @} end of SinCos group
149 | */
150 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/cmsis/system_DEVICE.c:
--------------------------------------------------------------------------------
1 | /**************************************************************************//**
2 | * @file system_.c
3 | * @brief CMSIS Cortex-M# Device Peripheral Access Layer Source File for
4 | * Device
5 | * @version V3.10
6 | * @date 23. November 2012
7 | *
8 | * @note
9 | *
10 | ******************************************************************************/
11 | /* Copyright (c) 2012 ARM LIMITED
12 |
13 | All rights reserved.
14 | Redistribution and use in source and binary forms, with or without
15 | modification, are permitted provided that the following conditions are met:
16 | - Redistributions of source code must retain the above copyright
17 | notice, this list of conditions and the following disclaimer.
18 | - Redistributions in binary form must reproduce the above copyright
19 | notice, this list of conditions and the following disclaimer in the
20 | documentation and/or other materials provided with the distribution.
21 | - Neither the name of ARM nor the names of its contributors may be used
22 | to endorse or promote products derived from this software without
23 | specific prior written permission.
24 | *
25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 | ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
29 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 | POSSIBILITY OF SUCH DAMAGE.
36 | ---------------------------------------------------------------------------*/
37 |
38 |
39 | #include
40 | #include "DEVICE.h"
41 |
42 |
43 | /*----------------------------------------------------------------------------
44 | DEFINES
45 | *----------------------------------------------------------------------------*/
46 |
47 | /*----------------------------------------------------------------------------
48 | Define clocks
49 | *----------------------------------------------------------------------------*/
50 | /* ToDo: add here your necessary defines for device initialization
51 | following is an example for different system frequencies */
52 | #define __HSI ( 6000000UL)
53 | #define __XTAL (12000000UL) /* Oscillator frequency */
54 | #define __SYS_OSC_CLK ( ___HSI) /* Main oscillator frequency */
55 |
56 | #define __SYSTEM_CLOCK (168000000UL)
57 |
58 |
59 | /*----------------------------------------------------------------------------
60 | Clock Variable definitions
61 | *----------------------------------------------------------------------------*/
62 | /* ToDo: initialize SystemCoreClock with the system core clock frequency value
63 | achieved after system intitialization.
64 | This means system core clock frequency after call to SystemInit() */
65 | uint32_t SystemCoreClock = __SYSTEM_CLOCK; /*!< System Clock Frequency (Core Clock)*/
66 |
67 |
68 | /*----------------------------------------------------------------------------
69 | Clock functions
70 | *----------------------------------------------------------------------------*/
71 | void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */
72 | {
73 | /* ToDo: add code to calculate the system frequency based upon the current
74 | register settings.
75 | This function can be used to retrieve the system core clock frequeny
76 | after user changed register sittings. */
77 | SystemCoreClock = __SYSTEM_CLOCK;
78 | }
79 |
80 | /**
81 | * Initialize the system
82 | *
83 | * @param none
84 | * @return none
85 | *
86 | * @brief Setup the microcontroller system.
87 | * Initialize the System.
88 | */
89 | void SystemInit (void)
90 | {
91 | /* ToDo: add code to initialize the system
92 | do not use global variables because this function is called before
93 | reaching pre-main. RW section maybe overwritten afterwards. */
94 | SystemCoreClock = __SYSTEM_CLOCK;
95 | }
96 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/cmsis/vectors_DEVICE.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // ----------------------------------------------------------------------------
29 |
30 | #include "cortexm/ExceptionHandlers.h"
31 |
32 | // ----------------------------------------------------------------------------
33 |
34 | void __attribute__((weak))
35 | Default_Handler(void);
36 |
37 | // Forward declaration of the specific IRQ handlers. These are aliased
38 | // to the Default_Handler, which is a 'forever' loop. When the application
39 | // defines a handler (with the same name), this will automatically take
40 | // precedence over these weak definitions
41 | //
42 | // TODO: Rename this and add the actual routines here.
43 |
44 | void __attribute__ ((weak, alias ("Default_Handler")))
45 | DeviceInterrupt_Handler(void);
46 |
47 | // ----------------------------------------------------------------------------
48 |
49 | extern unsigned int _estack;
50 |
51 | typedef void
52 | (* const pHandler)(void);
53 |
54 | // ----------------------------------------------------------------------------
55 |
56 | // The vector table.
57 | // This relies on the linker script to place at correct location in memory.
58 |
59 | __attribute__ ((section(".isr_vector"),used))
60 | pHandler __isr_vectors[] =
61 | { //
62 | (pHandler) &_estack, // The initial stack pointer
63 | Reset_Handler, // The reset handler
64 |
65 | NMI_Handler, // The NMI handler
66 | HardFault_Handler, // The hard fault handler
67 |
68 | #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
69 | MemManage_Handler, // The MPU fault handler
70 | BusFault_Handler,// The bus fault handler
71 | UsageFault_Handler,// The usage fault handler
72 | #else
73 | 0, 0, 0, // Reserved
74 | #endif
75 | 0, // Reserved
76 | 0, // Reserved
77 | 0, // Reserved
78 | 0, // Reserved
79 | SVC_Handler, // SVCall handler
80 | #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
81 | DebugMon_Handler, // Debug monitor handler
82 | #else
83 | 0, // Reserved
84 | #endif
85 | 0, // Reserved
86 | PendSV_Handler, // The PendSV handler
87 | SysTick_Handler, // The SysTick handler
88 |
89 | // ----------------------------------------------------------------------
90 | // DEVICE vectors
91 | DeviceInterrupt_Handler, // Device specific
92 | // TODO: rename and add more vectors here
93 | };
94 |
95 | // ----------------------------------------------------------------------------
96 |
97 | // Processor ends up here if an unexpected interrupt occurs or a specific
98 | // handler is not present in the application code.
99 |
100 | void __attribute__ ((section(".after_vectors")))
101 | Default_Handler(void)
102 | {
103 | while (1)
104 | {
105 | }
106 | }
107 |
108 | // ----------------------------------------------------------------------------
109 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/cortexm/_initialize_hardware.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // ----------------------------------------------------------------------------
29 |
30 | #include "cmsis_device.h"
31 |
32 | // ----------------------------------------------------------------------------
33 |
34 | extern unsigned int __vectors_start;
35 |
36 | // Forward declarations.
37 |
38 | void
39 | __initialize_hardware_early(void);
40 |
41 | void
42 | __initialize_hardware(void);
43 |
44 | // ----------------------------------------------------------------------------
45 |
46 | // This is the early hardware initialisation routine, it can be
47 | // redefined in the application for more complex cases that
48 | // require early inits (before BSS init).
49 | //
50 | // Called early from _start(), right before data & bss init.
51 | //
52 | // After Reset the Cortex-M processor is in Thread mode,
53 | // priority is Privileged, and the Stack is set to Main.
54 |
55 | void
56 | __attribute__((weak))
57 | __initialize_hardware_early(void)
58 | {
59 | // Call the CSMSIS system initialisation routine.
60 | SystemInit();
61 |
62 | #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
63 | // Set VTOR to the actual address, provided by the linker script.
64 | // Override the manual, possibly wrong, SystemInit() setting.
65 | SCB->VTOR = (uint32_t)(&__vectors_start);
66 | #endif
67 |
68 | // The current version of SystemInit() leaves the value of the clock
69 | // in a RAM variable (SystemCoreClock), which will be cleared shortly,
70 | // so it needs to be recomputed after the RAM initialisations
71 | // are completed.
72 |
73 | #if defined(OS_INCLUDE_STARTUP_INIT_FP) || (defined (__VFP_FP__) && !defined (__SOFTFP__))
74 |
75 | // Normally FP init is done by SystemInit(). In case this is not done
76 | // there, it is possible to force its inclusion by defining
77 | // OS_INCLUDE_STARTUP_INIT_FP.
78 |
79 | // Enable the Cortex-M4 FPU only when -mfloat-abi=hard.
80 | // Code taken from Section 7.1, Cortex-M4 TRM (DDI0439C)
81 |
82 | // Set bits 20-23 to enable CP10 and CP11 coprocessor
83 | SCB->CPACR |= (0xF << 20);
84 |
85 | #endif // (__VFP_FP__) && !(__SOFTFP__)
86 |
87 | #if defined(OS_DEBUG_SEMIHOSTING_FAULTS)
88 | SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk;
89 | #endif
90 | }
91 |
92 | // This is the second hardware initialisation routine, it can be
93 | // redefined in the application for more complex cases that
94 | // require custom inits (before constructors), otherwise these can
95 | // be done in main().
96 | //
97 | // Called from _start(), right after data & bss init, before
98 | // constructors.
99 |
100 | void
101 | __attribute__((weak))
102 | __initialize_hardware(void)
103 | {
104 | // Call the CSMSIS system clock routine to store the clock frequency
105 | // in the SystemCoreClock global RAM location.
106 | SystemCoreClockUpdate();
107 | }
108 |
109 | // ----------------------------------------------------------------------------
110 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/cortexm/_reset_hardware.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // ----------------------------------------------------------------------------
29 |
30 | #include "cmsis_device.h"
31 |
32 | // ----------------------------------------------------------------------------
33 |
34 | extern void
35 | __attribute__((noreturn))
36 | NVIC_SystemReset(void);
37 |
38 | // ----------------------------------------------------------------------------
39 |
40 | // Forward declarations
41 |
42 | void
43 | __reset_hardware(void);
44 |
45 | // ----------------------------------------------------------------------------
46 |
47 | // This is the default hardware reset routine; it can be
48 | // redefined in the application for more complex applications.
49 | //
50 | // Called from _exit().
51 |
52 | void
53 | __attribute__((weak,noreturn))
54 | __reset_hardware()
55 | {
56 | NVIC_SystemReset();
57 | }
58 |
59 | // ----------------------------------------------------------------------------
60 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/diag/Trace.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // ----------------------------------------------------------------------------
29 |
30 | #if defined(TRACE)
31 |
32 | #include
33 | #include
34 | #include "diag/Trace.h"
35 | #include "string.h"
36 |
37 | #ifndef OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE
38 | #define OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE (128)
39 | #endif
40 |
41 | // ----------------------------------------------------------------------------
42 |
43 | int
44 | trace_printf(const char* format, ...)
45 | {
46 | int ret;
47 | va_list ap;
48 |
49 | va_start (ap, format);
50 |
51 | // TODO: rewrite it to no longer use newlib, it is way too heavy
52 |
53 | static char buf[OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE];
54 |
55 | // Print to the local buffer
56 | ret = vsnprintf (buf, sizeof(buf), format, ap);
57 | if (ret > 0)
58 | {
59 | // Transfer the buffer to the device
60 | ret = trace_write (buf, (size_t)ret);
61 | }
62 |
63 | va_end (ap);
64 | return ret;
65 | }
66 |
67 | int
68 | trace_puts(const char *s)
69 | {
70 | trace_write(s, strlen(s));
71 | return trace_write("\n", 1);
72 | }
73 |
74 | int
75 | trace_putchar(int c)
76 | {
77 | trace_write((const char*)&c, 1);
78 | return c;
79 | }
80 |
81 | void
82 | trace_dump_args(int argc, char* argv[])
83 | {
84 | trace_printf("main(argc=%d, argv=[", argc);
85 | for (int i = 0; i < argc; ++i)
86 | {
87 | if (i != 0)
88 | {
89 | trace_printf(", ");
90 | }
91 | trace_printf("\"%s\"", argv[i]);
92 | }
93 | trace_printf("]);\n");
94 | }
95 |
96 | // ----------------------------------------------------------------------------
97 |
98 | #endif // TRACE
99 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/newlib/README.txt:
--------------------------------------------------------------------------------
1 |
2 | The following files extend or replace some of the the newlib functionality:
3 |
4 | _startup.c: a customised startup sequence, written in C
5 |
6 | _exit.c: a customised exit() implementation
7 |
8 | _syscalls.c: local versions of the libnosys/librdimon code
9 |
10 | _sbrk.c: a custom _sbrk() to match the actual linker scripts
11 |
12 | assert.c: implementation for the asserion macros
13 |
14 | _cxx.cpp: local versions of some C++ support, to avoid references to
15 | large functions.
16 |
17 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/newlib/_cxx.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // ----------------------------------------------------------------------------
29 |
30 | // These functions are redefined locally, to avoid references to some
31 | // heavy implementations in the standard C++ library.
32 |
33 | // ----------------------------------------------------------------------------
34 |
35 | #include
36 | #include
37 | #include "diag/Trace.h"
38 |
39 | // ----------------------------------------------------------------------------
40 |
41 | namespace __gnu_cxx
42 | {
43 | void
44 | __attribute__((noreturn))
45 | __verbose_terminate_handler();
46 |
47 | void
48 | __verbose_terminate_handler()
49 | {
50 | trace_puts(__func__);
51 | abort();
52 | }
53 | }
54 |
55 | // ----------------------------------------------------------------------------
56 |
57 | extern "C"
58 | {
59 | void
60 | __attribute__((noreturn))
61 | __cxa_pure_virtual();
62 |
63 | void
64 | __cxa_pure_virtual()
65 | {
66 | trace_puts(__func__);
67 | abort();
68 | }
69 | }
70 |
71 | // ----------------------------------------------------------------------------
72 |
73 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/newlib/_exit.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // ----------------------------------------------------------------------------
29 |
30 | #include
31 | #include "diag/Trace.h"
32 |
33 | // ----------------------------------------------------------------------------
34 |
35 | #if !defined(DEBUG)
36 | extern void
37 | __attribute__((noreturn))
38 | __reset_hardware(void);
39 | #endif
40 |
41 | // ----------------------------------------------------------------------------
42 |
43 | // Forward declaration
44 |
45 | void
46 | _exit(int code);
47 |
48 | // ----------------------------------------------------------------------------
49 |
50 | // On Release, call the hardware reset procedure.
51 | // On Debug we just enter an infinite loop, to be used as landmark when halting
52 | // the debugger.
53 | //
54 | // It can be redefined in the application, if more functionality
55 | // is required.
56 |
57 | void
58 | __attribute__((weak))
59 | _exit(int code __attribute__((unused)))
60 | {
61 | #if !defined(DEBUG)
62 | __reset_hardware();
63 | #endif
64 |
65 | // TODO: write on trace
66 | while (1)
67 | ;
68 | }
69 |
70 | // ----------------------------------------------------------------------------
71 |
72 | void
73 | __attribute__((weak,noreturn))
74 | abort(void)
75 | {
76 | trace_puts("abort(), exiting...");
77 |
78 | _exit(1);
79 | }
80 |
81 | // ----------------------------------------------------------------------------
82 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/newlib/_sbrk.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | // ----------------------------------------------------------------------------
29 |
30 | #include
31 | #include
32 |
33 | // ----------------------------------------------------------------------------
34 |
35 | caddr_t
36 | _sbrk(int incr);
37 |
38 | // ----------------------------------------------------------------------------
39 |
40 | // The definitions used here should be kept in sync with the
41 | // stack definitions in the linker script.
42 |
43 | caddr_t
44 | _sbrk(int incr)
45 | {
46 | extern char _Heap_Begin; // Defined by the linker.
47 | extern char _Heap_Limit; // Defined by the linker.
48 |
49 | static char* current_heap_end;
50 | char* current_block_address;
51 |
52 | if (current_heap_end == 0)
53 | {
54 | current_heap_end = &_Heap_Begin;
55 | }
56 |
57 | current_block_address = current_heap_end;
58 |
59 | // Need to align heap to word boundary, else will get
60 | // hard faults on Cortex-M0. So we assume that heap starts on
61 | // word boundary, hence make sure we always add a multiple of
62 | // 4 to it.
63 | incr = (incr + 3) & (~3); // align value to 4
64 | if (current_heap_end + incr > &_Heap_Limit)
65 | {
66 | // Some of the libstdc++-v3 tests rely upon detecting
67 | // out of memory errors, so do not abort here.
68 | #if 0
69 | extern void abort (void);
70 |
71 | _write (1, "_sbrk: Heap and stack collision\n", 32);
72 |
73 | abort ();
74 | #else
75 | // Heap has overflowed
76 | errno = ENOMEM;
77 | return (caddr_t) - 1;
78 | #endif
79 | }
80 |
81 | current_heap_end += incr;
82 |
83 | return (caddr_t) current_block_address;
84 | }
85 |
86 | // ----------------------------------------------------------------------------
87 |
88 |
--------------------------------------------------------------------------------
/ebike-g4/system/src/newlib/assert.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the µOS++ distribution.
3 | * (https://github.com/micro-os-plus)
4 | * Copyright (c) 2014 Liviu Ionescu.
5 | *
6 | * Permission is hereby granted, free of charge, to any person
7 | * obtaining a copy of this software and associated documentation
8 | * files (the "Software"), to deal in the Software without
9 | * restriction, including without limitation the rights to use,
10 | * copy, modify, merge, publish, distribute, sublicense, and/or
11 | * sell copies of the Software, and to permit persons to whom
12 | * the Software is furnished to do so, subject to the following
13 | * conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be
16 | * included in all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 | * OTHER DEALINGS IN THE SOFTWARE.
26 | */
27 |
28 | #include
29 | #include
30 | #include
31 |
32 | #include "diag/Trace.h"
33 |
34 | // ----------------------------------------------------------------------------
35 |
36 | void
37 | __attribute__((noreturn))
38 | __assert_func (const char *file, int line, const char *func,
39 | const char *failedexpr)
40 | {
41 | trace_printf ("assertion \"%s\" failed: file \"%s\", line %d%s%s\n",
42 | failedexpr, file, line, func ? ", function: " : "",
43 | func ? func : "");
44 | abort ();
45 | /* NOTREACHED */
46 | }
47 |
48 | // ----------------------------------------------------------------------------
49 |
50 | // This is STM32 specific, but can be used on other platforms too.
51 | // If you need it, add the following to your application header:
52 |
53 | //#ifdef USE_FULL_ASSERT
54 | //#define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
55 | //void assert_failed(uint8_t* file, uint32_t line);
56 | //#else
57 | //#define assert_param(expr) ((void)0)
58 | //#endif // USE_FULL_ASSERT
59 |
60 | #if defined(USE_FULL_ASSERT)
61 |
62 | void
63 | assert_failed (uint8_t* file, uint32_t line);
64 |
65 | // Called from the assert_param() macro, usually defined in the stm32f*_conf.h
66 | void
67 | __attribute__((noreturn, weak))
68 | assert_failed (uint8_t* file, uint32_t line)
69 | {
70 | trace_printf ("assert_param() failed: file \"%s\", line %d\n", file, line);
71 | abort ();
72 | /* NOTREACHED */
73 | }
74 |
75 | #endif // defined(USE_FULL_ASSERT)
76 |
77 | // ----------------------------------------------------------------------------
78 |
--------------------------------------------------------------------------------
/scripts/comm_commands.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/scripts/live_data_ids.py:
--------------------------------------------------------------------------------
1 |
2 | #!/usr/bin/python
3 | # -*- coding: utf-8 -*-
4 | """
5 | Auto-generated file. Do not edit!
6 | If changes are needed, edit the variable settings in 'datavars.xml' and
7 | re-run 'datavar_codegen.py' to recreate this file.
8 |
9 | Defines the ID codes for debugging outputs.
10 | """
11 |
12 | class Debug_IDs:
13 | variables = [
14 | {'name':'IA', 'id': 1, 'longname': 'Phase A current (amps)'},
15 | {'name':'IB', 'id': 2, 'longname': 'Phase B current (amps)'},
16 | {'name':'IC', 'id': 3, 'longname': 'Phase C current (amps)'},
17 | {'name':'TA', 'id': 4, 'longname': 'Phase A PWM duty cycle (percent)'},
18 | {'name':'TB', 'id': 5, 'longname': 'Phase B PWM duty cycle (percent)'},
19 | {'name':'TC', 'id': 6, 'longname': 'Phase C PWM duty cycle (percent)'},
20 | {'name':'THROTTLE', 'id': 7, 'longname': 'Throttle position (percent)'},
21 | {'name':'HALLANGLE', 'id': 8, 'longname': 'Hall sensor angle (zero to one)'},
22 | {'name':'HALLSPEED', 'id': 9, 'longname': 'Hall sensor speed (Hz)'},
23 | {'name':'HALLACCEL', 'id': 10, 'longname': 'Hall sensor acceleration (Hz/s)'},
24 | {'name':'HALLSTATE', 'id': 11, 'longname': 'Hall sensor state (1 to 6)'},
25 | {'name':'VBUS', 'id': 12, 'longname': 'Battery voltage'},
26 | {'name':'ID', 'id': 13, 'longname': 'D phase current (amps)'},
27 | {'name':'IQ', 'id': 14, 'longname': 'Q phase current (amps)'},
28 | {'name':'TD', 'id': 15, 'longname': 'D phase duty cycle (percent)'},
29 | {'name':'TQ', 'id': 16, 'longname': 'Q phase duty cycle (percent)'},
30 | {'name':'VA', 'id': 17, 'longname': 'Phase A voltage'},
31 | {'name':'VB', 'id': 18, 'longname': 'Phase B voltage'},
32 | {'name':'VC', 'id': 19, 'longname': 'Phase C voltage'},
33 | {'name':'FTEMP', 'id': 20, 'longname': 'Motor controller (MOSFET) temperature (degC)'},
34 | {'name':'ERRORCODE', 'id': 21, 'longname': 'Error code (packed binary)'},
35 | {'name':'RAWTHROTTLE', 'id': 22, 'longname': 'Raw throttle voltage'},
36 | ]
37 |
38 |
--------------------------------------------------------------------------------
/scripts/plotMotorData/ebike_controller_packet.py:
--------------------------------------------------------------------------------
1 | '''
2 |
3 | Creates and upacks packets using the ebike-controller format.
4 | Packets are constructed as follows:
5 |
6 | 0->1: Start of Packet
7 | 2: PacketID
8 | 3: nPacketID
9 | 4->5: length of data field (n)
10 | 6->6+n: data
11 | 7+n-10+n: CRC32 on bytes 0->6+n
12 |
13 | '''
14 |
15 | import zlib
16 |
17 | class Packet:
18 | SOP1 = 0x9A
19 | SOP2 = 0xCC
20 | def __init__(self, packetID, data):
21 | self.PacketID = packetID
22 | self.Data = data
23 |
24 | def crc32_padded(input_bytes):
25 | packet_for_crc = input_bytes
26 | while((len(packet_for_crc) % 4) != 0):
27 | packet_for_crc = packet_for_crc + bytes([0])
28 |
29 | crc32 = zlib.crc32(packet_for_crc)
30 | return crc32
31 |
32 | def ebike_unpack(raw_bytes):
33 | # Search for the start string
34 | sop_loc = raw_bytes.find(bytes([Packet.SOP1,Packet.SOP2]))
35 | if(sop_loc < 0):
36 | # No packets found
37 | return (Packet(0,0), -1, -1)
38 | if(sop_loc+6 > len(raw_bytes)):
39 | # Raw data length too short, but packet might still be coming
40 | return (Packet(0,0), sop_loc, -1)
41 |
42 | # Get packet ID and nPacket ID
43 | packetID = raw_bytes[sop_loc + 2]
44 | nPacketID = raw_bytes[sop_loc + 3]
45 | if(not (packetID == ((~nPacketID)&255))):
46 | # Packet ID failed, could have been false SOP
47 | # Try remainder of data with some recursion
48 | (pkt, sop_loc, packet_length) = ebike_unpack(raw_bytes[sop_loc+2:])
49 | if(sop_loc >= 0 and packet_length > 0):
50 | return (pkt, sop_loc, packet_length)
51 | else:
52 | return (Packet(0,0), -1, -1)
53 |
54 | data_length = (raw_bytes[sop_loc+4] << 8) + raw_bytes[sop_loc+5]
55 | if(sop_loc+6+data_length+4 > len(raw_bytes)):
56 | # Raw data length too short, but packet might still be coming
57 | return (Packet(0,0), sop_loc, -1)
58 |
59 | data = raw_bytes[sop_loc+6:sop_loc+6+data_length]
60 | remote_crc = raw_bytes[sop_loc+6+data_length:sop_loc+10+data_length]
61 | local_crc = crc32_padded(raw_bytes[sop_loc:sop_loc+6+data_length]).to_bytes(4,byteorder='big')
62 | if(remote_crc != local_crc):
63 | # CRC failed. Check the rest of the data for SOP and packet
64 | (pkt, sop_loc, packet_length) = ebike_unpack(raw_bytes[sop_loc+2:])
65 | if(sop_loc >= 0 and packet_length > 0):
66 | return (pkt, sop_loc, packet_length)
67 | else:
68 | return (Packet(0,0), -1, -1)
69 | # If we get here, everything was succesful!
70 | return (Packet(packetID, data), sop_loc, 10+data_length)
71 |
72 | def ebike_pack(packetID, data):
73 | packet_bytes = bytearray([Packet.SOP1,Packet.SOP2])
74 |
75 | packet_bytes+=bytes([packetID&255, ((~packetID)&255)])
76 |
77 | data_length = len(data)
78 | packet_bytes+=bytes([((data_length&0xFF00) >> 8), (data_length&0x00FF)])
79 |
80 | packet_bytes+=data
81 |
82 | mycrc = crc32_padded(packet_bytes).to_bytes(4,byteorder='big')
83 | packet_bytes+=mycrc
84 | return packet_bytes
85 |
--------------------------------------------------------------------------------
/scripts/plotMotorData/params.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 | ParamsForm
4 |
5 |
6 |
7 | 0
8 | 0
9 | 286
10 | 491
11 |
12 |
13 |
14 | Set Parameters
15 |
16 |
17 | -
18 |
19 |
20 | Data Rate: 50Hz
21 |
22 |
23 |
24 | -
25 |
26 |
27 | -
28 |
29 |
30 | Param10
31 |
32 |
33 |
34 | -
35 |
36 |
37 |
38 | 120
39 | 0
40 |
41 |
42 |
43 | Number of Variables
44 |
45 |
46 |
47 | -
48 |
49 |
50 | 1
51 |
52 |
53 | 10
54 |
55 |
56 |
57 | -
58 |
59 |
60 | -
61 |
62 |
63 | -
64 |
65 |
66 | -
67 |
68 |
69 | -
70 |
71 |
72 | Param2
73 |
74 |
75 |
76 | -
77 |
78 |
79 | -
80 |
81 |
82 | Param3
83 |
84 |
85 |
86 | -
87 |
88 |
89 | Param9
90 |
91 |
92 |
93 | -
94 |
95 |
96 | -
97 |
98 |
99 | Param7
100 |
101 |
102 |
103 | -
104 |
105 |
106 | Cancel
107 |
108 |
109 |
110 | -
111 |
112 |
113 | Param8
114 |
115 |
116 |
117 | -
118 |
119 |
120 | 5
121 |
122 |
123 | 1
124 |
125 |
126 | true
127 |
128 |
129 |
130 | -
131 |
132 |
133 | -
134 |
135 |
136 | Param4
137 |
138 |
139 |
140 | -
141 |
142 |
143 | Param5
144 |
145 |
146 |
147 | -
148 |
149 |
150 | Param1
151 |
152 |
153 |
154 | -
155 |
156 |
157 | Param6
158 |
159 |
160 |
161 | -
162 |
163 |
164 | -
165 |
166 |
167 | -
168 |
169 |
170 | Ok
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
--------------------------------------------------------------------------------
/scripts/plotMotorData/plotwin.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Form implementation generated from reading ui file '.\plotMotorData\plotwin.ui',
4 | # licensing of '.\plotMotorData\plotwin.ui' applies.
5 | #
6 | # Created: Sat Aug 17 14:34:33 2019
7 | # by: pyside2-uic running on PySide2 5.12.2
8 | #
9 | # WARNING! All changes made in this file will be lost!
10 |
11 | from PySide2 import QtCore, QtGui, QtWidgets
12 | from PySide2 import QtCharts
13 |
14 | class Ui_Form(object):
15 | def setupUi(self, Form):
16 | Form.setObjectName("Form")
17 | Form.resize(749, 455)
18 | self.gridLayout = QtWidgets.QGridLayout(Form)
19 | self.gridLayout.setObjectName("gridLayout")
20 | self.btnStop = QtWidgets.QPushButton(Form)
21 | self.btnStop.setObjectName("btnStop")
22 | self.gridLayout.addWidget(self.btnStop, 1, 1, 1, 1)
23 | self.btnStart = QtWidgets.QPushButton(Form)
24 | self.btnStart.setObjectName("btnStart")
25 | self.gridLayout.addWidget(self.btnStart, 1, 0, 1, 1)
26 | self.listwPorts = QtWidgets.QListWidget(Form)
27 | self.listwPorts.setObjectName("listwPorts")
28 | self.gridLayout.addWidget(self.listwPorts, 3, 0, 1, 2)
29 | self.btnListPorts = QtWidgets.QPushButton(Form)
30 | self.btnListPorts.setObjectName("btnListPorts")
31 | self.gridLayout.addWidget(self.btnListPorts, 4, 0, 1, 2)
32 | self.btnSetParams = QtWidgets.QPushButton(Form)
33 | self.btnSetParams.setObjectName("btnSetParams")
34 | self.gridLayout.addWidget(self.btnSetParams, 5, 0, 1, 2)
35 | self.btnOpen = QtWidgets.QPushButton(Form)
36 | self.btnOpen.setObjectName("btnOpen")
37 | self.gridLayout.addWidget(self.btnOpen, 0, 0, 1, 2)
38 | self.chartview = QtCharts.QtCharts.QChartView(Form)
39 | self.chartview.setObjectName("chartview")
40 | self.gridLayout.addWidget(self.chartview, 0, 2, 4, 1)
41 | self.btnAutoScale = QtWidgets.QPushButton(Form)
42 | self.btnAutoScale.setObjectName("btnAutoScale")
43 | self.gridLayout.addWidget(self.btnAutoScale, 4, 2, 1, 1)
44 | self.btnSaveData = QtWidgets.QPushButton(Form)
45 | self.btnSaveData.setObjectName("btnSaveData")
46 | self.gridLayout.addWidget(self.btnSaveData, 5, 2, 1, 1)
47 |
48 | self.retranslateUi(Form)
49 | QtCore.QMetaObject.connectSlotsByName(Form)
50 | Form.setTabOrder(self.btnOpen, self.btnStart)
51 | Form.setTabOrder(self.btnStart, self.btnStop)
52 | Form.setTabOrder(self.btnStop, self.listwPorts)
53 | Form.setTabOrder(self.listwPorts, self.btnListPorts)
54 | Form.setTabOrder(self.btnListPorts, self.btnSetParams)
55 |
56 | def retranslateUi(self, Form):
57 | Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Live Plotting", None, -1))
58 | self.btnStop.setText(QtWidgets.QApplication.translate("Form", "Stop Comms", None, -1))
59 | self.btnStart.setText(QtWidgets.QApplication.translate("Form", "Start Comms", None, -1))
60 | self.btnListPorts.setText(QtWidgets.QApplication.translate("Form", "List Comm Ports", None, -1))
61 | self.btnSetParams.setText(QtWidgets.QApplication.translate("Form", "Set Params", None, -1))
62 | self.btnOpen.setText(QtWidgets.QApplication.translate("Form", "Open Serial Port", None, -1))
63 | self.btnAutoScale.setText(QtWidgets.QApplication.translate("Form", "Auto Scale", None, -1))
64 | self.btnSaveData.setText(QtWidgets.QApplication.translate("Form", "Save Data", None, -1))
65 |
66 |
--------------------------------------------------------------------------------
/scripts/plotMotorData/plotwin.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 | Form
4 |
5 |
6 |
7 | 0
8 | 0
9 | 749
10 | 455
11 |
12 |
13 |
14 | Live Plotting
15 |
16 |
17 | -
18 |
19 |
20 | Stop Comms
21 |
22 |
23 |
24 | -
25 |
26 |
27 | Start Comms
28 |
29 |
30 |
31 | -
32 |
33 |
34 | -
35 |
36 |
37 | List Comm Ports
38 |
39 |
40 |
41 | -
42 |
43 |
44 | Set Params
45 |
46 |
47 |
48 | -
49 |
50 |
51 | Open Serial Port
52 |
53 |
54 |
55 | -
56 |
57 |
58 | -
59 |
60 |
61 | Auto Scale
62 |
63 |
64 |
65 | -
66 |
67 |
68 | Save Data
69 |
70 |
71 |
72 |
73 |
74 |
75 | btnOpen
76 | btnStart
77 | btnStop
78 | listwPorts
79 | btnListPorts
80 | btnSetParams
81 |
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/scripts/project_live_data_ids.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | * Filename: project_live_data_ids.h
4 | ******************************************************************************
5 |
6 | Copyright (c) 2022 David Miller
7 |
8 | Permission is hereby granted, free of charge, to any person obtaining a copy
9 | of this software and associated documentation files (the "Software"), to deal
10 | in the Software without restriction, including without limitation the rights
11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 | copies of the Software, and to permit persons to whom the Software is
13 | furnished to do so, subject to the following conditions:
14 |
15 | The above copyright notice and this permission notice shall be included in all
16 | copies or substantial portions of the Software.
17 |
18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 | SOFTWARE.
25 | */
26 |
27 |
28 | // Auto-generated file. Do not edit!
29 | // If changes are needed, edit the variable settings in 'datavars.xml' and
30 | // re-run 'datavar_codegen.py' to recreate this file.
31 |
32 | #ifndef PROJECT_LIVE_DATA_IDS_H_
33 | #define PROJECT_LIVE_DATA_IDS_H_
34 |
35 |
36 | // Debugging output id definitions
37 | #define MAX_LIVE_DATA_CHOICES (22)
38 | #define LIVE_CHOICE_UNUSED (0)
39 | #define LIVE_CHOICE_IA (1) // Phase A current (amps)
40 | #define LIVE_CHOICE_IB (2) // Phase B current (amps)
41 | #define LIVE_CHOICE_IC (3) // Phase C current (amps)
42 | #define LIVE_CHOICE_TA (4) // Phase A PWM duty cycle (percent)
43 | #define LIVE_CHOICE_TB (5) // Phase B PWM duty cycle (percent)
44 | #define LIVE_CHOICE_TC (6) // Phase C PWM duty cycle (percent)
45 | #define LIVE_CHOICE_THROTTLE (7) // Throttle position (percent)
46 | #define LIVE_CHOICE_HALLANGLE (8) // Hall sensor angle (zero to one)
47 | #define LIVE_CHOICE_HALLSPEED (9) // Hall sensor speed (Hz)
48 | #define LIVE_CHOICE_HALLACCEL (10) // Hall sensor acceleration (Hz/s)
49 | #define LIVE_CHOICE_HALLSTATE (11) // Hall sensor state (1 to 6)
50 | #define LIVE_CHOICE_VBUS (12) // Battery voltage
51 | #define LIVE_CHOICE_ID (13) // D phase current (amps)
52 | #define LIVE_CHOICE_IQ (14) // Q phase current (amps)
53 | #define LIVE_CHOICE_TD (15) // D phase duty cycle (percent)
54 | #define LIVE_CHOICE_TQ (16) // Q phase duty cycle (percent)
55 | #define LIVE_CHOICE_VA (17) // Phase A voltage
56 | #define LIVE_CHOICE_VB (18) // Phase B voltage
57 | #define LIVE_CHOICE_VC (19) // Phase C voltage
58 | #define LIVE_CHOICE_FTEMP (20) // Motor controller (MOSFET) temperature (degC)
59 | #define LIVE_CHOICE_ERRORCODE (21) // Error code (packed binary)
60 | #define LIVE_CHOICE_RAWTHROTTLE (22) // Raw throttle voltage
61 |
62 | #endif // PROJECT_LIVE_DATA_IDS_H_
63 |
--------------------------------------------------------------------------------