From deea94b076f75eee7e3b9197e24ce839906f53a0 Mon Sep 17 00:00:00 2001 From: matei jordache Date: Thu, 9 Nov 2023 19:02:15 -0500 Subject: [PATCH] try to fix submodule --- firmware/lib/Arduino-FOC | 1 - firmware/lib/Arduino-FOC-drivers | 1 - firmware/lib/Arduino-FOC-drivers/LICENSE | 21 + firmware/lib/Arduino-FOC-drivers/README.md | 117 +++ .../drv8316/drv8316_3pwm/drv8316_3pwm.ino | 123 +++ .../drv8316/drv8316_6pwm/drv8316_6pwm.ino | 111 ++ .../encoders/calibrated/calibrated.ino | 86 ++ .../encoders/mt6816/mt6816_spi/mt6816_spi.ino | 106 ++ .../examples/encoders/smoothing/smoothing.ino | 141 +++ firmware/lib/Arduino-FOC-drivers/keywords.txt | 11 + .../Arduino-FOC-drivers/library.properties | 11 + .../src/SimpleFOCDrivers.h | 11 + .../Arduino-FOC-drivers/src/comms/README.md | 5 + .../src/comms/RegisterReceiver.cpp | 131 +++ .../src/comms/RegisterReceiver.h | 15 + .../src/comms/RegisterSender.cpp | 193 ++++ .../src/comms/RegisterSender.h | 18 + .../src/comms/SimpleFOCRegisters.h | 72 ++ .../src/comms/i2c/I2CCommander.cpp | 424 ++++++++ .../src/comms/i2c/I2CCommander.h | 49 + .../src/comms/i2c/I2CCommanderMaster.cpp | 59 ++ .../src/comms/i2c/I2CCommanderMaster.h | 42 + .../src/comms/i2c/README.md | 98 ++ .../src/comms/serial/README.md | 49 + .../src/comms/serial/SerialASCIITelemetry.cpp | 65 ++ .../src/comms/serial/SerialASCIITelemetry.h | 27 + .../comms/serial/SerialBinaryCommander.cpp | 153 +++ .../src/comms/serial/SerialBinaryCommander.h | 57 ++ .../src/comms/stm32speeddir/README.md | 58 ++ .../stm32speeddir/STM32SpeedDirInput.cpp | 29 + .../comms/stm32speeddir/STM32SpeedDirInput.h | 31 + .../src/comms/telemetry/README.md | 42 + .../src/comms/telemetry/Telemetry.cpp | 67 ++ .../src/comms/telemetry/Telemetry.h | 53 + .../src/drivers/drv8316/README.md | 175 ++++ .../src/drivers/drv8316/drv8316.cpp | 586 +++++++++++ .../src/drivers/drv8316/drv8316.h | 316 ++++++ .../src/drivers/drv8316/drv8316_registers.h | 184 ++++ .../src/drivers/stspin32g4/README.md | 42 + .../src/drivers/stspin32g4/STSPIN32G4.cpp | 182 ++++ .../src/drivers/stspin32g4/STSPIN32G4.h | 148 +++ .../src/drivers/tmc6200/README.md | 147 +++ .../src/drivers/tmc6200/TMC6200.cpp | 221 ++++ .../src/drivers/tmc6200/TMC6200.hpp | 171 ++++ .../src/drivers/tmc6200/TMC6200_Registers.hpp | 111 ++ .../src/encoders/a1334/A1334.cpp | 54 + .../src/encoders/a1334/A1334.h | 51 + .../encoders/a1334/MagneticSensorA1334.cpp | 27 + .../src/encoders/a1334/MagneticSensorA1334.h | 24 + .../src/encoders/aeat8800q24/AEAT8800Q24.cpp | 102 ++ .../src/encoders/aeat8800q24/AEAT8800Q24.h | 119 +++ .../aeat8800q24/MagneticSensorAEAT8800Q24.cpp | 24 + .../aeat8800q24/MagneticSensorAEAT8800Q24.h | 18 + .../src/encoders/aeat8800q24/README.md | 75 ++ .../src/encoders/as5047/AS5047.cpp | 245 +++++ .../src/encoders/as5047/AS5047.h | 167 +++ .../encoders/as5047/MagneticSensorAS5047.cpp | 29 + .../encoders/as5047/MagneticSensorAS5047.h | 20 + .../src/encoders/as5047/README.md | 82 ++ .../src/encoders/as5047u/AS5047U.cpp | 350 +++++++ .../src/encoders/as5047u/AS5047U.h | 225 +++++ .../as5047u/MagneticSensorAS5047U.cpp | 29 + .../encoders/as5047u/MagneticSensorAS5047U.h | 20 + .../src/encoders/as5047u/README.md | 81 ++ .../src/encoders/as5048a/AS5048A.cpp | 118 +++ .../src/encoders/as5048a/AS5048A.h | 89 ++ .../as5048a/MagneticSensorAS5048A.cpp | 26 + .../encoders/as5048a/MagneticSensorAS5048A.h | 20 + .../as5048a/PreciseMagneticSensorAS5048A.cpp | 50 + .../as5048a/PreciseMagneticSensorAS5048A.h | 33 + .../src/encoders/as5048a/README.md | 86 ++ .../encoders/as5145/MagneticSensorAS5145.cpp | 34 + .../encoders/as5145/MagneticSensorAS5145.h | 39 + .../src/encoders/as5145/README.md | 50 + .../src/encoders/as5600/AS5600.cpp | 175 ++++ .../src/encoders/as5600/AS5600.h | 104 ++ .../encoders/as5600/MagneticSensorAS5600.cpp | 18 + .../encoders/as5600/MagneticSensorAS5600.h | 22 + .../src/encoders/as5600/README.md | 131 +++ .../encoders/calibrated/CalibratedSensor.cpp | 257 +++++ .../encoders/calibrated/CalibratedSensor.h | 61 ++ .../src/encoders/calibrated/README.md | 91 ++ .../src/encoders/ma330/MA330.cpp | 146 +++ .../src/encoders/ma330/MA330.h | 82 ++ .../encoders/ma330/MagneticSensorMA330.cpp | 26 + .../src/encoders/ma330/MagneticSensorMA330.h | 19 + .../src/encoders/ma330/README.md | 66 ++ .../src/encoders/ma730/MA730.cpp | 125 +++ .../src/encoders/ma730/MA730.h | 76 ++ .../encoders/ma730/MagneticSensorMA730.cpp | 26 + .../src/encoders/ma730/MagneticSensorMA730.h | 19 + .../encoders/ma730/MagneticSensorMA730SSI.cpp | 34 + .../encoders/ma730/MagneticSensorMA730SSI.h | 25 + .../src/encoders/ma730/README.md | 74 ++ .../mt6701/MagneticSensorMT6701SSI.cpp | 42 + .../encoders/mt6701/MagneticSensorMT6701SSI.h | 43 + .../src/encoders/mt6701/README.md | 82 ++ .../src/encoders/mt6816/MT6816.cpp | 56 ++ .../src/encoders/mt6816/MT6816.h | 40 + .../encoders/mt6816/MagneticSensorMT6816.cpp | 26 + .../encoders/mt6816/MagneticSensorMT6816.h | 17 + .../src/encoders/mt6835/MT6835.cpp | 291 ++++++ .../src/encoders/mt6835/MT6835.h | 217 ++++ .../encoders/mt6835/MagneticSensorMT6835.cpp | 24 + .../encoders/mt6835/MagneticSensorMT6835.h | 17 + .../src/encoders/mt6835/README.md | 64 ++ .../sc60228/MagneticSensorSC60228.cpp | 24 + .../encoders/sc60228/MagneticSensorSC60228.h | 20 + .../src/encoders/sc60228/README.md | 47 + .../src/encoders/sc60228/SC60228.cpp | 57 ++ .../src/encoders/sc60228/SC60228.h | 50 + .../src/encoders/smoothing/README.md | 69 ++ .../encoders/smoothing/SmoothingSensor.cpp | 57 ++ .../src/encoders/smoothing/SmoothingSensor.h | 46 + .../src/encoders/stm32hwencoder/README.md | 49 + .../stm32hwencoder/STM32HWEncoder.cpp | 78 ++ .../encoders/stm32hwencoder/STM32HWEncoder.h | 36 + .../src/encoders/stm32pwmsensor/README.md | 46 + .../stm32pwmsensor/STM32MagneticSensorPWM.cpp | 35 + .../stm32pwmsensor/STM32MagneticSensorPWM.h | 28 + .../tle5012b/MagneticSensorTLE5012B.cpp | 18 + .../tle5012b/MagneticSensorTLE5012B.h | 25 + .../src/encoders/tle5012b/README.md | 91 ++ .../src/encoders/tle5012b/STM32TLE5012B.cpp | 159 +++ .../src/encoders/tle5012b/STM32TLE5012B.h | 45 + .../HybridStepperMotor/HybridStepperMotor.cpp | 548 ++++++++++ .../HybridStepperMotor/HybridStepperMotor.h | 112 +++ .../src/motors/HybridStepperMotor/README.md | 45 + .../src/settings/README.md | 143 +++ .../src/settings/SettingsStorage.cpp | 120 +++ .../src/settings/SettingsStorage.h | 70 ++ .../i2c/CAT24I2CFlashSettingsStorage.cpp | 98 ++ .../i2c/CAT24I2CFlashSettingsStorage.h | 35 + .../src/settings/i2c/README.md | 26 + .../src/settings/samd/README.md | 49 + .../settings/samd/SAMDNVMSettingsStorage.cpp | 164 +++ .../settings/samd/SAMDNVMSettingsStorage.h | 85 ++ .../samd/eeprom_emulation_screenshot.jpg | Bin 0 -> 73543 bytes .../src/utilities/PreciseAngle.cpp | 113 +++ .../src/utilities/PreciseAngle.h | 57 ++ .../src/utilities/README.md | 25 + .../src/utilities/stm32math/README.md | 41 + .../stm32math/STM32G4CORDICTrigFunctions.cpp | 83 ++ .../stm32math/STM32G4CORDICTrigFunctions.h | 10 + .../src/utilities/stm32pwm/README.md | 73 ++ .../src/utilities/stm32pwm/STM32PWMInput.cpp | 108 ++ .../src/utilities/stm32pwm/STM32PWMInput.h | 29 + .../src/voltage/GenericVoltageSense.cpp | 44 + .../src/voltage/GenericVoltageSense.h | 23 + .../src/voltage/VoltageSense.cpp | 23 + .../src/voltage/VoltageSense.h | 24 + firmware/lib/Arduino-FOC/CITATION.cff | 48 + firmware/lib/Arduino-FOC/CODE_OF_CONDUCT.md | 128 +++ firmware/lib/Arduino-FOC/LICENSE | 21 + firmware/lib/Arduino-FOC/README.md | 223 ++++ .../B_G431B_ESC1/B_G431B_ESC1.ino | 109 ++ .../B_G431B_ESC1/build_opt.h | 1 + .../bluepill_position_control.ino | 115 +++ .../bluepill_position_control.ino | 115 +++ .../full_control_serial.ino | 130 +++ .../full_control_serial.ino | 129 +++ .../esp32_current_control_low_side.ino | 167 +++ .../stm32_current_control_low_side.ino | 167 +++ .../esp32_position_control.ino | 107 ++ .../esp32_position_control.ino | 112 +++ .../position_control/position_control.ino | 127 +++ .../voltage_control/voltage_control.ino | 110 ++ .../odrive_example_encoder.ino | 134 +++ .../odrive_example_spi/odrive_example_spi.ino | 132 +++ .../SAMD_examples/README.md | 62 ++ .../nano33IoT_velocity_control.ino | 64 ++ .../single_full_control_example.ino | 102 ++ .../angle_control/angle_control.ino | 125 +++ .../double_full_control_example.ino | 118 +++ .../single_full_control_example.ino | 89 ++ .../double_full_control_example.ino | 144 +++ .../single_full_control_example.ino | 101 ++ .../single_full_control_example.ino | 101 ++ .../smartstepper_control.ino | 61 ++ .../bldc_driver_6pwm_standalone.ino | 41 + .../open_loop_velocity_6pwm.ino | 65 ++ .../bldc_driver_6pwm_standalone.ino | 57 ++ .../open_loop_velocity_6pwm.ino | 80 ++ .../open_loop_position_example.ino | 70 ++ .../open_loop_velocity_example.ino | 68 ++ .../encoder/angle_control/angle_control.ino | 129 +++ .../angle_control/angle_control.ino | 133 +++ .../angle_control/angle_control.ino | 112 +++ .../current_control/current_control.ino | 107 ++ .../voltage_control/voltage_control.ino | 92 ++ .../voltage_control/voltage_control.ino | 95 ++ .../voltage_control/voltage_control.ino | 84 ++ .../velocity_control/velocity_control.ino | 137 +++ .../velocity_control/velocity_control.ino | 125 +++ .../velocity_control/velocity_control.ino | 106 ++ .../full_control_serial.ino | 106 ++ .../full_control_serial.ino | 114 +++ .../full_control_serial.ino | 104 ++ .../examples/osc_control_examples/README.md | 28 + .../osc_esp32_3pwm/layout1.touchosc | Bin 0 -> 511 bytes .../osc_esp32_3pwm/osc_esp32_3pwm.ino | 183 ++++ .../osc_esp32_fullcontrol.ino | 351 +++++++ .../osc_esp32_fullcontrol/osc_fullcontrol.pd | 384 +++++++ .../osc_esp32_fullcontrol/ssid.h_rename_me | 4 + .../osc_fullcontrol_screenshot.png | Bin 0 -> 261643 bytes .../alignment_and_cogging_test.ino | 125 +++ .../encoder/find_kv_rating/find_kv_rating.ino | 102 ++ .../find_kv_rating/find_kv_rating.ino | 99 ++ .../find_kv_rating/find_kv_rating.ino | 96 ++ .../find_pole_pairs_number.ino | 173 ++++ .../find_pole_pairs_number.ino | 173 ++++ .../find_sensor_offset_and_direction.ino | 84 ++ .../commander_extend_example.ino | 53 + .../commander_no_serial.ino | 51 + .../commander_tune_custom_loop.ino | 79 ++ .../step_dir_listener_simple.ino | 36 + .../step_dir_listener_software_interrupt.ino | 44 + .../step_dir_motor_example.ino | 98 ++ .../generic_current_sense.ino | 59 ++ .../inline_current_sense_test.ino | 36 + .../bldc_driver_3pwm_standalone.ino | 34 + .../bldc_driver_6pwm_standalone.ino | 35 + .../stepper_driver_2pwm_standalone.ino | 39 + .../stepper_driver_4pwm_standalone.ino | 34 + .../encoder_example/encoder_example.ino | 44 + .../encoder_software_interrupts_example.ino | 57 ++ .../generic_sensor/generic_sensor.ino | 51 + .../hall_sensor_example.ino | 48 + ...all_sensor_software_interrupts_example.ino | 59 ++ .../find_raw_centers/find_raw_centers.ino | 62 ++ .../find_raw_min_max/find_raw_min_max.ino | 56 ++ .../magnetic_sensor_analog_example.ino | 37 + .../esp32_i2c_dual_bus_example.ino | 40 + .../stm32_i2c_dual_bus_example.ino | 39 + .../magnetic_sensor_i2c_example.ino | 43 + .../find_raw_min_max/find_raw_min_max.ino | 49 + .../magnetic_sensor_pwm_example.ino | 38 + ...magnetic_sensor_pwm_software_interrupt.ino | 44 + .../esp32_spi_alt_example.ino | 41 + .../stm32_spi_alt_example.ino | 32 + .../magnetic_sensor_spi_example.ino | 32 + firmware/lib/Arduino-FOC/keywords.txt | 251 +++++ firmware/lib/Arduino-FOC/library.properties | 10 + firmware/lib/Arduino-FOC/src/BLDCMotor.cpp | 736 ++++++++++++++ firmware/lib/Arduino-FOC/src/BLDCMotor.h | 115 +++ firmware/lib/Arduino-FOC/src/SimpleFOC.h | 119 +++ firmware/lib/Arduino-FOC/src/StepperMotor.cpp | 463 +++++++++ firmware/lib/Arduino-FOC/src/StepperMotor.h | 117 +++ .../src/common/base_classes/BLDCDriver.h | 42 + .../src/common/base_classes/CurrentSense.cpp | 121 +++ .../src/common/base_classes/CurrentSense.h | 75 ++ .../src/common/base_classes/FOCDriver.h | 21 + .../src/common/base_classes/FOCMotor.cpp | 155 +++ .../src/common/base_classes/FOCMotor.h | 251 +++++ .../src/common/base_classes/Sensor.cpp | 78 ++ .../src/common/base_classes/Sensor.h | 139 +++ .../src/common/base_classes/StepperDriver.h | 18 + .../lib/Arduino-FOC/src/common/defaults.h | 49 + .../lib/Arduino-FOC/src/common/foc_utils.cpp | 73 ++ .../lib/Arduino-FOC/src/common/foc_utils.h | 106 ++ .../Arduino-FOC/src/common/lowpass_filter.cpp | 28 + .../Arduino-FOC/src/common/lowpass_filter.h | 28 + firmware/lib/Arduino-FOC/src/common/pid.cpp | 64 ++ firmware/lib/Arduino-FOC/src/common/pid.h | 41 + .../lib/Arduino-FOC/src/common/time_utils.cpp | 31 + .../lib/Arduino-FOC/src/common/time_utils.h | 22 + .../src/communication/Commander.cpp | 685 +++++++++++++ .../Arduino-FOC/src/communication/Commander.h | 301 ++++++ .../src/communication/SimpleFOCDebug.cpp | 104 ++ .../src/communication/SimpleFOCDebug.h | 79 ++ .../src/communication/StepDirListener.cpp | 40 + .../src/communication/StepDirListener.h | 65 ++ .../Arduino-FOC/src/communication/commands.h | 52 + .../src/current_sense/GenericCurrentSense.cpp | 163 +++ .../src/current_sense/GenericCurrentSense.h | 40 + .../src/current_sense/InlineCurrentSense.cpp | 253 +++++ .../src/current_sense/InlineCurrentSense.h | 73 ++ .../src/current_sense/LowsideCurrentSense.cpp | 254 +++++ .../src/current_sense/LowsideCurrentSense.h | 73 ++ .../src/current_sense/hardware_api.h | 65 ++ .../hardware_specific/atmega_mcu.cpp | 40 + .../hardware_specific/due_mcu.cpp | 27 + .../esp32/esp32_adc_driver.cpp | 259 +++++ .../esp32/esp32_adc_driver.h | 88 ++ .../esp32/esp32_ledc_mcu.cpp | 27 + .../hardware_specific/esp32/esp32_mcu.cpp | 162 +++ .../esp32/esp32s_adc_driver.cpp | 258 +++++ .../hardware_specific/generic_mcu.cpp | 41 + .../hardware_specific/rp2040/rp2040_mcu.cpp | 265 +++++ .../hardware_specific/rp2040/rp2040_mcu.h | 93 ++ .../hardware_specific/samd/samd21_mcu.cpp | 318 ++++++ .../hardware_specific/samd/samd21_mcu.h | 69 ++ .../hardware_specific/samd/samd_mcu.cpp | 23 + .../stm32/b_g431/b_g431_hal.cpp | 364 +++++++ .../stm32/b_g431/b_g431_hal.h | 18 + .../stm32/b_g431/b_g431_mcu.cpp | 164 +++ .../hardware_specific/stm32/stm32_mcu.cpp | 33 + .../hardware_specific/stm32/stm32_mcu.h | 21 + .../stm32/stm32f1/stm32f1_hal.cpp | 162 +++ .../stm32/stm32f1/stm32f1_hal.h | 17 + .../stm32/stm32f1/stm32f1_mcu.cpp | 104 ++ .../stm32/stm32f4/stm32f4_hal.cpp | 170 ++++ .../stm32/stm32f4/stm32f4_hal.h | 18 + .../stm32/stm32f4/stm32f4_mcu.cpp | 96 ++ .../stm32/stm32f4/stm32f4_utils.cpp | 193 ++++ .../stm32/stm32f4/stm32f4_utils.h | 34 + .../stm32/stm32g4/stm32g4_hal.cpp | 267 +++++ .../stm32/stm32g4/stm32g4_hal.h | 19 + .../stm32/stm32g4/stm32g4_mcu.cpp | 98 ++ .../stm32/stm32g4/stm32g4_utils.cpp | 237 +++++ .../stm32/stm32g4/stm32g4_utils.h | 34 + .../stm32/stm32l4/stm32l4_hal.cpp | 266 +++++ .../stm32/stm32l4/stm32l4_hal.h | 19 + .../stm32/stm32l4/stm32l4_mcu.cpp | 98 ++ .../stm32/stm32l4/stm32l4_utils.cpp | 221 ++++ .../stm32/stm32l4/stm32l4_utils.h | 34 + .../hardware_specific/teensy_mcu.cpp | 24 + .../src/drivers/BLDCDriver3PWM.cpp | 92 ++ .../Arduino-FOC/src/drivers/BLDCDriver3PWM.h | 64 ++ .../src/drivers/BLDCDriver6PWM.cpp | 103 ++ .../Arduino-FOC/src/drivers/BLDCDriver6PWM.h | 70 ++ .../src/drivers/StepperDriver2PWM.cpp | 107 ++ .../src/drivers/StepperDriver2PWM.h | 68 ++ .../src/drivers/StepperDriver4PWM.cpp | 81 ++ .../src/drivers/StepperDriver4PWM.h | 55 + .../Arduino-FOC/src/drivers/hardware_api.h | 180 ++++ .../atmega/atmega2560_mcu.cpp | 278 +++++ .../atmega/atmega328_mcu.cpp | 255 +++++ .../atmega/atmega32u4_mcu.cpp | 222 ++++ .../src/drivers/hardware_specific/due_mcu.cpp | 449 +++++++++ .../esp32/esp32_driver_mcpwm.h | 96 ++ .../esp32/esp32_ledc_mcu.cpp | 185 ++++ .../hardware_specific/esp32/esp32_mcu.cpp | 431 ++++++++ .../drivers/hardware_specific/esp8266_mcu.cpp | 121 +++ .../drivers/hardware_specific/generic_mcu.cpp | 125 +++ .../drivers/hardware_specific/nrf52_mcu.cpp | 397 ++++++++ .../hardware_specific/portenta_h7_mcu.cpp | 545 ++++++++++ .../hardware_specific/renesas/renesas.cpp | 609 +++++++++++ .../hardware_specific/renesas/renesas.h | 28 + .../hardware_specific/rp2040/rp2040_mcu.cpp | 237 +++++ .../hardware_specific/rp2040/rp2040_mcu.h | 22 + .../hardware_specific/samd/samd21_mcu.cpp | 353 +++++++ .../hardware_specific/samd/samd51_mcu.cpp | 351 +++++++ .../hardware_specific/samd/samd_mcu.cpp | 914 +++++++++++++++++ .../drivers/hardware_specific/samd/samd_mcu.h | 127 +++ .../hardware_specific/stm32/stm32_mcu.cpp | 952 ++++++++++++++++++ .../hardware_specific/stm32/stm32_mcu.h | 32 + .../hardware_specific/teensy/teensy3_mcu.cpp | 228 +++++ .../hardware_specific/teensy/teensy4_mcu.cpp | 306 ++++++ .../hardware_specific/teensy/teensy4_mcu.h | 110 ++ .../hardware_specific/teensy/teensy_mcu.cpp | 116 +++ .../hardware_specific/teensy/teensy_mcu.h | 14 + .../lib/Arduino-FOC/src/sensors/Encoder.cpp | 229 +++++ .../lib/Arduino-FOC/src/sensors/Encoder.h | 91 ++ .../Arduino-FOC/src/sensors/GenericSensor.cpp | 26 + .../Arduino-FOC/src/sensors/GenericSensor.h | 31 + .../Arduino-FOC/src/sensors/HallSensor.cpp | 173 ++++ .../lib/Arduino-FOC/src/sensors/HallSensor.h | 98 ++ .../src/sensors/MagneticSensorAnalog.cpp | 42 + .../src/sensors/MagneticSensorAnalog.h | 51 + .../src/sensors/MagneticSensorI2C.cpp | 156 +++ .../src/sensors/MagneticSensorI2C.h | 84 ++ .../src/sensors/MagneticSensorPWM.cpp | 117 +++ .../src/sensors/MagneticSensorPWM.h | 73 ++ .../src/sensors/MagneticSensorSPI.cpp | 161 +++ .../src/sensors/MagneticSensorSPI.h | 84 ++ 366 files changed, 40228 insertions(+), 2 deletions(-) delete mode 160000 firmware/lib/Arduino-FOC delete mode 160000 firmware/lib/Arduino-FOC-drivers create mode 100644 firmware/lib/Arduino-FOC-drivers/LICENSE create mode 100644 firmware/lib/Arduino-FOC-drivers/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_3pwm/drv8316_3pwm.ino create mode 100644 firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_6pwm/drv8316_6pwm.ino create mode 100644 firmware/lib/Arduino-FOC-drivers/examples/encoders/calibrated/calibrated.ino create mode 100644 firmware/lib/Arduino-FOC-drivers/examples/encoders/mt6816/mt6816_spi/mt6816_spi.ino create mode 100644 firmware/lib/Arduino-FOC-drivers/examples/encoders/smoothing/smoothing.ino create mode 100644 firmware/lib/Arduino-FOC-drivers/keywords.txt create mode 100644 firmware/lib/Arduino-FOC-drivers/library.properties create mode 100644 firmware/lib/Arduino-FOC-drivers/src/SimpleFOCDrivers.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/SimpleFOCRegisters.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/i2c/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/serial/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316_registers.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.hpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200_Registers.hpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/i2c/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/samd/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/samd/SAMDNVMSettingsStorage.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/samd/SAMDNVMSettingsStorage.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/settings/samd/eeprom_emulation_screenshot.jpg create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/README.md create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.h create mode 100644 firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.cpp create mode 100644 firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.h create mode 100644 firmware/lib/Arduino-FOC/CITATION.cff create mode 100644 firmware/lib/Arduino-FOC/CODE_OF_CONDUCT.md create mode 100644 firmware/lib/Arduino-FOC/LICENSE create mode 100644 firmware/lib/Arduino-FOC/README.md create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/B_G431B_ESC1.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/build_opt.h create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/encoder/bluepill_position_control/bluepill_position_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/magnetic_sensor/bluepill_position_control/bluepill_position_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/3pwm_example/encoder/full_control_serial/full_control_serial.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/6pwm_example/encoder/full_control_serial/full_control_serial.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/esp32_current_control_low_side/esp32_current_control_low_side.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/stm32_current_control_low_side/stm32_current_control_low_side.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/encoder/esp32_position_control/esp32_position_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/magnetic_sensor/esp32_position_control/esp32_position_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/position_control/position_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/voltage_control/voltage_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_encoder/odrive_example_encoder.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_spi/odrive_example_spi.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/README.md create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/nano33IoT/nano33IoT_velocity_control/nano33IoT_velocity_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOC-PowerShield/version_v02/single_full_control_example/single_full_control_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCMini/angle_control/angle_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/double_full_control_example/double_full_control_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/single_full_control_example/single_full_control_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/double_full_control_example/double_full_control_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/single_full_control_example/single_full_control_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v3/single_full_control_example/single_full_control_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Smart_Stepper/smartstepper_control/smartstepper_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino create mode 100644 firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_position_example/open_loop_position_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_velocity_example/open_loop_velocity_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/encoder/angle_control/angle_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/hall_sensor/angle_control/angle_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/magnetic_sensor/angle_control/angle_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/current_control/current_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/voltage_control/voltage_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/torque_control/hall_sensor/voltage_control/voltage_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/torque_control/magnetic_sensor/voltage_control/voltage_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/encoder/velocity_control/velocity_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/hall_sensor/velocity_control/velocity_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/magnetic_sensor/velocity_control/velocity_control.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/encoder/full_control_serial/full_control_serial.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/hall_sensor/full_control_serial/full_control_serial.ino create mode 100644 firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/magnetic_sensor/full_control_serial/full_control_serial.ino create mode 100644 firmware/lib/Arduino-FOC/examples/osc_control_examples/README.md create mode 100644 firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_3pwm/layout1.touchosc create mode 100644 firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_3pwm/osc_esp32_3pwm.ino create mode 100644 firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_esp32_fullcontrol.ino create mode 100644 firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_fullcontrol.pd create mode 100644 firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/ssid.h_rename_me create mode 100644 firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_fullcontrol_screenshot.png create mode 100644 firmware/lib/Arduino-FOC/examples/utils/calibration/alignment_and_cogging_test/alignment_and_cogging_test.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/encoder/find_kv_rating/find_kv_rating.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/hall_sensor/find_kv_rating/find_kv_rating.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/magnetic_sensor/find_kv_rating/find_kv_rating.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/encoder/find_pole_pairs_number/find_pole_pairs_number.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/magnetic_sensor/find_pole_pairs_number/find_pole_pairs_number.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/calibration/find_sensor_offset_and_direction/find_sensor_offset_and_direction.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_extend_example/commander_extend_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_no_serial/commander_no_serial.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_tune_custom_loop/commander_tune_custom_loop.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_simple/step_dir_listener_simple.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_software_interrupt/step_dir_listener_software_interrupt.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_motor_example/step_dir_motor_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/current_sense_test/generic_current_sense/generic_current_sense.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/current_sense_test/inline_current_sense_test/inline_current_sense_test.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_3pwm_standalone/bldc_driver_3pwm_standalone.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_2pwm_standalone/stepper_driver_2pwm_standalone.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_4pwm_standalone/stepper_driver_4pwm_standalone.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_example/encoder_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_software_interrupts_example/encoder_software_interrupts_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/generic_sensor/generic_sensor.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_example/hall_sensor_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_software_interrupts_example/hall_sensor_software_interrupts_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/linear_hall_sensors/find_raw_centers/find_raw_centers.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/find_raw_min_max/find_raw_min_max.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/magnetic_sensor_analog_example/magnetic_sensor_analog_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/esp32_i2c_dual_bus_example/esp32_i2c_dual_bus_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/stm32_i2c_dual_bus_example/stm32_i2c_dual_bus_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_example/magnetic_sensor_i2c_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/find_raw_min_max/find_raw_min_max.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_example/magnetic_sensor_pwm_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_software_interrupt/magnetic_sensor_pwm_software_interrupt.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/esp32_spi_alt_example/esp32_spi_alt_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/stm32_spi_alt_example/stm32_spi_alt_example.ino create mode 100644 firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_example/magnetic_sensor_spi_example.ino create mode 100644 firmware/lib/Arduino-FOC/keywords.txt create mode 100644 firmware/lib/Arduino-FOC/library.properties create mode 100644 firmware/lib/Arduino-FOC/src/BLDCMotor.cpp create mode 100644 firmware/lib/Arduino-FOC/src/BLDCMotor.h create mode 100644 firmware/lib/Arduino-FOC/src/SimpleFOC.h create mode 100644 firmware/lib/Arduino-FOC/src/StepperMotor.cpp create mode 100644 firmware/lib/Arduino-FOC/src/StepperMotor.h create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/BLDCDriver.h create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.cpp create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.h create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/FOCDriver.h create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.cpp create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.h create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.cpp create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.h create mode 100644 firmware/lib/Arduino-FOC/src/common/base_classes/StepperDriver.h create mode 100644 firmware/lib/Arduino-FOC/src/common/defaults.h create mode 100644 firmware/lib/Arduino-FOC/src/common/foc_utils.cpp create mode 100644 firmware/lib/Arduino-FOC/src/common/foc_utils.h create mode 100644 firmware/lib/Arduino-FOC/src/common/lowpass_filter.cpp create mode 100644 firmware/lib/Arduino-FOC/src/common/lowpass_filter.h create mode 100644 firmware/lib/Arduino-FOC/src/common/pid.cpp create mode 100644 firmware/lib/Arduino-FOC/src/common/pid.h create mode 100644 firmware/lib/Arduino-FOC/src/common/time_utils.cpp create mode 100644 firmware/lib/Arduino-FOC/src/common/time_utils.h create mode 100644 firmware/lib/Arduino-FOC/src/communication/Commander.cpp create mode 100644 firmware/lib/Arduino-FOC/src/communication/Commander.h create mode 100644 firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.cpp create mode 100644 firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.h create mode 100644 firmware/lib/Arduino-FOC/src/communication/StepDirListener.cpp create mode 100644 firmware/lib/Arduino-FOC/src/communication/StepDirListener.h create mode 100644 firmware/lib/Arduino-FOC/src/communication/commands.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_api.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/atmega_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/due_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_ledc_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32s_adc_driver.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/generic_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.cpp create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.h create mode 100644 firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/teensy_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_api.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega2560_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega328_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega32u4_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/due_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_driver_mcpwm.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_ledc_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp8266_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/generic_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/nrf52_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/portenta_h7_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd21_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd51_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy3_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.cpp create mode 100644 firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.h create mode 100644 firmware/lib/Arduino-FOC/src/sensors/Encoder.cpp create mode 100644 firmware/lib/Arduino-FOC/src/sensors/Encoder.h create mode 100644 firmware/lib/Arduino-FOC/src/sensors/GenericSensor.cpp create mode 100644 firmware/lib/Arduino-FOC/src/sensors/GenericSensor.h create mode 100644 firmware/lib/Arduino-FOC/src/sensors/HallSensor.cpp create mode 100644 firmware/lib/Arduino-FOC/src/sensors/HallSensor.h create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.cpp create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.h create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.cpp create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.h create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.cpp create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.h create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.cpp create mode 100644 firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.h diff --git a/firmware/lib/Arduino-FOC b/firmware/lib/Arduino-FOC deleted file mode 160000 index f9e9a2d..0000000 --- a/firmware/lib/Arduino-FOC +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f9e9a2d29e912957bd75302d4f9a83a1cdff37a5 diff --git a/firmware/lib/Arduino-FOC-drivers b/firmware/lib/Arduino-FOC-drivers deleted file mode 160000 index c66b9db..0000000 --- a/firmware/lib/Arduino-FOC-drivers +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c66b9db82a70678d2d7fddf2392ecbd36f9a7000 diff --git a/firmware/lib/Arduino-FOC-drivers/LICENSE b/firmware/lib/Arduino-FOC-drivers/LICENSE new file mode 100644 index 0000000..53dcc14 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Richard Unger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/firmware/lib/Arduino-FOC-drivers/README.md b/firmware/lib/Arduino-FOC-drivers/README.md new file mode 100644 index 0000000..cb33e97 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/README.md @@ -0,0 +1,117 @@ +# SimpleFOC Driver and Support Library + +![Library Compile](https://github.com/simplefoc/Arduino-FOC-drivers/workflows/Library%20Compile/badge.svg) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +![Release](https://www.ardu-badge.com/badge/SimpleFOCDrivers.svg?) + +This library contains an assortment of drivers and supporting code for SimpleFOC. + +The intent is to keep the core of SimpleFOC clean, and thus easy to maintain, understand and port to different platforms. In addition to this core, there are various drivers and supporting code which has grown around SimpleFOC, and which we would like to make available to the community. + +## New Release + +v1.0.6 - Released July 2023, for Simple FOC 2.3.1 or later + +What's changed since 1.0.5? +- Added AS5600 Sensor Driver +- Bugfixes [included](https://github.com/simplefoc/Arduino-FOC-drivers/issues?q=is%3Aissue+milestone%3A1.0.6+) + +## What is included + +What is here? See the sections below. Each driver or function should come with its own more detailed README. + +### Motor/Gate driver ICs + + - [TMC6200 driver](src/drivers/tmc6200/) - SPI driver for Trinamics TMC6200 motor driver IC. + - [DRV8316 driver](src/drivers/drv8316/) - SPI driver for TI's DRV8316 motor driver IC. + +### Encoders + + - [AS5048A SPI driver](src/encoders/as5048a/) - SPI driver for the AMS AS5048A absolute position magnetic rotary encoder IC. + - [AS5047 SPI driver](src/encoders/as5047/) - SPI driver for the AMS AS5047P and AS5047D absolute position magnetic rotary encoder ICs. + - [AS5047U SPI driver](src/encoders/as5047u/) - SPI driver for the AMS AS5047U absolute position magnetic rotary encoder ICs. + - [AS5600 I2C driver](src/encoders/as5600/) - I2C driver for the AMS AS5600 and AS5600L absolute position magnetic rotary encoder ICs. + - [MA730 SPI driver](src/encoders/ma730/) - SPI driver for the MPS MagAlpha MA730 absolute position magnetic rotary encoder IC. + - [MA730 SSI driver](src/encoders/ma730/) - SSI driver for the MPS MagAlpha MA730 absolute position magnetic rotary encoder IC. + - [AS5145 SSI driver](src/encoders/as5145/) - SSI driver for the AMS AS5145 and AS5045 absolute position magnetic rotary encoder ICs. + - [TLE5012B SPI driver](src/encoders/tle5012b/) - SPI (half duplex) driver for TLE5012B absolute position magnetic rotary encoder IC. + - [STM32 Hardware Encoder](src/encoders/stm32hwencoder/) - Hardware timer based encoder driver for ABI type quadrature encoders. + - [SC60228 SPI driver](src/encoders/sc60228/) - SPI driver for SemiMent SC60288 magnetic encoder IC. + - [MA330 SPI driver](src/encoders/ma330/) - SPI driver for the MPS MagAlpha MA330 absolute position magnetic rotary encoder IC. + - [MT6816 SPI driver](src/encoders/mt6816/) - SPI driver for the MagnTek MT6816 absolute position magnetic rotary encoder IC. + - [MT6701 SSI driver](src/encoders/mt6701/) - SSI driver for the MagnTek MT6701 absolute position magnetic rotary encoder IC. + - [MT6835 SPI driver](src/encoders/mt6835/) - SPI driver for the MagnTek MT6835 21 bit magnetic rotary encoder IC. + - [STM32 PWM sensor driver](src/encoders/stm32pwmsensor/) - STM32 native timer-based driver for PWM angle sensors. + - [SmoothingSensor](src/encoders/smoothing/) - A SimpleFOC Sensor wrapper implementation which adds angle extrapolation. + +### Communications + + - [I2CCommander I2C driver](src/comms/i2c/) - I2C communications protocol and drivers for both controller and target devices, based on register abstraction + - [STM32 SpeedDir Input](src/comms/stm32speeddir/) - Control target velocity with PWM speed and direction inputs + - [SerialBinaryCommander](src/comms/serial/) - Serial communications with binary protocol, based on register abstraction + - [Telemetry](src/comms/telemetry/) - Telemetry abstraction, based on registers + - [SerialASCIITelemetry](src/comms/serial/) - Serial communications with ascii protocol, based on register abstraction + +### Settings + +Load and store SimpleFOC motor settings, based on register abstraction. + + - [SAMD NVM storage driver](src/settings/samd/) - Store settings to the NVM flash memory in your SAMD MCU + - [CAT24 I2C EEPROM storage driver](src/settings/i2c/) - Store settings to CAT24 I2C EEPROMs + +### Utilities + + - [STM32 PWM Input driver](src/utilities/stm32pwm/) - PWM Input driver for STM32 MCUs. Accurately measure PWM inputs with zero MCU overhead. + + +## How to use + +#### Arduino Library Manager +The simplest way to get hold of the library is directly by using Arduino IDE and its integrated Library Manager. +- Open Arduino IDE and start Arduino Library Manager by clicking: `Tools > Manage Libraries...`. +- Search for `Simple FOC drivers` library and install the latest version. +- Reopen Arduino IDE and you should have the library examples in `File > Examples > Simple FOC drivers`. + +#### Using Github website +- Go to the [github repository](https://github.com/simplefoc/Arduino-FOC-drivers) +- Click first on `Clone or Download > Download ZIP`. +- Unzip it and place it in `Arduino Libraries` folder. Windows: `Documents > Arduino > libraries`. +- Reopen Arduino IDE and you should have the library examples in `File > Examples > Simple FOC drivers`. + +#### Using parts + +You can copy parts of the library, for example to minimize your code size, or make it easier to add adaptations of your own. +If you do so, please be sure to adhere to and include the [LICENSE](https://github.com/simplefoc/Arduino-FOC-drivers/LICENSE). + + +## Further Documentation + +Find out more information about the Arduino SimpleFOC project on the [docs website](https://docs.simplefoc.com/) + +## Release History + +What's changed since 1.0.4? +- Added smoothing sensor by [@dekutree64](https://github.com/dekutree64) +- Added TMD6200 SPI driver by [@YaseenTwati](https://github.com/YaseenTwati) +- Added HybridStepperMotor by [@VIPQualityPost](https://github.com/VIPQualityPost) +- New Settings abstraction to load and save SimpleFOC settings and calibration +- New Settings driver: SAMDNVMSettingsStorage +- SimpleFOCRegisters abstraction, mapping SimpleFOC parameters to virtual "Registers" +- Updated I2CCommander to use the new registers abstraction +- Bugfixes [included](https://github.com/simplefoc/Arduino-FOC-drivers/issues?q=is%3Aissue+milestone%3A1.0.5+) + +What's changed since 1.0.3? +- New Comms/Input: STM32SpeedDirCommander +- New Utility: STM32PWMInput +- Fixed MT6835 driver bugs +- Improved AS5047 driver, fixed bugs +- Improved AS5047U driver, fixed bugs + +What's changed since 1.0.2? +- New Sensor: MT6835 +- Fixed bugs + +What's changed since 1.0.1? +- Calibrated sensor by @MarethyuPrefect +- New Sensors: MT6701, MA330, MT6816 +- Fixed bugs diff --git a/firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_3pwm/drv8316_3pwm.ino b/firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_3pwm/drv8316_3pwm.ino new file mode 100644 index 0000000..be89c74 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_3pwm/drv8316_3pwm.ino @@ -0,0 +1,123 @@ + + + +#include "Arduino.h" +#include +#include +#include +#include "drivers/drv8316/drv8316.h" + + + + +BLDCMotor motor = BLDCMotor(11); +DRV8316Driver3PWM driver = DRV8316Driver3PWM(2,3,4,7,false); // use the right pins for your setup! +#define ENABLE_A 0 +#define ENABLE_B 1 +#define ENABLE_C 6 + + +void printDRV8316Status() { + DRV8316Status status = driver.getStatus(); + Serial.println("DRV8316 Status:"); + Serial.print("Fault: "); + Serial.println(status.isFault()); + Serial.print("Buck Error: "); + Serial.print(status.isBuckError()); + Serial.print(" Undervoltage: "); + Serial.print(status.isBuckUnderVoltage()); + Serial.print(" OverCurrent: "); + Serial.println(status.isBuckOverCurrent()); + Serial.print("Charge Pump UnderVoltage: "); + Serial.println(status.isChargePumpUnderVoltage()); + Serial.print("OTP Error: "); + Serial.println(status.isOneTimeProgrammingError()); + Serial.print("OverCurrent: "); + Serial.print(status.isOverCurrent()); + Serial.print(" Ah: "); + Serial.print(status.isOverCurrent_Ah()); + Serial.print(" Al: "); + Serial.print(status.isOverCurrent_Al()); + Serial.print(" Bh: "); + Serial.print(status.isOverCurrent_Bh()); + Serial.print(" Bl: "); + Serial.print(status.isOverCurrent_Bl()); + Serial.print(" Ch: "); + Serial.print(status.isOverCurrent_Ch()); + Serial.print(" Cl: "); + Serial.println(status.isOverCurrent_Cl()); + Serial.print("OverTemperature: "); + Serial.print(status.isOverTemperature()); + Serial.print(" Shutdown: "); + Serial.print(status.isOverTemperatureShutdown()); + Serial.print(" Warning: "); + Serial.println(status.isOverTemperatureWarning()); + Serial.print("OverVoltage: "); + Serial.println(status.isOverVoltage()); + Serial.print("PowerOnReset: "); + Serial.println(status.isPowerOnReset()); + Serial.print("SPI Error: "); + Serial.print(status.isSPIError()); + Serial.print(" Address: "); + Serial.print(status.isSPIAddressError()); + Serial.print(" Clock: "); + Serial.print(status.isSPIClockFramingError()); + Serial.print(" Parity: "); + Serial.println(status.isSPIParityError()); + if (status.isFault()) + driver.clearFault(); + delayMicroseconds(1); // ensure 400ns delay + DRV8316_PWMMode val = driver.getPWMMode(); + Serial.print("PWM Mode: "); + Serial.println(val); + delayMicroseconds(1); // ensure 400ns delay + bool lock = driver.isRegistersLocked(); + Serial.print("Lock: "); + Serial.println(lock); +} + + + + + +void setup() { + + Serial.begin(115200); + while (!Serial); + delay(1); + Serial.println("Initializing..."); + + pinMode(ENABLE_A, OUTPUT); + digitalWrite(ENABLE_A, 1); // enable + pinMode(ENABLE_B, OUTPUT); + digitalWrite(ENABLE_B, 1); // enable + pinMode(ENABLE_C, OUTPUT); + digitalWrite(ENABLE_C, 1); // enable + + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + motor.controller = MotionControlType::velocity_openloop; + motor.voltage_limit = 3; + motor.velocity_limit = 20; + motor.init(); + Serial.println("Init complete..."); + + delay(100); + printDRV8316Status(); +} + + +// velocity set point variable +float target_velocity = 7.0; + + +void loop() { + //delay(100); + //driver.setPwm(7.4/4, 7.4/2, 7.4/4*3); + motor.move(target_velocity); +} + + + + diff --git a/firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_6pwm/drv8316_6pwm.ino b/firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_6pwm/drv8316_6pwm.ino new file mode 100644 index 0000000..2eb0dd3 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/examples/drivers/drv8316/drv8316_6pwm/drv8316_6pwm.ino @@ -0,0 +1,111 @@ + + + +#include "Arduino.h" +#include +#include +#include +#include "drivers/drv8316/drv8316.h" + + + + +BLDCMotor motor = BLDCMotor(11); +DRV8316Driver6PWM driver = DRV8316Driver6PWM(0,1,2,3,4,6,7,false); // use the right pins for your setup! + + + +void printDRV8316Status() { + DRV8316Status status = driver.getStatus(); + Serial.println("DRV8316 Status:"); + Serial.print("Fault: "); + Serial.println(status.isFault()); + Serial.print("Buck Error: "); + Serial.print(status.isBuckError()); + Serial.print(" Undervoltage: "); + Serial.print(status.isBuckUnderVoltage()); + Serial.print(" OverCurrent: "); + Serial.println(status.isBuckOverCurrent()); + Serial.print("Charge Pump UnderVoltage: "); + Serial.println(status.isChargePumpUnderVoltage()); + Serial.print("OTP Error: "); + Serial.println(status.isOneTimeProgrammingError()); + Serial.print("OverCurrent: "); + Serial.print(status.isOverCurrent()); + Serial.print(" Ah: "); + Serial.print(status.isOverCurrent_Ah()); + Serial.print(" Al: "); + Serial.print(status.isOverCurrent_Al()); + Serial.print(" Bh: "); + Serial.print(status.isOverCurrent_Bh()); + Serial.print(" Bl: "); + Serial.print(status.isOverCurrent_Bl()); + Serial.print(" Ch: "); + Serial.print(status.isOverCurrent_Ch()); + Serial.print(" Cl: "); + Serial.println(status.isOverCurrent_Cl()); + Serial.print("OverTemperature: "); + Serial.print(status.isOverTemperature()); + Serial.print(" Shutdown: "); + Serial.print(status.isOverTemperatureShutdown()); + Serial.print(" Warning: "); + Serial.println(status.isOverTemperatureWarning()); + Serial.print("OverVoltage: "); + Serial.println(status.isOverVoltage()); + Serial.print("PowerOnReset: "); + Serial.println(status.isPowerOnReset()); + Serial.print("SPI Error: "); + Serial.print(status.isSPIError()); + Serial.print(" Address: "); + Serial.print(status.isSPIAddressError()); + Serial.print(" Clock: "); + Serial.print(status.isSPIClockFramingError()); + Serial.print(" Parity: "); + Serial.println(status.isSPIParityError()); + if (status.isFault()) + driver.clearFault(); + delayMicroseconds(1); // ensure 400ns delay + DRV8316_PWMMode val = driver.getPWMMode(); + Serial.print("PWM Mode: "); + Serial.println(val); + delayMicroseconds(1); // ensure 400ns delay + bool lock = driver.isRegistersLocked(); + Serial.print("Lock: "); + Serial.println(lock); +} + + + + + +void setup() { + Serial.begin(115200); + while (!Serial); + delay(1); + Serial.println("Initializing..."); + + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + motor.controller = MotionControlType::velocity_openloop; + motor.voltage_limit = 3; + motor.velocity_limit = 20; + motor.init(); + Serial.println("Init complete..."); + + delay(100); + printDRV8316Status(); +} + + +// velocity set point variable +float target_velocity = 7.0; + + +void loop() { + motor.move(target_velocity); +} + + + + diff --git a/firmware/lib/Arduino-FOC-drivers/examples/encoders/calibrated/calibrated.ino b/firmware/lib/Arduino-FOC-drivers/examples/encoders/calibrated/calibrated.ino new file mode 100644 index 0000000..6cc6110 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/examples/encoders/calibrated/calibrated.ino @@ -0,0 +1,86 @@ +/** + * Torque control example using voltage control loop. + * + * Most of the low-end BLDC driver boards doesn't have current measurement therefore SimpleFOC offers + * you a way to control motor torque by setting the voltage to the motor instead hte current. + * + * This makes the BLDC motor effectively a DC motor, and you can use it in a same way. + */ +#include +#include +#include "encoders/calibrated/CalibratedSensor.h" + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5048_SPI, PB6); +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(PB4,PC7,PB10,PA9); +// instantiate the calibrated sensor object +CalibratedSensor sensor_calibrated = CalibratedSensor(sensor); + +// voltage set point variable +float target_voltage = 2; + +// instantiate the commander +Commander command = Commander(Serial); + +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } + +void setup() { + + SPI.setMISO(PB14); + SPI.setMOSI(PB15); + SPI.setSCLK(PB13); + + sensor.init(); + // Link motor to sensor + motor.linkSensor(&sensor); + // power supply voltage + driver.voltage_power_supply = 20; + driver.init(); + motor.linkDriver(&driver); + // aligning voltage + motor.voltage_sensor_align = 8; + motor.voltage_limit = 20; + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_variables = _MON_VEL; + motor.monitor_downsample = 10; // default 10 + + // initialize motor + motor.init(); + + // set voltage to run calibration + sensor_calibrated.voltage_calibration = 6; + // Running calibration + sensor_calibrated.calibrate(motor); + + //Serial.println("Calibrating Sensor Done."); + // Linking sensor to motor object + motor.linkSensor(&sensor_calibrated); + + // calibrated init FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + + Serial.println(F("Motor ready.")); + + Serial.println(F("Set the target voltage using serial terminal:")); + _delay(1000); +} + +void loop() { + + motor.loopFOC(); + motor.move(target_voltage); + command.run(); + motor.monitor(); + +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/examples/encoders/mt6816/mt6816_spi/mt6816_spi.ino b/firmware/lib/Arduino-FOC-drivers/examples/encoders/mt6816/mt6816_spi/mt6816_spi.ino new file mode 100644 index 0000000..c1ac1cd --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/examples/encoders/mt6816/mt6816_spi/mt6816_spi.ino @@ -0,0 +1,106 @@ +/** + * Comprehensive BLDC motor control example using magnetic sensor MT6816 + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * See more info in docs.simplefoc.com/commander_interface + */ +#include +#include +#include + +// magnetic sensor instance - MT6816 SPI mode +MagneticSensorMT6816 sensor = MagneticSensorMT6816(5); + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(7); +BLDCDriver3PWM driver = BLDCDriver3PWM(32, 25, 26, 33); + +// Inline Current Sense instance +InlineCurrentSense current_sense = InlineCurrentSense(0.01f, 50.0f, 35, 34); + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + // choose FOC modulation + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // contoller configuration based on the control type + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop velocity limit + motor.velocity_limit = 50; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + current_sense.linkDriver(&driver); + current_sense.init(); + current_sense.gain_b *= -1; + current_sense.skip_align = true; + motor.linkCurrentSense(¤t_sense); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // define the motor id + command.add('A', onMotor, "motor"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println(F("Motor commands sketch | Initial motion control > torque/voltage : target 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + // velocity, position or voltage + // if tatget not set in parameter uses motor.target variable + motor.move(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC-drivers/examples/encoders/smoothing/smoothing.ino b/firmware/lib/Arduino-FOC-drivers/examples/encoders/smoothing/smoothing.ino new file mode 100644 index 0000000..1ff658d --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/examples/encoders/smoothing/smoothing.ino @@ -0,0 +1,141 @@ +/** + * + * Hall sensor velocity motion control example, modified to demonstrate usage of SmoothingSensor + * Steps: + * 1) Configure the motor and sensor + * 2) Run the code + * 3) Set the target velocity (in radians per second) from serial terminal + * 4) Try with and without smoothing to see the difference (send E1 and E0 commands from serial terminal) + * + * + * + * NOTE : + * > Specifically for Arduino UNO example code for running velocity motion control using a hall sensor + * > Since Arduino UNO doesn't have enough interrupt pins we have to use software interrupt library PciManager. + * + * > If running this code with Nucleo or Bluepill or any other board which has more than 2 interrupt pins + * > you can supply doC directly to the sensor.enableInterrupts(doA,doB,doC) and avoid using PciManger + * + */ +#include +// software interrupt library +#include +#include +#include +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// hall sensor instance +HallSensor sensor = HallSensor(2, 3, 4, 11); +// wrapper instance +SmoothingSensor smooth(sensor, motor); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} +// If no available hadware interrupt pins use the software interrupt +PciListenerImp listenerIndex(sensor.pinC, doC); + +// velocity set point variable +float target_velocity = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } + +void enableSmoothing(char* cmd) { + float enable; + command.scalar(&enable, cmd); + motor.linkSensor(enable == 0 ? (Sensor*)&sensor : (Sensor*)&smooth); +} + +void setup() { + + // initialize sensor sensor hardware + sensor.init(); + sensor.enableInterrupts(doA, doB); //, doC); + // software interrupts + PciManager.registerListener(&listenerIndex); + // set SmoothingSensor phase correction for hall sensors + smooth.phase_correction = -_PI_6; + // link the SmoothingSensor to the motor + motor.linkSensor(&smooth); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::velocity; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 2; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + + // add smoothing enable/disable command E (send E0 to use hall sensor alone, or E1 to use smoothing) + command.add('E', enableSmoothing, "enable smoothing"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target velocity using serial terminal:")); + _delay(1000); +} + + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_velocity); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/keywords.txt b/firmware/lib/Arduino-FOC-drivers/keywords.txt new file mode 100644 index 0000000..516cc85 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/keywords.txt @@ -0,0 +1,11 @@ +SimpleFOC KEYWORD1 +DRV8316 KEYWORD1 +AS5048A KEYWORD1 +AS5047 KEYWORD1 +AS5145 KEYWORD1 +MA730 KEYWORD1 +MT6835 KEYWORD1 +SC60228 KEYWORD1 +TLE5012B KEYWORD1 +I2CCommander KEYWORD1 +STM32HWEncoder KEYWORD1 diff --git a/firmware/lib/Arduino-FOC-drivers/library.properties b/firmware/lib/Arduino-FOC-drivers/library.properties new file mode 100644 index 0000000..8b4fcb8 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/library.properties @@ -0,0 +1,11 @@ +name=SimpleFOCDrivers +version=1.0.6 +author=Simplefoc +maintainer=Simplefoc +sentence=A library of supporting drivers for SimpleFOC. Motor drivers chips, encoder chips, current sensing and supporting code. +paragraph=SimpleFOC runs BLDC and Stepper motors using the FOC algorithm. This library supports the core SimpleFOC code by adding support for specific hardware like motor driver ICs, encoders, current sensing and other supporting code. +category=Device Control +url=https://docs.simplefoc.com +architectures=* +includes=SimpleFOCDrivers.h +depends=Simple FOC \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/SimpleFOCDrivers.h b/firmware/lib/Arduino-FOC-drivers/src/SimpleFOCDrivers.h new file mode 100644 index 0000000..689ea30 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/SimpleFOCDrivers.h @@ -0,0 +1,11 @@ + +#ifndef __SIMPLEFOC_DRIVERS_H__ +#define __SIMPLEFOC_DRIVERS_H__ + +// empty header file. In Arduino IDE, include this header to enable the +// IDE to "find" the library. +// Then include the headers for the individual drivers/sensors/utilities +// that you want to use. + +#endif + diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/README.md b/firmware/lib/Arduino-FOC-drivers/src/comms/README.md new file mode 100644 index 0000000..4469af6 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/README.md @@ -0,0 +1,5 @@ + +# SimpleFOC communications support code + +This folder contains classes to support you communicating between MCUs running SimpleFOC, and other systems. + diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.cpp new file mode 100644 index 0000000..44f7c54 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.cpp @@ -0,0 +1,131 @@ + +#include "./RegisterReceiver.h" +#include "BLDCMotor.h" + + +void RegisterReceiver::setRegister(SimpleFOCRegister reg, FOCMotor* motor){ + // write a register value for the given motor + switch(reg) { + case REG_ENABLE: + readByte((uint8_t*)&(motor->enabled)); + break; + case REG_MODULATION_MODE: + readByte((uint8_t*)&(motor->foc_modulation)); + break; + case REG_TORQUE_MODE: + readByte((uint8_t*)&(motor->torque_controller)); + break; + case REG_CONTROL_MODE: + readByte((uint8_t*)&(motor->controller)); + break; + case REG_TARGET: + readFloat(&(motor->target)); + break; + case REG_VEL_PID_P: + readFloat(&(motor->PID_velocity.P)); + break; + case REG_VEL_PID_I: + readFloat(&(motor->PID_velocity.I)); + break; + case REG_VEL_PID_D: + readFloat(&(motor->PID_velocity.D)); + break; + case REG_VEL_LPF_T: + readFloat(&(motor->LPF_velocity.Tf)); + break; + case REG_ANG_PID_P: + readFloat(&(motor->P_angle.P)); + break; + case REG_VEL_LIMIT: + readFloat(&(motor->velocity_limit)); + break; + case REG_VEL_MAX_RAMP: + readFloat(&(motor->PID_velocity.output_ramp)); + break; + + case REG_CURQ_PID_P: + readFloat(&(motor->PID_current_q.P)); + break; + case REG_CURQ_PID_I: + readFloat(&(motor->PID_current_q.I)); + break; + case REG_CURQ_PID_D: + readFloat(&(motor->PID_current_q.D)); + break; + case REG_CURQ_LPF_T: + readFloat(&(motor->LPF_current_q.Tf)); + break; + case REG_CURD_PID_P: + readFloat(&(motor->PID_current_d.P)); + break; + case REG_CURD_PID_I: + readFloat(&(motor->PID_current_d.I)); + break; + case REG_CURD_PID_D: + readFloat(&(motor->PID_current_d.D)); + break; + case REG_CURD_LPF_T: + readFloat(&(motor->LPF_current_d.Tf)); + break; + + case REG_VOLTAGE_LIMIT: + readFloat(&(motor->voltage_limit)); + break; + case REG_CURRENT_LIMIT: + readFloat(&(motor->current_limit)); + break; + case REG_MOTION_DOWNSAMPLE: + readByte((uint8_t*)&(motor->motion_downsample)); + break; + case REG_DRIVER_VOLTAGE_LIMIT: + readFloat(&(((BLDCMotor*)motor)->driver->voltage_limit)); + break; + case REG_PWM_FREQUENCY: + readInt((uint32_t*)&(((BLDCMotor*)motor)->driver->pwm_frequency)); + break; + + case REG_ZERO_ELECTRIC_ANGLE: + readFloat(&(motor->zero_electric_angle)); + break; + case REG_SENSOR_DIRECTION: + readByte((uint8_t*)&(motor->sensor_direction)); + break; + case REG_ZERO_OFFSET: + readFloat(&(motor->sensor_offset)); + break; + case REG_PHASE_RESISTANCE: + readFloat(&(motor->phase_resistance)); + break; + case REG_KV: + readFloat(&(motor->KV_rating)); + break; + case REG_INDUCTANCE: + readFloat(&(motor->phase_inductance)); + break; + case REG_POLE_PAIRS: + readByte((uint8_t*)&(motor->pole_pairs)); + break; + // unknown register or read-only register (no write) or can't handle in superclass + case REG_STATUS: + case REG_ANGLE: + case REG_POSITION: + case REG_VELOCITY: + case REG_SENSOR_ANGLE: + case REG_VOLTAGE_Q: + case REG_VOLTAGE_D: + case REG_CURRENT_Q: + case REG_CURRENT_D: + case REG_CURRENT_A: + case REG_CURRENT_B: + case REG_CURRENT_C: + case REG_CURRENT_ABC: + case REG_SYS_TIME: + case REG_NUM_MOTORS: + case REG_MOTOR_ADDRESS: + case REG_ENABLE_ALL: + case REG_REPORT: + default: + break; + } +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.h b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.h new file mode 100644 index 0000000..fc2af1c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterReceiver.h @@ -0,0 +1,15 @@ + +#pragma once + +#include "./SimpleFOCRegisters.h" +#include "common/base_classes/FOCMotor.h" + + + +class RegisterReceiver { +protected: + virtual void setRegister(SimpleFOCRegister reg, FOCMotor* motor); + virtual uint8_t readByte(uint8_t* valueToSet) = 0; + virtual uint8_t readFloat(float* valueToSet) = 0; + virtual uint8_t readInt(uint32_t* valueToSet) = 0; +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.cpp new file mode 100644 index 0000000..2a163ce --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.cpp @@ -0,0 +1,193 @@ + +#include "./RegisterSender.h" +#include "common/foc_utils.h" +#include "BLDCMotor.h" + +bool RegisterSender::sendRegister(SimpleFOCRegister reg, FOCMotor* motor){ + // write a register value for the given motor + switch(reg) { + case REG_STATUS: + writeByte(motor->motor_status); + break; + case REG_ENABLE: + writeByte(motor->enabled); + break; + case REG_MODULATION_MODE: + writeByte(motor->foc_modulation); + break; + case REG_TORQUE_MODE: + writeByte(motor->torque_controller); + break; + case REG_CONTROL_MODE: + writeByte(motor->controller); + break; + case REG_TARGET: + writeFloat(motor->target); + break; + case REG_ANGLE: + writeFloat(motor->shaft_angle); + break; + case REG_POSITION: + if (motor->sensor) { + writeInt(motor->sensor->getFullRotations()); + writeFloat(motor->sensor->getMechanicalAngle()); + } + else { + writeInt(motor->shaft_angle/_2PI); + writeFloat(fmod(motor->shaft_angle, _2PI)); + } + break; + case REG_VELOCITY: + writeFloat(motor->shaft_velocity); + break; + case REG_SENSOR_ANGLE: + if (motor->sensor) + writeFloat(motor->sensor->getAngle()); // stored angle + else + writeFloat(motor->shaft_angle); + break; + + case REG_VOLTAGE_Q: + writeFloat(motor->voltage.q); + break; + case REG_VOLTAGE_D: + writeFloat(motor->voltage.d); + break; + case REG_CURRENT_Q: + writeFloat(motor->current.q); + break; + case REG_CURRENT_D: + writeFloat(motor->current.d); + break; + case REG_CURRENT_A: + if (motor->current_sense) + writeFloat(motor->current_sense->getPhaseCurrents().a); + else + writeFloat(0.0f); + break; + case REG_CURRENT_B: + if (motor->current_sense) + writeFloat(motor->current_sense->getPhaseCurrents().b); + else + writeFloat(0.0f); + break; + case REG_CURRENT_C: + if (motor->current_sense) + writeFloat(motor->current_sense->getPhaseCurrents().c); + else + writeFloat(0.0f); + break; + case REG_CURRENT_ABC: + if (motor->current_sense) { + PhaseCurrent_s currents = motor->current_sense->getPhaseCurrents(); + writeFloat(currents.a); + writeFloat(currents.b); + writeFloat(currents.c); + } + else { + writeFloat(0.0f); + writeFloat(0.0f); + writeFloat(0.0f); + } + break; + case REG_VEL_PID_P: + writeFloat(motor->PID_velocity.P); + break; + case REG_VEL_PID_I: + writeFloat(motor->PID_velocity.I); + break; + case REG_VEL_PID_D: + writeFloat(motor->PID_velocity.D); + break; + case REG_VEL_LPF_T: + writeFloat(motor->LPF_velocity.Tf); + break; + case REG_ANG_PID_P: + writeFloat(motor->P_angle.P); + break; + case REG_VEL_LIMIT: + writeFloat(motor->velocity_limit); + break; + case REG_VEL_MAX_RAMP: + writeFloat(motor->PID_velocity.output_ramp); + break; + + case REG_CURQ_PID_P: + writeFloat(motor->PID_current_q.P); + break; + case REG_CURQ_PID_I: + writeFloat(motor->PID_current_q.I); + break; + case REG_CURQ_PID_D: + writeFloat(motor->PID_current_q.D); + break; + case REG_CURQ_LPF_T: + writeFloat(motor->LPF_current_q.Tf); + break; + case REG_CURD_PID_P: + writeFloat(motor->PID_current_d.P); + break; + case REG_CURD_PID_I: + writeFloat(motor->PID_current_d.I); + break; + case REG_CURD_PID_D: + writeFloat(motor->PID_current_d.D); + break; + case REG_CURD_LPF_T: + writeFloat(motor->LPF_current_d.Tf); + break; + + case REG_VOLTAGE_LIMIT: + writeFloat(motor->voltage_limit); + break; + case REG_CURRENT_LIMIT: + writeFloat(motor->current_limit); + break; + case REG_MOTION_DOWNSAMPLE: + writeByte((uint8_t)motor->motion_downsample); + break; + case REG_DRIVER_VOLTAGE_LIMIT: + writeFloat(((BLDCMotor*)motor)->driver->voltage_limit); + break; + case REG_PWM_FREQUENCY: + writeInt(((BLDCMotor*)motor)->driver->pwm_frequency); + break; + + case REG_ZERO_ELECTRIC_ANGLE: + writeFloat(motor->zero_electric_angle); + break; + case REG_SENSOR_DIRECTION: + writeByte((int8_t)motor->sensor_direction); + break; + case REG_ZERO_OFFSET: + writeFloat(motor->sensor_offset); + break; + case REG_PHASE_RESISTANCE: + writeFloat(motor->phase_resistance); + break; + case REG_KV: + writeFloat(motor->KV_rating); + break; + case REG_INDUCTANCE: + writeFloat(motor->phase_inductance); + break; + case REG_POLE_PAIRS: + writeByte((uint8_t)motor->pole_pairs); + break; + + case REG_SYS_TIME: + // TODO how big is millis()? Same on all platforms? + writeInt((int)millis()); + break; + // unknown register or write only register (no read) or can't handle in superclass + case REG_NUM_MOTORS: + case REG_REPORT: + case REG_MOTOR_ADDRESS: + case REG_ENABLE_ALL: + default: + writeByte(0); // TODO what to send in this case? + return false; + } + return true; +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.h b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.h new file mode 100644 index 0000000..b2486a1 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/RegisterSender.h @@ -0,0 +1,18 @@ + +#pragma once + +#include "./SimpleFOCRegisters.h" +#include "common/base_classes/FOCMotor.h" + +/** + * Register sending functionality is shared by Commander and Telemetry implementations. + * Since the code to access all the registers is quite large, it makes sense to abstract it out, + * and also make sure registers are addressed in the same way for all implementations. + */ +class RegisterSender { +protected: + virtual bool sendRegister(SimpleFOCRegister reg, FOCMotor* motor); + virtual uint8_t writeByte(uint8_t value) = 0; + virtual uint8_t writeFloat(float value) = 0; + virtual uint8_t writeInt(uint32_t value) = 0; +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/SimpleFOCRegisters.h b/firmware/lib/Arduino-FOC-drivers/src/comms/SimpleFOCRegisters.h new file mode 100644 index 0000000..6fea825 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/SimpleFOCRegisters.h @@ -0,0 +1,72 @@ + +#pragma once + +#include + + +// this constant is changed each time the registers definition are changed *in an incompatible way*. This means that just adding new registers +// does not change the version, but removing or changing the meaning of existing registers does, or changing the number of an existing register. +#define SIMPLEFOC_REGISTERS_VERSION 0x01 + + + +typedef enum : uint8_t { + REG_STATUS = 0x00, // RO - 1 byte (motor status) + REG_MOTOR_ADDRESS = 0x01, // R/W - 1 byte + REG_REPORT = 0x02, // R/W - Write: variable, Read: variable, up to 32 bytes + REG_ENABLE_ALL = 0x03, // WO - 1 byte + REG_ENABLE = 0x04, // R/W - 1 byte + REG_CONTROL_MODE = 0x05, // R/W - 1 byte + REG_TORQUE_MODE = 0x06, // R/W - 1 byte + REG_MODULATION_MODE = 0x07, // R/W - 1 byte + + REG_TARGET = 0x08, // R/W - float + REG_ANGLE = 0x09, // RO - float + REG_POSITION = 0x10, // RO - int32_t full rotations + float position (0-2PI, in radians) (4 bytes + 4 bytes) + REG_VELOCITY = 0x11, // RO - float + REG_SENSOR_ANGLE = 0x12, // RO - float + + REG_VOLTAGE_Q = 0x20, // RO - float + REG_VOLTAGE_D = 0x21, // RO - float + REG_CURRENT_Q = 0x22, // RO - float + REG_CURRENT_D = 0x23, // RO - float + REG_CURRENT_A = 0x24, // RO - float + REG_CURRENT_B = 0x25, // RO - float + REG_CURRENT_C = 0x26, // RO - float + REG_CURRENT_ABC = 0x27, // RO - 3xfloat = 12 bytes + REG_CURRENT_DC = 0x28, // RO - float + + REG_VEL_PID_P = 0x30, // R/W - float + REG_VEL_PID_I = 0x31, // R/W - float + REG_VEL_PID_D = 0x32, // R/W - float + REG_VEL_LPF_T = 0x33, // R/W - float + REG_ANG_PID_P = 0x34, // R/W - float + REG_VEL_LIMIT = 0x35, // R/W - float + REG_VEL_MAX_RAMP = 0x36, // R/W - float + + REG_CURQ_PID_P = 0x40, // R/W - float + REG_CURQ_PID_I = 0x41, // R/W - float + REG_CURQ_PID_D = 0x42, // R/W - float + REG_CURQ_LPF_T = 0x43, // R/W - float + REG_CURD_PID_P = 0x44, // R/W - float + REG_CURD_PID_I = 0x45, // R/W - float + REG_CURD_PID_D = 0x46, // R/W - float + REG_CURD_LPF_T = 0x47, // R/W - float + + REG_VOLTAGE_LIMIT = 0x50, // R/W - float + REG_CURRENT_LIMIT = 0x51, // R/W - float + REG_MOTION_DOWNSAMPLE = 0x52, // R/W - uint32_t + REG_DRIVER_VOLTAGE_LIMIT = 0x53,// R/W - float + REG_PWM_FREQUENCY = 0x54, // R/W - uint32_t + + REG_ZERO_ELECTRIC_ANGLE = 0x60, // RO - float + REG_SENSOR_DIRECTION = 0x61, // RO - 1 byte + REG_ZERO_OFFSET = 0x62, // R/W - float + REG_POLE_PAIRS = 0x63, // RO - uint32_t + REG_PHASE_RESISTANCE = 0x64, // R/W - float + REG_KV = 0x65, // R/W - float + REG_INDUCTANCE = 0x66, // R/W - float + + REG_NUM_MOTORS = 0x70, // RO - 1 byte + REG_SYS_TIME = 0x71, // RO - uint32_t +} SimpleFOCRegister; diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.cpp new file mode 100644 index 0000000..737b2ee --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.cpp @@ -0,0 +1,424 @@ + +#include "I2CCommander.h" + +I2CCommander::I2CCommander(TwoWire* wire) : _wire(wire) { + +}; + +I2CCommander::~I2CCommander(){}; + +void I2CCommander::init(uint8_t address) { + _address = address; +}; + + + +void I2CCommander::addMotor(FOCMotor* motor){ + if (numMotorsavailable()>=numBytes){ + byte* bytes = (byte*)valueToSet; + for (int i=0;iread(); + return true; + } + commanderror = true; + return false; +}; + + + +void I2CCommander::writeFloat(float value){ + _wire->write((byte*)&value, 4); +}; + + + + +void I2CCommander::onReceive(int numBytes){ + lastcommanderror = commanderror; + lastcommandregister = curRegister; + commanderror = false; + if (numBytes>=1) { // set the current register + curRegister = static_cast(_wire->read()); + } + if (numBytes>1) { // read from i2c and update value represented by register as well... + if (!receiveRegister(curMotor, curRegister, numBytes)) + commanderror = true; + } + if (numBytes<1) + commanderror = true; +}; + + + +void I2CCommander::onRequest(){ + commanderror = false; + if (!sendRegister(curMotor, curRegister)) + commanderror = true; +}; + + + + +/* +Reads values from I2C bus and updates the motor's values. + +Currently this isn't really thread-safe, but works ok in practice on 32-bit MCUs. + +Do not use on 8-bit architectures where the 32 bit writes may not be atomic! + +Plan to make this safe: the writes should be buffered, and not actually executed +until in the main loop by calling commander->run(); +the run() method disables interrupts while the updates happen. +*/ +bool I2CCommander::receiveRegister(uint8_t motorNum, uint8_t registerNum, int numBytes) { + int val; + switch (registerNum) { + case REG_MOTOR_ADDRESS: + val = _wire->read(); // reading one more byte is definately ok, since numBytes>1 + if (val>=0 && val=3 && (numBytes&0x01)==1) { // numBytes must be odd, since we have register and n pairs of motor/register numbers + val = (numBytes-1)/2; + if (val>I2CCOMMANDER_MAX_REPORT_REGISTERS) + val = I2CCOMMANDER_MAX_REPORT_REGISTERS; + for (int i=0;iread(); + reportRegisters[i] = _wire->read(); + } + } + else + commanderror = true; + break; + case REG_ENABLE_ALL: + val = _wire->read(); + for (int i=0; i0)?motors[i]->enable():motors[i]->disable(); + break; + case REG_ENABLE: + val = _wire->read(); + (val>0)?motors[motorNum]->enable():motors[motorNum]->disable(); + break; + case REG_CONTROL_MODE: + val = _wire->read(); + if (val>=0 && val<=4) // TODO these enums don't have assigned constants + motors[motorNum]->controller = static_cast(val); + else + commanderror = true; + break; + case REG_TORQUE_MODE: + val = _wire->read(); + if (val>=0 && val<=2) + motors[motorNum]->torque_controller = static_cast(val); + else + commanderror = true; + break; + case REG_MODULATION_MODE: + val = _wire->read(); + if (val>=0 && val<=3) + motors[motorNum]->foc_modulation = static_cast(val); + else + commanderror = true; + break; + case REG_TARGET: + readBytes(&(motors[motorNum]->target), 4); + break; + case REG_VEL_PID_P: + readBytes(&(motors[motorNum]->PID_velocity.P), 4); + break; + case REG_VEL_PID_I: + readBytes(&(motors[motorNum]->PID_velocity.I), 4); + break; + case REG_VEL_PID_D: + readBytes(&(motors[motorNum]->PID_velocity.D), 4); + break; + case REG_VEL_LPF_T: + readBytes(&(motors[motorNum]->LPF_velocity.Tf), 4); + break; + case REG_ANG_PID_P: + readBytes(&(motors[motorNum]->P_angle.P), 4); + break; + case REG_VEL_LIMIT: + readBytes(&(motors[motorNum]->velocity_limit), 4); + break; + case REG_VEL_MAX_RAMP: + readBytes(&(motors[motorNum]->PID_velocity.output_ramp), 4); + break; + case REG_CURQ_PID_P: + readBytes(&(motors[motorNum]->PID_current_q.P), 4); + break; + case REG_CURQ_PID_I: + readBytes(&(motors[motorNum]->PID_current_q.I), 4); + break; + case REG_CURQ_PID_D: + readBytes(&(motors[motorNum]->PID_current_q.D), 4); + break; + case REG_CURQ_LPF_T: + readBytes(&(motors[motorNum]->LPF_current_q.Tf), 4); + break; + case REG_CURD_PID_P: + readBytes(&(motors[motorNum]->PID_current_d.P), 4); + break; + case REG_CURD_PID_I: + readBytes(&(motors[motorNum]->PID_current_d.I), 4); + break; + case REG_CURD_PID_D: + readBytes(&(motors[motorNum]->PID_current_d.D), 4); + break; + case REG_CURD_LPF_T: + readBytes(&(motors[motorNum]->LPF_current_d.Tf), 4); + break; + case REG_VOLTAGE_LIMIT: + readBytes(&(motors[motorNum]->voltage_limit), 4); + break; + case REG_CURRENT_LIMIT: + readBytes(&(motors[motorNum]->current_limit), 4); + break; + case REG_MOTION_DOWNSAMPLE: + readBytes(&(motors[motorNum]->motion_downsample), 4); + break; + case REG_ZERO_OFFSET: + readBytes(&(motors[motorNum]->sensor_offset), 4); + break; + // RO registers + case REG_STATUS: + case REG_ANGLE: + case REG_POSITION: + case REG_VELOCITY: + case REG_SENSOR_ANGLE: + case REG_VOLTAGE_Q: + case REG_VOLTAGE_D: + case REG_CURRENT_Q: + case REG_CURRENT_D: + case REG_CURRENT_A: + case REG_CURRENT_B: + case REG_CURRENT_C: + case REG_CURRENT_ABC: + case REG_ZERO_ELECTRIC_ANGLE: + case REG_SENSOR_DIRECTION: + case REG_POLE_PAIRS: + case REG_PHASE_RESISTANCE: + case REG_NUM_MOTORS: + case REG_SYS_TIME: + default: // unknown register + return false; + } + return true; +} + + + + + +/* + Reads values from motor/sensor and writes them to I2C bus. Intended to be run + from the Wire.onRequest interrupt. + + Assumes atomic 32 bit reads. On 8-bit arduino this assumption does not hold and this + code is not safe on those platforms. You might read "half-written" floats. + + A solution might be to maintain a complete set of shadow registers in the commander + class, and update them in the run() method (which runs with interrupts off). Not sure + of the performance impact of all those 32 bit read/writes though. In any case, since + I use only 32 bit MCUs I'll leave it as an excercise to the one who needs it. ;-) + + On 32 bit platforms the implication is that reads will occur atomically, so data will + be intact, but they can occur at any time during motor updates, so different values might + not be in a fully consistent state (i.e. phase A current might be from the current iteration + but phase B current from the previous iteration). +*/ +bool I2CCommander::sendRegister(uint8_t motorNum, uint8_t registerNum) { + // read the current register + switch(registerNum) { + case REG_STATUS: + _wire->write(curMotor); + _wire->write((uint8_t)lastcommandregister); + _wire->write((uint8_t)lastcommanderror+1); + for (int i=0;(iwrite(motors[i]->motor_status); + } + break; + case REG_MOTOR_ADDRESS: + _wire->write(curMotor); + break; + case REG_REPORT: + for (int i=0;iwrite(motors[motorNum]->enabled); + break; + case REG_MODULATION_MODE: + _wire->write(motors[motorNum]->foc_modulation); + break; + case REG_TORQUE_MODE: + _wire->write(motors[motorNum]->torque_controller); + break; + case REG_CONTROL_MODE: + _wire->write(motors[motorNum]->controller); + break; + + case REG_TARGET: + writeFloat(motors[motorNum]->target); + break; + case REG_ANGLE: + writeFloat(motors[motorNum]->shaft_angle); + break; + case REG_VELOCITY: + writeFloat(motors[motorNum]->shaft_velocity); + break; + case REG_SENSOR_ANGLE: + if (motors[motorNum]->sensor) + writeFloat(motors[motorNum]->sensor->getAngle()); // stored angle + else + writeFloat(motors[motorNum]->shaft_angle); + break; + + case REG_VOLTAGE_Q: + writeFloat(motors[motorNum]->voltage.q); + break; + case REG_VOLTAGE_D: + writeFloat(motors[motorNum]->voltage.d); + break; + case REG_CURRENT_Q: + writeFloat(motors[motorNum]->current.q); + break; + case REG_CURRENT_D: + writeFloat(motors[motorNum]->current.d); + break; + case REG_CURRENT_A: + if (motors[motorNum]->current_sense) // TODO check if current sense can be called from inside this callback function + writeFloat(motors[motorNum]->current_sense->getPhaseCurrents().a); + else + writeFloat(0.0f); + break; + case REG_CURRENT_B: + if (motors[motorNum]->current_sense) + writeFloat(motors[motorNum]->current_sense->getPhaseCurrents().b); + else + writeFloat(0.0f); + break; + case REG_CURRENT_C: + if (motors[motorNum]->current_sense) + writeFloat(motors[motorNum]->current_sense->getPhaseCurrents().c); + else + writeFloat(0.0f); + break; + case REG_CURRENT_ABC: + if (motors[motorNum]->current_sense) { + PhaseCurrent_s currents = motors[motorNum]->current_sense->getPhaseCurrents(); + writeFloat(currents.a); + writeFloat(currents.b); + writeFloat(currents.c); + } + else { + writeFloat(0.0f); + writeFloat(0.0f); + writeFloat(0.0f); + } + break; + case REG_VEL_PID_P: + writeFloat(motors[motorNum]->PID_velocity.P); + break; + case REG_VEL_PID_I: + writeFloat(motors[motorNum]->PID_velocity.I); + break; + case REG_VEL_PID_D: + writeFloat(motors[motorNum]->PID_velocity.D); + break; + case REG_VEL_LPF_T: + writeFloat(motors[motorNum]->LPF_velocity.Tf); + break; + case REG_ANG_PID_P: + writeFloat(motors[motorNum]->P_angle.P); + break; + case REG_VEL_LIMIT: + writeFloat(motors[motorNum]->velocity_limit); + break; + case REG_VEL_MAX_RAMP: + writeFloat(motors[motorNum]->PID_velocity.output_ramp); + break; + + case REG_CURQ_PID_P: + writeFloat(motors[motorNum]->PID_current_q.P); + break; + case REG_CURQ_PID_I: + writeFloat(motors[motorNum]->PID_current_q.I); + break; + case REG_CURQ_PID_D: + writeFloat(motors[motorNum]->PID_current_q.D); + break; + case REG_CURQ_LPF_T: + writeFloat(motors[motorNum]->LPF_current_q.Tf); + break; + case REG_CURD_PID_P: + writeFloat(motors[motorNum]->PID_current_d.P); + break; + case REG_CURD_PID_I: + writeFloat(motors[motorNum]->PID_current_d.I); + break; + case REG_CURD_PID_D: + writeFloat(motors[motorNum]->PID_current_d.D); + break; + case REG_CURD_LPF_T: + writeFloat(motors[motorNum]->LPF_current_d.Tf); + break; + + case REG_VOLTAGE_LIMIT: + writeFloat(motors[motorNum]->voltage_limit); + break; + case REG_CURRENT_LIMIT: + writeFloat(motors[motorNum]->current_limit); + break; + case REG_MOTION_DOWNSAMPLE: + _wire->write((int)motors[motorNum]->motion_downsample); // TODO int will have different sizes on different platforms + // but using uint32 doesn't compile clean on all, e.g. RP2040 + break; + + case REG_ZERO_ELECTRIC_ANGLE: + writeFloat(motors[motorNum]->zero_electric_angle); + break; + case REG_SENSOR_DIRECTION: + _wire->write((int8_t)motors[motorNum]->sensor_direction); + break; + case REG_ZERO_OFFSET: + writeFloat(motors[motorNum]->sensor_offset); + break; + case REG_PHASE_RESISTANCE: + writeFloat(motors[motorNum]->phase_resistance); + break; + case REG_POLE_PAIRS: + _wire->write((int)motors[motorNum]->pole_pairs); + break; + + case REG_SYS_TIME: + // TODO how big is millis()? Same on all platforms? + _wire->write((int)millis()); + break; + case REG_NUM_MOTORS: + _wire->write(numMotors); + break; + + // unknown register or write only register (no read) + case REG_ENABLE_ALL: + default: + _wire->write(0); // TODO what to send in this case? + return false; + } + return true; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.h b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.h new file mode 100644 index 0000000..65cefde --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommander.h @@ -0,0 +1,49 @@ + +#ifndef SIMPLEFOC_I2CCOMMANDER_H +#define SIMPLEFOC_I2CCOMMANDER_H + +#include "Arduino.h" +#include "Wire.h" +#include "common/base_classes/FOCMotor.h" +#include "../SimpleFOCRegisters.h" + +#ifndef I2CCOMMANDER_MAX_MOTORS_COMMANDABLE +#define I2CCOMMANDER_MAX_MOTORS_COMMANDABLE 4 +#endif + +#define I2CCOMMANDER_MIN_VELOCITY_FOR_MOTOR_MOVING 0.1f // in rad/s +#define I2CCOMMANDER_MAX_REPORT_REGISTERS 8 + + +class I2CCommander { + public: + I2CCommander(TwoWire* wire = &Wire); + ~I2CCommander(); + + void addMotor(FOCMotor* motor); // first add motors + virtual void init(uint8_t address); // then init + + void onReceive(int numBytes); + void onRequest(); + + protected: + void writeFloat(float value); + bool readBytes(void* valueToSet, uint8_t numBytes); + virtual bool sendRegister(uint8_t motorNum, uint8_t registerNum); + virtual bool receiveRegister(uint8_t motorNum, uint8_t registerNum, int numBytes); + + uint8_t _address; + TwoWire* _wire; + uint8_t numMotors = 0; + uint8_t curMotor = 0; + SimpleFOCRegister curRegister = REG_STATUS; + bool commanderror = false; + bool lastcommanderror = false; + uint8_t lastcommandregister = REG_STATUS; + FOCMotor* motors[I2CCOMMANDER_MAX_MOTORS_COMMANDABLE]; + uint8_t numReportRegisters = 0; + uint8_t reportMotors[I2CCOMMANDER_MAX_REPORT_REGISTERS]; + uint8_t reportRegisters[I2CCOMMANDER_MAX_REPORT_REGISTERS]; +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.cpp new file mode 100644 index 0000000..666e009 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.cpp @@ -0,0 +1,59 @@ + +#include "I2CCommanderMaster.h" + + +I2CCommanderMaster::I2CCommanderMaster(int maxMotors) : maxMotors(maxMotors), motors(new I2CRemoteMotor[maxMotors]) { +}; + + + +I2CCommanderMaster::~I2CCommanderMaster(){ +}; + + + +void I2CCommanderMaster::init(){ +}; + + +// TODO handle multiple motors per target +void I2CCommanderMaster::addI2CMotors(uint8_t i2cAddress, uint8_t motorCount, TwoWire *wire){ + for (int i=0;ibeginTransmission(motors[motor].address); + motors[motor].wire->write((uint8_t)registerNum); + motors[motor].wire->write((uint8_t*)data, size); + motors[motor].wire->endTransmission(); + return size; +}; + + +int I2CCommanderMaster::readRegister(int motor, SimpleFOCRegister registerNum, void* data, uint8_t size){ + motors[motor].wire->beginTransmission(motors[motor].address); + int numWrite = motors[motor].wire->write((uint8_t)registerNum); // TODO check return value + motors[motor].wire->endTransmission(); + if (numWrite==1) + return readLastUsedRegister(motor, data, size); + return 0; +}; + + +int I2CCommanderMaster::readLastUsedRegister(int motor, void* data, uint8_t size){ + int numRead = motors[motor].wire->requestFrom(motors[motor].address, size); + if (numRead==size) + motors[motor].wire->readBytes((uint8_t*)data, size); + else { + return 0; + } + return numRead; +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.h b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.h new file mode 100644 index 0000000..9b52ae7 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/I2CCommanderMaster.h @@ -0,0 +1,42 @@ +#ifndef SIMPLEFOC_I2CCOMMANDER_H +#define SIMPLEFOC_I2CCOMMANDER_H + +#include +#include + +#include "../SimpleFOCRegisters.h" + +#define I2COMMANDER_DEFAULT_MAX_REMOTE_MOTORS 4 + + +typedef struct { + TwoWire* wire; + uint8_t address; +} I2CRemoteMotor; + + +class I2CCommanderMaster { + + public: + I2CCommanderMaster(int maxMotors = I2COMMANDER_DEFAULT_MAX_REMOTE_MOTORS); + ~I2CCommanderMaster(); + void init(); + void addI2CMotors(uint8_t i2cAddress, uint8_t motorCount, TwoWire *wire = &Wire); + + int writeRegister(int motor, SimpleFOCRegister registerNum, void* data, uint8_t size); + int readRegister(int motor, SimpleFOCRegister registerNum, void* data, uint8_t size); + int readLastUsedRegister(int motor, void* data, uint8_t size); + + // Motor intialization interface for convenience - think about how this will best work + // i.e. which parameters should be set by i2c and which should be hard-coded, and where config info is saved + // TODO bool initializeMotor(int motor); + + private: + int maxMotors; + int numMotors = 0; + I2CRemoteMotor* motors; + +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/README.md b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/README.md new file mode 100644 index 0000000..eac9e34 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/i2c/README.md @@ -0,0 +1,98 @@ + +# I2CCommander + +Implementation of SimpleFOC Commander for I2C communication bus. + +This code takes the point of view that the motor driver (the "muscle") is the I2C target device, and another MCU/CPU (the "brain") is the I2C controller device, which is coordinating one or more motor drivers on the same or different I2C buses. Each motor driver can offer one or more motors for control via the I2CCommander. So fairly flexible setups are possible, with multiple motors per driver, multiple drivers per I2C bus and multiple I2C buses on the brain MCU. + +## Warning + +This is new code, and has not been extensively tested. Your milage may vary. That said, basic use cases have been tested, and we would certainly appreciate feedback and help with testing it out. + +In particular, there are concurrency issues with reading/writing the SimpleFOC motor values from I2C while the motor is running. These should be solved soon in an upcoming version. + +**Do not run on 8-bit MCUs!** The code currently assumes atomic 32 bit reads, so running on Arduino UNO or Nano is unfortunately a no-go. + +## Using + +As would be expected for I2C, each target device needs a unique I2C address on its bus, and setting up and discovering these addresses is out-of-scope for I2CCommander. Setting up and configuring the TwoWire objects (which pins, speed, etc...) is also out of scope and finished, initialized TwoWire objects must be passed to I2CCommander. If you don't specify a different reference, the standard *Wire* object is assumed. + +Communication with the motor drivers happens via a register paradigm. The driver board offers many registers, some of which can be read, some can be written, and some are read/write. The controller MCU sends I2C messages to the target device to read or write a register as desired. The size of the data to be read/written depends on the register, and must be known by the controller. See Registers, below, for more details on the individual registers. + +Since each target motor driver can handle multiple motors, one of the registers contains the currently selected motor. Most of the other registers then operate on the currently selected motor. There are some exceptions, like REG_ENABLE_ALL - which operates on all the motors, or REG_STATUS, which returns stati for all the motors. + +### Target device (motor driver) + +The target device (motor driver) initializes and uses an instance of I2CCommander. Only one instance is needed for all attached motors: + +```c++ +#include "Arduino.h" +#include +#include +#include "SimpleFOCDrivers.h" +#include "comms/i2c/I2CCommander.h" + +// commander instance +uint8_t i2c_addr = 0x60; // can be anything you choose +I2CCommander commander; +// interrupt callbacks +void onReceive(int numBytes) { commander.onReceive(numBytes); } +void onRequest() { commander.onRequest(); } + + +// ... other variables, like sensor, etc... +BLDCMotor motor = BLDCMotor(POLE_PAIRS); + + +void setup() { + + // ...other setup code + + Wire.setClock(400000); // use same speed on controller device + Wire.begin(i2c_addr, true); // initialize i2c in target mode + commander.addMotor(&motor); // add a motor + //commander.addMotor(&motor2); // you could add more than one motor + commander.init(i2c_addr); // initialize commander + Wire.onReceive(onReceive); // connect the interrupt handlers + Wire.onRequest(onRequest); + +} +``` + +### Controller device ("brain" MCU) + +On the controller device, you use an instance of I2CCommanderMaster, which you initialize by adding one or more target devices to it: + +```c++ +#include "Arduino.h" +#include +#include +#include "SimpleFOCDrivers.h" +#include "comms/i2c/I2CCommanderMaster.h" + +#define TARGET_I2C_ADDRESS 0x60 +I2CCommanderMaster commander; + +void setup() { + + // ...other setup code + + Wire.setClock(400000); // use same speed on target device! + Wire.begin(); // initialize i2c in controller mode + commander.addI2CMotors(TARGET_I2C_ADDRESS, 1); // add target device, it has 1 motor + //commander.addI2CMotors(TARGET_I2C_ADDRESS2, 1); // you could add another target device on the same bus + //commander.addI2CMotors(TARGET_I2C_ADDRESS, 1, &wire2); // or on a different i2c bus + commander.init(); // init commander + Wire.onReceive(onReceive); // connect the interrupt handlers + Wire.onRequest(onRequest); + +} + +``` + + +## Extending + +The API is somewhat opinionated, and unlike the standard serial commander, currently does not support hooking in your own variables for reading/writing to them via I2C. This is because I2C is a bit less flexible than Serial. + +If you want to extend I2CCommander please subclass it and override the functions `sendRegister` and `receiveRegister` to add new registers. Use register numbers above 0x80 to prevent collisions with the standard registers. \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/serial/README.md b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/README.md new file mode 100644 index 0000000..2e1b733 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/README.md @@ -0,0 +1,49 @@ + +# Serial communications classes + +Serial communications classes for register-based control and telemetry from SimpleFOC. + +## SerialASCIITelemetry + +:warning: unfinished, untested + +Telemetry class that sends telemetry as ASCII on a serial port. Similar to the classic "monitoring" functionality of SimpleFOC, but allows you to configure telemetry based on most of the defined registers. + +Usage: + +```c++ + +SerialASCIITelemetry telemetry = SerialASCIITelemetry(); // number of float digits to display + +void setup() { + ... + telemetry.addMotor(&motor); + telemetry.setTelemetryRegisters(2, [REG_VELOCITY, REG_VOLTAGE_Q]); + telemetry.init(); + ... +} + +void loop() { + motor.move(); + motor.loopFOC(); + telemetry.run(); +} +``` + +Some options are supported: + +```c++ + telemetry.floatPrecision = 4; // send floats with 4 decimal places + telemetry.min_elapsed_time = 0; // microseconds between sending telemetry + telemetry.downsample = 100; // send every this many loop iterations +``` + + + +## SerialBinaryCommander + +:warning: unfinished, untested! + +Control SimpleFOC via a binary protocol over the serial port. The standard SimpleFOC registers are used. + +TODO document the protocol \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.cpp new file mode 100644 index 0000000..084b940 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.cpp @@ -0,0 +1,65 @@ + +#include "./SerialASCIITelemetry.h" + +SerialASCIITelemetry::SerialASCIITelemetry(int floatPrecision) : Telemetry() { + this->floatPrecision = floatPrecision; +}; + +SerialASCIITelemetry::~SerialASCIITelemetry(){ + +}; + +void SerialASCIITelemetry::init(Print* print){ + this->_print = print; + this->Telemetry::init(); +}; + + + +void SerialASCIITelemetry::sendHeader() { + if (numRegisters > 0) { + writeChar('H'); + writeChar(' '); + for (uint8_t i = 0; i < numRegisters; i++) { + writeByte(registers_motor[i]); + writeChar(':'); + writeByte(registers[i]); + if (i < numRegisters-1) + writeChar(' '); + }; + writeChar('\n'); + }; +}; + + + +void SerialASCIITelemetry::sendTelemetry(){ + if (numRegisters > 0) { + for (uint8_t i = 0; i < numRegisters; i++) { + sendRegister(static_cast(registers[i]), motors[registers_motor[i]]); + if (i < numRegisters-1) + writeChar(' '); + }; + writeChar('\n'); + } +}; + + + +uint8_t SerialASCIITelemetry::writeChar(char value){ + return _print->print(value); +}; + +uint8_t SerialASCIITelemetry::writeByte(uint8_t value){ + return _print->print(value); +}; + + +uint8_t SerialASCIITelemetry::writeFloat(float value){ + return _print->print(value, floatPrecision); +}; + + +uint8_t SerialASCIITelemetry::writeInt(uint32_t value){ + return _print->print(value); +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.h b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.h new file mode 100644 index 0000000..e218f3b --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialASCIITelemetry.h @@ -0,0 +1,27 @@ + +#pragma once + +#include "Arduino.h" +#include "../telemetry/Telemetry.h" + +class SerialASCIITelemetry : public Telemetry { +public: + SerialASCIITelemetry(int floatPrecision = 2); + virtual ~SerialASCIITelemetry(); + + void init(Print* print = &Serial); + +protected: + uint8_t writeByte(uint8_t value) override; + uint8_t writeFloat(float value) override; + uint8_t writeInt(uint32_t value) override; + uint8_t writeChar(char value); + + void sendTelemetry() override; + void sendHeader() override; + + Print* _print; + int floatPrecision = 2; +}; + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.cpp new file mode 100644 index 0000000..ffa2406 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.cpp @@ -0,0 +1,153 @@ + +#include "SerialBinaryCommander.h" + + + +SerialBinaryCommander::SerialBinaryCommander(bool echo) : Telemetry(), echo(echo) { + +}; + + + +SerialBinaryCommander::~SerialBinaryCommander(){ + +}; + + + +void SerialBinaryCommander::init(Stream &serial) { + _serial = &serial; + this->Telemetry::init(); +}; + + + +void SerialBinaryCommander::run() { + if (_serial->available()>2) { // TODO make this work with partial packets... + uint8_t command = _serial->read(); + uint8_t registerNum = _serial->read(); + uint8_t motorNum = _serial->read(); + if (command==SERIALBINARY_COMMAND_READ){ + startFrame(registerNum, SERIALBINARY_FRAMETYPE_REGISTER); // TODO call is incorrect + sendRegister(static_cast(registerNum), motors[motorNum]); + endFrame(); + } + else if (command==SERIALBINARY_COMMAND_WRITE) { + setRegister(static_cast(registerNum), motors[motorNum]); + if (echo) { + startFrame(registerNum, SERIALBINARY_FRAMETYPE_REGISTER); // TODO call is incorrect + sendRegister(static_cast(registerNum), motors[motorNum]); + endFrame(); + } + } + } + // and handle the telemetry + this->Telemetry::run(); +}; + + + +uint8_t SerialBinaryCommander::readBytes(void* valueToSet, uint8_t numBytes){ + if (_serial->available()read(); + } + return numBytes; +}; + + + + +uint8_t SerialBinaryCommander::writeBytes(void* valueToSend, uint8_t numBytes){ + uint8_t* value = (uint8_t*)valueToSend; + for (uint8_t i=0; iwrite(value[i]); + } + return numBytes; +}; + + + + + + +void SerialBinaryCommander::startFrame(uint8_t frameSize, uint8_t type){ + _serial->write(0xA5); + _serial->write((uint8_t)((type<<6)|frameSize)); +}; + + + + + +void SerialBinaryCommander::endFrame(){ + _serial->write(0x5A); +}; + + + + +uint8_t SerialBinaryCommander::writeByte(uint8_t value){ + return writeBytes(&value, 1); +}; + + + +uint8_t SerialBinaryCommander::writeFloat(float value){ + return writeBytes(&value, 4); +}; + + + +uint8_t SerialBinaryCommander::writeInt(uint32_t value){ + return writeBytes(&value, 4); +}; + + + + +uint8_t SerialBinaryCommander::readByte(uint8_t* valueToSet){ + return readBytes(valueToSet, 1); +}; + + + +uint8_t SerialBinaryCommander::readFloat(float* valueToSet){ + return readBytes(valueToSet, 4); +}; + + + +uint8_t SerialBinaryCommander::readInt(uint32_t* valueToSet){ + return readBytes(valueToSet, 4); +}; + + + + + + +void SerialBinaryCommander::sendHeader() { + if (numRegisters > 0) { + startFrame(numRegisters*2, TELEMETRY_FRAMETYPE_HEADER); + for (uint8_t i = 0; i < numRegisters; i++) { + writeByte(registers[i]); + writeByte(registers_motor[i]); + }; + endFrame(); + }; +}; + + + +void SerialBinaryCommander::sendTelemetry(){ + if (numRegisters > 0) { + startFrame(frameSize, TELEMETRY_FRAMETYPE_DATA); + for (uint8_t i = 0; i < numRegisters; i++) { + sendRegister(static_cast(registers[i]), motors[registers_motor[i]]); + }; + endFrame(); + } +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.h b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.h new file mode 100644 index 0000000..f80ccc4 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/serial/SerialBinaryCommander.h @@ -0,0 +1,57 @@ + +#pragma once + +#include +#include "../RegisterReceiver.h" +#include "../telemetry/Telemetry.h" + + +#ifndef COMMS_MAX_REPORT_REGISTERS +#define COMMS_MAX_REPORT_REGISTERS 7 +#endif + + +#define SERIALBINARY_FRAMETYPE_REGISTER 0x03 +#define SERIALBINARY_COMMAND_READ 0x00 +#define SERIALBINARY_COMMAND_WRITE 0x80 + + +class SerialBinaryCommander : public Telemetry, public RegisterReceiver { +public: + SerialBinaryCommander(bool echo = false); + virtual ~SerialBinaryCommander(); + + void init(Stream &serial = Serial); + void run(); + + + bool echo; +protected: + virtual void startFrame(uint8_t frameSize, uint8_t type = TELEMETRY_FRAMETYPE_DATA); + virtual void endFrame(); + uint8_t readBytes(void* valueToSet, uint8_t numBytes); + uint8_t writeBytes(void* valueToSend, uint8_t numBytes); + + uint8_t writeByte(uint8_t value) override; + uint8_t writeFloat(float value) override; + uint8_t writeInt(uint32_t value) override; + + uint8_t readByte(uint8_t* valueToSet) override; + uint8_t readFloat(float* valueToSet) override; + uint8_t readInt(uint32_t* valueToSet) override; + + void sendTelemetry() override; + void sendHeader() override; + + uint8_t curMotor = 0; + SimpleFOCRegister curRegister = REG_STATUS; + bool commanderror = false; + bool lastcommanderror = false; + uint8_t lastcommandregister = REG_STATUS; + + uint8_t numReportRegisters = 0; + uint8_t reportMotors[COMMS_MAX_REPORT_REGISTERS]; + SimpleFOCRegister reportRegisters[COMMS_MAX_REPORT_REGISTERS]; + + Stream* _serial; +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/README.md b/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/README.md new file mode 100644 index 0000000..1e36a5a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/README.md @@ -0,0 +1,58 @@ + +# STM32SpeedDirInput + +Control SimpleFOC using PWM speed and direction inputs. + +Based on STM32 timer PWM-Input capabilities, which means this can only be used on STM32 MCUs. It can cover a wide range of PWM frequencies, and runs without MCU overhead in the timer hardware. + + + +## Setup + +The PWM speed input should be connected to either channel 1 or channel 2 of a general purpose or advanced control timer on your STM32 MCU. Suitable timers are: +- Advanced control timers: TIM1, TIM8 +- General purpose timers (32 bit): TIM2, TIM5 +- General purpose timers (16 bit): TIM3, TIM4, TIM9, TIM12 +If in doubt, check in STM32CubeIDE and see if the PWM-Input mode can be enabled (under "Combined Channels") for the timer. + +The optional direction input can be connected to any GPIO pin. By default a high level direction input is associated with a positive velocity value, while a low level direction input results in a negative velocity value. To reverse this, set the option `dir_positive_high = false` + +The direction input is optional - if not provided, you can control the direction from software using the `direction` field. + +The velocity values returned are in the range `min_speed` to `max_speed`, while the input PWM duty cycle should lie within the range `min_pwm` to `max_pwm`. Actual input values smaller than `min_pwm` will be treated as `min_pwm`, values larger than `max_pwm` will be treated as `max_pwm`. The behaviour for 100% or 0% duty cycles is undefined, and they should be avoided. + +## Usage + +Use it like this: + +```c++ +#include "comms/stm32speeddir/STM32SpeedDirInput.h" + +// some example pins - the speed pin has to be on channel 1 or 2 of a timer +#define PIN_SPEED PC6 +#define PIN_DIRECTION PB8 + +STM32SpeedDirInput speed_dir = STM32SpeedDirInput(PIN_SPEED, PIN_DIRECTION); + +float target = 0.0f; + +void setup(){ + ... + + speed_dir.min_speed = 10.0f; // 10rad/s min speed + speed_dir.max_speed = 100.0f; // 100rad/s max speed + speed_dir.min_pwm = 5.0f; // 5% min duty cycle + speed_dir.max_pwm = 95.0f; // 95% max duty cycle + speed_dir.init(); + + ... +} + + +void loop(){ + target = speed_dir.getTargetVelocity(); + motor.move(target); + motor.loopFOC(); +} + +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.cpp new file mode 100644 index 0000000..4bc8bee --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.cpp @@ -0,0 +1,29 @@ + +#include "./STM32SpeedDirInput.h" + +#if defined(_STM32_DEF_) + +STM32SpeedDirInput::STM32SpeedDirInput(int pin_speed, int pin_dir) : STM32PWMInput(pin_speed) { + _pin_speed = pin_speed; + _pin_dir = pin_dir; +}; + +STM32SpeedDirInput::~STM32SpeedDirInput(){}; + +int STM32SpeedDirInput::init(){ + pinMode(_pin_dir, INPUT); + return STM32PWMInput::initialize(); +}; + + +float STM32SpeedDirInput::getTargetVelocity(){ + if (_pin_dir != NOT_SET) + direction = digitalRead(_pin_dir); + float speed = getDutyCyclePercent(); + speed = constrain(speed, min_pwm, max_pwm); + speed = (speed - min_pwm)/(max_pwm - min_pwm) * (max_speed - min_speed) + min_speed; + return (direction == dir_positive_high) ? speed : -speed; +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.h b/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.h new file mode 100644 index 0000000..3a3647b --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/stm32speeddir/STM32SpeedDirInput.h @@ -0,0 +1,31 @@ + +#pragma once + +#include "Arduino.h" + +#if defined(_STM32_DEF_) + +#include "common/foc_utils.h" +#include "utilities/stm32pwm/STM32PWMInput.h" + +class STM32SpeedDirInput : public STM32PWMInput { + public: + STM32SpeedDirInput(int pin_speed, int pin_dir = NOT_SET); + ~STM32SpeedDirInput(); + + int init(); + float getTargetVelocity(); + + float min_speed = 0; // min speed in rad/s + float max_speed = 100; // max speed in rad/s + float min_pwm = 5.0; // min duty cycle in % + float max_pwm = 95.0; // max duty cycle in % + bool dir_positive_high = true; // true if the direction pin is high when the motor is spinning in the positive direction + bool direction = true; // direction of rotation, default positive + protected: + int _pin_speed; + int _pin_dir; +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/README.md b/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/README.md new file mode 100644 index 0000000..384098f --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/README.md @@ -0,0 +1,42 @@ + +# SimpleFOC Telemetry + +:warning: unfinished, untested + +A flexible abstraction for telemetry (monitoring) of SimpleFOC systems. + +The telemetry implementation is based on the SimpleFOC registers, and allows you to send telemetry for any (readable) register. Telemetry supports multiple motors. + +The concept allows you to choose registers which are then sent by the telemetry automatically, on a regular schedule. + +The method of sending depends on the type of telemetry you add to your program. There are telemetry drivers for: + +- Serial ASCII telemetry +- Serial Binary telemetry +- and more drivers will be added in the future + +Multiple motors can be added to the same telemetry, to monitor several motors at the same time. The registers reported by telemetry can be changed at run-time. Multiple instances of telemetry can be used to monitor different sets of values at different time intervals, or to send to multiple channels at the same time. + +## Usage + +Using telemetry is simple: + +```c++ + +SerialASCIITelemetry telemetry = SerialASCIITelemetry(); +... + +void setup() { + ... + telemetry.addMotor(&motor); + telemetry.setTelemetryRegisters(3, { REG_TARGET, REG_ANGLE, REG_VELOCITY }); + telemetry.init(); + ... +} + +void loop() { + motor.move(); + motor.loopFOC(); + telemetry.run(); +} +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.cpp b/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.cpp new file mode 100644 index 0000000..6a6c446 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.cpp @@ -0,0 +1,67 @@ + + +#include "./Telemetry.h" + + + +Telemetry::Telemetry() { + this->numRegisters = 0; +}; + + + +Telemetry::~Telemetry(){ + +}; + + + + + +void Telemetry::setTelemetryRegisters(uint8_t numRegisters, uint8_t* registers, uint8_t* motors){ + if (numRegisters<=TELEMETRY_MAX_REGISTERS) { + this->numRegisters = numRegisters; + for (uint8_t i=0; iregisters[i] = registers[i]; + if (motors!=NULL) + this->registers_motor[i] = motors[i]; + else + this->registers_motor[i] = 0; + } + } +}; + + + +void Telemetry::init() { + headerSent = false; +}; + + + +void Telemetry::run() { + if (numRegisters<1) + return; + if (!headerSent) { + sendHeader(); + headerSent = true; + } + if (downsampleCnt++ < downsample) return; + downsampleCnt = 0; + if (min_elapsed_time > 0) { + long now = _micros(); + if (now - last_run_time < min_elapsed_time) return; + last_run_time = now; + } + sendTelemetry(); +} + + + +void Telemetry::addMotor(FOCMotor* motor) { + if (numMotors < TELEMETRY_MAX_MOTORS) { + motors[numMotors] = motor; + numMotors++; + } +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.h b/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.h new file mode 100644 index 0000000..256036a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/comms/telemetry/Telemetry.h @@ -0,0 +1,53 @@ + +#pragma once + +#include "../SimpleFOCRegisters.h" +#include "../RegisterSender.h" + +#ifndef TELEMETRY_MAX_REGISTERS +#define TELEMETRY_MAX_REGISTERS 8 +#endif + +#ifndef TELEMETRY_MAX_MOTORS +#define TELEMETRY_MAX_MOTORS 4 +#endif + + +#define DEF_TELEMETRY_DOWNSAMPLE 100 + + +typedef enum : uint8_t { + TELEMETRY_FRAMETYPE_DATA = 0x01, + TELEMETRY_FRAMETYPE_HEADER = 0x02 +} TelemetryFrameType; + + + + +class Telemetry : public RegisterSender { +public: + Telemetry(); + virtual ~Telemetry(); + virtual void init(); + void addMotor(FOCMotor* motor); + void setTelemetryRegisters(uint8_t numRegisters, uint8_t* registers, uint8_t* motors = NULL); + void run(); + + uint16_t downsample = DEF_TELEMETRY_DOWNSAMPLE; + uint32_t min_elapsed_time = 0; +protected: + virtual void sendTelemetry() = 0; + virtual void sendHeader() = 0; + + FOCMotor* motors[TELEMETRY_MAX_MOTORS]; + uint8_t numMotors = 0; + + uint8_t numRegisters; + uint8_t registers[TELEMETRY_MAX_REGISTERS]; + uint8_t registers_motor[TELEMETRY_MAX_REGISTERS]; + uint8_t frameSize; + bool headerSent; + long last_run_time = 0; + uint16_t downsampleCnt = 0; +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/README.md b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/README.md new file mode 100644 index 0000000..8d15d0c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/README.md @@ -0,0 +1,175 @@ + +# DRV8316 SimpleFOC driver + +The DRV8316 is a integrated FET, integrated current sensing 3-phase BLDC driver IC from Texas Instruments, including all protections and many cool configuration optons. See https://www.ti.com/product/DRV8316 for more information. + +This driver includes a DRV8316 SPI driver, and specific subclasses for SimpleFOCs BLDCDriver3PWM and BLDCDriver6PWM generic drivers. The code is designed to be "Ardunio compatible" and should work with any of the hardware architectures supported by SimpleFOC. + +## Hardware setup + +To use the DRV8316 you will have to connect the following: + +- GND +- SPI MOSI +- SPI MISO +- SPI CLK +- SPI nCS +- INH_U - connect to motor PWM pin +- INH_V - connect to motor PWM pin +- INH_W - connect to motor PWM pin +- INL_U - connect to motor PWM pin for 6-PWM, or to digital out (or pull up to VCC) for 3-PWM operation +- INL_V - connect to motor PWM pin for 6-PWM, or to digital out (or pull up to VCC) for 3-PWM operation +- INL_W - connect to motor PWM pin for 6-PWM, or to digital out (or pull up to VCC) for 3-PWM operation + +Optionally, but probably useful: + +- nFault - digital in, active low +- DRVOFF - digital out + +For current sensting: + +- VREF - either connect to DAC output of the MCU or a fixed voltage reference. +- ISENA - connect to analog in +- ISENB - connect to analog in +- ISENC - connect to analog in + +For current limiting: + +- ILIM (same as VREF) - connect it to a DAC output of the MCU if you want to control the current limit from the MCU + +## Usage + +Usage is quite easy, especially if you already know SimpleFOC. See also the [examples](https://github.com/simplefoc/Arduino-FOC-drivers/examples/drivers/drv8316/) + +```c++ +#include "Arduino.h" +#include +#include +#include +#include "SimpleFOCDrivers.h" +#include "drivers/drv8316/drv8316.h" + +BLDCMotor motor = BLDCMotor(11); +DRV8316Driver6PWM driver = DRV8316Driver6PWM(A3,0,A4,1,2,6,7,false); // MKR1010 6-PWM + +//... normal simpleFOC init code... +``` + +Or, for 3-PWM: + +```c++ +#include "Arduino.h" +#include +#include +#include +#include "SimpleFOCDrivers.h" +#include "drivers/drv8316/drv8316.h" + +BLDCMotor motor = BLDCMotor(11); +DRV8316Driver3PWM driver = DRV8316Driver3PWM(A3,A4,2,7,false); // MKR1010 3-PWM +// these are examples, for 3-PWM you could use any output pins as the enable pins. +#define ENABLE_A 0 +#define ENABLE_B 1 +#define ENABLE_C 6 + +void setup() { + + + pinMode(ENABLE_A, OUTPUT); + digitalWrite(ENABLE_A, 1); // enable + pinMode(ENABLE_B, OUTPUT); + digitalWrite(ENABLE_B, 1); // enable + pinMode(ENABLE_C, OUTPUT); + digitalWrite(ENABLE_C, 1); // enable + + +//... normal simpleFOC init code... + + +} + +``` + +You can use the driver's features. In general you can do this at any time, but certain features only make sense at setup-time (e.g. setting the PWM mode, which is handled automatically by the DRV8316Driver3PWM class, or setting the current limit, which you generally want to get done before applying power to the motor). + +Driver usage, for example reading and printing the complete status: + +```c++ + DRV8316Status status = driver.getStatus(); + Serial.println("DRV8316 Status:"); + Serial.print("Fault: "); + Serial.println(status.isFault()); + Serial.print("Buck Error: "); + Serial.print(status.isBuckError()); + Serial.print(" Undervoltage: "); + Serial.print(status.isBuckUnderVoltage()); + Serial.print(" OverCurrent: "); + Serial.println(status.isBuckOverCurrent()); + Serial.print("Charge Pump UnderVoltage: "); + Serial.println(status.isChargePumpUnderVoltage()); + Serial.print("OTP Error: "); + Serial.println(status.isOneTimeProgrammingError()); + Serial.print("OverCurrent: "); + Serial.print(status.isOverCurrent()); + Serial.print(" Ah: "); + Serial.print(status.isOverCurrent_Ah()); + Serial.print(" Al: "); + Serial.print(status.isOverCurrent_Al()); + Serial.print(" Bh: "); + Serial.print(status.isOverCurrent_Bh()); + Serial.print(" Bl: "); + Serial.print(status.isOverCurrent_Bl()); + Serial.print(" Ch: "); + Serial.print(status.isOverCurrent_Ch()); + Serial.print(" Cl: "); + Serial.println(status.isOverCurrent_Cl()); + Serial.print("OverTemperature: "); + Serial.print(status.isOverTemperature()); + Serial.print(" Shutdown: "); + Serial.print(status.isOverTemperatureShutdown()); + Serial.print(" Warning: "); + Serial.println(status.isOverTemperatureWarning()); + Serial.print("OverVoltage: "); + Serial.println(status.isOverVoltage()); + Serial.print("PowerOnReset: "); + Serial.println(status.isPowerOnReset()); + Serial.print("SPI Error: "); + Serial.print(status.isSPIError()); + Serial.print(" Address: "); + Serial.print(status.isSPIAddressError()); + Serial.print(" Clock: "); + Serial.print(status.isSPIClockFramingError()); + Serial.print(" Parity: "); + Serial.println(status.isSPIParityError()); + if (status.isFault()) + driver.clearFault(); + delayMicroseconds(1); // ensure 400ns delay + DRV8316_PWMMode val = driver.getPWMMode(); + Serial.print("PWM Mode: "); + Serial.println(val); + delayMicroseconds(1); // ensure 400ns delay + bool lock = driver.isRegistersLocked(); + Serial.print("Lock: "); + Serial.println(lock); +``` + + +Setting options can be conveniently done via the provided setter methods. All documented registers and options are available via the driver, and the option values can be accessed via enums. + +Leave at least 400ns delay between reading and/or writing options to ensure you don't talk to the DRV8316 too quickly: + +```c++ +driver.setPWM100Frequency(DRV8316_PWM100DUTY::FREQ_40KHz); +delayMicroseconds(1); // ensure 400ns delay +driver.setBuckVoltage(DRV8316_BuckVoltage::VB_5V7); +``` + + +### Current sensing + +TODO... + +### Current limiting + +TODO... + diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.cpp b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.cpp new file mode 100644 index 0000000..9586faa --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.cpp @@ -0,0 +1,586 @@ + + +#include "./drv8316.h" + + +void DRV8316Driver3PWM::init(SPIClass* _spi) { + DRV8316Driver::init(_spi); + setRegistersLocked(false); + delayMicroseconds(1); + DRV8316Driver::setPWMMode(DRV8316_PWMMode::PWM3_Mode); + BLDCDriver3PWM::init(); +}; + + +void DRV8316Driver6PWM::init(SPIClass* _spi) { + DRV8316Driver::init(_spi); + setRegistersLocked(false); + delayMicroseconds(1); + DRV8316Driver::setPWMMode(DRV8316_PWMMode::PWM6_Mode); // default mode is 6-PWM + BLDCDriver6PWM::init(); +}; + + + + + + +/* + * SPI setup: + * + * capture on falling, propagate on rising = + * MSB first + * + * 16 bit words + * outgoing: R/W:1 addr:6 parity:1 data:8 + * incoming: status:8 data:8 + * + * on reads, incoming data is content of register being read + * on writes, incomnig data is content of register being written + * + * + */ + +void handleInterrupt() { + +} + +void DRV8316Driver::init(SPIClass* _spi) { + // TODO make SPI speed configurable + spi = _spi; + settings = SPISettings(1000000, MSBFIRST, SPI_MODE1); + + //setup pins + pinMode(cs, OUTPUT); + digitalWrite(cs, HIGH); // switch off + + //SPI has an internal SPI-device counter, it is possible to call "begin()" from different devices + spi->begin(); + + if (_isset(nFault)) { + pinMode(nFault, INPUT); + // TODO add interrupt handler on the nFault pin if configured + // add configuration for how to handle faults... idea: interrupt handler calls a callback, depending on the type of fault + // consider what would be a useful configuration in practice? What do we want to do on a fault, e.g. over-temperature for example? + + //attachInterrupt(digitalPinToInterrupt(nFault), handleInterrupt, PinStatus::FALLING); + } +}; + + + + +bool DRV8316Driver::getParity(uint16_t data) { + //PARITY = XNOR(CMD, A5..A0, D7..D0) + uint8_t par = 0; + for (int i=0;i<16;i++) { + if (((data)>>i) & 0x0001) + par+=1; + } + return (par&0x01)==0x01; // even number of bits means true +} + + + + +uint16_t DRV8316Driver::readSPI(uint8_t addr) { + digitalWrite(cs, 0); + spi->beginTransaction(settings); + uint16_t data = (((addr<<1) | 0x80)<<8)|0x0000; + if (getParity(data)) + data |= 0x0100; + uint16_t result = spi->transfer16(data); + spi->endTransaction(); + digitalWrite(cs, 1); +// Serial.print("SPI Read Result: "); +// Serial.print(data, HEX); +// Serial.print(" -> "); +// Serial.println(result, HEX); + return result; +} + + +uint16_t DRV8316Driver::writeSPI(uint8_t addr, uint8_t value) { + digitalWrite(cs, 0); + spi->beginTransaction(settings); + uint16_t data = ((addr<<1)<<8)|value; + if (getParity(data)) + data |= 0x0100; + uint16_t result = spi->transfer16(data); + spi->endTransaction(); + digitalWrite(cs, 1); +// Serial.print("SPI Write Result: "); +// Serial.print(data, HEX); +// Serial.print(" -> "); +// Serial.println(result, HEX); + return result; +} + + + +DRV8316Status DRV8316Driver::getStatus() { + IC_Status data; + Status__1 data1; + Status__2 data2; + uint16_t result = readSPI(IC_Status_ADDR); + data.reg = (result & 0x00FF); + delayMicroseconds(1); // delay at least 400ns between operations + result = readSPI(Status__1_ADDR); + data1.reg = (result & 0x00FF); + delayMicroseconds(1); // delay at least 400ns between operations + result = readSPI(Status__2_ADDR); + data2.reg = (result & 0x00FF); + return DRV8316Status(data, data1, data2); +} + + + + + + + + +void DRV8316Driver::clearFault() { + uint16_t result = readSPI(Control__2_ADDR); + Control__2 data; + data.reg = (result & 0x00FF); + data.CLR_FLT |= 1; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__2_ADDR, data.reg); +}; + + + + + + + + +bool DRV8316Driver::isRegistersLocked(){ + uint16_t result = readSPI(Control__1_ADDR); + Control__1 data; + data.reg = (result & 0x00FF); + return data.REG_LOCK==REG_LOCK_LOCK; +} +void DRV8316Driver::setRegistersLocked(bool lock){ + uint16_t result = readSPI(Control__1_ADDR); + Control__1 data; + data.reg = (result & 0x00FF); + data.REG_LOCK = lock?REG_LOCK_LOCK:REG_LOCK_UNLOCK; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__1_ADDR, data.reg); +} + + + +DRV8316_PWMMode DRV8316Driver::getPWMMode() { + uint16_t result = readSPI(Control__2_ADDR); + Control__2 data; + data.reg = (result & 0x00FF); + return (DRV8316_PWMMode)data.PWM_MODE; +}; +void DRV8316Driver::setPWMMode(DRV8316_PWMMode pwmMode){ + uint16_t result = readSPI(Control__2_ADDR); + Control__2 data; + data.reg = (result & 0x00FF); + data.PWM_MODE = pwmMode; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__2_ADDR, data.reg); +}; + + + +DRV8316_Slew DRV8316Driver::getSlew() { + uint16_t result = readSPI(Control__2_ADDR); + Control__2 data; + data.reg = (result & 0x00FF); + return (DRV8316_Slew)data.SLEW; +}; +void DRV8316Driver::setSlew(DRV8316_Slew slewRate) { + uint16_t result = readSPI(Control__2_ADDR); + Control__2 data; + data.reg = (result & 0x00FF); + data.SLEW = slewRate; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__2_ADDR, data.reg); +}; + + + +DRV8316_SDOMode DRV8316Driver::getSDOMode() { + uint16_t result = readSPI(Control__2_ADDR); + Control__2 data; + data.reg = (result & 0x00FF); + return (DRV8316_SDOMode)data.SDO_MODE; +}; +void DRV8316Driver::setSDOMode(DRV8316_SDOMode sdoMode) { + uint16_t result = readSPI(Control__2_ADDR); + Control__2 data; + data.reg = (result & 0x00FF); + data.SDO_MODE = sdoMode; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__2_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isOvertemperatureReporting(){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + return data.OTW_REP==OTW_REP_ENABLE; +}; +void DRV8316Driver::setOvertemperatureReporting(bool reportFault){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + data.OTW_REP = reportFault?OTW_REP_ENABLE:OTW_REP_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__3_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isSPIFaultReporting(){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + return data.SPI_FLT_REP==SPI_FLT_REP_ENABLE; +} +void DRV8316Driver::setSPIFaultReporting(bool reportFault){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + data.SPI_FLT_REP = reportFault?SPI_FLT_REP_ENABLE:SPI_FLT_REP_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__3_ADDR, data.reg); +} + + + +bool DRV8316Driver::isOvervoltageProtection(){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + return data.OVP_EN==OVP_EN_ENABLE; +}; +void DRV8316Driver::setOvervoltageProtection(bool enabled){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + data.OVP_EN = enabled?OVP_EN_ENABLE:OVP_EN_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__3_ADDR, data.reg); +}; + + + +DRV8316_OVP DRV8316Driver::getOvervoltageLevel(){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + return (DRV8316_OVP)data.OVP_SEL; +}; +void DRV8316Driver::setOvervoltageLevel(DRV8316_OVP voltage){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + data.OVP_SEL = voltage; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__3_ADDR, data.reg); +}; + + + +DRV8316_PWM100DUTY DRV8316Driver::getPWM100Frequency(){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + return (DRV8316_PWM100DUTY)data.PWM_100_DUTY_SEL; +}; +void DRV8316Driver::setPWM100Frequency(DRV8316_PWM100DUTY freq){ + uint16_t result = readSPI(Control__3_ADDR); + Control__3 data; + data.reg = (result & 0x00FF); + data.PWM_100_DUTY_SEL = freq; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__3_ADDR, data.reg); +}; + + + +DRV8316_OCPMode DRV8316Driver::getOCPMode(){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + return (DRV8316_OCPMode)data.OCP_MODE; + +}; +void DRV8316Driver::setOCPMode(DRV8316_OCPMode ocpMode){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + data.OCP_MODE = ocpMode; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__4_ADDR, data.reg); +}; + + + +DRV8316_OCPLevel DRV8316Driver::getOCPLevel(){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + return (DRV8316_OCPLevel)data.OCP_LVL; +}; +void DRV8316Driver::setOCPLevel(DRV8316_OCPLevel amps){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + data.OCP_LVL = amps; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__4_ADDR, data.reg); +}; + + + +DRV8316_OCPRetry DRV8316Driver::getOCPRetryTime(){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + return (DRV8316_OCPRetry)data.OCP_RETRY; +}; +void DRV8316Driver::setOCPRetryTime(DRV8316_OCPRetry ms){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + data.OCP_RETRY = ms; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__4_ADDR, data.reg); +}; + + + +DRV8316_OCPDeglitch DRV8316Driver::getOCPDeglitchTime(){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + return (DRV8316_OCPDeglitch)data.OCP_DEG; +}; +void DRV8316Driver::setOCPDeglitchTime(DRV8316_OCPDeglitch ms){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + data.OCP_DEG = ms; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__4_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isOCPClearInPWMCycleChange(){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + return data.OCP_CBC==OCP_CBC_ENABLE; +}; +void DRV8316Driver::setOCPClearInPWMCycleChange(bool enable){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + data.OCP_CBC = enable?OCP_CBC_ENABLE:OCP_CBC_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__4_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isDriverOffEnabled(){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + return data.DRV_OFF==DRV_OFF_ENABLE; +}; +void DRV8316Driver::setDriverOffEnabled(bool enabled){ + uint16_t result = readSPI(Control__4_ADDR); + Control__4 data; + data.reg = (result & 0x00FF); + data.DRV_OFF = enabled?DRV_OFF_ENABLE:DRV_OFF_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__4_ADDR, data.reg); +}; + + + +DRV8316_CSAGain DRV8316Driver::getCurrentSenseGain(){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + return (DRV8316_CSAGain)data.CSA_GAIN; +}; +void DRV8316Driver::setCurrentSenseGain(DRV8316_CSAGain gain){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + data.CSA_GAIN = gain; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__5_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isActiveSynchronousRectificationEnabled(){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + return data.EN_ASR==EN_ASR_ENABLE; + +}; +void DRV8316Driver::setActiveSynchronousRectificationEnabled(bool enabled){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + data.EN_ASR = enabled?EN_ASR_ENABLE:EN_ASR_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__5_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isActiveAsynchronousRectificationEnabled(){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + return data.EN_AAR==EN_AAR_ENABLE; +}; +void DRV8316Driver::setActiveAsynchronousRectificationEnabled(bool enabled){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + data.EN_AAR = enabled?EN_AAR_ENABLE:EN_AAR_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__5_ADDR, data.reg); +}; + + + +DRV8316_Recirculation DRV8316Driver::getRecirculationMode(){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + return (DRV8316_Recirculation)data.ILIM_RECIR; +}; +void DRV8316Driver::setRecirculationMode(DRV8316_Recirculation recirculationMode){ + uint16_t result = readSPI(Control__5_ADDR); + Control__5 data; + data.reg = (result & 0x00FF); + data.ILIM_RECIR = recirculationMode; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__5_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isBuckEnabled(){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + return data.BUCK_DIS==BUCK_DIS_BUCK_ENABLE; +}; +void DRV8316Driver::setBuckEnabled(bool enabled){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + data.BUCK_DIS = enabled?BUCK_DIS_BUCK_ENABLE:BUCK_DIS_BUCK_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__6_ADDR, data.reg); +}; + + + +DRV8316_BuckVoltage DRV8316Driver::getBuckVoltage(){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + return (DRV8316_BuckVoltage)data.BUCK_SEL; +}; +void DRV8316Driver::setBuckVoltage(DRV8316_BuckVoltage volts){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + data.BUCK_SEL = volts; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__6_ADDR, data.reg); +}; + + + +DRV8316_BuckCurrentLimit DRV8316Driver::getBuckCurrentLimit(){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + return (DRV8316_BuckCurrentLimit)data.BUCK_CL; +}; +void DRV8316Driver::setBuckCurrentLimit(DRV8316_BuckCurrentLimit mamps){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + data.BUCK_CL = mamps; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__6_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isBuckPowerSequencingEnabled(){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + return data.BUCK_PS_DIS==BUCK_PS_DIS_ENABLE; + +}; +void DRV8316Driver::setBuckPowerSequencingEnabled(bool enabled){ + uint16_t result = readSPI(Control__6_ADDR); + Control__6 data; + data.reg = (result & 0x00FF); + data.BUCK_PS_DIS = enabled?BUCK_PS_DIS_ENABLE:BUCK_PS_DIS_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__6_ADDR, data.reg); +}; + + + +DRV8316_DelayTarget DRV8316Driver::getDelayTarget(){ + uint16_t result = readSPI(Control__10_ADDR); + Control__10 data; + data.reg = (result & 0x00FF); + return (DRV8316_DelayTarget)data.DLY_TARGET; +}; +void DRV8316Driver::setDelayTarget(DRV8316_DelayTarget us){ + uint16_t result = readSPI(Control__10_ADDR); + Control__10 data; + data.reg = (result & 0x00FF); + data.DLY_TARGET = us; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__10_ADDR, data.reg); +}; + + + +bool DRV8316Driver::isDelayCompensationEnabled(){ + uint16_t result = readSPI(Control__10_ADDR); + Control__10 data; + data.reg = (result & 0x00FF); + return data.DLYCMP_EN==DLYCMP_EN_ENABLE; +}; +void DRV8316Driver::setDelayCompensationEnabled(bool enabled){ + uint16_t result = readSPI(Control__10_ADDR); + Control__10 data; + data.reg = (result & 0x00FF); + data.DLYCMP_EN = enabled?DLYCMP_EN_ENABLE:DLYCMP_EN_DISABLE; + delayMicroseconds(1); // delay at least 400ns between operations + result = writeSPI(Control__10_ADDR, data.reg); +}; + + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.h b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.h new file mode 100644 index 0000000..dfec32e --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316.h @@ -0,0 +1,316 @@ + + +#ifndef SIMPLEFOC_DRV8316 +#define SIMPLEFOC_DRV8316 + + +#include "Arduino.h" +#include +#include +#include + +#include "./drv8316_registers.h" + + +enum DRV8316_PWMMode { + PWM6_Mode = 0b00, + PWM6_CurrentLimit_Mode = 0b01, + PWM3_Mode = 0b10, + PWM3_CurrentLimit_Mode = 0b11 +}; + + +enum DRV8316_SDOMode { + SDOMode_OpenDrain = 0b0, + SDOMode_PushPull = 0b1 +}; + + +enum DRV8316_Slew { + Slew_25Vus = 0b00, + Slew_50Vus = 0b01, + Slew_150Vus = 0b10, + Slew_200Vus = 0b11 +}; + + +enum DRV8316_OVP { + OVP_SEL_32V = 0b0, + OVP_SEL_20V = 0b1 +}; + + +enum DRV8316_PWM100DUTY { + FREQ_20KHz = 0b0, + FREQ_40KHz = 0b1 +}; + + +enum DRV8316_OCPMode { + Latched_Fault = 0b00, + AutoRetry_Fault = 0b01, + ReportOnly = 0b10, + NoAction = 0b11 +}; + + +enum DRV8316_OCPLevel { + Curr_16A = 0b0, + Curr_24A = 0b1 +}; + + +enum DRV8316_OCPRetry { + Retry5ms = 0b0, + Retry500ms = 0b1 +}; + + +enum DRV8316_OCPDeglitch { + Deglitch_0us2 = 0b00, + Deglitch_0us6 = 0b01, + Deglitch_1us1 = 0b10, + Deglitch_1us6 = 0b11 +}; + + +enum DRV8316_CSAGain { + Gain_0V15 = 0b00, + Gain_0V1875 = 0b01, + Gain_0V25 = 0b10, + Gain_0V375 = 0b11 +}; + + +enum DRV8316_Recirculation { + BrakeMode = 0b00, // FETs + CoastMode = 0b01 // Diodes +}; + + +enum DRV8316_BuckVoltage { + VB_3V3 = 0b00, + VB_5V = 0b01, + VB_4V = 0b10, + VB_5V7 = 0b11 +}; + + +enum DRV8316_BuckCurrentLimit { + Limit_600mA = 0b00, + Limit_150mA = 0b01 +}; + + +enum DRV8316_DelayTarget { + Delay_0us = 0x0, + Delay_0us4 = 0x1, + Delay_0us6 = 0x2, + Delay_0us8 = 0x3, + Delay_1us = 0x4, + Delay_1us2 = 0x5, + Delay_1us4 = 0x6, + Delay_1us6 = 0x7, + Delay_1us8 = 0x8, + Delay_2us = 0x9, + Delay_2us2 = 0xA, + Delay_2us4 = 0xB, + Delay_2us6 = 0xC, + Delay_2us8 = 0xD, + Delay_3us = 0xE, + Delay_3us2 = 0xF +}; + + + +class DRV8316ICStatus { +public: + DRV8316ICStatus(IC_Status status) : status(status) {}; + ~DRV8316ICStatus() {}; + + bool isFault() { return status.FAULT==0b1; }; + bool isOverTemperature() { return status.OT==0b1; }; + bool isOverCurrent() { return status.OCP==0b1; }; + bool isOverVoltage() { return status.OVP==0b1; }; + bool isSPIError() { return status.SPI_FLT==0b1; }; + bool isBuckError() { return status.BK_FLT==0b1; }; + bool isPowerOnReset() { return status.NPOR==0b1; }; + + IC_Status status; +}; + + +class DRV8316Status1 { +public: + DRV8316Status1(Status__1 status1) : status1(status1) {}; + ~DRV8316Status1() {}; + + + bool isOverCurrent_Ah() { return status1.OCP_HA==0b1; }; + bool isOverCurrent_Al() { return status1.OCP_LA==0b1; }; + bool isOverCurrent_Bh() { return status1.OCP_HB==0b1; }; + bool isOverCurrent_Bl() { return status1.OCP_LB==0b1; }; + bool isOverCurrent_Ch() { return status1.OCP_HC==0b1; }; + bool isOverCurrent_Cl() { return status1.OCP_LC==0b1; }; + bool isOverTemperatureShutdown() { return status1.OTS==0b1; }; + bool isOverTemperatureWarning() { return status1.OTW==0b1; }; + + Status__1 status1; +}; + + +class DRV8316Status2 { +public: + DRV8316Status2(Status__2 status2) : status2(status2) {}; + ~DRV8316Status2() {}; + + + bool isOneTimeProgrammingError() { return status2.OTP_ERR==0b1; }; + bool isBuckOverCurrent() { return status2.BUCK_OCP==0b1; }; + bool isBuckUnderVoltage() { return status2.BUCK_UV==0b1; }; + bool isChargePumpUnderVoltage() { return status2.VCP_UV==0b1; }; + bool isSPIParityError() { return status2.SPI_PARITY==0b1; }; + bool isSPIClockFramingError() { return status2.SPI_SCLK_FLT==0b1; }; + bool isSPIAddressError() { return status2.SPI_ADDR_FLT==0b1; }; + + Status__2 status2; +}; + + + +class DRV8316Status : public DRV8316ICStatus, public DRV8316Status1, public DRV8316Status2 { + public: + DRV8316Status(IC_Status status, Status__1 status1, Status__2 status2) : DRV8316ICStatus(status), DRV8316Status1(status1), DRV8316Status2(status2) {}; + ~DRV8316Status() {}; +}; + + + + +class DRV8316Driver { + + public: + DRV8316Driver(int cs, bool currentLimit = false, int nFault = NOT_SET) : currentLimit(currentLimit), cs(cs), nFault(nFault), spi(&SPI), settings(1000000, MSBFIRST, SPI_MODE1) {}; + virtual ~DRV8316Driver() {}; + + virtual void init(SPIClass* _spi = &SPI); + + void clearFault(); // TODO check for fault condition methods + + DRV8316Status getStatus(); + + bool isRegistersLocked(); + void setRegistersLocked(bool lock); + + DRV8316_PWMMode getPWMMode(); + void setPWMMode(DRV8316_PWMMode pwmMode); + + DRV8316_Slew getSlew(); + void setSlew(DRV8316_Slew slewRate); + + DRV8316_SDOMode getSDOMode(); + void setSDOMode(DRV8316_SDOMode sdoMode); + + bool isOvertemperatureReporting(); + void setOvertemperatureReporting(bool reportFault); + + bool isSPIFaultReporting(); + void setSPIFaultReporting(bool reportFault); + + bool isOvervoltageProtection(); + void setOvervoltageProtection(bool enabled); + + DRV8316_OVP getOvervoltageLevel(); + void setOvervoltageLevel(DRV8316_OVP voltage); + + DRV8316_PWM100DUTY getPWM100Frequency(); + void setPWM100Frequency(DRV8316_PWM100DUTY freq); + + DRV8316_OCPMode getOCPMode(); + void setOCPMode(DRV8316_OCPMode ocpMode); + + DRV8316_OCPLevel getOCPLevel(); + void setOCPLevel(DRV8316_OCPLevel amps); + + DRV8316_OCPRetry getOCPRetryTime(); + void setOCPRetryTime(DRV8316_OCPRetry ms); + + DRV8316_OCPDeglitch getOCPDeglitchTime(); + void setOCPDeglitchTime(DRV8316_OCPDeglitch ms); + + bool isOCPClearInPWMCycleChange(); + void setOCPClearInPWMCycleChange(bool enable); + + bool isDriverOffEnabled(); + void setDriverOffEnabled(bool enabled); + + DRV8316_CSAGain getCurrentSenseGain(); + void setCurrentSenseGain(DRV8316_CSAGain gain); + + bool isActiveSynchronousRectificationEnabled(); + void setActiveSynchronousRectificationEnabled(bool enabled); + + bool isActiveAsynchronousRectificationEnabled(); + void setActiveAsynchronousRectificationEnabled(bool enabled); + + DRV8316_Recirculation getRecirculationMode(); + void setRecirculationMode(DRV8316_Recirculation recirculationMode); + + bool isBuckEnabled(); + void setBuckEnabled(bool enabled); + + DRV8316_BuckVoltage getBuckVoltage(); + void setBuckVoltage(DRV8316_BuckVoltage volts); + + DRV8316_BuckCurrentLimit getBuckCurrentLimit(); + void setBuckCurrentLimit(DRV8316_BuckCurrentLimit mamps); + + bool isBuckPowerSequencingEnabled(); + void setBuckPowerSequencingEnabled(bool enabled); + + DRV8316_DelayTarget getDelayTarget(); + void setDelayTarget(DRV8316_DelayTarget us); + + bool isDelayCompensationEnabled(); + void setDelayCompensationEnabled(bool enabled); + + private: + uint16_t readSPI(uint8_t addr); + uint16_t writeSPI(uint8_t addr, uint8_t data); + bool getParity(uint16_t data); + + bool currentLimit; + int cs; + int nFault; + SPIClass* spi; + SPISettings settings; +}; + + + +class DRV8316Driver3PWM : public DRV8316Driver, public BLDCDriver3PWM { + + public: + DRV8316Driver3PWM(int phA,int phB,int phC, int cs, bool currentLimit = false, int en = NOT_SET, int nFault = NOT_SET) : + DRV8316Driver(cs, currentLimit, nFault), BLDCDriver3PWM(phA, phB, phC, en) { enable_active_high=false; }; + virtual ~DRV8316Driver3PWM() {}; + + virtual void init(SPIClass* _spi = &SPI) override; + +}; + + + +class DRV8316Driver6PWM : public DRV8316Driver, public BLDCDriver6PWM { + + public: + DRV8316Driver6PWM(int phA_h,int phA_l,int phB_h,int phB_l,int phC_h,int phC_l, int cs, bool currentLimit = false, int en = NOT_SET, int nFault = NOT_SET) : + DRV8316Driver(cs, currentLimit, nFault), BLDCDriver6PWM(phA_h, phA_l, phB_h, phB_l, phC_h, phC_l, en) { enable_active_high=false; }; + virtual ~DRV8316Driver6PWM() {}; + + virtual void init(SPIClass* _spi = &SPI) override; + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316_registers.h b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316_registers.h new file mode 100644 index 0000000..04bca1e --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/drv8316/drv8316_registers.h @@ -0,0 +1,184 @@ + + +#ifndef SIMPLEFOC_DRV8316_REGISTERS +#define SIMPLEFOC_DRV8316_REGISTERS + + +#define IC_Status_ADDR 0x0 +#define Status__1_ADDR 0x1 +#define Status__2_ADDR 0x2 +#define Control__1_ADDR 0x3 +#define Control__2_ADDR 0x4 +#define Control__3_ADDR 0x5 +#define Control__4_ADDR 0x6 +#define Control__5_ADDR 0x7 +#define Control__6_ADDR 0x8 +#define Control__10_ADDR 0xC + +#define REG_LOCK_LOCK 0b110 +#define REG_LOCK_UNLOCK 0b011 +#define CLR_FAULT_CLR 0b1 +#define OTW_REP_ENABLE 0b1 +#define OTW_REP_DISABLE 0b0 +#define SPI_FLT_REP_ENABLE 0b0 +#define SPI_FLT_REP_DISABLE 0b1 +#define OVP_EN_ENABLE 0b1 +#define OVP_EN_DISABLE 0b0 +#define OCP_CBC_ENABLE 0b1 +#define OCP_CBC_DISABLE 0b0 +#define DRV_OFF_ENABLE 0b1 +#define DRV_OFF_DISABLE 0b0 +#define EN_ASR_ENABLE 0b1 +#define EN_ASR_DISABLE 0b0 +#define EN_AAR_ENABLE 0b1 +#define EN_AAR_DISABLE 0b0 +#define BUCK_DIS_BUCK_DISABLE 0b1 +#define BUCK_DIS_BUCK_ENABLE 0b0 +#define BUCK_PS_DIS_DISABLE 0b1 +#define BUCK_PS_DIS_ENABLE 0b0 +#define DLYCMP_EN_ENABLE 0b1 +#define DLYCMP_EN_DISABLE 0b0 + + + + +typedef union { + struct { + uint8_t REG_LOCK:3; + uint8_t :5; + }; + uint8_t reg; +} Control__1; + + +typedef union { + struct { + uint8_t CLR_FLT:1; + uint8_t PWM_MODE:2; + uint8_t SLEW:2; + uint8_t SDO_MODE:1; + uint8_t :2; + }; + uint8_t reg; +} Control__2; + + +typedef union { + struct { + uint8_t OTW_REP:1; + uint8_t SPI_FLT_REP:1; + uint8_t OVP_EN:1; + uint8_t OVP_SEL:1; + uint8_t PWM_100_DUTY_SEL:1; + uint8_t :3; + }; + uint8_t reg; +} Control__3; + + +typedef union { + struct { + uint8_t OCP_MODE:2; + uint8_t OCP_LVL:1; + uint8_t OCP_RETRY:1; + uint8_t OCP_DEG:2; + uint8_t OCP_CBC:1; + uint8_t DRV_OFF:1; + }; + uint8_t reg; +} Control__4; + + + + +typedef union { + struct { + uint8_t CSA_GAIN:2; + uint8_t EN_ASR:1; + uint8_t EN_AAR:1; + uint8_t :2; + uint8_t ILIM_RECIR:1; + uint8_t :1; + }; + uint8_t reg; +} Control__5; + + + + +typedef union { + struct { + uint8_t BUCK_DIS:1; + uint8_t BUCK_SEL:2; + uint8_t BUCK_CL:1; + uint8_t BUCK_PS_DIS:1; + uint8_t :2; + }; + uint8_t reg; +} Control__6; + + + + +typedef union { + struct { + uint8_t DLY_TARGET:4; + uint8_t DLYCMP_EN:1; + uint8_t :3; + }; + uint8_t reg; +} Control__10; + + + + +typedef union { + struct { + uint8_t FAULT:1; + uint8_t OT:1; + uint8_t OVP:1; + uint8_t NPOR:1; + uint8_t OCP:1; + uint8_t SPI_FLT:1; + uint8_t BK_FLT:1; + uint8_t :1; + }; + uint8_t reg; +} IC_Status; + + + + +typedef union { + struct { + uint8_t OCP_LA:1; + uint8_t OCP_HA:1; + uint8_t OCP_LB:1; + uint8_t OCP_HB:1; + uint8_t OCP_LC:1; + uint8_t OCP_HC:1; + uint8_t OTS:1; + uint8_t OTW:1; + }; + uint8_t reg; +} Status__1; + + + + +typedef union { + struct { + uint8_t SPI_ADDR_FLT:1; + uint8_t SPI_SCLK_FLT:1; + uint8_t SPI_PARITY:1; + uint8_t VCP_UV:1; + uint8_t BUCK_UV:1; + uint8_t BUCK_OCP:1; + uint8_t OTP_ERR:1; + uint8_t :1; + }; + uint8_t reg; +} Status__2; + + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/README.md b/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/README.md new file mode 100644 index 0000000..6b296d7 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/README.md @@ -0,0 +1,42 @@ + +# SimpleFOC STSPIN32G4 Driver + +This driver initializes the PWM stage of the STSPIN32G4, and provides access to its configuration via I2C. + +:warning: in development! + +## Setup + +Since there are currently no standard boards for Arduino based on the STSPIN32G4 you will need a custom board definition, associated linker script and project setup to compile for your board. These topics are out of scope for this driver, but you can find a working example for the [FunQi STSPIN32G4 board](TODO link) [here](TODO link); + +Once you can compile for your board, and flash it with a "blinky" test sketch, then you're ready to try SimpleFOC and more complex code. + +## Usage + +Basic usage, as you can see it is very simple. Since the pins are all pre-defined due to internal connections, setup +is easier than with the standard drivers. Here is an example for open loop mode: + +```c++ +#include +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "drivers/stspin32g4/STSPIN32G4.h" + + +STSPIN32G4 driver = STSPIN32G4(); +BLDCMotor motor = BLDCMotor(7); + +void setup() { + driver.voltage_power_supply = 12.0f; + driver.init(); + motor.voltage_limit = driver.voltage_limit / 2.0f; + motor.controller = MotionControlType::velocity_openloop; + motor.linkDriver(&driver); + motor.init(); +} + +void loop(){ + motor.move(5.0f); // 5 rad/s open loop + delayMicroseconds(100); // STM32G4 is very fast, add a delay in open loop if we do nothing else +} +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.cpp b/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.cpp new file mode 100644 index 0000000..2917791 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.cpp @@ -0,0 +1,182 @@ + +#include "./STSPIN32G4.h" + +#ifdef ARDUINO_GENERIC_G431VBTX + + +STSPIN32G4::STSPIN32G4() : BLDCDriver6PWM(STSPIN32G4_PIN_INUH, STSPIN32G4_PIN_INUL, STSPIN32G4_PIN_INVH, + STSPIN32G4_PIN_INVL, STSPIN32G4_PIN_INWH, STSPIN32G4_PIN_INWL), + _wire(STSPIN32G4_PIN_SDA, STSPIN32G4_PIN_SCL) { + +}; + + + +STSPIN32G4::~STSPIN32G4(){ + _wire.end(); +}; + + + +int STSPIN32G4::init(){ + // init pins + pinMode(STSPIN32G4_PIN_WAKE, OUTPUT); + digitalWrite(STSPIN32G4_PIN_WAKE, LOW); + pinMode(STSPIN32G4_PIN_READY, INPUT_PULLUP); + pinMode(STSPIN32G4_PIN_FAULT, INPUT_PULLUP); + + int result = this->BLDCDriver6PWM::init(); + if(result == 0) return result; + setPwm(0,0,0); // set the phases to off + + // init I2C + _wire.begin(); + + delayMicroseconds(50); // give driver a moment to wake up + clearFaults(); // clear the faults + + // TODO init fault monitor + + return isReady() ? 1 : 0; +}; + + + +void STSPIN32G4::wake() { + digitalWrite(STSPIN32G4_PIN_WAKE, HIGH); + delayMicroseconds(50); // 50ms high pulse to wake up + digitalWrite(STSPIN32G4_PIN_WAKE, LOW); +}; + + + +void STSPIN32G4::sleep() { + digitalWrite(STSPIN32G4_PIN_WAKE, LOW); + writeRegister(STSPIN32G4_REG_STBY, 0x01); +}; + + + +bool STSPIN32G4::isReady(){ + return digitalRead(STSPIN32G4_PIN_READY)==HIGH; +}; + + + +bool STSPIN32G4::isFault(){ + return digitalRead(STSPIN32G4_PIN_FAULT)==LOW; +}; + + + +STSPIN32G4Status STSPIN32G4::status(){ + STSPIN32G4Status result; + result.reg = readRegister(STSPIN32G4_REG_STATUS); + return result; +}; + + + +void STSPIN32G4::lock(){ + writeRegister(STSPIN32G4_REG_LOCK, 0x00); +}; + + + +void STSPIN32G4::unlock(){ + writeRegister(STSPIN32G4_REG_LOCK, 0xF0); +}; + + + +STSPIN32G4NFault STSPIN32G4::getNFaultRegister(){ + STSPIN32G4NFault result; + result.reg = readRegister(STSPIN32G4_REG_NFAULT); + return result; +}; + + + +STSPIN32G4Ready STSPIN32G4::getReadyRegister(){ + STSPIN32G4Ready result; + result.reg = readRegister(STSPIN32G4_REG_READY); + return result; +}; + + + +STSPIN32G4Logic STSPIN32G4::getLogicRegister(){ + STSPIN32G4Logic result; + result.reg = readRegister(STSPIN32G4_REG_LOGIC); + return result; +}; + + + +STSPIN32G4PowMng STSPIN32G4::getPowMngRegister(){ + STSPIN32G4PowMng result; + result.reg = readRegister(STSPIN32G4_REG_POWMNG); + return result; +}; + + + +void STSPIN32G4::setNFaultRegister(STSPIN32G4NFault value){ + writeRegister(STSPIN32G4_REG_NFAULT, value.reg); +}; + + + +void STSPIN32G4::setReadyRegister(STSPIN32G4Ready value){ + writeRegister(STSPIN32G4_REG_READY, value.reg); +}; + + + +void STSPIN32G4::setLogicRegister(STSPIN32G4Logic value){ + writeRegister(STSPIN32G4_REG_LOGIC, value.reg); +}; + + + +void STSPIN32G4::setPowMngRegister(STSPIN32G4PowMng value){ + writeRegister(STSPIN32G4_REG_POWMNG, value.reg); +}; + + + +void STSPIN32G4::resetRegisters(){ + // write 0xFF to reset register + writeRegister(STSPIN32G4_REG_RESET, 0xFF); +}; + + + +void STSPIN32G4::clearFaults(){ + // write 0xFF to clear faults + writeRegister(STSPIN32G4_REG_CLEAR, 0xFF); +}; + + + +uint8_t STSPIN32G4::readRegister(uint8_t reg){ + uint8_t result = 0; + _wire.beginTransmission(STSPIN32G4_I2C_ADDR); + _wire.write(reg); + _wire.endTransmission(false); + _wire.requestFrom(STSPIN32G4_I2C_ADDR, 1); + result = _wire.read(); + return result; +}; + + + +void STSPIN32G4::writeRegister(uint8_t reg, uint8_t val){ + _wire.beginTransmission(STSPIN32G4_I2C_ADDR); + _wire.write(reg); + _wire.write(val); + _wire.endTransmission(); +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.h b/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.h new file mode 100644 index 0000000..3df8137 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/stspin32g4/STSPIN32G4.h @@ -0,0 +1,148 @@ + +#pragma once + +#include "Arduino.h" + +#ifdef ARDUINO_GENERIC_G431VBTX + +#include "Wire.h" +#include "drivers/BLDCDriver6PWM.h" + + +#define STSPIN32G4_PIN_INUL PE8 +#define STSPIN32G4_PIN_INUH PE9 +#define STSPIN32G4_PIN_INVL PE10 +#define STSPIN32G4_PIN_INVH PE11 +#define STSPIN32G4_PIN_INWL PE12 +#define STSPIN32G4_PIN_INWH PE13 + +#define STSPIN32G4_PIN_WAKE PE7 +#define STSPIN32G4_PIN_READY PE14 +#define STSPIN32G4_PIN_FAULT PE15 + +#define STSPIN32G4_PIN_SDA PC9 +#define STSPIN32G4_PIN_SCL PC8 + +#define STSPIN32G4_I2C_ADDR 0b1000111 + +#define STSPIN32G4_REG_POWMNG 0x01 +#define STSPIN32G4_REG_LOGIC 0x02 +#define STSPIN32G4_REG_READY 0x07 +#define STSPIN32G4_REG_NFAULT 0x08 +#define STSPIN32G4_REG_CLEAR 0x09 +#define STSPIN32G4_REG_STBY 0x0A +#define STSPIN32G4_REG_LOCK 0x0B +#define STSPIN32G4_REG_RESET 0x0C +#define STSPIN32G4_REG_STATUS 0x80 + + + + + +union STSPIN32G4Status { + struct { + uint8_t vcc_uvlo:1; + uint8_t thsd:1; + uint8_t vds_p:1; + uint8_t reset:1; + uint8_t unused:3; + uint8_t lock:1; + }; + uint8_t reg; +}; + + + +union STSPIN32G4NFault { + struct { + uint8_t vcc_uvlo_flt:1; + uint8_t thsd_flt:1; + uint8_t vds_p_flt:1; + uint8_t unused:5; + }; + uint8_t reg; +}; + + +union STSPIN32G4Ready { + struct { + uint8_t vcc_uvlo_rdy:1; + uint8_t thsd_rdy:1; + uint8_t unused:1; + uint8_t stby_rdy:1; + uint8_t unused2:4; + }; + uint8_t reg; +}; + + + +union STSPIN32G4Logic { + struct { + uint8_t ilock:1; + uint8_t dtmin:1; + uint8_t vds_p_deg:2; + uint8_t unused:4; + }; + uint8_t reg; +}; + + + +union STSPIN32G4PowMng { + struct { + uint8_t vcc_val:2; + uint8_t unused:2; + uint8_t stby_reg_en:1; + uint8_t vcc_dis:1; + uint8_t reg3v3_dis:1; + uint8_t unused2:1; + }; + uint8_t reg; +}; + + + + + + + + + + + +class STSPIN32G4 : public BLDCDriver6PWM { +public: + STSPIN32G4(); + ~STSPIN32G4(); + + int init() override; + + void wake(); + void sleep(); + bool isReady(); + bool isFault(); + + STSPIN32G4Status status(); + void lock(); + void unlock(); + STSPIN32G4NFault getNFaultRegister(); + STSPIN32G4Ready getReadyRegister(); + STSPIN32G4Logic getLogicRegister(); + STSPIN32G4PowMng getPowMngRegister(); + void setNFaultRegister(STSPIN32G4NFault value); + void setReadyRegister(STSPIN32G4Ready value); + void setLogicRegister(STSPIN32G4Logic value); + void setPowMngRegister(STSPIN32G4PowMng value); + void resetRegisters(); + void clearFaults(); + +protected: + uint8_t readRegister(uint8_t reg); + void writeRegister(uint8_t reg, uint8_t val); + + TwoWire _wire; +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/README.md b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/README.md new file mode 100644 index 0000000..b34ba7a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/README.md @@ -0,0 +1,147 @@ + +# TMC6200 SimpleFOC Driver + +by [@YaseenTwati](https://github.com/YaseenTwati) + +The TMC6200 is a Universal high voltage BLDC/PMSM/Servo MOSFET 3-halfbridge gate-driver with in line motor current +sensing. External MOSFETs for up to 100A motor current. + +See https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC6200_datasheet_Rev1.05.pdf for more information. + +## Hardware setup + +To use the TMC6200 you will have to connect the following: + +- GND +- VCC_IO - 3.3V or 5V +- SPE - pull up to VCC to enable SPI mode +- SPI MOSI ( SDI ) +- SPI MISO ( SDO ) +- SPI CLK +- SPI nCS +- DRV_EN - connect to digital out (or pull up to VCC) +- UH - connect to motor PWM pin +- VH - connect to motor PWM pin +- WH - connect to motor PWM pin +- UL - connect to motor PWM pin for 6-PWM, or to digital out (or pull up to VCC) for 3-PWM operation +- VL - connect to motor PWM pin for 6-PWM, or to digital out (or pull up to VCC) for 3-PWM operation +- WL - connect to motor PWM pin for 6-PWM, or to digital out (or pull up to VCC) for 3-PWM operation + +Optionally, but useful: + +- FAULT - digital in, active high + +For current sensing: + +- CURU - connect to analog in +- CURV - connect to analog in +- CURW - connect to analog in + +## Usage + +Usage is quite easy, especially if you already know SimpleFOC. See also the [examples](https://github.com/simplefoc/Arduino-FOC-drivers/examples/drivers/drv8316/) + +```c++ +#include "Arduino.h" +#include +#include "SimpleFOCDrivers.h" +#include "drivers/tmc6200/TMC6200.hpp" + +BLDCMotor motor = BLDCMotor(15); +TMC6200Driver6PWM driver = DRV8316Driver6PWM(UH, UL, VH, VL, WH, WL, nCS, DRV_EN); + +//... normal simpleFOC init code... +``` + +Or, for 3-PWM: + +```c++ +#include "Arduino.h" +#include +#include "SimpleFOCDrivers.h" +#include "drivers/tmc6200/TMC6200.hpp" + +BLDCMotor motor = BLDCMotor(15); +TMC6200Driver3PWM driver = TMC6200Driver3PWM(UH, MOTOR_VH, MOTOR_WH, nCS, DRV_EN); + +void setup() { + + pinMode(UL, OUTPUT); + pinMode(VL, OUTPUT); + pinMode(WL, OUTPUT); + + digitalWrite(WL, HIGH); + digitalWrite(UL, HIGH); + digitalWrite(VL, HIGH); + + //... normal simpleFOC init code... +} + +``` + +### Validating the SPI Connection +You can validate the SPI connection by checking the value of VERSION field in IOIN register. The value should be 0x10. + +```c++ + if(driver.getInputs().VERSION != TMC6200_VERSION){ + // something is wrong with the spi connection + } +``` + +### Current Sensing +The gain of the internal current amplifiers can be set to 5, 10 or 20 through `setCurrentSenseGain()` + +```c++ + driver.setCurrentSenseGain(TMC6200_AmplificationGain::_5); + //driver.setCurrentSenseGain(TMC6200_AmplificationGain::_10); + //driver.setCurrentSenseGain(TMC6200_AmplificationGain::_20); +``` +The sense amplifiers can also be turned off ( they are on by default ), through `setCurrentSenseAmplifierState()` + +```c++ + driver.setCurrentSenseAmplifierState(false); +``` +### Driver Strength +The strength of the mosfet drivers can be controlled through `setDriverStrength()` + +```c++ + driver.setDriverStrength(TMC6200_DRVStrength::Weak); + //driver.setDriverStrength(TMC6200_DRVStrength::WeakTC); // (medium above OTPW level) + //driver.setDriverStrength(TMC6200_DRVStrength::Medium); + //driver.setDriverStrength(TMC6200_DRVStrength::Strong); +``` + +### Handling Faults +The fault line will go high if a fault occurs such as a short, an interrupt can be used to handle it. +Note that some faults will disable the driver and will require the DRV_EN to be cycled to clear the fault. + +```c++ + // somewhere in setup + attachInterrupt(digitalPinToInterrupt(FAULT), handleFault, RISING); +``` + +```c++ + void handleFault() + { + // you can read the status register to see what happened + TMC6200GStatus status = driver.getStatus(); + Serial.print("hasUShorted: "); Serial.println(status.hasUShorted()); + Serial.print("hasVShorted: "); Serial.println(status.hasVShorted()); + Serial.print("hasWShorted: "); Serial.println(status.hasWShorted()); + Serial.print("isUShortedToGround: "); Serial.println(status.isUShortedToGround()); + Serial.print("isUShortedToSupply: "); Serial.println(status.isUShortedToSupply()); + Serial.print("isVShortedToGround: "); Serial.println(status.isVShortedToGround()); + Serial.print("isVShortedToSupply: "); Serial.println(status.isVShortedToSupply()); + Serial.print("isWShortedToGround: "); Serial.println(status.isWShortedToGround()); + Serial.print("isWShortedToSupply: "); Serial.println(status.isWShortedToSupply()); + Serial.print("isOverTemperaturePreWarning: "); Serial.println(status.isOverTemperaturePreWarning()); + Serial.print("isChargePumpUnderVoltage: "); Serial.println(status.isChargePumpUnderVoltage()); + + // the driver must be cycled to clear the fault + digitalWrite(DRV_EN, LOW); + delayMicrosockets(someSmallDelay); + digitalWrite(DRV_EN, HIGH); + } +``` + +The driver provides other features such as controlling the tolerences of short detection and the BBM cycle time and so on, setting the options can be conveniently done via the provided setter methods. All documented registers and options are available via the driver, and the option values can be accessed via enums. diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.cpp b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.cpp new file mode 100644 index 0000000..659ab5d --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.cpp @@ -0,0 +1,221 @@ +#include "TMC6200.hpp" + +void TMC6200Driver::init(SPIClass *_spi) { + spi = _spi; + settings = SPISettings(500000, MSBFIRST, SPI_MODE3); + + pinMode(csPin, OUTPUT); + digitalWrite(csPin, HIGH); +} + +// TMC6200_GCONF ------ + +void TMC6200Driver::setDriverState(bool state) { + TMC6200_GCONF gConf; + gConf.reg = readRegister(TMC6200_GCONF_REG); + + gConf.DISABLE = state ? 0 : 1; + writeRegister(TMC6200_GCONF_REG, gConf.reg); +} + +void TMC6200Driver::setPWMMode(TMC6200_PWMMode pwmMode) { + TMC6200_GCONF gConf; + gConf.reg = readRegister(TMC6200_GCONF_REG); + + gConf.SINGLE_LINE = pwmMode; + writeRegister(TMC6200_GCONF_REG, gConf.reg); +} + +void TMC6200Driver::setFaultDirect(TMC6200_FaultDirect faultDirect) { + TMC6200_GCONF gConf; + gConf.reg = readRegister(TMC6200_GCONF_REG); + + gConf.FAULT_DIRECT = faultDirect; + writeRegister(TMC6200_GCONF_REG, gConf.reg); +} + +void TMC6200Driver::setCurrentSenseAmplifierState(bool state) { + TMC6200_GCONF gConf; + gConf.reg = readRegister(TMC6200_GCONF_REG); + + gConf.AMPLIFIER_OFF = state ? 0 : 1; + writeRegister(TMC6200_GCONF_REG, gConf.reg); +} + +void TMC6200Driver::setCurrentSenseGain(TMC6200_AmplificationGain amplificationGain) { + TMC6200_GCONF gConf; + gConf.reg = readRegister(TMC6200_GCONF_REG); + + gConf.AMPLIFICATION = amplificationGain; + writeRegister(TMC6200_GCONF_REG, gConf.reg); + + gConf.reg = readRegister(TMC6200_GCONF_REG); +} + +// TMC6200_DRV_CONF ------ + +void TMC6200Driver::setOverTemperatureThreshold(TMC6200_OTSelect otLevel) { + TMC6200_DRV_CONF drvConf; + drvConf.reg = readRegister(TMC6200_DRV_CONF_REG); + + drvConf.OT_SELECT = otLevel; + writeRegister(TMC6200_DRV_CONF_REG, drvConf.reg); +} + +void TMC6200Driver::setDriverStrength(TMC6200_DRVStrength strength) { + TMC6200_DRV_CONF drvConf; + drvConf.reg = readRegister(TMC6200_DRV_CONF_REG); + + drvConf.DRV_STRENGTH = strength; + writeRegister(TMC6200_DRV_CONF_REG, drvConf.reg); +} + +void TMC6200Driver::setBBMCycles(uint8_t clockCycles) { + TMC6200_DRV_CONF drvConf; + drvConf.reg = readRegister(TMC6200_DRV_CONF_REG); + + drvConf.BBMCLKS = clockCycles; + writeRegister(TMC6200_DRV_CONF_REG, drvConf.reg); +} + +// TMC6200_SHORT_CONF ------ + +void TMC6200Driver::setShortDelay(TMC6200_ShortDelay shortDelay) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.SHORT_DELAY = shortDelay; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +void TMC6200Driver::shortFilter(TMC6200_ShortFilter shortFilter) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.SHORT_FILTER = shortFilter; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +void TMC6200Driver::setShortToSupplySensitivityLevel(uint8_t level) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.S2VS_LEVEL = level; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +void TMC6200Driver::setShortToGroundSensitivityLevel(uint8_t level) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.S2G_LEVEL = level; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +void TMC6200Driver::setShortRetries(uint8_t retries) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.RETRY = retries; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +void TMC6200Driver::setParallelProtect(TMC6200_ParallelProtect parallelProtect) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.PROTECT_PARALLEL = parallelProtect; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +void TMC6200Driver::setShortToGroundDetectionState(bool state) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.DISABLE_S2G = state ? 0 : 1; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +void TMC6200Driver::setShortToSupplyDetectionState(bool state) { + TMC6200_SHORT_CONF shortConf; + shortConf.reg = readRegister(TMC6200_SHORT_CONF_REG); + + shortConf.DISABLE_S2VS = state ? 0 : 1; + writeRegister(TMC6200_SHORT_CONF_REG, shortConf.reg); +} + +// TMC6200_IOIN ------ + +TMC6200_IOIN TMC6200Driver::getInputs() { + TMC6200_IOIN ioin; + ioin.reg = readRegister(TMC6200_IOIN_REG); + + return ioin; +} + +// TMC6200_GSTAT ------ + +TMC6200GStatus TMC6200Driver::getStatus() { + TMC6200_GSTAT gstat; + gstat.reg = readRegister(TMC6200_GSTAT_REG); + + return {gstat}; +} + +void TMC6200Driver::setStatus(TMC6200_GSTAT status) { + writeRegister(TMC6200_GSTAT_REG, status.reg); +} + +uint32_t TMC6200Driver::readRegister(uint8_t addr) { + digitalWrite(csPin, LOW); + spi->beginTransaction(settings); + + // Address + spi->transfer(TMC_ADDRESS(addr)); + + // 32bit Data + uint32_t value = 0; + value |= (spi->transfer(0x00) << 24); + value |= (spi->transfer(0x00) << 16); + value |= (spi->transfer(0x00) << 8); + value |= (spi->transfer(0x00) << 0); + + spi->end(); + digitalWrite(csPin, HIGH); + + return value; +} + +void TMC6200Driver::writeRegister(uint8_t addr, uint32_t data) { + digitalWrite(csPin, LOW); + spi->beginTransaction(settings); + + // Address + spi->transfer(addr | TMC_WRITE_BIT); + + // 32bit Data + spi->transfer(0xFF & (data >> 24)); + spi->transfer(0xFF & (data >> 16)); + spi->transfer(0xFF & (data >> 8)); + spi->transfer(0xFF & (data >> 0)); + + spi->end(); + digitalWrite(csPin, HIGH); +} + +// -------------------- + +void TMC6200Driver3PWM::init(SPIClass *_spi) { + TMC6200Driver::init(_spi); + delayMicroseconds(1); + TMC6200Driver::setPWMMode(TMC6200_PWMMode::SingleLine); + BLDCDriver3PWM::init(); +}; + + +void TMC6200Driver6PWM::init(SPIClass *_spi) { + TMC6200Driver::init(_spi); + delayMicroseconds(1); + TMC6200Driver::setPWMMode(TMC6200_PWMMode::Individual); + BLDCDriver6PWM::init(); +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.hpp b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.hpp new file mode 100644 index 0000000..7a5215c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200.hpp @@ -0,0 +1,171 @@ +#pragma once + +#include +#include +#include +#include +#include "TMC6200_Registers.hpp" + +#define TMC6200_VERSION 0x10 + +enum TMC6200_PWMMode { + Individual = 0, // 6PWM + SingleLine = 1, // 3PWM +}; + +enum TMC6200_AmplificationGain { + _5 = 0, + _10 = 1, + _Also_10 = 2, // maybe just remove this + _20 = 3, +}; + +enum TMC6200_ShortDelay { + _750nS = 0, + _1500nS = 1, +}; + +enum TMC6200_ShortFilter { + _100nS = 0, + _1uS = 1, + _2uS = 2, + _3uS = 3, +}; + +enum TMC6200_ParallelProtect { + Detected = 0, + All = 1, +}; + +enum TMC6200_FaultDirect { + AtLeastOneBridgeDown = 0, + EachProtectiveAction = 1, +}; + +enum TMC6200_OTSelect { + _150 = 0b00, + _143 = 0b01, + _136 = 0b10, + _120 = 0b11, +}; + +enum TMC6200_DRVStrength { + Weak = 0b00, + WeakTC = 0b01, // (medium above OTPW level) + Medium = 0b10, + Strong = 0b11, +}; + +class TMC6200GStatus { +public: + TMC6200GStatus(TMC6200_GSTAT status) : status(status) {}; + + bool isReset() const { return status.RESET == 0b1; }; + + bool isOverTemperaturePreWarning() const { return status.DRV_OTPW == 0b1; }; + + bool isOverTemperature() const { return status.DRV_OT == 0b1; }; + + bool isChargePumpUnderVoltage() const { return status.UV_CP == 0b1; }; + + bool hasUShorted() const { return status.SHORT_DET_U == 0b1; }; + + bool hasVShorted() const { return status.SHORT_DET_V == 0b1; }; + + bool hasWShorted() const { return status.SHORT_DET_W == 0b1; }; + + bool isUShortedToGround() const { return status.S2GU == 0b1; }; + + bool isUShortedToSupply() const { return status.S2VSU == 0b1; }; + + bool isVShortedToGround() const { return status.S2GV == 0b1; }; + + bool isVShortedToSupply() const { return status.S2VSV == 0b1; }; + + bool isWShortedToGround() const { return status.S2GW == 0b1; }; + + bool isWShortedToSupply() const { return status.S2VSW == 0b1; }; + + TMC6200_GSTAT status; +}; + +class TMC6200Driver { + +public: + TMC6200Driver(int csPin) : csPin(csPin), spi(&SPI), settings(1000000, MSBFIRST, SPI_MODE3) {}; + + virtual ~TMC6200Driver() {}; + + virtual void init(SPIClass *_spi); + + void setDriverState(bool state); + + void setPWMMode(TMC6200_PWMMode pwmMode); + + void setFaultDirect(TMC6200_FaultDirect faultDirect); + + void setCurrentSenseGain(TMC6200_AmplificationGain amplificationGain); + + void setOverTemperatureThreshold(TMC6200_OTSelect otLevel); + + void setDriverStrength(TMC6200_DRVStrength strength); + + void setCurrentSenseAmplifierState(bool state); + + void setShortDelay(TMC6200_ShortDelay shortDelay); + + void shortFilter(TMC6200_ShortFilter shortFilter); + + void setShortToSupplySensitivityLevel(uint8_t level); + + void setShortToGroundSensitivityLevel(uint8_t level); + + void setShortRetries(uint8_t retries); + + void setParallelProtect(TMC6200_ParallelProtect parallelProtect); + + void setShortToGroundDetectionState(bool state); + + void setShortToSupplyDetectionState(bool state); + + void setBBMCycles(uint8_t clockCycles); + + void setStatus(TMC6200_GSTAT status); + + TMC6200GStatus getStatus(); + + TMC6200_IOIN getInputs(); + +private: + uint32_t readRegister(uint8_t addr); + + void writeRegister(uint8_t addr, uint32_t data); + + int csPin; + SPIClass *spi; + SPISettings settings; +}; + + +class TMC6200Driver3PWM : public TMC6200Driver, public BLDCDriver3PWM { + +public: + TMC6200Driver3PWM(int phA, int phB, int phC, int cs, int en = NOT_SET) : + TMC6200Driver(cs), BLDCDriver3PWM(phA, phB, phC, en) {}; + + ~TMC6200Driver3PWM() override = default; + + virtual void init(SPIClass *_spi = &SPI) override; +}; + + +class TMC6200Driver6PWM : public TMC6200Driver, public BLDCDriver6PWM { + +public: + TMC6200Driver6PWM(int phA_h, int phA_l, int phB_h, int phB_l, int phC_h, int phC_l, int cs, int en = NOT_SET) : + TMC6200Driver(cs), BLDCDriver6PWM(phA_h, phA_l, phB_h, phB_l, phC_h, phC_l, en) {}; + + ~TMC6200Driver6PWM() override = default; + + virtual void init(SPIClass *_spi = &SPI) override; +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200_Registers.hpp b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200_Registers.hpp new file mode 100644 index 0000000..aff9fed --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/drivers/tmc6200/TMC6200_Registers.hpp @@ -0,0 +1,111 @@ +#pragma once + +// ------ + +#define TMC_WRITE_BIT 0x80 +#define TMC_ADDRESS_MASK 0x7F +#define TMC_ADDRESS(x) ((x) & (TMC_ADDRESS_MASK)) + +// ------ + +#define TMC6200_GCONF_REG 0x00 // RW +#define TMC6200_GSTAT_REG 0x01 // RW + WC +#define TMC6200_IOIN_REG 0x04 // R + +#define TMC6200_OTP_PROG_REG 0x06 // not used +#define TMC6200_OTP_READ_REG 0x07 // not used +#define TMC6200_FACTORY_CONF_REG 0x08 // not used + +#define TMC6200_SHORT_CONF_REG 0x09 // RW +#define TMC6200_DRV_CONF_REG 0x0A // RW + +typedef union { + struct { + uint32_t DISABLE: 1; + uint32_t SINGLE_LINE: 1; + uint32_t FAULT_DIRECT: 1; + uint32_t : 1; + uint32_t AMPLIFICATION: 2; + uint32_t AMPLIFIER_OFF: 1; + uint32_t TMC6200_TEST_MODE: 1; + uint32_t : 24; + }; + uint32_t reg; +} TMC6200_GCONF; + +typedef union { + struct { + uint32_t RESET: 1; + uint32_t DRV_OTPW: 1; + uint32_t DRV_OT: 1; + uint32_t UV_CP: 1; + + uint32_t SHORT_DET_U: 1; + uint32_t S2GU: 1; + uint32_t S2VSU: 1; + uint32_t : 1; + + uint32_t SHORT_DET_V: 1; + uint32_t S2GV: 1; + uint32_t S2VSV: 1; + uint32_t : 1; + + uint32_t SHORT_DET_W: 1; + uint32_t S2GW: 1; + uint32_t S2VSW: 1; + uint32_t : 1; + }; + uint32_t reg; +} TMC6200_GSTAT; + +typedef union { + struct { + unsigned UL: 1; + uint32_t UH: 1; + uint32_t VL: 1; + uint32_t VH: 1; + uint32_t WL: 1; + uint32_t WH: 1; + uint32_t DRV_EN: 1; + uint32_t _reserved1: 1; + uint32_t OTPW: 1; + uint32_t OT136C: 1; + uint32_t OT143C: 1; + uint32_t OT150C: 1; + uint32_t _reserved2: 12; + uint32_t VERSION: 8; + }; + + uint32_t reg; +} TMC6200_IOIN; + +typedef union { + struct { + uint32_t S2VS_LEVEL: 4; + uint32_t : 4; + uint32_t S2G_LEVEL: 4; + uint32_t : 4; + uint32_t SHORT_FILTER: 2; + uint32_t : 2; + uint32_t SHORT_DELAY: 1; + uint32_t : 4; + uint32_t RETRY: 2; + uint32_t : 2; + uint32_t PROTECT_PARALLEL: 1; + uint32_t DISABLE_S2G: 1; + uint32_t DISABLE_S2VS: 1; + uint32_t : 2; + }; + uint32_t reg; +} TMC6200_SHORT_CONF; + +typedef union { + struct { + uint32_t BBMCLKS: 5; + uint32_t : 11; + uint32_t OT_SELECT: 2; + uint32_t DRV_STRENGTH: 2; + uint32_t : 12; + }; + uint32_t reg; +} TMC6200_DRV_CONF; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.cpp new file mode 100644 index 0000000..85a4e11 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.cpp @@ -0,0 +1,54 @@ + +#include "./A1334.h" + + + +A1334::A1334(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + // nix +}; + + + +A1334::~A1334() { +}; + + + + +void A1334::init(SPIClass* _spi) { + spi = _spi; + if (nCS>=0) + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + //SPI has an internal SPI-device counter, it is possible to call "begin()" from different devices + spi->begin(); + readRawAngle(); // read an angle +}; + + + + +A1334Angle A1334::readRawAngle() { + uint16_t command = A1334_REG_ANG; + uint16_t cmdResult = spi_transfer16(command); // TODO fast mode + cmdResult = spi_transfer16(command); + A1334Angle result = { .reg = cmdResult }; + // TODO check parity + // errorflag = result.ef; + return result; +}; + + + + +uint16_t A1334::spi_transfer16(uint16_t outdata) { + if (nCS>=0) + digitalWrite(nCS, 0); + spi->beginTransaction(settings); + uint16_t result = spi->transfer16(outdata); + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, 1); + return result; +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.h new file mode 100644 index 0000000..798dcc4 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/A1334.h @@ -0,0 +1,51 @@ + + +#ifndef __A1334_H__ +#define __A1334_H__ + +#include +#include + + +#define A1334_CPR 4096 +#define A1334_BITORDER MSBFIRST + +static SPISettings A1334SPISettings(8000000, A1334_BITORDER, SPI_MODE3); // @suppress("Invalid arguments") + + +typedef union { + struct { + uint16_t angle:12; + uint16_t p:1; + uint16_t nf:1; + uint16_t ef:1; + uint16_t ridc:1; + }; + uint16_t reg; +} A1334Angle; + + +#define A1334_REG_ANG 0x2000 + + + + +class A1334 { +public: + A1334(SPISettings settings = A1334SPISettings, int nCS = -1); + virtual ~A1334(); + + virtual void init(SPIClass* _spi = &SPI); + A1334Angle readRawAngle(); // 10 or 12 bit angle value +protected: + uint16_t spi_transfer16(uint16_t outdata); + SPIClass* spi; + SPISettings settings; + int nCS = -1; +}; + + + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.cpp new file mode 100644 index 0000000..c793947 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.cpp @@ -0,0 +1,27 @@ + +#include "./MagneticSensorA1334.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorA1334::MagneticSensorA1334(int nCS, SPISettings settings) : A1334(settings, nCS) { + +} + + +MagneticSensorA1334::~MagneticSensorA1334(){ + +} + + +void MagneticSensorA1334::init(SPIClass* _spi) { + this->A1334::init(_spi); + this->Sensor::init(); +} + + +float MagneticSensorA1334::getSensorAngle() { + A1334Angle angle_data = readRawAngle(); + float result = ( angle_data.angle / (float)A1334_CPR) * _2PI; + // return the shaft angle + return result; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.h new file mode 100644 index 0000000..59ae961 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/a1334/MagneticSensorA1334.h @@ -0,0 +1,24 @@ + +#ifndef __MAGNETIC_SENSOR_A1334_H__ +#define __MAGNETIC_SENSOR_A1334_H__ + +#include "common/base_classes/Sensor.h" +#include "./A1334.h" + + + +class MagneticSensorA1334 : public Sensor, public A1334 { +public: + MagneticSensorA1334(int nCS = -1, SPISettings settings = A1334SPISettings); + virtual ~MagneticSensorA1334(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +private: +}; + + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.cpp new file mode 100644 index 0000000..8be3bd5 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.cpp @@ -0,0 +1,102 @@ + +#include "AEAT8800Q24.h" + + +AEAT8800Q24::AEAT8800Q24(int nCS, int pinNSL, SPISettings spiSettings, SPISettings ssiSettings) : nCS(nCS), pinNSL(pinNSL), spiSettings(spiSettings), ssiSettings(ssiSettings) { +}; +AEAT8800Q24::~AEAT8800Q24(){ +}; + +void AEAT8800Q24::init(SPIClass* _spi){ + spi = _spi; + spi->beginTransaction(ssiSettings); +}; + + +float AEAT8800Q24::getCurrentAngle() { + return ((float)readRawAngle())/(float)AEAT8800Q24_CPR * 2.0f * (float)PI; +}; // angle in radians, return current value + + +// reads angle via ssi +uint16_t AEAT8800Q24::readRawAngle() { + // digitalWrite(pinNSL, LOW); //TODO maybe we don't need it... + // // 300ns delay + // delayMicroseconds(1); + uint16_t value = spi->transfer16(0x0000); + uint8_t status = spi->transfer(0x00); + //digitalWrite(pinNSL, HIGH); + // // 200ns delay before next read... + // delayMicroseconds(1); + lastStatus.reg = status; + return value; +}; + +AEAT8800Q24_Status_t AEAT8800Q24::getLastStatus() { + return lastStatus; +} + +uint16_t AEAT8800Q24::getZero(){ + uint8_t value = readRegister(AEAT8800Q24_REG_ZERO_MSB); + return (value<<8)|readRegister(AEAT8800Q24_REG_ZERO_LSB); +}; +void AEAT8800Q24::setZero(uint16_t value){ + writeRegister(AEAT8800Q24_REG_ZERO_MSB, (value>>8)&0xFF); + writeRegister(AEAT8800Q24_REG_ZERO_LSB, value&0xFF); +}; + +AEAT8800Q24_CONF0_t AEAT8800Q24::getConf0(){ + AEAT8800Q24_CONF0_t result; + result.reg = readRegister(AEAT8800Q24_REG_CONF0); + return result; +}; +void AEAT8800Q24::setConf0(AEAT8800Q24_CONF0_t value){ + writeRegister(AEAT8800Q24_REG_CONF0, value.reg); +}; + +AEAT8800Q24_CONF1_t AEAT8800Q24::getConf1(){ + AEAT8800Q24_CONF1_t result; + result.reg = readRegister(AEAT8800Q24_REG_CONF1); + return result; +}; +void AEAT8800Q24::setConf1(AEAT8800Q24_CONF1_t value){ + writeRegister(AEAT8800Q24_REG_CONF1, value.reg); +}; + +AEAT8800Q24_CONF2_t AEAT8800Q24::getConf2(){ + AEAT8800Q24_CONF2_t result; + result.reg = readRegister(AEAT8800Q24_REG_CONF2); + return result; +}; +void AEAT8800Q24::setConf2(AEAT8800Q24_CONF2_t value){ + writeRegister(AEAT8800Q24_REG_CONF2, value.reg); +}; + + + + +uint16_t AEAT8800Q24::transfer16SPI(uint16_t outValue) { + // delay 1us between switching the CS line to SPI + delayMicroseconds(1); + if (nCS >= 0) + digitalWrite(nCS, LOW); + spi->endTransaction(); + spi->beginTransaction(spiSettings); + uint16_t value = spi->transfer16(outValue); + spi->endTransaction(); + if (nCS >= 0) + digitalWrite(nCS, HIGH); + // delay 1us between switching the CS line to SSI + delayMicroseconds(1); + spi->beginTransaction(ssiSettings); + return value; +}; +uint8_t AEAT8800Q24::readRegister(uint8_t reg) { + uint16_t cmd = 0x8000 | ((reg&0x001F)<<8); + uint16_t value = transfer16SPI(cmd); + return value&0x00FF; +}; +void AEAT8800Q24::writeRegister(uint8_t reg, uint8_t value) { + uint16_t cmd = 0x4000 | ((reg&0x1F)<<8) | value; + /*uint16_t result =*/ transfer16SPI(cmd); +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.h new file mode 100644 index 0000000..4acfe6d --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/AEAT8800Q24.h @@ -0,0 +1,119 @@ +#ifndef __AEAT8800Q24_H__ +#define __AEAT8800Q24_H__ + + +#include "Arduino.h" +#include "SPI.h" + +#define AEAT8800Q24_CPR 65536 + +#define AEAT8800Q24_REG_CUST0 0x00 +#define AEAT8800Q24_REG_CUST1 0x01 +#define AEAT8800Q24_REG_ZERO_LSB 0x02 +#define AEAT8800Q24_REG_ZERO_MSB 0x03 +#define AEAT8800Q24_REG_CONF0 0x04 +#define AEAT8800Q24_REG_CONF1 0x05 +#define AEAT8800Q24_REG_CONF2 0x06 +#define AEAT8800Q24_REG_CONF_OTP 0x13 +#define AEAT8800Q24_REG_CAL_OTP 0x1B +#define AEAT8800Q24_REG_CUST_OTP 0x11 +#define AEAT8800Q24_REG_CAL 0x17 + +#define AEAT8800Q24_CONF_OTP_ON 0xA3 +#define AEAT8800Q24_CAL_OTP_ON 0xA5 +#define AEAT8800Q24_CUST_OTP_ON 0xA1 +#define AEAT8800Q24_CAL_ON 0x02 +#define AEAT8800Q24_CAL_OFF 0x00 + + +typedef union { + struct { + uint8_t uvw_pwm_mode:1; + uint8_t pwm:2; + uint8_t iwidth:2; + uint8_t uvw:3; + }; + uint8_t reg; +} AEAT8800Q24_CONF0_t; + + +typedef union { + struct { + uint8_t cpr1:4; + uint8_t hys:4; + }; + uint8_t reg; +} AEAT8800Q24_CONF1_t; + + +typedef union { + struct { + uint8_t dir:1; + uint8_t zero_latency:1; + uint8_t abs_res:2; + uint8_t cpr2:4; + }; + uint8_t reg; +} AEAT8800Q24_CONF2_t; + + + +typedef union { + struct { + uint8_t mhi:1; + uint8_t mlo:1; + uint8_t ready:1; + uint8_t parity:1; + uint8_t :4; + }; + uint8_t reg; +} AEAT8800Q24_Status_t; + + +#ifndef MSBFIRST +#define MSBFIRST BitOrder::MSBFIRST +#endif + +static SPISettings AEAT8800Q24SPISettings(1000000, MSBFIRST, SPI_MODE3); // @suppress("Invalid arguments") +static SPISettings AEAT8800Q24SSISettings(4000000, MSBFIRST, SPI_MODE2); // @suppress("Invalid arguments") + + +class AEAT8800Q24 { +public: + AEAT8800Q24(int nCS, int pinNSL = MOSI, SPISettings spiSettings = AEAT8800Q24SPISettings, SPISettings ssiSettings = AEAT8800Q24SSISettings); + virtual ~AEAT8800Q24(); + + virtual void init(SPIClass* _spi = &SPI); + + float getCurrentAngle(); // angle in radians, return current value + + uint16_t readRawAngle(); // 14bit angle value + AEAT8800Q24_Status_t getLastStatus(); // get status associated with last angle read + + uint16_t getZero(); + void setZero(uint16_t); + + AEAT8800Q24_CONF0_t getConf0(); + void setConf0(AEAT8800Q24_CONF0_t); + + AEAT8800Q24_CONF1_t getConf1(); + void setConf1(AEAT8800Q24_CONF1_t); + + AEAT8800Q24_CONF2_t getConf2(); + void setConf2(AEAT8800Q24_CONF2_t); + +private: + int nCS = -1; + int pinNSL = -1; + SPISettings spiSettings; + SPISettings ssiSettings; + SPIClass* spi; + AEAT8800Q24_Status_t lastStatus; + + uint16_t transfer16SPI(uint16_t outValue); + uint8_t readRegister(uint8_t reg); + void writeRegister(uint8_t reg, uint8_t value); +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.cpp new file mode 100644 index 0000000..f1ad32c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.cpp @@ -0,0 +1,24 @@ +#include "./MagneticSensorAEAT8800Q24.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorAEAT8800Q24::MagneticSensorAEAT8800Q24(int nCS, int pinNSL, SPISettings spiSettings, SPISettings ssiSettings) : AEAT8800Q24(nCS, pinNSL, spiSettings, ssiSettings) { +}; + + +MagneticSensorAEAT8800Q24::~MagneticSensorAEAT8800Q24(){ +}; + + +void MagneticSensorAEAT8800Q24::init(SPIClass* _spi) { + this->AEAT8800Q24::init(_spi); + this->Sensor::init(); +}; + + +float MagneticSensorAEAT8800Q24::getSensorAngle() { + float angle_data = readRawAngle(); + angle_data = ( angle_data / (float)AEAT8800Q24_CPR) * _2PI; + // return the shaft angle + return angle_data; +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.h new file mode 100644 index 0000000..01d6e04 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/MagneticSensorAEAT8800Q24.h @@ -0,0 +1,18 @@ +#ifndef __MAGNETICSENSORAEAT8800Q24_H__ +#define __MAGNETICSENSORAEAT8800Q24_H__ + + +#include "common/base_classes/Sensor.h" +#include "./AEAT8800Q24.h" + +class MagneticSensorAEAT8800Q24 : public Sensor, public AEAT8800Q24 { +public: + MagneticSensorAEAT8800Q24(int nCS, int pinNSL = MOSI, SPISettings spiSettings = AEAT8800Q24SPISettings, SPISettings ssiSettings = AEAT8800Q24SSISettings); + virtual ~MagneticSensorAEAT8800Q24(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/README.md new file mode 100644 index 0000000..0afa47d --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/aeat8800q24/README.md @@ -0,0 +1,75 @@ +# AEAT-8800-Q24 SimpleFOC driver + +SPI/SSI driver for the absolute position magnetic rotary encoder. This encoder is not supported by the +normal SimpleFOC drivers due to its mixed SPI/SSI mode. + +- access to the configuration registers of the AEAT-8800-Q24, enabling you to set parameters +- angles are read via SSI, with 16 bit (!) precision +- currently only 16 bit resolution is supported, don't lower the resolution + + +## Hardware setup + +Connect as per normal for your SPI bus. No special hardware setup is needed to use this driver. nCS pin is +required. + +Note that due to the way SSI and SPI share pins, you can normally only run one of these sensors per SPI bus. + +## Software setup + +Its actually easier to use than the standard SPI sensor class, because it is less generic: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/aeat8800q24/MagneticSensorAEAT8800Q24.h" + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorAEAT8800Q24 sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +Set some options: + +```c++ +MagneticSensorAEAT8800Q24 sensor1(SENSOR1_CS, MOSI_pin, mySPISettings, mySSISettings); +``` + +Use another SPI bus: + +```c++ +void setup() { + sensor1.init(SPI2); +} +``` + +Here's how you can use it: + +```c++ + // get the angle, in radians, including full rotations + float a1 = sensor1.getAngle(); + + // get the velocity, in rad/s - note: you have to call getAngle() on a regular basis for it to work + float v1 = sensor1.getVelocity(); + + // get the angle, in radians, no full rotations + float a2 = sensor1.getCurrentAngle(); + + // get the raw 16 bit value + uint16_t raw = sensor1.readRawAngle(); + + // check status + float angle = sensor1.getSensorAngle(); + AEAT8800Q24_Status_t status = sensor1.getLastStatus(); + if (status.mlo) + Serial.println("Sensor magnet low error"); + if (status.mhi) + Serial.println("Sensor magnet high error"); +``` diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.cpp new file mode 100644 index 0000000..9455775 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.cpp @@ -0,0 +1,245 @@ +/* + * AS5047.cpp + * + * Created on: 2 May 2021 + * Author: runger + */ + +#include "./AS5047.h" + +AS5047::AS5047(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + // nix +} + +AS5047::~AS5047() { +} + + +void AS5047::init(SPIClass* _spi) { + spi = _spi; + if (nCS>=0) + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + //SPI has an internal SPI-device counter, it is possible to call "begin()" from different devices + spi->begin(); + readRawAngle(); // read an angle +} + +float AS5047::getCurrentAngle(){ + readCorrectedAngle(); + return ((float)readCorrectedAngle())/(float)AS5047_CPR * 2.0f * (float)PI; +} + +float AS5047::getFastAngle(){ + return ((float)readCorrectedAngle())/(float)AS5047_CPR * 2.0f * (float)PI; +} + + +uint16_t AS5047::readRawAngle(){ + uint16_t command = AS5047_ANGLEUNC_REG | AS5047_RW; // set r=1 and parity=0, result is 0x7FFE + uint16_t lastresult = spi_transfer16(command)&AS5047_RESULT_MASK; + return lastresult; +} +uint16_t AS5047::readCorrectedAngle(){ + uint16_t command = AS5047_ANGLECOM_REG | AS5047_PARITY | AS5047_RW; // set r=1 and parity=1, result is 0xFFFF + uint16_t lastresult = spi_transfer16(command)&AS5047_RESULT_MASK; + return lastresult; +} + + +uint16_t AS5047::readMagnitude(){ + uint16_t command = AS5047_MAGNITUDE_REG | AS5047_RW; // set r=1, result is 0x7FFD + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop(); + return result; +} + + +bool AS5047::isErrorFlag(){ + return errorflag; +} + + +AS5047Error AS5047::clearErrorFlag(){ + uint16_t command = AS5047_ERROR_REG | AS5047_RW; // set r=1, result is 0x4001 + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop(); + AS5047Error err = { + .framingError = ((result&0x0001)!=0x0000), + .commandInvalid = ((result&0x0002)!=0x0000), + .parityError = ((result&0x0004)!=0x0000) + }; + return err; +} + + +AS5047Settings1 AS5047::readSettings1(){ + uint16_t command = AS5047_SETTINGS1_REG | AS5047_PARITY | AS5047_RW; // set r=1, result is 0xC018 + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047Settings1 result = { + .reg = nop() + }; + return result; +} + + +void AS5047::writeSettings1(AS5047Settings1 settings){ + uint16_t command = AS5047_SETTINGS1_REG; // set r=0, result is 0x0018 + spi_transfer16(command); + spi_transfer16(calcParity(settings.reg)); +} + + +AS5047Settings2 AS5047::readSettings2(){ + uint16_t command = AS5047_SETTINGS2_REG | AS5047_RW; // set r=1, result is 0x4019 + spi_transfer16(command); + AS5047Settings2 result = { + .reg = nop() + }; + return result; +} + + +void AS5047::writeSettings2(AS5047Settings2 settings){ + uint16_t command = AS5047_SETTINGS2_REG | AS5047_PARITY; // set r=0, result is 0x8019 + spi_transfer16(command); + spi_transfer16(calcParity(settings.reg)); +} + + + +AS5047Diagnostics AS5047::readDiagnostics(){ + uint16_t command = AS5047_DIAGNOSTICS_REG | AS5047_PARITY | AS5047_RW; // set r=1, result is 0xFFFC + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047Diagnostics result = { + .reg = nop() + }; + return result; +} + + +void AS5047::enablePWM(bool enable){ + AS5047Settings1 settings = readSettings1(); + if (settings.pwmon == enable) return; // no change + settings.pwmon = enable; + writeSettings1(settings); +} + +void AS5047::enableABI(bool enable){ + AS5047Settings1 settings = readSettings1(); + uint8_t val = enable?0:1; + if (settings.uvw_abi == val) return; // no change + settings.uvw_abi = val; + writeSettings1(settings); +} + + +void AS5047::enableDEAC(bool enable){ + AS5047Settings1 settings = readSettings1(); + uint8_t val = enable?0:1; + if (settings.daecdis == val) return; // no change + settings.daecdis = enable?0:1; + writeSettings1(settings); +} + + +void AS5047::useCorrectedAngle(bool useCorrected){ + AS5047Settings1 settings = readSettings1(); + uint8_t val = useCorrected?0:1; + if (settings.dataselect == val) return; // no change + settings.dataselect = val; + writeSettings1(settings); +} + + + +void AS5047::setHysteresis(uint8_t hyst){ + if (hyst>3) hyst = 3; + uint8_t val = 3-hyst; + AS5047Settings2 settings = readSettings2(); + if (settings.hys == val) return; // no change + settings.hys = val; + writeSettings2(settings); +} + + + + +void AS5047::setABIResolution(AS5047ABIRes res){ + AS5047Settings1 settings = readSettings1(); + uint8_t val = (res>>3)&0x01; + if (settings.abibin!=val || settings.uvw_abi!=0) { + settings.abibin = val; + settings.uvw_abi = 0; + writeSettings1(settings); + } + AS5047Settings2 settings2 = readSettings2(); + val = (res&0x07); + if (settings2.abires!=val) { + settings2.abires = val; + writeSettings2(settings2); + } +} + + + +uint16_t AS5047::setZero(uint16_t value){ + uint16_t command = AS5047_ZPOSL_REG | AS5047_PARITY | AS5047_RW; + spi_transfer16(command); + AS5047ZPosL posL = { + .reg = nop() + }; + command = AS5047_ZPOSM_REG | AS5047_PARITY; + spi_transfer16(command); + spi_transfer16(calcParity((value>>6)&0x00FF)); + command = AS5047_ZPOSL_REG; + posL.zposl = value&0x003F; + spi_transfer16(command); + spi_transfer16(calcParity(posL.reg)); + + return getZero(); +} + + +uint16_t AS5047::getZero() { + uint16_t command = AS5047_ZPOSM_REG | AS5047_RW; + spi_transfer16(command); + command = AS5047_ZPOSL_REG | AS5047_PARITY | AS5047_RW; + uint16_t result = spi_transfer16(command); + AS5047ZPosL posL = { + .reg = nop() + }; + return ((result&0x00FF)<<6) | posL.zposl; +} + + +uint16_t AS5047::nop(){ + uint16_t result = spi_transfer16(0xFFFF); // using 0xFFFF as nop instead of 0x0000, then next call to fastAngle will return an angle + return result&AS5047_RESULT_MASK; +} + + +uint16_t AS5047::calcParity(uint16_t data){ + data = data & 0x7FFF; + int sum = 0; + for (int i=0;i<15;i++) + if ((data>>i)&0x0001) + sum++; + return (sum&0x01)==0x01?(data|0x8000):data; +} + + +uint16_t AS5047::spi_transfer16(uint16_t outdata) { + if (nCS>=0) + digitalWrite(nCS, 0); + spi->beginTransaction(settings); + uint16_t result = spi->transfer16(outdata); + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, 1); + // TODO check parity + errorflag = ((result&AS5047_ERRFLG)>0); + return result; +} + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.h new file mode 100644 index 0000000..e3cc80c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/AS5047.h @@ -0,0 +1,167 @@ +/* + * AS5047.h + * + * Created on: 2 May 2021 + * Author: runger + */ + +#ifndef AS5047_H_ +#define AS5047_H_ + +#include "Arduino.h" +#include "SPI.h" + + + + +union AS5047Diagnostics { + struct { + uint16_t agc:8; + uint16_t lf:1; + uint16_t cof:1; + uint16_t magh:1; + uint16_t magl:1; + uint16_t unused:4; + }; + uint16_t reg; +}; + + +union AS5047ZPosM { + struct { + uint16_t zposm:8; + uint16_t unused:8; + }; + uint16_t reg; +}; + + +union AS5047ZPosL { + struct { + uint16_t zposl:6; + uint16_t comp_l_error_en:1; + uint16_t comp_h_error_en:1; + uint16_t unused:8; + }; + uint16_t reg; +}; + + +union AS5047Settings1 { + struct { + uint16_t reserved:1; + uint16_t noiseset:1; + uint16_t dir:1; + uint16_t uvw_abi:1; + uint16_t daecdis:1; + uint16_t abibin:1; + uint16_t dataselect:1; + uint16_t pwmon:1; + uint16_t unused:8; + }; + uint16_t reg; +}; + + +union AS5047Settings2 { + struct { + uint16_t uvwpp:3; + uint16_t hys:2; + uint16_t abires:3; + uint16_t unused:8; + }; + uint16_t reg; +}; + + +struct AS5047Error { + bool framingError; + bool commandInvalid; + bool parityError; +}; + + +enum AS5047ABIRes : uint8_t { + AS5047_ABI_1024 = 0b1010, + AS5047_ABI_2048 = 0b1001, + AS5047_ABI_4096 = 0b1000, + AS5047_ABI_100 = 0b0111, + AS5047_ABI_200 = 0b0110, + AS5047_ABI_400 = 0b0101, + AS5047_ABI_800 = 0b0100, + AS5047_ABI_1200 = 0b0011, + AS5047_ABI_1600 = 0b0010, + AS5047_ABI_2000 = 0b0001, + AS5047_ABI_4000 = 0b0000 +}; + + +#define AS5047_CPR 16384 +#define AS5047_ANGLECOM_REG 0x3FFF +#define AS5047_ANGLEUNC_REG 0x3FFE +#define AS5047_MAGNITUDE_REG 0x3FFD +#define AS5047_DIAGNOSTICS_REG 0x3FFC +#define AS5047_ERROR_REG 0x0001 +#define AS5047_PROG_REG 0x0003 +#define AS5047_ZPOSM_REG 0x0016 +#define AS5047_ZPOSL_REG 0x0017 +#define AS5047_SETTINGS1_REG 0x0018 +#define AS5047_SETTINGS2_REG 0x0019 + +#define AS5047_PARITY 0x8000 +#define AS5047_RW 0x4000 +#define AS5047_ERRFLG 0x4000 +#define AS5047_RESULT_MASK 0x3FFF + + +#define AS5047_BITORDER MSBFIRST + +static SPISettings AS5047SPISettings(8000000, AS5047_BITORDER, SPI_MODE1); // @suppress("Invalid arguments") + + +class AS5047 { +public: + AS5047(SPISettings settings = AS5047SPISettings, int nCS = -1); + virtual ~AS5047(); + + virtual void init(SPIClass* _spi = &SPI); + + float getCurrentAngle(); // angle in radians, return current value + float getFastAngle(); // angle in radians, return last value and read new + + uint16_t readRawAngle(); // 14bit angle value + uint16_t readCorrectedAngle(); // 14bit corrected angle value + uint16_t readMagnitude(); // 14bit magnitude value + + bool isErrorFlag(); + AS5047Error clearErrorFlag(); + + AS5047Diagnostics readDiagnostics(); + AS5047Settings1 readSettings1(); + void writeSettings1(AS5047Settings1 settings); + AS5047Settings2 readSettings2(); + void writeSettings2(AS5047Settings2 settings); + void enablePWM(bool enable); + void enableABI(bool enable); + void setABIResolution(AS5047ABIRes res); + void enableDEAC(bool enable); + void useCorrectedAngle(bool useCorrected); + void setHysteresis(uint8_t hyst); + + uint16_t setZero(uint16_t); + uint16_t getZero(); + + uint16_t calcParity(uint16_t data); + +private: + + uint16_t nop(); + uint16_t spi_transfer16(uint16_t outdata); + SPIClass* spi; + SPISettings settings; + bool errorflag = false; + int nCS = -1; + +}; + +#endif /* AS5047_H_ */ diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.cpp new file mode 100644 index 0000000..f5f2e5f --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.cpp @@ -0,0 +1,29 @@ + +#include "./MagneticSensorAS5047.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorAS5047::MagneticSensorAS5047(int nCS, bool fastMode, SPISettings settings) : AS5047(settings, nCS), fastMode(fastMode) { + +} + + +MagneticSensorAS5047::~MagneticSensorAS5047(){ + +} + + +void MagneticSensorAS5047::init(SPIClass* _spi) { + this->AS5047::init(_spi); + this->Sensor::init(); +} + + +float MagneticSensorAS5047::getSensorAngle() { + float angle_data = readRawAngle(); + if (!fastMode) // read again to ensure current value + angle_data = readRawAngle(); + angle_data = ( angle_data / (float)AS5047_CPR) * _2PI; + // return the shaft angle + return angle_data; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.h new file mode 100644 index 0000000..aae3f54 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/MagneticSensorAS5047.h @@ -0,0 +1,20 @@ + +#ifndef __MAGNETICSENSORAS5047PD_H__ +#define __MAGNETICSENSORAS5047PD_H__ + +#include "common/base_classes/Sensor.h" +#include "./AS5047.h" + +class MagneticSensorAS5047 : public Sensor, public AS5047 { +public: + MagneticSensorAS5047(int nCS = -1, bool fastMode = false, SPISettings settings = AS5047SPISettings); + virtual ~MagneticSensorAS5047(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +private: + bool fastMode = false; +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/README.md new file mode 100644 index 0000000..22de36b --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047/README.md @@ -0,0 +1,82 @@ +# AS5047 SimpleFOC driver + +While the AS5047 absolute position magnetic rotary encoder is supported by the standard MagneticSensorSPI driver included in the base distribution, this AS5047-specific driver includes some optimisations: + +- access to the other registers of the AS5047, including the magnitude value which can be used to check the magnet strength, and the diagnostics register +- access to the error state of the sensor, and ability to clear errors +- it has a fastMode setting, in which the sensor is sent only 1 command per getAngle() call - the value returned will be from previous getAngle() invocation + +This driver should work with AS5047P and AS5047D models. The AS5047U has it's own driver [here](../as5047u/). + +## Hardware setup + +Connect as per normal for your SPI bus. No special hardware setup is needed to use this driver. + +## Software setup + +Its actually easier to use than the standard SPI sensor class, because it is less generic: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/as5047/MagneticSensorAS5047.h" + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorAS5047 sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +Set some options: + +```c++ +MagneticSensorAS5047 sensor1(SENSOR1_CS, true, mySPISettings); +``` + +Use another SPI bus: + +```c++ +void setup() { + sensor1.init(SPI2); +} +``` + +Here's how you can use it: + +```c++ + // update the sensor (only needed if using the sensor without a motor) + sensor1.update(); + + // get the angle, in radians, including full rotations + float a1 = sensor1.getAngle(); + + // get the velocity, in rad/s - note: you have to call getAngle() on a regular basis for it to work + float v1 = sensor1.getVelocity(); + + // get the angle, in radians, no full rotations + float a2 = sensor1.getCurrentAngle(); + + // get the raw 14 bit value + uint16_t raw = sensor1.readRawAngle(); + + // read the CORDIC magnitude value, a measure of the magnet field strength + float m1 = sensor1.readMagnitude(); + + // check for errors + if (sensor1.isErrorFlag()) { + AS5047Error error = sensor1.clearErrorFlag(); + if (error.parityError) { // also error.framingError, error.commandInvalid + // etc... + } + } + + // get diagnostics + AS5047Diagnostics diagnostics = sensor1.readDiagnostics(); +``` + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.cpp new file mode 100644 index 0000000..bfe70be --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.cpp @@ -0,0 +1,350 @@ +/* + * AS5047U.cpp + * + * Created on: 24 Feb 2022 + * Author: runger + */ + +#include "./AS5047U.h" + +AS5047U::AS5047U(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + // nix +} + +AS5047U::~AS5047U() { +} + + +void AS5047U::init(SPIClass* _spi) { + spi = _spi; + if (nCS>=0) + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + //SPI has an internal SPI-device counter, it is possible to call "begin()" from different devices + spi->begin(); + readRawAngle(); // read an angle +} + +float AS5047U::getCurrentAngle(){ + readCorrectedAngle(); + return ((float)readCorrectedAngle())/(float)AS5047U_CPR * 2.0f * (float)PI; +} + +float AS5047U::getFastAngle(){ + return ((float)readCorrectedAngle())/(float)AS5047U_CPR * 2.0f * (float)PI; +} + + +uint16_t AS5047U::readRawAngle(){ + uint16_t command = AS5047U_ANGLEUNC_REG | AS5047U_RW; + uint16_t lastresult = spi_transfer16(command)&AS5047U_RESULT_MASK; + return lastresult; +} + + +uint16_t AS5047U::readCorrectedAngle(){ + uint16_t command = AS5047U_ANGLECOM_REG | AS5047U_RW; + uint16_t lastresult = spi_transfer16(command)&AS5047U_RESULT_MASK; + return lastresult; +} + + +uint16_t AS5047U::readMagnitude(){ + uint16_t command = AS5047U_MAGNITUDE_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop16(); + return result; +} + + +uint16_t AS5047U::readVelocity(){ + uint16_t command = AS5047U_VELOCITY_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop16(); + return result; +} + + +bool AS5047U::isErrorFlag(){ + return errorflag; +} + +bool AS5047U::isWarningFlag(){ + return warningflag; +} + + +AS5047UError AS5047U::clearErrorFlag(){ + uint16_t command = AS5047U_ERROR_REG | AS5047U_RW; // set r=1, result is 0x4001 + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047UError result; + result.reg = nop16(); + return result; +} + + +AS5047USettings1 AS5047U::readSettings1(){ + uint16_t command = AS5047U_SETTINGS1_REG | AS5047U_RW; // set r=1, result is 0xC018 + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047USettings1 result = { + .reg = nop16() + }; + return result; +} + + + + +void AS5047U::writeSettings1(AS5047USettings1 settings){ + writeRegister24(AS5047U_SETTINGS1_REG, settings.reg); +} + + + + +AS5047USettings2 AS5047U::readSettings2(){ + uint16_t command = AS5047U_SETTINGS2_REG | AS5047U_RW; // set r=1, result is 0x4019 + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047USettings2 result = { + .reg = nop16() + }; + return result; +} + + + + + +void AS5047U::writeSettings2(AS5047USettings2 settings){ + writeRegister24(AS5047U_SETTINGS2_REG, settings.reg); +} + + + + + +AS5047USettings3 AS5047U::readSettings3(){ + uint16_t command = AS5047U_SETTINGS3_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047USettings3 result = { + .reg = nop16() + }; + return result; +} + + + + + +void AS5047U::writeSettings3(AS5047USettings3 settings){ + writeRegister24(AS5047U_SETTINGS3_REG, settings.reg); +} + + + + +AS5047UDiagnostics AS5047U::readDiagnostics(){ + uint16_t command = AS5047U_DIAGNOSTICS_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047UDiagnostics result = { + .reg = nop16() + }; + return result; +} + + + + +uint8_t AS5047U::readAGC(){ + uint16_t command = AS5047U_AGC_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop16(); + return result & 0x00FF; +}; + + + +uint8_t AS5047U::readECCCHK(){ + uint16_t command = AS5047U_ECCCHK_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop16(); + return result & 0x007F; +}; + + + + +AS5047UDisableSettings AS5047U::readDisableSettings(){ + uint16_t command = AS5047U_DISABLE_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047UDisableSettings result = { + .reg = nop16() + }; + return result; +}; + + + +void AS5047U::writeDisableSettings(AS5047UDisableSettings settings){ + writeRegister24(AS5047U_DISABLE_REG, settings.reg); +}; + + + +AS5047UECCSettings AS5047U::readECCSettings(){ + uint16_t command = AS5047U_ECC_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047UECCSettings result = { + .reg = nop16() + }; + return result; +}; + + + +void AS5047U::writeECCSettings(AS5047UECCSettings settings){ + writeRegister24(AS5047U_ECC_REG, settings.reg); +}; + + + + + + + +void AS5047U::enablePWM(bool enable, bool pwmOnWPin){ + // AS5047UDisableSettings settings = readDisableSettings(); + // if (settings.uvw_off==1) { + // settings.uvw_off = 0; + // writeDiableSettings(settings); + // } + AS5047USettings2 settings2 = readSettings2(); + settings2.uvw_abi = pwmOnWPin?0:1; + settings2.pwm_on = enable; + writeSettings2(settings2); +} + + + + +void AS5047U::enableABI(bool enable){ + AS5047UDisableSettings settings = readDisableSettings(); + settings.abi_off = enable?0:1; + writeDisableSettings(settings); + delayMicroseconds(50); + if (enable) { + AS5047USettings2 settings2 = readSettings2(); + settings2.uvw_abi = 0; + writeSettings2(settings2); + } +} + + + +void AS5047U::enableUVW(bool enable){ + AS5047UDisableSettings settings = readDisableSettings(); + settings.uvw_off = enable?0:1; + writeDisableSettings(settings); + if (enable) { + AS5047USettings2 settings2 = readSettings2(); + settings2.uvw_abi = 1; + writeSettings2(settings2); + } +} + + + + +uint16_t AS5047U::getZero(){ + uint16_t command = AS5047U_ZPOSM_REG | AS5047U_RW; + spi_transfer16(command); + command = AS5047U_ZPOSL_REG | AS5047U_RW; + uint16_t result = spi_transfer16(command); + AS5047UZPosL posL = { + .reg = nop16() + }; + return ((result&0x00FF)<<6) | posL.zposl; +} + + + +uint16_t AS5047U::setZero(uint16_t value){ + uint16_t command = AS5047U_ZPOSL_REG | AS5047U_RW; + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5047UZPosL posL = { + .reg = nop16() + }; + posL.zposl = value&0x003F; + writeRegister24(AS5047U_ZPOSL_REG, posL.reg); + writeRegister24(AS5047U_ZPOSM_REG, (value>>6)&0x00FF); + return getZero(); +} + + + + +uint16_t AS5047U::nop16(){ + uint16_t result = spi_transfer16(0xFFFF); // using 0xFFFF as nop instead of 0x0000, then next call to fastAngle will return an angle + return result&AS5047U_RESULT_MASK; +} + + + +uint16_t AS5047U::spi_transfer16(uint16_t outdata) { + if (nCS>=0) + digitalWrite(nCS, 0); + spi->beginTransaction(settings); + uint16_t result = spi->transfer16(outdata); + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, 1); + errorflag = ((result&AS5047U_ERROR)>0); + warningflag = ((result&AS5047U_WARNING)>0); + return result; +} + +uint8_t AS5047U::calcCRC(uint16_t data){ + uint8_t crc = 0xC4; // Initial value + for (int i = 0; i < 16; i++) { + if ((crc ^ data) & 0x8000) { + crc = (crc << 1) ^ 0x1D; + } else { + crc <<= 1; + } + data <<= 1; + } + return crc ^ 0xFF; +} + +uint16_t AS5047U::writeRegister24(uint16_t reg, uint16_t data) { + uint8_t buff[3]; + buff[0] = (reg>>8)&0x3F; + buff[1] = reg&0xFF; + buff[2] = calcCRC(reg); + if (nCS>=0) + digitalWrite(nCS, 0); + spi->beginTransaction(settings); + spi->transfer(buff, 3); + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, 1); + errorflag = ((buff[0]&0x40)>0); + warningflag = ((buff[0]&0x80)>0); + + buff[0] = (data>>8)&0x3F; + buff[1] = data&0xFF; + buff[2] = calcCRC(data); + if (nCS>=0) + digitalWrite(nCS, 0); + spi->beginTransaction(settings); + spi->transfer(buff, 3); + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, 1); + errorflag = ((buff[0]&0x40)>0); + warningflag = ((buff[0]&0x80)>0); + + delayMicroseconds(50); + + return buff[0]<<8 | buff[1]; +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.h new file mode 100644 index 0000000..cb9cf10 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/AS5047U.h @@ -0,0 +1,225 @@ +/* + * AS5047.h + * + * Created on: 24 Feb 2022 + * Author: runger + */ + +#ifndef AS5047U_H_ +#define AS5047U_H_ + +#include "Arduino.h" +#include "SPI.h" + + +union AS5047UDisableSettings { + struct { + uint16_t :9; + uint16_t filter_disable:1; + uint16_t :4; + uint16_t abi_off:1; + uint16_t uvw_off:1; + }; + uint16_t reg; +}; + + + +union AS5047UDiagnostics { + struct { + uint16_t spi_cnt:2; + uint16_t :1; + uint16_t agc_finished:1; + uint16_t off_finished:1; + uint16_t sin_finished:1; + uint16_t cos_finished:1; + uint16_t maghalf_flag:1; + uint16_t comp_h:1; + uint16_t comp_l:1; + uint16_t cordic_ovf:1; + uint16_t loops_finished:1; + uint16_t vdd_mode:1; + }; + uint16_t reg; +}; + + +union AS5047UZPosM { + struct { + uint16_t zposm:8; + }; + uint16_t reg; +}; + + +union AS5047UZPosL { + struct { + uint16_t zposl:6; + uint16_t dia1_en:1; // automotive version only + uint16_t dia2_en:1; // automotive version only + }; + uint16_t reg; +}; + + +union AS5047USettings1 { + struct { + uint16_t k_max:3; + uint16_t k_min:3; + uint16_t dia3_en:1; // not applicable + uint16_t dia4_en:1; // not applicable + }; + uint16_t reg; +}; + + +union AS5047USettings2 { + struct { + uint16_t iwidth:1; + uint16_t noiseset:1; + uint16_t dir:1; + uint16_t uvw_abi:1; + uint16_t daecdis:1; + uint16_t abi_dec:1; + uint16_t data_select:1; + uint16_t pwm_on:1; + }; + uint16_t reg; +}; + + + + +union AS5047USettings3 { + struct { + uint16_t uvwpp:3; + uint16_t hys:2; + uint16_t abires:3; + }; + uint16_t reg; +}; + + + + +union AS5047UECCSettings { + struct { + uint16_t ecc_chsum:7; + uint16_t ecc_en:1; + }; + uint16_t reg; +}; + + + + +struct AS5047UError { + struct { + uint16_t cordic_ovf:1; + uint16_t off_notfinished:1; + uint16_t :1; + uint16_t wdtst:1; + uint16_t crc_error:1; + uint16_t cmd_error:1; + uint16_t frame_error:1; + uint16_t p2ram_error:1; + uint16_t p2ram_warning:1; + uint16_t maghalf:1; + uint16_t agc_warning:1; + }; + uint16_t reg; +}; + + + + + +#define AS5047U_CPR 16384 +#define AS5047U_ANGLECOM_REG 0x3FFF +#define AS5047U_ANGLEUNC_REG 0x3FFE +#define AS5047U_MAGNITUDE_REG 0x3FFD +#define AS5047U_VELOCITY_REG 0x3FFC +#define AS5047U_SIN_REG 0x3FFA +#define AS5047U_COS_REG 0x3FFB +#define AS5047U_AGC_REG 0x3FF9 +#define AS5047U_DIAGNOSTICS_REG 0x3FF5 +#define AS5047U_ERROR_REG 0x0001 +#define AS5047U_PROG_REG 0x0003 +#define AS5047U_ECCCHK_REG 0x00D1 + +#define AS5047U_DISABLE_REG 0x0015 +#define AS5047U_ZPOSM_REG 0x0016 +#define AS5047U_ZPOSL_REG 0x0017 +#define AS5047U_SETTINGS1_REG 0x0018 +#define AS5047U_SETTINGS2_REG 0x0019 +#define AS5047U_SETTINGS3_REG 0x001A +#define AS5047U_ECC_REG 0x001B + +#define AS5047U_WARNING 0x8000 +#define AS5047U_ERROR 0x4000 +#define AS5047U_RW 0x4000 +#define AS5047U_ERRFLG 0xC000 +#define AS5047U_RESULT_MASK 0x3FFF + + +#define AS5047U_BITORDER MSBFIRST + +static SPISettings AS5047USPISettings(8000000, AS5047U_BITORDER, SPI_MODE1); // @suppress("Invalid arguments") + + +class AS5047U { +public: + AS5047U(SPISettings settings = AS5047USPISettings, int nCS = -1); + virtual ~AS5047U(); + + virtual void init(SPIClass* _spi = &SPI); + + float getCurrentAngle(); // angle in radians, return current value + float getFastAngle(); // angle in radians, return last value and read new + + uint16_t readRawAngle(); // 14bit angle value + uint16_t readCorrectedAngle(); // 14bit corrected angle value + uint16_t readMagnitude(); // 14bit magnitude value + uint16_t readVelocity(); // 14bit magnitude value + + bool isErrorFlag(); + bool isWarningFlag(); + AS5047UError clearErrorFlag(); + + AS5047UDiagnostics readDiagnostics(); + uint8_t readAGC(); + uint8_t readECCCHK(); + + AS5047UDisableSettings readDisableSettings(); + void writeDisableSettings(AS5047UDisableSettings settings); + AS5047USettings1 readSettings1(); + void writeSettings1(AS5047USettings1 settings); + AS5047USettings2 readSettings2(); + void writeSettings2(AS5047USettings2 settings); + AS5047USettings3 readSettings3(); + void writeSettings3(AS5047USettings3 settings); + AS5047UECCSettings readECCSettings(); + void writeECCSettings(AS5047UECCSettings settings); + + void enablePWM(bool enable, bool pwmOnWPin = true); + void enableABI(bool enable); + void enableUVW(bool enable); + + uint16_t setZero(uint16_t); + uint16_t getZero(); + +private: + + uint16_t nop16(); + uint16_t spi_transfer16(uint16_t outdata); + uint8_t calcCRC(uint16_t data); + uint16_t writeRegister24(uint16_t reg, uint16_t data); + SPIClass* spi; + SPISettings settings; + bool errorflag = false; + bool warningflag = false; + int nCS = -1; + +}; + +#endif /* AS5047U_H_ */ diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.cpp new file mode 100644 index 0000000..e5fe89a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.cpp @@ -0,0 +1,29 @@ + +#include "./MagneticSensorAS5047U.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorAS5047U::MagneticSensorAS5047U(int nCS, bool fastMode, SPISettings settings) : AS5047U(settings, nCS), fastMode(fastMode) { + +} + + +MagneticSensorAS5047U::~MagneticSensorAS5047U(){ + +} + + +void MagneticSensorAS5047U::init(SPIClass* _spi) { + this->AS5047U::init(_spi); + this->Sensor::init(); +} + + +float MagneticSensorAS5047U::getSensorAngle() { + float angle_data = readRawAngle(); + if (!fastMode) // read again to ensure current value + angle_data = readRawAngle(); + angle_data = ( angle_data / (float)AS5047U_CPR) * _2PI; + // return the shaft angle + return angle_data; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.h new file mode 100644 index 0000000..e6ef813 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/MagneticSensorAS5047U.h @@ -0,0 +1,20 @@ + +#ifndef __MAGNETICSENSORAS5047U_H__ +#define __MAGNETICSENSORAS5047U_H__ + +#include "common/base_classes/Sensor.h" +#include "./AS5047U.h" + +class MagneticSensorAS5047U : public Sensor, public AS5047U { +public: + MagneticSensorAS5047U(int nCS = -1, bool fastMode = false, SPISettings settings = AS5047USPISettings); + virtual ~MagneticSensorAS5047U(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +private: + bool fastMode = false; +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/README.md new file mode 100644 index 0000000..2a6743c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5047u/README.md @@ -0,0 +1,81 @@ +# AS5047U SimpleFOC driver + +While AS5047U absolute position magnetic rotary encoder is supported by the standard MagneticSensorSPI driver included in the base distribution, this AS5047U-specific driver includes some optimisations: + +- access to the other registers of the AS5047U, including the magnitude value which can be used to check the magnet strength, the velocity register and the diagnostics register +- access to the error state of the sensor, and ability to clear errors +- it has a fastMode setting, in which the sensor is sent only 1 command per getAngle() call - the value returned will be from previous getAngle() invocation + + +## Hardware setup + +Connect as per normal for your SPI bus. No special hardware setup is needed to use this driver. + +## Software setup + +Its actually easier to use than the standard SPI sensor class, because it is less generic: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/as5047u/MagneticSensorAS5047U.h" + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorAS5047U sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +Set some options: + +```c++ +MagneticSensorAS5047U sensor1(SENSOR1_CS, true, mySPISettings); +``` + +Use another SPI bus: + +```c++ +void setup() { + sensor1.init(SPI2); +} +``` + +Here's how you can use it: + +```c++ + // update the sensor (only needed if using the sensor without a motor) + sensor1.update(); + + // get the angle, in radians, including full rotations + float a1 = sensor1.getAngle(); + + // get the velocity, in rad/s - note: you have to call getAngle() on a regular basis for it to work + float v1 = sensor1.getVelocity(); + + // get the angle, in radians, no full rotations + float a2 = sensor1.getCurrentAngle(); + + // get the raw 14 bit value + uint16_t raw = sensor1.readRawAngle(); + + // read the CORDIC magnitude value, a measure of the magnet field strength + float m1 = sensor1.readMagnitude(); + + // check for errors + if (sensor1.isErrorFlag()) { + AS5047UError error = sensor1.clearErrorFlag(); + if (error.parityError) { // also error.framingError, error.commandInvalid + // etc... + } + } + + // get diagnostics + AS5047Diagnostics diagnostics = sensor1.readDiagnostics(); +``` + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.cpp new file mode 100644 index 0000000..27ef254 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.cpp @@ -0,0 +1,118 @@ +/* + * AS5048A.cpp + * + * Created on: 8 Mar 2021 + * Author: runger + */ + +#include "AS5048A.h" + +AS5048A::AS5048A(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + // nix +} + +AS5048A::~AS5048A() { +} + + +void AS5048A::init(SPIClass* _spi) { + spi = _spi; + if (nCS>=0) + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + //SPI has an internal SPI-device counter, it is possible to call "begin()" from different devices + spi->begin(); + readRawAngle(); // read an angle +} + +float AS5048A::getCurrentAngle(){ + readRawAngle(); + return ((float)readRawAngle())/(float)AS5048A_CPR * 2.0f * (float)PI; +} + +float AS5048A::getFastAngle(){ + return ((float)readRawAngle())/(float)AS5048A_CPR * 2.0f * (float)PI; +} + + +uint16_t AS5048A::readRawAngle(){ + uint16_t command = AS5048A_ANGLE_REG | AS5048A_PARITY | AS5048A_RW; // set r=1 and parity=1, result ix 0xFFFF + uint16_t lastresult = spi_transfer16(command)&AS5048A_RESULT_MASK; + return lastresult; +} + + +uint16_t AS5048A::readMagnitude(){ + uint16_t command = AS5048A_MAGNITUDE_REG | AS5048A_RW; // set r=1, result ix 0x7FFE + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop(); + return result; +} + + +bool AS5048A::isErrorFlag(){ + return errorflag; +} + + +AS5048Error AS5048A::clearErrorFlag(){ + uint16_t command = AS5048A_ERROR_REG | AS5048A_RW; // set r=1, result ix 0x4001 + /*uint16_t cmdresult =*/ spi_transfer16(command); + uint16_t result = nop(); + AS5048Error err = { + .parityError = ((result&0x0004)!=0x0000), + .commandInvalid = ((result&0x0002)!=0x0000), + .framingError = ((result&0x0001)!=0x0000) + }; + return err; +} + + +AS5048Diagnostics AS5048A::readDiagnostics(){ + uint16_t command = AS5048A_DIAGNOSTICS_REG | AS5048A_RW; // set r=1, result ix 0x7FFD + /*uint16_t cmdresult =*/ spi_transfer16(command); + AS5048Diagnostics result = { + .reg = nop() + }; + return result; +} + + +uint16_t AS5048A::setZero(uint16_t){ + // TODO implement me! + return 0; +} + + +uint16_t AS5048A::enableOneTimeProgramming(){ + // no plans to implement this at the moment. one-time-programming a $10 chip isn't really a "maker" thing to do. The zero + // position can be easily retained in software, stored on the MCU, and thereby the sensor can be reused in another project. + return 0; +} + + +uint16_t AS5048A::programZero(){ + // no plans to implement this at the moment. one-time-programming a $10 chip isn't really a "maker" thing to do. The zero + // position can be easily retained in software, stored on the MCU, and thereby the sensor can be reused in another project. + return 0; +} + +uint16_t AS5048A::nop(){ + uint16_t result = spi_transfer16(0xFFFF); // using 0xFFFF as nop instead of 0x0000, then next call to fastAngle will return an angle + return result&AS5048A_RESULT_MASK; +} + +uint16_t AS5048A::spi_transfer16(uint16_t outdata) { + if (nCS>=0) + digitalWrite(nCS, 0); + spi->beginTransaction(settings); + uint16_t result = spi->transfer16(outdata); + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, 1); + // TODO check parity + errorflag = ((result&AS5048A_ERRFLG)>0); + return result; +} + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.h new file mode 100644 index 0000000..00a4fe6 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/AS5048A.h @@ -0,0 +1,89 @@ +/* + * AS5048A.h + * + * Created on: 8 Mar 2021 + * Author: runger + */ + +#ifndef AS5048A_H_ +#define AS5048A_H_ + +#include "Arduino.h" +#include "SPI.h" + + + + +union AS5048Diagnostics { + struct { + uint16_t agc:8; + uint16_t ocf:1; + uint16_t cof:1; + uint16_t compLow:1; + uint16_t compHigh:1; + }; + uint16_t reg; +}; + + +struct AS5048Error { + bool parityError; + bool commandInvalid; + bool framingError; +}; + + +#define AS5048A_CPR 16384 +#define AS5048A_ANGLE_REG 0x3FFF +#define AS5048A_ERROR_REG 0x0001 +#define AS5048A_PROGCTL_REG 0x0003 +#define AS5048A_OTPHIGH_REG 0x0016 +#define AS5048A_OTPLOW_REG 0x0017 +#define AS5048A_DIAGNOSTICS_REG 0x3FFD +#define AS5048A_MAGNITUDE_REG 0x3FFE +#define AS5048A_PARITY 0x8000 +#define AS5048A_RW 0x4000 +#define AS5048A_ERRFLG 0x4000 +#define AS5048A_RESULT_MASK 0x3FFF + + +#define AS5048_BITORDER MSBFIRST + + +static SPISettings AS5048SPISettings(8000000, AS5048_BITORDER, SPI_MODE1); // @suppress("Invalid arguments") + + +class AS5048A { +public: + AS5048A(SPISettings settings = AS5048SPISettings, int nCS = -1); + virtual ~AS5048A(); + + virtual void init(SPIClass* _spi = &SPI); + + float getCurrentAngle(); // angle in radians, return current value + float getFastAngle(); // angle in radians, return last value and read new + + uint16_t readRawAngle(); // 14bit angle value + uint16_t readMagnitude(); // 14bit magnitude value + + bool isErrorFlag(); + AS5048Error clearErrorFlag(); + + AS5048Diagnostics readDiagnostics(); + + uint16_t setZero(uint16_t); + uint16_t enableOneTimeProgramming(); + uint16_t programZero(); + +private: + + uint16_t nop(); + uint16_t spi_transfer16(uint16_t outdata); + SPIClass* spi; + SPISettings settings; + bool errorflag = false; + int nCS = -1; + +}; + +#endif /* AS5048A_H_ */ diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.cpp new file mode 100644 index 0000000..a58b1b9 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.cpp @@ -0,0 +1,26 @@ + +#include "./MagneticSensorAS5048A.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorAS5048A::MagneticSensorAS5048A(int nCS, bool fastMode, SPISettings settings) : AS5048A(settings, nCS), fastMode(fastMode) { + +} + +MagneticSensorAS5048A::~MagneticSensorAS5048A(){ + +} +void MagneticSensorAS5048A::init(SPIClass* _spi) { + this->AS5048A::init(_spi); + this->Sensor::init(); +} + +float MagneticSensorAS5048A::getSensorAngle() { + float angle_data = readRawAngle(); + if (!fastMode) // read again to ensure current value + angle_data = readRawAngle(); + + angle_data = ( angle_data / (float)AS5048A_CPR ) * _2PI; + // return the shaft angle + return angle_data; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.h new file mode 100644 index 0000000..0f7e2b7 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/MagneticSensorAS5048A.h @@ -0,0 +1,20 @@ + +#ifndef __MAGNETICSENSORAS5048A_H__ +#define __MAGNETICSENSORAS5048A_H__ + +#include "common/base_classes/Sensor.h" +#include "./AS5048A.h" + +class MagneticSensorAS5048A : public Sensor, public AS5048A { +public: + MagneticSensorAS5048A(int nCS = -1, bool fastMode = false, SPISettings settings = AS5048SPISettings); + virtual ~MagneticSensorAS5048A(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +protected: + bool fastMode = false; +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.cpp new file mode 100644 index 0000000..9f340c4 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.cpp @@ -0,0 +1,50 @@ +/* + * PreciseMagneticSensorAS5048A.cpp + * + * Created on: 1 May 2021 + * Author: runger + */ + +#include +#include "common/foc_utils.h" +#include "common/time_utils.h" + +PreciseMagneticSensorAS5048A::PreciseMagneticSensorAS5048A(int nCS, bool fastMode, SPISettings settings) : AS5048A(settings, nCS), fastMode(fastMode) { } + +PreciseMagneticSensorAS5048A::~PreciseMagneticSensorAS5048A() { } + + +void PreciseMagneticSensorAS5048A::init(SPIClass* _spi) { + this->AS5048A::init(_spi); + // velocity calculation init + current_ts = _micros(); + /*uint16_t angle_data =*/ readRawAngle(); + current_angle = PreciseAngle(readRawAngle(), 0); + getAngle(); +} + + + +float PreciseMagneticSensorAS5048A::getSensorAngle() { + previous_ts = current_ts; + previous_angle = current_angle; + uint16_t angle_data = readRawAngle(); + if (!fastMode) // read again to ensure current value + angle_data = readRawAngle(); + current_ts = _micros(); + current_angle.update(angle_data); + return current_angle.asFloat(); +} + + + +/* +unlike the normal MagneticSensorSPI implementation, this one uses the angle previously read by the last call to getAngle to do its +calculation, and does not directly poll any data from the sensor. +This is an optimisation for speed, based on the assumption that loopFOC() (which calls getAngle()) is invoked at least as often as +move() (which calls getVelocity()). If this is the case, getVelocity() should always have a sufficiently "fresh" value to work with. +If using this function in a different context, simply call getAngle() first to be sure of a fresh angle value. +*/ +float PreciseMagneticSensorAS5048A::getVelocity() { + return current_angle.velocity(previous_angle, (current_ts-previous_ts)); +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.h new file mode 100644 index 0000000..389b6f7 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/PreciseMagneticSensorAS5048A.h @@ -0,0 +1,33 @@ +/* + * PreciseMagneticSensorAS5048A.h + * + * Created on: 1 May 2021 + * Author: runger + */ + +#ifndef LIBRARIES_ARDUNIO_FOC_DRIVERS_SRC_ENCODERS_AS5048A_PRECISEMAGNETICSENSORAS5048A_H_ +#define LIBRARIES_ARDUNIO_FOC_DRIVERS_SRC_ENCODERS_AS5048A_PRECISEMAGNETICSENSORAS5048A_H_ + +#include "common/base_classes/Sensor.h" +#include "./AS5048A.h" +#include "utilities/PreciseAngle.h" + +class PreciseMagneticSensorAS5048A : public Sensor, public AS5048A { +public: + PreciseMagneticSensorAS5048A(int nCS = -1, bool fastMode = false, SPISettings settings = AS5048SPISettings); + virtual ~PreciseMagneticSensorAS5048A(); + + virtual float getSensorAngle() override; + virtual float getVelocity() override; + + virtual void init(SPIClass* _spi = &SPI) override; + +protected: + bool fastMode = false; + PreciseAngle previous_angle = PreciseAngle(); + PreciseAngle current_angle = PreciseAngle(); + unsigned long previous_ts = 0; + unsigned long current_ts = 1; +}; + +#endif /* LIBRARIES_ARDUNIO_FOC_DRIVERS_SRC_ENCODERS_AS5048A_PRECISEMAGNETICSENSORAS5048A_H_ */ diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/README.md new file mode 100644 index 0000000..468994c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5048a/README.md @@ -0,0 +1,86 @@ +# AS5048A SimpleFOC driver + +While AS5048A absolute position magnetic rotary encoder is supported by the standard MagneticSensorSPI driver included in the base distribution, this AS5048A-specific driver includes some optimisations: + +- access to the other registers of the AS5048A, including the magnitude value which can be used to check the magnet strength, and the diagnostics register +- access to the error state of the sensor, and ability to clear errors +- it has a fastMode setting, in which the sensor is sent only 1 command per getAngle() call - the value returned will be from previous getAngle() invocation + + +## Hardware setup + +Connect as per normal for your SPI bus. No special hardware setup is needed to use this driver. + +## Software setup + +Its actually easier to use than the standard SPI sensor class, because it is less generic: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/as5048a/MagneticSensorAS5048A.h" + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorAS5048A sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +Set some options: + +```c++ +MagneticSensorAS5048A sensor1(SENSOR1_CS, true, mySPISettings); +``` + +Use another SPI bus: + +```c++ +void setup() { + sensor1.init(SPI2); +} +``` + +Here's how you can use it: + +```c++ + // update the sensor (only needed if using the sensor without a motor) + sensor1.update(); + + // get the angle, in radians, including full rotations + float a1 = sensor1.getAngle(); + + // get the velocity, in rad/s - note: you have to call getAngle() on a regular basis for it to work + float v1 = sensor1.getVelocity(); + + // get the angle, in radians, no full rotations + float a2 = sensor1.getCurrentAngle(); + + // get the raw 14 bit value + uint16_t raw = sensor1.readRawAngle(); + + // read the CORDIC magnitude value, a measure of the magnet field strength + float m1 = sensor1.readMagnitude(); + + // check for errors + if (sensor1.isErrorFlag()) { + AS5048Error error = sensor1.clearErrorFlag(); + if (error.parityError) { // also error.framingError, error.commandInvalid + // etc... + } + } + + // get diagnostics + AS5048Diagnostics diagnostics = sensor1.readDiagnostics(); +``` + + +## PreciseMagneticSensorAS5048A + +This is a variant of the sensor that uses [PreciseAngle](../utilities) to represent the angle, allowing a (much) greater range of rotation. + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.cpp new file mode 100644 index 0000000..6d60000 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.cpp @@ -0,0 +1,34 @@ +#include "./MagneticSensorAS5145.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorAS5145::MagneticSensorAS5145(SPISettings settings) : settings(settings) { + +} + + +MagneticSensorAS5145::~MagneticSensorAS5145() { + +} + +void MagneticSensorAS5145::init(SPIClass* _spi) { + this->spi=_spi; + this->Sensor::init(); +} + +// check 40us delay between each read? +float MagneticSensorAS5145::getSensorAngle() { + float angle_data = readRawAngleSSI(); + angle_data = ( (float)angle_data / AS5145_CPR ) * _2PI; + // return the shaft angle + return angle_data; +} + + +uint16_t MagneticSensorAS5145::readRawAngleSSI() { + spi->beginTransaction(settings); + uint16_t value = spi->transfer16(0x0000); + //uint16_t parity = spi->transfer(0x00); + spi->endTransaction(); + return (value>>3)&0x1FFF; // TODO this isn't what I expected from the datasheet... maybe there's a leading 0 bit? +}; // 12bit angle value diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.h new file mode 100644 index 0000000..ee1f34a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/MagneticSensorAS5145.h @@ -0,0 +1,39 @@ + +#ifndef __MAGNETIC_SENSOR_AS5145_H__ +#define __MAGNETIC_SENSOR_AS5145_H__ + +#include "Arduino.h" +#include "SPI.h" +#include "common/base_classes/Sensor.h" + +#ifndef MSBFIRST +#define MSBFIRST BitOrder::MSBFIRST +#endif + +#define AS5145_BITORDER MSBFIRST +#define AS5145_CPR 4096.0f +#define _2PI 6.28318530718f + + +static SPISettings AS5145SSISettings(1000000, AS5145_BITORDER, SPI_MODE2); // @suppress("Invalid arguments") + + +class MagneticSensorAS5145 : public Sensor { +public: + MagneticSensorAS5145(SPISettings settings = AS5145SSISettings); + virtual ~MagneticSensorAS5145(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); + + uint16_t readRawAngleSSI(); + +private: + SPIClass* spi; + SPISettings settings; +}; + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/README.md new file mode 100644 index 0000000..f0474b9 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5145/README.md @@ -0,0 +1,50 @@ +# AS5145 SimpleFOC driver + +SSI protocol driver for the AMS AS5145 magnetic encoder. Any of the A, B or H variants should work. AS5045 encoders should also be supported. + +Only angle reading is supported, might get to the status bits at a later time. +The SSI protocol is "emulated" using the SPI peripheral. + +Tested with AS5145A on STM32G491 so far. + +## Hardware setup + +Wire the sensor's data (DO) line to the MISO (CIPO) pin, nCS, SCK as normal. Leave the MOSI pin unconnected. + +## Software setup + +``` +#include +#include +#include +#include "encoders/as5145/MagneticSensorAS5145.h" + +MagneticSensorAS5145 sensor; +SPIClass spi_ssi(PB15, PB14, PB13, PB12); + +long ts; + +void setup() { + Serial.begin(115200); + while (!Serial) ; + delay(2000); + + Serial.println("Initializing sensor..."); + + spi_ssi.begin(); + sensor.init(&spi_ssi); + + Serial.println("Sensor initialized."); + + ts = millis(); +} + +void loop() { + sensor.update(); + if (millis() - ts > 1000) { + Serial.println(sensor.getAngle(), 3); + ts = millis(); + } + delay(1); +} +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.cpp new file mode 100644 index 0000000..84e66e2 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.cpp @@ -0,0 +1,175 @@ + + +#include "./AS5600.h" + + +AS5600::AS5600(uint8_t address) : _address(address) {}; +AS5600::~AS5600() {}; + +void AS5600::init(TwoWire* wire){ + _wire = wire; + _wire->begin(); + if (!closeTransactions) { + setAngleRegister(); + } +}; + + +void AS5600::setAngleRegister() { + _wire->beginTransmission(_address); + if (useHysteresis) + _wire->write(AS5600_REG_ANGLE); + else + _wire->write(AS5600_REG_ANGLE_RAW); + _wire->endTransmission(false); +} + + +uint16_t AS5600::angle() { + uint16_t result = 0; + if (!closeTransactions) { + setAngleRegister(); + } + _wire->requestFrom(_address, (uint8_t)2, (uint8_t)closeTransactions); + result = _wire->read()<<8; + result |= _wire->read(); + return result; +}; + + +uint16_t AS5600::readRawAngle() { + return readRegister(AS5600_REG_ANGLE_RAW, 2); +}; + + +uint16_t AS5600::readAngle() { + return readRegister(AS5600_REG_ANGLE, 2); +}; + + + +uint16_t AS5600::readMagnitude() { + return readRegister(AS5600_REG_MAGNITUDE, 2); +}; + + +AS5600Status AS5600::readStatus() { + AS5600Status result; + result.reg = (uint8_t)readRegister(AS5600_REG_STATUS, 1); // TODO: shift bits around + return result; +}; + + +uint8_t AS5600::readAGC() { + return (uint8_t)readRegister(AS5600_REG_AGC, 1); +}; + + + +AS5600Conf AS5600::readConf() { + AS5600Conf result; + result.reg = readRegister(AS5600_REG_CONF, 2); + return result; +}; + + +uint16_t AS5600::readMang() { + return readRegister(AS5600_REG_MANG, 2); +}; + + +uint16_t AS5600::readMPos() { + return readRegister(AS5600_REG_MPOS, 2); +}; + + +uint16_t AS5600::readZPos() { + return readRegister(AS5600_REG_ZPOS, 2); +}; + + +uint8_t AS5600::readZMCO() { + return (readRegister(AS5600_REG_ZMCO, 1)&0x03); +}; + +uint8_t AS5600::readI2CAddr() { + return (readRegister(AS5600_REG_I2CADDR, 1)>>1); +}; + + +// set registers +void AS5600::setConf(AS5600Conf value) { + // TODO: read before write + writeRegister(AS5600_REG_CONF, value.reg); +}; + + +void AS5600::setMang(uint16_t value) { + // TODO: read before write + writeRegister(AS5600_REG_MANG, value); +}; + + +void AS5600::setMPos(uint16_t value) { + // TODO: read before write + writeRegister(AS5600_REG_MPOS, value); +}; + + +void AS5600::setZPos(uint16_t value) { + // TODO: read before write + writeRegister(AS5600_REG_ZPOS, value); +}; + +void AS5600::setI2CAddr(uint8_t value) { + uint8_t val = (uint8_t)readRegister(AS5600_REG_I2CADDR, 1); + val = (value<<1) | (val&0x01); + writeRegister(AS5600_REG_I2CADDR, val); +}; + +void AS5600::setI2CUpdt(uint8_t value) { + uint8_t val = (uint8_t)readRegister(AS5600_REG_I2CUPDT, 1); + val = (value<<1) | (val&0x01); + writeRegister(AS5600_REG_I2CUPDT, val); +}; + + +void AS5600::burnSettings(){ + writeRegister(AS5600_REG_BURN, 0x40, 1); +} + + + +uint16_t AS5600::readRegister(uint8_t reg, uint8_t len){ + uint16_t result = 0; + _wire->beginTransmission(_address); + _wire->write(reg); + _wire->endTransmission(false); + _wire->requestFrom(_address, len, (uint8_t)closeTransactions); + if (!closeTransactions) { + setAngleRegister(); + } + result = _wire->read(); + if (len == 2) { + result <<= 8; + result |= _wire->read(); + } + return result; +}; + + + +void AS5600::writeRegister(uint8_t reg, uint16_t val, uint8_t len){ + _wire->beginTransmission(_address); + _wire->write(reg); + if (len == 2) { + _wire->write(val>>8); + } + _wire->write(val&0xFF); + _wire->endTransmission(closeTransactions); + if (!closeTransactions) { + setAngleRegister(); + } +}; + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.h new file mode 100644 index 0000000..8518c17 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/AS5600.h @@ -0,0 +1,104 @@ + +#pragma once + + +#include +#include + + +#define AS5600_REG_ZMCO 0x00 +#define AS5600_REG_ZPOS 0x01 +#define AS5600_REG_MPOS 0x03 +#define AS5600_REG_MANG 0x05 +#define AS5600_REG_CONF 0x07 + +#define AS5600_REG_I2CADDR 0x20 +#define AS5600_REG_I2CUPDT 0x21 + +#define AS5600_REG_ANGLE 0x0E +#define AS5600_REG_ANGLE_RAW 0x0C + +#define AS5600_REG_STATUS 0x0B +#define AS5600_REG_AGC 0x1A +#define AS5600_REG_MAGNITUDE 0x1B + +#define AS5600_REG_BURN 0xFF + +#define AS5600_CPR (4096.0f) + + +union AS5600Conf { + struct { + uint16_t pm:2; + uint16_t hyst:2; + uint16_t outs:2; + uint16_t pwmf:2; + uint16_t sf:2; + uint16_t fth:3; + uint16_t wd:1; + uint16_t unused:2; + }; + uint16_t reg; +}; + +union AS5600Status { + struct { + uint8_t unused:3; + uint8_t mh:1; + uint8_t ml:1; + uint8_t md:1; + uint8_t unused2:2; + }; + uint8_t reg; +}; + + + + +class AS5600 { +public: + AS5600(uint8_t address = 0x36); + ~AS5600(); + + virtual void init(TwoWire* wire = &Wire); + + // read an angle, either with or without hysteresis, depending on the useHysteresis flag + // and using fast mode (not closing transactions) if so configured + uint16_t angle(); + + // read registers + uint16_t readRawAngle(); + uint16_t readAngle(); + + uint16_t readMagnitude(); + AS5600Status readStatus(); + uint8_t readAGC(); + + AS5600Conf readConf(); + uint16_t readMang(); + uint16_t readMPos(); + uint16_t readZPos(); + uint8_t readZMCO(); + uint8_t readI2CAddr(); + + // set registers + void setConf(AS5600Conf value); + void setMang(uint16_t value); + void setMPos(uint16_t value); + void setZPos(uint16_t value); + void setI2CAddr(uint8_t value); + void setI2CUpdt(uint8_t value); + + void burnSettings(); + + bool closeTransactions = true; + bool useHysteresis = true; + uint8_t _address; +protected: + TwoWire* _wire; + + void setAngleRegister(); + uint16_t readRegister(uint8_t reg, uint8_t len); + void writeRegister(uint8_t reg, uint16_t val, uint8_t len = 2); +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.cpp new file mode 100644 index 0000000..4cea5cf --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.cpp @@ -0,0 +1,18 @@ + + +#include "./MagneticSensorAS5600.h" +#include "common/foc_utils.h" + +MagneticSensorAS5600::MagneticSensorAS5600(uint8_t _address) : AS5600(_address) {}; +MagneticSensorAS5600::~MagneticSensorAS5600() {}; + +void MagneticSensorAS5600::init(TwoWire* wire) { + AS5600::init(wire); + Sensor::init(); +}; + + +float MagneticSensorAS5600::getSensorAngle() { + uint16_t raw = readRawAngle(); + return raw / AS5600_CPR * _2PI; +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.h new file mode 100644 index 0000000..82a8419 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/MagneticSensorAS5600.h @@ -0,0 +1,22 @@ + +#pragma once + + +#include "./AS5600.h" +#include "common/base_classes/Sensor.h" + + +class MagneticSensorAS5600 : public Sensor, public AS5600 { + +public: + MagneticSensorAS5600(uint8_t _address = 0x36); + ~MagneticSensorAS5600(); + + virtual void init(TwoWire* wire = &Wire); + + virtual float getSensorAngle() override; + +protected: + +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/README.md new file mode 100644 index 0000000..eb0f37a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/as5600/README.md @@ -0,0 +1,131 @@ +# AS5600 SimpleFOC driver + +I2C protocol driver for the AMS AS5600 magnetic encoder (digital potentiometer). Also supports the newer AS5600L variant. + +:warning: work in progress + +## Hardware setup + +Connect the sensor to 3.3V or 5V power as appropriate, and to I2C (SDA and SCL). + +Important: please make sure the direction pin (DIR) is either pulled up to VDD, or down to GND. Do not leave the direction pin floating. + +## Software setup + +The sensor driver is easy to use. + +```c++ +#include +#include +#include +#include "encoders/as5600/MagneticSensorAS5600.h" + +MagneticSensorAS5600 sensor; + +void setup() { + sensor.init(); +} + +long ts; + +void loop() { + sensor.update(); + if (millis() - ts > 1000) { + Serial.println(sensor.getAngle(), 3); + ts = millis(); + } + delay(1); +} +``` + +You can use a different I2C bus by passing a pointer to its TwoWire object in the init method: + +```c++ +MagneticSensorAS5600 sensor1; +MagneticSensorAS5600 sensor2; +TwoWire myI2C; + +void setup() { + + ... + + sensor1.init(&myI2C); + sensor2.init(&Wire2); +} +``` + +Using the sensor without releasing the bus should give you considerably more speed. Setting closeTransactions to false means the sensor will not release the bus between angle reads, and also will not re-write the register to the device, which boosts angle reading throughput significantly. + +```c++ +MagneticSensorAS5600 sensor; + +void setup() { + sensor.closeTransactions = false; + sensor.init(); +} +``` + +The sensor's other registers are exposed. Note that using the setter functions to set register values only performs a normal write, not a permanent programing of the register. Permanent programming (BURN function) is not supported by this driver. + +```c++ + +MagneticSensorAS5600 sensor; + +void setup() { + sensor.closeTransactions = false; + sensor.init(); + + uint16_t magnitude = sensor.readMagnitude(); + AS5600Status status = sensor.readStatus(); + // print the values or something +} + +``` + +The AS5600L has a default address of 0x40, and you can set the I2C address. To temporarily change the address (resets to default on restart): + +```c++ + +MagneticSensorAS5600 sensor(0x40); // default address of AS5600L is 0x40 + +void setup() { + Serial.begin(115200); + delay(2000); + + sensor.closeTransactions = true; // use normal transactons + sensor.init(); + sensor.setI2CAddr(0x41); // set address to 0x41 + sensor.setI2CUpdt(0x41); // i2c address is now 0x41 + sensor._address = 0x41; + delay(10); + // sensor is using new address + uint16_t magnitude = sensor.readMagnitude(); +} +``` + + +You can program an I2C address permanently (AS5600L only). The address will remain after reset. This programming operation can only be done once. + +```c++ + +MagneticSensorAS5600 sensor(0x40); // default address of AS5600L is 0x40 + +void setup() { + Serial.begin(115200); + delay(2000); + + sensor.closeTransactions = true; // use normal transactons + sensor.init(); + + uint8_t addr = sensor.readI2CAddr(); // read I2C address, should be 0x40 + Serial.print("Current Address: "); + Serial.println(addr); + + sensor.setI2CAddr(0x41); // set address to 0x41 + sensor.burnSettings(); // permanently set new address + Serial.println("Permanently changed address to 0x41. Restart the system."); + while (1); +} + + +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.cpp new file mode 100644 index 0000000..e3d579c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.cpp @@ -0,0 +1,257 @@ +#include "CalibratedSensor.h" + + +// CalibratedSensor() +// sensor - instance of original sensor object +CalibratedSensor::CalibratedSensor(Sensor& wrapped) : _wrapped(wrapped) +{ +}; + + +CalibratedSensor::~CalibratedSensor() +{ + delete calibrationLut; +}; + +// call update of calibrated sensor +void CalibratedSensor::update(){ + _wrapped.update(); + this->Sensor::update(); +}; + +// Retrieve the calibrated sensor angle +void CalibratedSensor::init() { + // assume wrapped sensor has already been initialized + this->Sensor::init(); // call superclass init +} + +// Retrieve the calibrated sensor angle +float CalibratedSensor::getSensorAngle(){ + // raw encoder position e.g. 0-2PI + float rawAngle = _wrapped.getMechanicalAngle(); + + // index of the bucket that rawAngle is part of. + // e.g. rawAngle = 0 --> bucketIndex = 0. + // e.g. rawAngle = 2PI --> bucketIndex = 128. + int bucketIndex = floor(rawAngle/(_2PI/n_lut)); + float remainder = rawAngle - ((_2PI/n_lut)*bucketIndex); + + // Extract the lower and upper LUT value in counts + float y0 = calibrationLut[bucketIndex]; + float y1 = calibrationLut[(bucketIndex+1)%n_lut]; + + // Linear Interpolation Between LUT values y0 and y1 using the remainder + // If remainder = 0, interpolated offset = y0 + // If remainder = 2PI/n_lut, interpolated offset = y1 + float interpolatedOffset = (((_2PI/n_lut)-remainder)/(_2PI/n_lut))*y0 + (remainder/(_2PI/n_lut))*y1; + + // add offset to the raw sensor count. Divide multiply by 2PI/CPR to get radians + float calibratedAngle = rawAngle+interpolatedOffset; + + // return calibrated angle in radians + return calibratedAngle; +} + +void CalibratedSensor::calibrate(BLDCMotor& motor){ + + Serial.println("Starting Sensor Calibration."); + + int _NPP = motor.pole_pairs; // number of pole pairs which is user input + const int n_ticks = 128*_NPP; // number of positions to be sampled per mechanical rotation. Multiple of NPP for filtering reasons (see later) + const int n2_ticks = 40; // increments between saved samples (for smoothing motion) + float deltaElectricalAngle = _2PI*_NPP/(n_ticks*n2_ticks); // Electrical Angle increments for calibration steps + float* error_f = new float[n_ticks](); // pointer to error array rotating forwards + // float* raw_f = new float[n_ticks](); // pointer to raw forward position + float* error_b = new float[n_ticks](); // pointer to error array rotating forwards + // float* raw_b = new float[n_ticks](); // pointer to raw backword position + float* error = new float[n_ticks](); // pointer to error array (average of forward & backward) + float* error_filt = new float[n_ticks](); // pointer to filtered error array (low pass filter) + const int window = 128; // window size for moving average filter of raw error + motor.zero_electric_angle = 0; // Set position sensor offset + + // find natural direction (this is copy of the init code) + // move one electrical revolution forward + for (int i = 0; i <=500; i++ ) { + float angle = _3PI_2 + _2PI * i / 500.0f; + motor.setPhaseVoltage(voltage_calibration, 0, angle); + _wrapped.update(); + _delay(2); + } + // take and angle in the middle + _wrapped.update(); + float mid_angle = _wrapped.getAngle(); + // move one electrical revolution backwards + for (int i = 500; i >=0; i-- ) { + float angle = _3PI_2 + _2PI * i / 500.0f ; + motor.setPhaseVoltage(voltage_calibration, 0, angle); + _wrapped.update(); + _delay(2); + } + _wrapped.update(); + float end_angle = _wrapped.getAngle(); + motor.setPhaseVoltage(0, 0, 0); + _delay(200); + // determine the direction the sensor moved + int directionSensor; + if (mid_angle < end_angle) { + Serial.println("MOT: sensor_direction==CCW"); + directionSensor = -1; + motor.sensor_direction = Direction::CCW; + + } else{ + Serial.println("MOT: sensor_direction==CW"); + directionSensor = 1; + motor.sensor_direction = Direction::CW; + + } + + //Set voltage angle to zero, wait for rotor position to settle + // keep the motor in position while getting the initial positions + motor.setPhaseVoltage(voltage_calibration, 0, elec_angle); + _delay(1000); + _wrapped.update(); + float theta_init = _wrapped.getAngle(); + float theta_absolute_init = _wrapped.getMechanicalAngle(); + + /* + Start Calibration + Loop over electrical angles from 0 to NPP*2PI, once forward, once backward + store actual position and error as compared to electrical angle + */ + + /* + forwards rotation + */ + Serial.println("Rotating forwards"); + int k = 0; + for(int i = 0; i n_ticks-1) { + ind -= n_ticks;} + error_filt[i] += error[ind]/(float)window; + } + mean += error_filt[i]/n_ticks; + } + + // calculate offset index + int index_offset = floor(raw_offset/(_2PI/n_lut)); + + // Build Look Up Table + for (int i = 0; i (n_lut-1)){ + ind -= n_lut; + } + if(ind < 0 ){ + ind += n_lut; + } + calibrationLut[ind] = (float) (error_filt[i*_NPP] - mean); + //Serial.print(ind); + //Serial.print('\t'); + //Serial.println(calibrationLut[ind],5); + _delay(1); + } + + // de-allocate memory + delete error_filt; + delete error; + // delete raw_b; + delete error_b; + // delete raw_f; + delete error_f; + + Serial.println("Sensor Calibration Done."); + +} + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.h new file mode 100644 index 0000000..414c53a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/CalibratedSensor.h @@ -0,0 +1,61 @@ +#ifndef __CALIBRATEDSENSOR_H__ +#define __CALIBRATEDSENSOR_H__ + +#include "common/base_classes/Sensor.h" +#include "BLDCMotor.h" +#include "common/base_classes/FOCMotor.h" + + +class CalibratedSensor: public Sensor{ + +public: + // constructor of class with pointer to base class sensor and driver + CalibratedSensor(Sensor& wrapped); + ~CalibratedSensor(); + + /* + Override the update function + */ + virtual void update() override; + + /** + * Calibrate method computes the LUT for the correction + */ + virtual void calibrate(BLDCMotor& motor); + + // voltage to run the calibration: user input + float voltage_calibration = 1; + +protected: + + /** + * getSenorAngle() method of CalibratedSensor class. + * This should call getAngle() on the wrapped instance, and then apply the correction to + * the value returned. + */ + virtual float getSensorAngle() override; + /** + * init method of CaibratedSensor - call after calibration + */ + virtual void init() override; + /** + * delegate instance of Sensor class + */ + Sensor& _wrapped; + + // lut size, currently constan. Perhaps to be made variable by user? + const int n_lut { 128 } ; + // create pointer for lut memory + float* calibrationLut = new float[n_lut](); + + // Init inital angles + float theta_actual { 0.0 }; + float elecAngle { 0.0 }; + float elec_angle { 0.0 }; + float theta_absolute_post { 0.0 }; + float theta_absolute_init { 0.0 }; + float theta_init { 0.0 }; + float avg_elec_angle { 0.0 }; +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/README.md new file mode 100644 index 0000000..5768d92 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/calibrated/README.md @@ -0,0 +1,91 @@ +# Calibrated Sensor + +by [@MarethyuPrefect](https://github.com/MarethyuPrefect) + +A SimpleFOC Sensor wrapper implementation which adds sensor eccentricity calibration. + +Please also see our [forum thread](https://community.simplefoc.com/t/simplefoc-sensor-eccentricity-calibration/2212) on this topic. + + +When you mount your (magnetic) sensor on your frame or motor, there will always be a slight misalignment between magnet and sensor (measurement system). This misalignment between center of rotation and the center of the sensor is called the eccentricity error. + +As a result your measurement system output is non-linear with respect to the rotor of the motor. This will cause an error with respect to the ideal torque you attempt to create with the I_q vector as function of the position. You could interpret this as a disturbance on your control loop which you want to minimize for optimal performance. + +This calibration compensates the sensor reading in a feed forward fashion such that your performance improves. + + +## Hardware setup + +Connect your sensor as usual. Make sure the sensor is working 'normally' i.e. without calibration first. Once things are working and tuned without sensor calibration, you can add the CalibratedSensor to see if you get an improvement. + +Note that during calibration, the motor is turned through several turns, and should be in an unloaded condition. Please ensure your hardware setup can support the motor rotating through full turns. + + +## Softwate setup + +The CalibratedSensor acts as a wrapper to the actual sensor class. When creating the CalibratedSensor object, provide the real +sensor to the constructor of CalibratedSensor. + +First, initialize the real sensor instance as normal. Then, call calibrate() on the CalibratedSensor instance. Then link the +CalibratedSensor to the motor and call motor.initFOC(). + +The motor will then use the calibrated sensor instance. + + +```c++ +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5048_SPI, PB6); +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(PB4,PC7,PB10,PA9); +// instantiate the calibrated sensor, providing the real sensor as a constructor argument +CalibratedSensor sensor_calibrated = CalibratedSensor(sensor); + +void setup() { + sensor.init(); + // Link motor to sensor + motor.linkSensor(&sensor); + // power supply voltage + driver.voltage_power_supply = 20; + driver.init(); + motor.linkDriver(&driver); + // aligning voltage + motor.voltage_sensor_align = 8; + motor.voltage_limit = 20; + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_variables = _MON_VEL; + motor.monitor_downsample = 10; // default 10 + + // initialize motor + motor.init(); + + // set voltage to run calibration + sensor_calibrated.voltage_calibration = 6; + // Running calibration + sensor_calibrated.calibrate(motor); + + //Serial.println("Calibrating Sensor Done."); + // Linking sensor to motor object + motor.linkSensor(&sensor_calibrated); + + // calibrated init FOC + motor.initFOC(); +} +``` + +Please see the more complete [example](https://github.com/simplefoc/Arduino-FOC-drivers/blob/master/examples/encoders/calibrated/sensor_calibration.ino) in our examples directory. + + +## Roadmap + +Possible future improvements we've thought about: + +- Improve memory usage and performance +- Make calibration able to be saved/restored + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.cpp new file mode 100644 index 0000000..6e5eac0 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.cpp @@ -0,0 +1,146 @@ +#include "MA330.h" + +MA330::MA330(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + +}; +MA330::~MA330() { + +}; + +void MA330::init(SPIClass* _spi) { + spi = _spi; + if (nCS >= 0) { + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + } +}; + +float MA330::getCurrentAngle() { + return (readRawAngle() * _2PI)/MA330_CPR; +}; // angle in radians, return current value + +uint16_t MA330::readRawAngle() { + uint16_t angle = transfer16(0x0000); + return angle; +}; // 9-14bit angle value + +uint16_t MA330::getZero() { + uint16_t result = readRegister(MA330_REG_ZERO_POSITION_MSB)<<8; + result |= readRegister(MA330_REG_ZERO_POSITION_LSB); + return result; +}; +uint8_t MA330::getBiasCurrentTrimming() { + return readRegister(MA330_REG_BCT); +}; +bool MA330::isBiasCurrrentTrimmingX() { + return (readRegister(MA330_REG_ET) & 0x01)==0x01; +}; +bool MA330::isBiasCurrrentTrimmingY() { + return (readRegister(MA330_REG_ET) & 0x02)==0x02; +}; +uint16_t MA330::getPulsesPerTurn() { + uint16_t result = readRegister(MA330_REG_ILIP_PPT_LSB)>>6; + result |= ((uint16_t)readRegister(MA330_REG_PPT_MSB))<<2; + return result+1; +}; +uint8_t MA330::getIndexLength() { + return (readRegister(MA330_REG_ILIP_PPT_LSB)>>2)&0x0F; +}; +uint8_t MA330::getNumberPolePairs() { + return (readRegister(MA330_REG_NPP)>>5)&0x07;; +}; +uint8_t MA330::getRotationDirection() { + return (readRegister(MA330_REG_RD)>>7); +}; +uint8_t MA330::getFieldStrengthHighThreshold() { + return (readRegister(MA330_REG_MGLT_MGHT)>>2)&0x07; +}; +uint8_t MA330::getFieldStrengthLowThreshold() { + return (readRegister(MA330_REG_MGLT_MGHT)>>5)&0x07; +}; +uint8_t MA330::getFilterWidth() { + return readRegister(MA330_REG_FW); +}; +uint8_t MA330::getHysteresis() { + return readRegister(MA330_REG_HYS); +}; +FieldStrength MA330::getFieldStrength() { + return (FieldStrength)(readRegister(MA330_REG_MGH_MGL)>>6); +}; + + + +void MA330::setZero(uint16_t value) { + writeRegister(MA330_REG_ZERO_POSITION_MSB, value>>8); + writeRegister(MA330_REG_ZERO_POSITION_LSB, value&0x00FF); +}; +void MA330::setBiasCurrentTrimming(uint8_t value) { + writeRegister(MA330_REG_BCT, value); +}; +void MA330::setBiasCurrrentTrimmingEnabled(bool Xenabled, bool Yenabled) { + uint8_t val = Xenabled ? 0x01 : 0x00; + val |= (Yenabled ? 0x02 : 0x00); + writeRegister(MA330_REG_ET, val); +}; +void MA330::setPulsesPerTurn(uint16_t value) { + uint16_t pptVal = value - 1; + writeRegister(MA330_REG_PPT_MSB, pptVal>>2); + uint8_t val = readRegister(MA330_REG_ILIP_PPT_LSB); + val &= 0x3F; + val |= (pptVal&0x03)<<6; + writeRegister(MA330_REG_ILIP_PPT_LSB, val); +}; +void MA330::setIndexLength(uint8_t value) { + uint8_t val = readRegister(MA330_REG_ILIP_PPT_LSB); + val &= 0xC0; + val |= ((value<<2)&0x3F); + writeRegister(MA330_REG_ILIP_PPT_LSB, val); +}; +void MA330::setNumberPolePairs(uint8_t value) { + uint8_t val = readRegister(MA330_REG_NPP); + val &= 0x1F; + val |= (value<<5); + writeRegister(MA330_REG_NPP, val); +}; +void MA330::setRotationDirection(uint8_t value) { + if (value==0) + writeRegister(MA330_REG_RD, 0x00); + else + writeRegister(MA330_REG_RD, 0x80); +}; +void MA330::setFilterWidth(uint8_t value) { + writeRegister(MA330_REG_FW, value); +}; +void MA330::setHysteresis(uint8_t value) { + writeRegister(MA330_REG_HYS, value); +}; +void MA330::setFieldStrengthThresholds(uint8_t high, uint8_t low) { + uint8_t val = (low<<5) | (high<<2); + writeRegister(MA330_REG_MGLT_MGHT, val); +}; + + +uint16_t MA330::transfer16(uint16_t outValue) { + if (nCS >= 0) + digitalWrite(nCS, LOW); + spi->beginTransaction(settings); + uint16_t value = spi->transfer16(outValue); + spi->endTransaction(); + if (nCS >= 0) + digitalWrite(nCS, HIGH); + return value; +}; +uint8_t MA330::readRegister(uint8_t reg) { + uint16_t cmd = 0x4000 | ((reg&0x001F)<<8); + uint16_t value = transfer16(cmd); + delayMicroseconds(1); + value = transfer16(0x0000); + return value>>8; +}; +uint8_t MA330::writeRegister(uint8_t reg, uint8_t value) { + uint16_t cmd = 0x8000 | ((reg&0x1F)<<8) | value; + uint16_t result = transfer16(cmd); + delay(20); // 20ms delay required + result = transfer16(0x0000); + return result>>8; +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.h new file mode 100644 index 0000000..4b89bc9 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MA330.h @@ -0,0 +1,82 @@ +#ifndef __MA330_H__ +#define __MA330_H__ + + +#include "Arduino.h" +#include "SPI.h" + +enum FieldStrength : uint8_t { + FS_NORMAL = 0x00, + FS_LOW = 0x01, + FS_HIGH = 0x02, + FS_ERR = 0x03 // impossible state +}; + + +#define _2PI 6.28318530718f +#define MA330_CPR 65536.0f + +#define MA330_REG_ZERO_POSITION_LSB 0x00 +#define MA330_REG_ZERO_POSITION_MSB 0x01 +#define MA330_REG_BCT 0x02 +#define MA330_REG_ET 0x03 +#define MA330_REG_ILIP_PPT_LSB 0x04 +#define MA330_REG_PPT_MSB 0x05 +#define MA330_REG_MGLT_MGHT 0x06 +#define MA330_REG_NPP 0x07 +#define MA330_REG_RD 0x09 +#define MA330_REG_FW 0x0E +#define MA330_REG_HYS 0x10 +#define MA330_REG_MGH_MGL 0x1B + +#define MA330_BITORDER MSBFIRST + +static SPISettings MA330SPISettings(1000000, MA330_BITORDER, SPI_MODE3); // @suppress("Invalid arguments") + +class MA330 { +public: + MA330(SPISettings settings = MA330SPISettings, int nCS = -1); + virtual ~MA330(); + + virtual void init(SPIClass* _spi = &SPI); + + float getCurrentAngle(); // angle in radians, return current value + + uint16_t readRawAngle(); // 9-14bit angle value + + uint16_t getZero(); + uint8_t getBiasCurrentTrimming(); + bool isBiasCurrrentTrimmingX(); + bool isBiasCurrrentTrimmingY(); + uint16_t getPulsesPerTurn(); + uint8_t getIndexLength(); + uint8_t getNumberPolePairs(); + uint8_t getRotationDirection(); + uint8_t getFilterWidth(); + uint8_t getHysteresis(); + uint8_t getFieldStrengthHighThreshold(); + uint8_t getFieldStrengthLowThreshold(); + FieldStrength getFieldStrength(); + + void setZero(uint16_t); + void setBiasCurrentTrimming(uint8_t); + void setBiasCurrrentTrimmingEnabled(bool Xenabled, bool Yenabled); + void setPulsesPerTurn(uint16_t); + void setIndexLength(uint8_t); + void setNumberPolePairs(uint8_t); + void setRotationDirection(uint8_t); + void setFilterWidth(uint8_t); + void setHysteresis(uint8_t); + void setFieldStrengthThresholds(uint8_t high, uint8_t low); + +private: + SPIClass* spi; + SPISettings settings; + int nCS = -1; + + uint16_t transfer16(uint16_t outValue); + uint8_t readRegister(uint8_t reg); + uint8_t writeRegister(uint8_t reg, uint8_t value); +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.cpp new file mode 100644 index 0000000..a884065 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.cpp @@ -0,0 +1,26 @@ +#include "./MagneticSensorMA330.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorMA330::MagneticSensorMA330(int nCS, SPISettings settings) : MA330(settings, nCS) { + +} + + +MagneticSensorMA330::~MagneticSensorMA330(){ + +} + + +void MagneticSensorMA330::init(SPIClass* _spi) { + this->MA330::init(_spi); + this->Sensor::init(); +} + + +float MagneticSensorMA330::getSensorAngle() { + float angle_data = readRawAngle(); + angle_data = ( angle_data / (float)MA330_CPR) * _2PI; + // return the shaft angle + return angle_data; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.h new file mode 100644 index 0000000..1befbdf --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/MagneticSensorMA330.h @@ -0,0 +1,19 @@ +#ifndef __MAGNETIC_SENSOR_MA330_H__ +#define __MAGNETIC_SENSOR_MA330_H__ + + +#include "common/base_classes/Sensor.h" +#include "./MA330.h" + +class MagneticSensorMA330 : public Sensor, public MA330 { +public: + MagneticSensorMA330(int nCS = -1, SPISettings settings = MA330SPISettings); + virtual ~MagneticSensorMA330(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/README.md new file mode 100644 index 0000000..fcf635d --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma330/README.md @@ -0,0 +1,66 @@ +# MA330 SimpleFOC driver + +While MA330 absolute position magnetic rotary encoder is supported by the standard MagneticSensorSPI driver included in the base distribution, this MA330-specific driver includes some optimisations: + +- access to the other registers of the MA330 +- this driver directly reads the angle with one call to SPI +- this will halve the number of 16-bit SPI transfers per simpleFOC loop iteration + + +## Hardware setup + +Connect as per normal for your SPI bus. No special hardware setup is needed to use this driver. + +## Software setup + +Its actually easier to use than the standard SPI sensor class, because it is less generic: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/MA330/MagneticSensorMA330.h" + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorMA330 sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +Set some options: + +```c++ +MagneticSensorMA330 sensor1(SENSOR1_CS, true, mySPISettings); +``` + +Use another SPI bus: + +```c++ +void setup() { + sensor1.init(SPI2); +} +``` + +Here's how you can use it: + +```c++ + // update the sensor (only needed if using the sensor without a motor) + sensor1.update(); + + // get the angle, in radians, including full rotations + float a1 = sensor1.getAngle(); + + // get the velocity, in rad/s - note: you have to call getAngle() on a regular basis for it to work + float v1 = sensor1.getVelocity(); + + // get the angle, in radians, no full rotations + float a2 = sensor1.getCurrentAngle(); + + // get the raw 14 bit value + uint16_t raw = sensor1.readRawAngle(); +``` diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.cpp new file mode 100644 index 0000000..7a1b7b8 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.cpp @@ -0,0 +1,125 @@ +#include "MA730.h" + +MA730::MA730(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + +}; +MA730::~MA730() { + +}; + +void MA730::init(SPIClass* _spi) { + spi = _spi; + if (nCS >= 0) { + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + } +}; + +float MA730::getCurrentAngle() { + return (readRawAngle() * _2PI)/MA730_CPR; +}; // angle in radians, return current value + +uint16_t MA730::readRawAngle() { + uint16_t angle = transfer16(0x0000); + return angle; +}; // 14bit angle value + +uint16_t MA730::getZero() { + uint16_t result = readRegister(MA730_REG_ZERO_POSITION_MSB)<<8; + result |= readRegister(MA730_REG_ZERO_POSITION_LSB); + return result; +}; +uint8_t MA730::getBiasCurrentTrimming() { + return readRegister(MA730_REG_BCT); +}; +bool MA730::isBiasCurrrentTrimmingX() { + return (readRegister(MA730_REG_ET) & 0x01)==0x01; +}; +bool MA730::isBiasCurrrentTrimmingY() { + return (readRegister(MA730_REG_ET) & 0x02)==0x02; +}; +uint16_t MA730::getPulsesPerTurn() { + uint16_t result = readRegister(MA730_REG_ILIP_PPT_LSB)>>6; + result |= ((uint16_t)readRegister(MA730_REG_PPT_MSB))<<2; + return result+1; +}; +uint8_t MA730::getIndexLength() { + return (readRegister(MA730_REG_ILIP_PPT_LSB)>>2)&0x0F; +}; +uint8_t MA730::getRotationDirection() { + return (readRegister(MA730_REG_RD)>>7); +}; +uint8_t MA730::getFieldStrengthHighThreshold() { + return (readRegister(MA730_REG_MGLT_MGHT)>>2)&0x07; +}; +uint8_t MA730::getFieldStrengthLowThreshold() { + return (readRegister(MA730_REG_MGLT_MGHT)>>5)&0x07; +}; +FieldStrength MA730::getFieldStrength() { + return (FieldStrength)(readRegister(MA730_REG_MGH_MGL)>>6); +}; + + + +void MA730::setZero(uint16_t value) { + writeRegister(MA730_REG_ZERO_POSITION_MSB, value>>8); + writeRegister(MA730_REG_ZERO_POSITION_LSB, value&0x00FF); +}; +void MA730::setBiasCurrentTrimming(uint8_t value) { + writeRegister(MA730_REG_BCT, value); +}; +void MA730::setBiasCurrrentTrimmingEnabled(bool Xenabled, bool Yenabled) { + uint8_t val = Xenabled ? 0x01 : 0x00; + val |= (Yenabled ? 0x02 : 0x00); + writeRegister(MA730_REG_ET, val); +}; +void MA730::setPulsesPerTurn(uint16_t value) { + uint16_t pptVal = value - 1; + writeRegister(MA730_REG_PPT_MSB, pptVal>>2); + uint8_t val = readRegister(MA730_REG_ILIP_PPT_LSB); + val &= 0x3F; + val |= (pptVal&0x03)<<6; + writeRegister(MA730_REG_ILIP_PPT_LSB, val); +}; +void MA730::setIndexLength(uint8_t value) { + uint8_t val = readRegister(MA730_REG_ILIP_PPT_LSB); + val &= 0xC0; + val |= ((value<<2)&0x3F); + writeRegister(MA730_REG_ILIP_PPT_LSB, val); +}; +void MA730::setRotationDirection(uint8_t value) { + if (value==0) + writeRegister(MA730_REG_RD, 0x00); + else + writeRegister(MA730_REG_RD, 0x80); +}; +void MA730::setFieldStrengthThresholds(uint8_t high, uint8_t low) { + uint8_t val = (low<<5) | (high<<2); + writeRegister(MA730_REG_MGLT_MGHT, val); +}; + + +uint16_t MA730::transfer16(uint16_t outValue) { + if (nCS >= 0) + digitalWrite(nCS, LOW); + spi->beginTransaction(settings); + uint16_t value = spi->transfer16(outValue); + spi->endTransaction(); + if (nCS >= 0) + digitalWrite(nCS, HIGH); + return value; +}; +uint8_t MA730::readRegister(uint8_t reg) { + uint16_t cmd = 0x4000 | ((reg&0x001F)<<8); + uint16_t value = transfer16(cmd); + delayMicroseconds(1); + value = transfer16(0x0000); + return value>>8; +}; +uint8_t MA730::writeRegister(uint8_t reg, uint8_t value) { + uint16_t cmd = 0x8000 | ((reg&0x1F)<<8) | value; + uint16_t result = transfer16(cmd); + delay(20); // 20ms delay required + result = transfer16(0x0000); + return result>>8; +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.h new file mode 100644 index 0000000..56b0b5a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MA730.h @@ -0,0 +1,76 @@ +#ifndef __MA730_H__ +#define __MA730_H__ + + +#include "Arduino.h" +#include "SPI.h" + +enum FieldStrength : uint8_t { + FS_NORMAL = 0x00, + FS_LOW = 0x01, + FS_HIGH = 0x02, + FS_ERR = 0x03 // impossible state +}; + + +#define _2PI 6.28318530718f +#define MA730_CPR 65536.0f + +#define MA730_REG_ZERO_POSITION_LSB 0x00 +#define MA730_REG_ZERO_POSITION_MSB 0x01 +#define MA730_REG_BCT 0x02 +#define MA730_REG_ET 0x03 +#define MA730_REG_ILIP_PPT_LSB 0x04 +#define MA730_REG_PPT_MSB 0x05 +#define MA730_REG_MGLT_MGHT 0x06 +#define MA730_REG_RD 0x09 +#define MA730_REG_MGH_MGL 0x1B + +#define MA730_BITORDER MSBFIRST + +static SPISettings MA730SPISettings(1000000, MA730_BITORDER, SPI_MODE3); // @suppress("Invalid arguments") +static SPISettings MA730SSISettings(4000000, MA730_BITORDER, SPI_MODE1); // @suppress("Invalid arguments") + + +class MA730 { +public: + MA730(SPISettings settings = MA730SPISettings, int nCS = -1); + virtual ~MA730(); + + virtual void init(SPIClass* _spi = &SPI); + + float getCurrentAngle(); // angle in radians, return current value + + uint16_t readRawAngle(); // 14bit angle value + uint16_t readRawAngleSSI(); // 14bit angle value + + uint16_t getZero(); + uint8_t getBiasCurrentTrimming(); + bool isBiasCurrrentTrimmingX(); + bool isBiasCurrrentTrimmingY(); + uint16_t getPulsesPerTurn(); + uint8_t getIndexLength(); + uint8_t getRotationDirection(); + uint8_t getFieldStrengthHighThreshold(); + uint8_t getFieldStrengthLowThreshold(); + FieldStrength getFieldStrength(); + + void setZero(uint16_t); + void setBiasCurrentTrimming(uint8_t); + void setBiasCurrrentTrimmingEnabled(bool Xenabled, bool Yenabled); + void setPulsesPerTurn(uint16_t); + void setIndexLength(uint8_t); + void setRotationDirection(uint8_t); + void setFieldStrengthThresholds(uint8_t high, uint8_t low); + +private: + SPIClass* spi; + SPISettings settings; + int nCS = -1; + + uint16_t transfer16(uint16_t outValue); + uint8_t readRegister(uint8_t reg); + uint8_t writeRegister(uint8_t reg, uint8_t value); +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.cpp new file mode 100644 index 0000000..320618e --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.cpp @@ -0,0 +1,26 @@ +#include "./MagneticSensorMA730.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorMA730::MagneticSensorMA730(int nCS, SPISettings settings) : MA730(settings, nCS) { + +} + + +MagneticSensorMA730::~MagneticSensorMA730(){ + +} + + +void MagneticSensorMA730::init(SPIClass* _spi) { + this->MA730::init(_spi); + this->Sensor::init(); +} + + +float MagneticSensorMA730::getSensorAngle() { + float angle_data = readRawAngle(); + angle_data = ( angle_data / (float)MA730_CPR) * _2PI; + // return the shaft angle + return angle_data; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.h new file mode 100644 index 0000000..d579657 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730.h @@ -0,0 +1,19 @@ +#ifndef __MAGNETIC_SENSOR_MA730_H__ +#define __MAGNETIC_SENSOR_MA730_H__ + + +#include "common/base_classes/Sensor.h" +#include "./MA730.h" + +class MagneticSensorMA730 : public Sensor, public MA730 { +public: + MagneticSensorMA730(int nCS = -1, SPISettings settings = MA730SPISettings); + virtual ~MagneticSensorMA730(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.cpp new file mode 100644 index 0000000..bf87b2b --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.cpp @@ -0,0 +1,34 @@ +#include "./MagneticSensorMA730SSI.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorMA730SSI::MagneticSensorMA730SSI(SPISettings settings) : settings(settings) { + +} + + +MagneticSensorMA730SSI::~MagneticSensorMA730SSI() { + +} + +void MagneticSensorMA730SSI::init(SPIClass* _spi) { + this->spi=_spi; + this->Sensor::init(); +} + +// check 40us delay between each read? +float MagneticSensorMA730SSI::getSensorAngle() { + float angle_data = readRawAngleSSI(); + angle_data = ( angle_data / (float)MA730_CPR ) * _2PI; + // return the shaft angle + return angle_data; +} + + +uint16_t MagneticSensorMA730SSI::readRawAngleSSI() { + spi->beginTransaction(settings); + uint16_t value = spi->transfer16(0x0000); + //uint16_t parity = spi->transfer(0x00); + spi->endTransaction(); + return (value<<1); //>>1)&0x3FFF; +}; // 14bit angle value diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.h new file mode 100644 index 0000000..f45071f --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/MagneticSensorMA730SSI.h @@ -0,0 +1,25 @@ +#ifndef __MAGNETIC_SENSOR_MA730SSI_H__ +#define __MAGNETIC_SENSOR_MA730SSI_H__ + + +#include "common/base_classes/Sensor.h" +#include "./MA730.h" + +class MagneticSensorMA730SSI : public Sensor { +public: + MagneticSensorMA730SSI(SPISettings settings = MA730SSISettings); + virtual ~MagneticSensorMA730SSI(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); + + uint16_t readRawAngleSSI(); + +private: + SPIClass* spi; + SPISettings settings; +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/README.md new file mode 100644 index 0000000..1f88290 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/ma730/README.md @@ -0,0 +1,74 @@ +# MA730 SimpleFOC driver + +While MA730 absolute position magnetic rotary encoder is supported by the standard MagneticSensorSPI driver included in the base distribution, this MA730-specific driver includes some optimisations: + +- access to the other registers of the MA730 +- this driver directly reads the angle with one call to SPI +- this will halve the number of 16-bit SPI transfers per simpleFOC loop iteration + + +## Hardware setup + +Connect as per normal for your SPI bus. No special hardware setup is needed to use this driver. + +## Software setup + +Its actually easier to use than the standard SPI sensor class, because it is less generic: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/ma730/MagneticSensorMA730.h" + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorMA730 sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +Set some options: + +```c++ +MagneticSensorMA730 sensor1(SENSOR1_CS, mySPISettings); +``` + +Use another SPI bus: + +```c++ +void setup() { + sensor1.init(&SPI2); +} +``` + +Here's how you can use it: + +```c++ + // update the sensor (only needed if using the sensor without a motor) + sensor1.update(); + + // get the angle, in radians, including full rotations + float a1 = sensor1.getAngle(); + + // get the velocity, in rad/s - note: you have to call getAngle() on a regular basis for it to work + float v1 = sensor1.getVelocity(); + + // get the angle, in radians, no full rotations + float a2 = sensor1.getCurrentAngle(); + + // get the raw 14 bit value + uint16_t raw = sensor1.readRawAngle(); + + // get the field strength + FieldStrength fs = sensor1.getFieldStrength(); + Serial.print("Field strength: "); + Serial.println(fs); + + // set pulses per turn for encoder mode + sensor1.setPulsesPerTurn(999); // set to 999 if we want 1000 PPR == 4000 CPR +``` diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.cpp new file mode 100644 index 0000000..01e8d97 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.cpp @@ -0,0 +1,42 @@ +#include "./MagneticSensorMT6701SSI.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorMT6701SSI::MagneticSensorMT6701SSI(int nCS, SPISettings settings) : settings(settings), nCS(nCS) { + +} + + +MagneticSensorMT6701SSI::~MagneticSensorMT6701SSI() { + +} + +void MagneticSensorMT6701SSI::init(SPIClass* _spi) { + this->spi=_spi; + if (nCS >= 0) { + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + } + this->spi->begin(); + this->Sensor::init(); +} + +// check 40us delay between each read? +float MagneticSensorMT6701SSI::getSensorAngle() { + float angle_data = readRawAngleSSI(); + angle_data = ( angle_data / (float)MT6701_CPR ) * _2PI; + // return the shaft angle + return angle_data; +} + + +uint16_t MagneticSensorMT6701SSI::readRawAngleSSI() { + if (nCS >= 0) + digitalWrite(nCS, LOW); + spi->beginTransaction(settings); + uint16_t value = spi->transfer16(0x0000); + spi->endTransaction(); + if (nCS >= 0) + digitalWrite(nCS, HIGH); + return (value>>MT6701_DATA_POS)&0x3FFF; +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.h new file mode 100644 index 0000000..32abd1d --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/MagneticSensorMT6701SSI.h @@ -0,0 +1,43 @@ +#ifndef __MAGNETIC_SENSOR_MT6701_SSI_H__ +#define __MAGNETIC_SENSOR_MT6701_SSI_H__ + +#include "Arduino.h" +#include "SPI.h" +#include "common/base_classes/Sensor.h" + + +#define MT6701_CPR 16384.0f + +#define MT6701_BITORDER MSBFIRST + +#if defined(TARGET_RP2040)||defined(ESP_H)||defined(CORE_TEENSY) +#define MT6701_DATA_POS 1 +#else +#define MT6701_DATA_POS 2 +#endif + +// Use SPI mode 2, capture on falling edge. First bit is not valid data, so have to read 25 bits to get a full SSI frame. +// SSI frame is 1 bit ignore, 14 bits angle, 4 bit status and 6 bit CRC. +static SPISettings MT6701SSISettings(1000000, MT6701_BITORDER, SPI_MODE2); // @suppress("Invalid arguments") + + + +class MagneticSensorMT6701SSI : public Sensor { +public: + MagneticSensorMT6701SSI(int nCS = -1, SPISettings settings = MT6701SSISettings); + virtual ~MagneticSensorMT6701SSI(); + + virtual void init(SPIClass* _spi = &SPI); + + float getSensorAngle() override; // angle in radians, return current value + +protected: + uint16_t readRawAngleSSI(); + + SPISettings settings; + SPIClass* spi; + int nCS = -1; +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/README.md new file mode 100644 index 0000000..df04808 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6701/README.md @@ -0,0 +1,82 @@ +# MT6701 SimpleFOC driver + +:warning: work in progress... SSI driver is working. I2C not yet complete. + +Due to the peculiarities of its interfaces, this very versatile sensor is not directly supported by SimpleFOC's SPI or I2C magnetic sensor implementations. This folder contains dedicated SimpleFOC sensor drivers for the MT6701 for I2C and SSI. + +Note: the ABZ, UVW and Analog outputs of this sensor are supported by the standard SimpleFOC encoder, hall-sensor or analog sensor classes respectively. + +:warning: Note: the I2C output of this sensor is probably too slow for high performance motor control, but could be useful to program the sensor IC, and to read the absolute angle values for intializing ABZ or UVW modes. + +## Hardware setup + +For I2C, connect the sensor as normal for I2C, using the SDA and SCL lines. + +:warning: Note: to program the sensor via I2C, it has to be operated at 5V. + +For SSI, connect the CSN line to the nCS output of your MCU, the CLK line to the SCLK output of the MCU, and the DO line to the CIPO (MISO) input of the MCU. + +In my tests, the sensor was not able to work correctly together with other SPI devices on the same bus, but your experience might differ from mine. + +## Software setup + +### SSI code sample + +```c++ +#include "Arduino.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/MT6701/MagneticSensorMT6701SSI.h" + + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorMT6701SSI sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +To use a custom SPI bus: + +```c++ +void setup() { + sensor1.init(&SPI2); +} +``` + + + +### I2C code sample + +I2C usage is quite simple: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/MT6701/MagneticSensorMT6701I2C.h" + +MagneticSensorMT6701I2C sensor1(); + + +void setup() { + sensor1.init(); +} + +``` + +If you've programmed a different I2C address or want to use a different I2C bus you can: + +```c++ +#define I2C_ADDR 0x70 +MagneticSensorMT6701I2C sensor1(I2C_ADDR); + + +void setup() { + sensor1.init(&Wire2); +} +``` diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.cpp new file mode 100644 index 0000000..d874bad --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.cpp @@ -0,0 +1,56 @@ + +#include "MT6816.h" + +MT6816::MT6816(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { +}; + +MT6816::~MT6816() { +}; + +void MT6816::init(SPIClass* _spi) { + spi = _spi; + if (nCS >= 0) { + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + spi->begin(); + } +}; + +uint16_t MT6816::readRawAngle() { + uint16_t angle_data = 0; + angle_data = spi_transfer16(MT6816_READ_REG_03) << 8; + angle_data |= spi_transfer16(MT6816_READ_REG_04); + + if ((angle_data & MT6816_NO_MAGNET_WARNING_BIT) == MT6816_NO_MAGNET_WARNING_BIT) { + this->no_magnetic_reading = true; + } else { + this->no_magnetic_reading = false; + } + + if (!this->parityCheck(angle_data)) { + return 0; + } + + return (angle_data >> 2); +} + +bool MT6816::parityCheck(uint16_t data) { + data ^= data >> 8; + data ^= data >> 4; + data ^= data >> 2; + data ^= data >> 1; + + return (~data) & 1; +} + +uint16_t MT6816::spi_transfer16(uint16_t outdata) { + if (nCS>=0) + digitalWrite(nCS, 0); + spi->beginTransaction(settings); + uint16_t result = spi->transfer16(outdata); + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, 1); + + return result; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.h new file mode 100644 index 0000000..68b448a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MT6816.h @@ -0,0 +1,40 @@ + +#ifndef MT6816_H +#define MT6816_H + +#include "Arduino.h" +#include "SPI.h" + +#define _2PI 6.28318530718f +#define MT6816_CPR 16384.0f + +#define MT6816_READ_REG_03 0x8300 +#define MT6816_READ_REG_04 0x8400 + +#define MT6816_NO_MAGNET_WARNING_BIT 0x0002 +#define MT6816_BITORDER MSBFIRST + + +static SPISettings MT6816SPISettings(1000000, MT6816_BITORDER, SPI_MODE3); + +class MT6816 { +public: + MT6816(SPISettings settings = MT6816SPISettings, int nCS = -1); + virtual ~MT6816(); + + virtual void init(SPIClass* _spi = &SPI); + uint16_t readRawAngle(); + bool isNoMagneticReading() { + return no_magnetic_reading; + } + +private: + bool parityCheck(uint16_t data); + uint16_t spi_transfer16(uint16_t outdata); + SPIClass* spi; + SPISettings settings; + bool no_magnetic_reading = false; + int nCS = -1; +}; + +#endif /* MT6816_H */ diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.cpp new file mode 100644 index 0000000..4167d78 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.cpp @@ -0,0 +1,26 @@ + +#include "common/foc_utils.h" +#include "common/time_utils.h" +#include "MagneticSensorMT6816.h" + + +MagneticSensorMT6816::MagneticSensorMT6816(int nCS, SPISettings settings) : MT6816(settings, nCS) { +} + +MagneticSensorMT6816::~MagneticSensorMT6816(){ +} + +void MagneticSensorMT6816::init(SPIClass* _spi) { + this->MT6816::init(_spi); + this->Sensor::init(); +} + +float MagneticSensorMT6816::getSensorAngle() { + uint16_t raw_angle_data = readRawAngle(); + + if (this->MT6816::isNoMagneticReading()) { + return 0; + } + + return static_cast(raw_angle_data) / MT6816_CPR * _2PI; +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.h new file mode 100644 index 0000000..51628fc --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6816/MagneticSensorMT6816.h @@ -0,0 +1,17 @@ + +#ifndef MAGNETICSENSOR_MT6816_H +#define MAGNETICSENSOR_MT6816_H + +#include "common/base_classes/Sensor.h" +#include "MT6816.h" + +class MagneticSensorMT6816 : public Sensor, public MT6816 { +public: + MagneticSensorMT6816(int nCS = -1, SPISettings settings = MT6816SPISettings); + virtual ~MagneticSensorMT6816(); + + virtual float getSensorAngle() override; + virtual void init(SPIClass* _spi = &SPI); +}; + +#endif /* MAGNETICSENSOR_MT6816_H */ diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.cpp new file mode 100644 index 0000000..25e6089 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.cpp @@ -0,0 +1,291 @@ + +#include "./MT6835.h" +#include "common/foc_utils.h" + + +MT6835::MT6835(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + // nix +}; + +MT6835::~MT6835() { + // nix +}; + + + +void MT6835::init(SPIClass* _spi) { + spi = _spi; + if (nCS >= 0) { + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + } + spi->begin(); +}; + + + + +float MT6835::getCurrentAngle(){ + return readRawAngle21() / (float)MT6835_CPR * _2PI; +}; + + + +uint32_t MT6835::readRawAngle21(){ + uint8_t data[6]; // transact 48 bits + data[0] = (MT6835_OP_ANGLE<<4); + data[1] = MT6835_REG_ANGLE1; + data[2] = 0; + data[3] = 0; + data[4] = 0; + data[5] = 0; + spi->beginTransaction(settings); + if (nCS >= 0) + digitalWrite(nCS, LOW); + spi->transfer(data, 6); + if (nCS >= 0) + digitalWrite(nCS, HIGH); + spi->endTransaction(); + laststatus = data[4]&0x07; + return (data[2] << 13) | (data[3] << 5) | (data[4] >> 3); +}; + + +uint8_t MT6835::getStatus(){ + return laststatus; +}; + +uint8_t MT6835::getCalibrationStatus(){ + uint8_t data[3] = {0}; + data[0] = 0x31; // read register 0b0011, calibration register 0x113 + data[1] = 0x13; + spi->beginTransaction(settings); + if(nCS >= 0) + digitalWrite(nCS, LOW); + spi->transfer(data, 3); + if(nCS >= 0) + digitalWrite(nCS, HIGH); + spi->endTransaction(); + return data[2] >> 6; // Calibration state held in bits 6,7 +} + +bool MT6835::setZeroFromCurrentPosition(){ + MT6835Command cmd; + cmd.cmd = MT6835_OP_ZERO; + cmd.addr = 0x000; + transfer24(&cmd); + return cmd.data == MT6835_WRITE_ACK; +}; + + +/** + * Wait 6s after calling this method + */ +bool MT6835::writeEEPROM(){ + delay(1); // wait at least 1ms + MT6835Command cmd; + cmd.cmd = MT6835_OP_PROG; + cmd.addr = 0x000; + transfer24(&cmd); + return cmd.data == MT6835_WRITE_ACK; +}; + + + + + +uint8_t MT6835::getBandwidth(){ + MT6835Options5 opts = { .reg = readRegister(MT6835_REG_OPTS5) }; + return opts.bw; +}; +void MT6835::setBandwidth(uint8_t bw){ + MT6835Options5 opts = { .reg = readRegister(MT6835_REG_OPTS5) }; + opts.bw = bw; + writeRegister(MT6835_REG_OPTS5, opts.reg); +}; + +uint8_t MT6835::getHysteresis(){ + MT6835Options3 opts = { .reg = getOptions3().reg }; + return opts.hyst; +}; +void MT6835::setHysteresis(uint8_t hyst){ + MT6835Options3 opts = { .reg = getOptions3().reg }; + opts.hyst = hyst; + setOptions3(opts); +}; + +uint8_t MT6835::getRotationDirection(){ + MT6835Options3 opts = { .reg = getOptions3().reg }; + return opts.rot_dir; +}; +void MT6835::setRotationDirection(uint8_t dir){ + MT6835Options3 opts = { .reg = getOptions3().reg }; + opts.rot_dir = dir; + setOptions3(opts); +}; + + +uint16_t MT6835::getABZResolution(){ + uint8_t hi = readRegister(MT6835_REG_ABZ_RES1); + MT6835ABZRes lo = { + .reg = readRegister(MT6835_REG_ABZ_RES2) + }; + return (hi << 6) | lo.abz_res_low; +}; +void MT6835::setABZResolution(uint16_t res){ + uint8_t hi = (res >> 6); + MT6835ABZRes lo = { + .reg = readRegister(MT6835_REG_ABZ_RES2) + }; + lo.abz_res_low = (res & 0x3F); + writeRegister(MT6835_REG_ABZ_RES1, hi); + writeRegister(MT6835_REG_ABZ_RES2, lo.reg); +}; + + + +bool MT6835::isABZEnabled(){ + MT6835ABZRes lo = { + .reg = readRegister(MT6835_REG_ABZ_RES2) + }; + return lo.abz_off==0; +}; +void MT6835::setABZEnabled(bool enabled){ + MT6835ABZRes lo = { + .reg = readRegister(MT6835_REG_ABZ_RES2) + }; + lo.abz_off = enabled?0:1; + writeRegister(MT6835_REG_ABZ_RES2, lo.reg); +}; + + + +bool MT6835::isABSwapped(){ + MT6835ABZRes lo = { + .reg = readRegister(MT6835_REG_ABZ_RES2) + }; + return lo.ab_swap==1; +}; +void MT6835::setABSwapped(bool swapped){ + MT6835ABZRes lo = { + .reg = readRegister(MT6835_REG_ABZ_RES2) + }; + lo.ab_swap = swapped?1:0; + writeRegister(MT6835_REG_ABZ_RES2, lo.reg); +}; + + + +uint16_t MT6835::getZeroPosition(){ + uint8_t hi = readRegister(MT6835_REG_ZERO1); + MT6835Options0 lo = { + .reg = readRegister(MT6835_REG_ZERO2) + }; + return (hi << 4) | lo.zero_pos_low; +}; +void MT6835::setZeroPosition(uint16_t pos){ + uint8_t hi = (pos >> 4); + MT6835Options0 lo = { + .reg = readRegister(MT6835_REG_ZERO2) + }; + lo.zero_pos_low = pos & 0x0F; + writeRegister(MT6835_REG_ZERO1, hi); + writeRegister(MT6835_REG_ZERO2, lo.reg); +}; + + + +MT6835Options1 MT6835::getOptions1(){ + MT6835Options1 result = { + .reg = readRegister(MT6835_REG_OPTS1) + }; + return result; +}; +void MT6835::setOptions1(MT6835Options1 opts){ + writeRegister(MT6835_REG_OPTS1, opts.reg); +}; + + + +MT6835Options2 MT6835::getOptions2(){ + MT6835Options2 result = { + .reg = readRegister(MT6835_REG_OPTS2) + }; + return result; +}; +void MT6835::setOptions2(MT6835Options2 opts){ + MT6835Options2 val = getOptions2(); + val.nlc_en = opts.nlc_en; + val.pwm_fq = opts.pwm_fq; + val.pwm_pol = opts.pwm_pol; + val.pwm_sel = opts.pwm_sel; + writeRegister(MT6835_REG_OPTS2, val.reg); +}; + + + +MT6835Options3 MT6835::getOptions3(){ + MT6835Options3 result = { + .reg = readRegister(MT6835_REG_OPTS3) + }; + return result; +}; +void MT6835::setOptions3(MT6835Options3 opts){ + MT6835Options3 val = getOptions3(); + val.rot_dir = opts.rot_dir; + val.hyst = opts.hyst; + writeRegister(MT6835_REG_OPTS3, val.reg); +}; + + + +MT6835Options4 MT6835::getOptions4(){ + MT6835Options4 result = { + .reg = readRegister(MT6835_REG_OPTS4) + }; + return result; +}; +void MT6835::setOptions4(MT6835Options4 opts){ + MT6835Options4 val = getOptions4(); + val.gpio_ds = opts.gpio_ds; + val.autocal_freq = opts.autocal_freq; + writeRegister(MT6835_REG_OPTS4, val.reg); +}; + + + +uint32_t swap_bytes(uint32_t net) +{ + return __builtin_bswap32(net); +} + + + + + +void MT6835::transfer24(MT6835Command* outValue) { + uint32_t buff = swap_bytes(outValue->val); + spi->beginTransaction(settings); + if (nCS >= 0) + digitalWrite(nCS, LOW); + spi->transfer(&buff, 3); + if (nCS >= 0) + digitalWrite(nCS, HIGH); + spi->endTransaction(); + outValue->val = swap_bytes(buff); +}; +uint8_t MT6835::readRegister(uint16_t reg) { + MT6835Command cmd; + cmd.cmd = MT6835_OP_READ; + cmd.addr = reg; + transfer24(&cmd); + return cmd.data; +}; +bool MT6835::writeRegister(uint16_t reg, uint8_t value) { + MT6835Command cmd; + cmd.cmd = MT6835_OP_WRITE; + cmd.addr = reg; + cmd.data = value; + transfer24(&cmd); + return cmd.data == MT6835_WRITE_ACK; +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.h new file mode 100644 index 0000000..8518034 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MT6835.h @@ -0,0 +1,217 @@ + + +#pragma once + + + +#include "Arduino.h" +#include "SPI.h" + +#define MT6835_OP_READ 0b0011 +#define MT6835_OP_WRITE 0b0110 +#define MT6835_OP_PROG 0b1100 +#define MT6835_OP_ZERO 0b0101 +#define MT6835_OP_ANGLE 0b1010 + +#define MT6835_CMD_MASK 0b111100000000000000000000 +#define MT6835_ADDR_MASK 0b000011111111111100000000 +#define MT6835_DATA_MASK 0b000000000000000011111111 + +#define MT6835_CPR 2097152 + +#define MT6835_STATUS_OVERSPEED 0x01 +#define MT6835_STATUS_WEAKFIELD 0x02 +#define MT6835_STATUS_UNDERVOLT 0x04 + +#define MT6835_WRITE_ACK 0x55 + +#define MT6835_REG_USERID 0x001 + +#define MT6835_REG_ANGLE1 0x003 +#define MT6835_REG_ANGLE2 0x004 +#define MT6835_REG_ANGLE3 0x005 +#define MT6835_REG_ANGLE4 0x006 + +#define MT6835_REG_ABZ_RES1 0x007 +#define MT6835_REG_ABZ_RES2 0x008 + +#define MT6835_REG_ZERO1 0x009 +#define MT6835_REG_ZERO2 0x00A + +#define MT6835_REG_OPTS0 0x00A +#define MT6835_REG_OPTS1 0x00B +#define MT6835_REG_OPTS2 0x00C +#define MT6835_REG_OPTS3 0x00D +#define MT6835_REG_OPTS4 0x00E +#define MT6835_REG_OPTS5 0x011 + +// NLC table, 192 bytes +#define MT6835_REG_NLC_BASE 0x013 + +#define MT6835_REG_CAL_STATUS 0x113 + + +union MT6835ABZRes { + struct { + uint8_t ab_swap:1; + uint8_t abz_off:1; + uint8_t abz_res_low:6; + }; + uint8_t reg; +}; + + + +union MT6835Options0 { + struct { + uint8_t z_pul_wid:3; + uint8_t z_edge:1; + uint8_t zero_pos_low:4; + }; + uint8_t reg; +}; + + + +union MT6835Options1 { + struct { + uint8_t uvw_res:4; + uint8_t uvw_off:1; + uint8_t uvw_mux:1; + uint8_t z_phase:2; + }; + uint8_t reg; +}; + + + +union MT6835Options2 { + struct { + uint8_t pwm_sel:3; + uint8_t pwm_pol:1; + uint8_t pwm_fq:1; + uint8_t nlc_en:1; + uint8_t reserved:2; + }; + uint8_t reg; +}; + + + +union MT6835Options3 { + struct { + uint8_t hyst:3; + uint8_t rot_dir:1; + uint8_t reserved:4; + }; + uint8_t reg; +}; + + + +union MT6835Options4 { + struct { + uint8_t reserved:4; + uint8_t autocal_freq:3; + uint8_t gpio_ds:1; + }; + uint8_t reg; +}; + + + +union MT6835Options5 { + struct { + uint8_t bw:3; + uint8_t reserved:5; + }; + uint8_t reg; +}; + + + + +union MT6835Command { + struct { + uint32_t unused:8; + uint32_t data:8; + uint32_t addr:12; + uint32_t cmd:4; + }; + uint32_t val; +}; + + + + +#define MT6835_BITORDER MSBFIRST + +static SPISettings MT6835SPISettings(1000000, MT6835_BITORDER, SPI_MODE3); // @suppress("Invalid arguments") + + + + +class MT6835 { +public: + MT6835(SPISettings settings = MT6835SPISettings, int nCS = -1); + virtual ~MT6835(); + + virtual void init(SPIClass* _spi = &SPI); + + + float getCurrentAngle(); // angle in radians, return current value + + uint32_t readRawAngle21(); // up to 21bit precision angle value + + + uint8_t getBandwidth(); + void setBandwidth(uint8_t bw); + + uint8_t getHysteresis(); + void setHysteresis(uint8_t hyst); + + uint8_t getRotationDirection(); + void setRotationDirection(uint8_t dir); + + uint16_t getABZResolution(); + void setABZResolution(uint16_t res); + + bool isABZEnabled(); + void setABZEnabled(bool enabled); + + bool isABSwapped(); + void setABSwapped(bool swapped); + + uint16_t getZeroPosition(); + void setZeroPosition(uint16_t pos); + + MT6835Options1 getOptions1(); + void setOptions1(MT6835Options1 opts); + + MT6835Options2 getOptions2(); + void setOptions2(MT6835Options2 opts); + + MT6835Options3 getOptions3(); + void setOptions3(MT6835Options3 opts); + + MT6835Options4 getOptions4(); + void setOptions4(MT6835Options4 opts); + + uint8_t getStatus(); + + uint8_t getCalibrationStatus(); + + bool setZeroFromCurrentPosition(); + bool writeEEPROM(); // wait 6s after calling this method + +private: + SPIClass* spi; + SPISettings settings; + int nCS = -1; + uint8_t laststatus = 0; + + void transfer24(MT6835Command* outValue); + uint8_t readRegister(uint16_t reg); + bool writeRegister(uint16_t reg, uint8_t value); + +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.cpp new file mode 100644 index 0000000..73c8bbc --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.cpp @@ -0,0 +1,24 @@ + +#include "MagneticSensorMT6835.h" + + +MagneticSensorMT6835::MagneticSensorMT6835(int nCS, SPISettings settings) : Sensor(), MT6835(settings, nCS) { + // nix +}; + + +MagneticSensorMT6835::~MagneticSensorMT6835() { + // nix +}; + + +float MagneticSensorMT6835::getSensorAngle() { + return getCurrentAngle(); +}; + + +void MagneticSensorMT6835::init(SPIClass* _spi) { + this->MT6835::init(_spi); + this->Sensor::init(); +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.h new file mode 100644 index 0000000..e67ab0a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/MagneticSensorMT6835.h @@ -0,0 +1,17 @@ + +#pragma once + +#include "common/base_classes/Sensor.h" +#include "./MT6835.h" + +class MagneticSensorMT6835 : public Sensor, public MT6835 { +public: + MagneticSensorMT6835(int nCS = -1, SPISettings settings = MT6835SPISettings); + virtual ~MagneticSensorMT6835(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI); +}; + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/README.md new file mode 100644 index 0000000..66cbb33 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/mt6835/README.md @@ -0,0 +1,64 @@ +# MT6835 SimpleFOC driver + +Driver for the MagnTek MT6835 precision magnetic rotary encoder. + +This sensor features support for up to 21 bit resolution (!) and speeds up to 120,000RPM. While its full precision requires calibration using an external calibration system, it is impressively precise even in uncalibrated state, and it offers an internal self-calibration mode whose precision is somewhere between the other two. + +It has ABZ, UVW and SPI interfaces, and this driver is for its SPI inteface. You can use its ABZ interface with our Encoder classes, but due to the high resolution the interrupt-based Encoder might cause high MCU load. You can use its UVW interface with our Hall Sensor classes. + +# Hardware setup + +Connect the sensor to an SPI bus on your MCU. Pay attention to the voltage levels needed by your PCBs. The nCS line should have a pull-up resistor. + +# Software setup + +Usage example: + +```c++ +#include + +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" + +#include "encoders/mt6835/MagneticSensorMT6835.h" + +#define SENSOR_nCS PB6 + +SPISettings myMT6835SPISettings(1000000, MT6835_BITORDER, SPI_MODE3); +MagneticSensorMT6835 sensor = MagneticSensorMT6835(SENSOR_nCS, myMT6835SPISettings); + +long ts; + +void setup() { + sensor.init(); + ts = millis(); +} + +void loop() { + sensor.update(); + long now = millis(); + if (now - ts > 1000) { + ts = now; + SimpleFOCDebug::print("A: "); + SimpleFOCDebug::print(sensor.getAngle()); + SimpleFOCDebug::print(" V: "); + SimpleFOCDebug::println(sensor.getVelocity()); + } + delay(10); +} + +``` + +Set the zero position: + +```c++ +uint16_t pos = sensor.getZeroPosition(); // current value +sensor.setZeroFromCurrentPosition(); // set zero to current position +``` + +Set the ABZ resolution (needed if you want to use ABZ as the default is 1): + +```c++ +sensor.setABZResolution(2048); +``` + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.cpp new file mode 100644 index 0000000..a127358 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.cpp @@ -0,0 +1,24 @@ + +#include "./MagneticSensorSC60228.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + +MagneticSensorSC60228::MagneticSensorSC60228(int nCS, SPISettings settings) : SC60228(settings, nCS){ + // nix +}; +MagneticSensorSC60228::~MagneticSensorSC60228(){ }; + + + +float MagneticSensorSC60228::getSensorAngle(){ + SC60228Angle angle_data = readRawAngle(); + float result = ( angle_data.angle / (float)SC60228_CPR ) * _2PI; + return result; +}; + + + +void MagneticSensorSC60228::init(SPIClass* _spi){ + this->SC60228::init(_spi); + this->Sensor::init(); +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.h new file mode 100644 index 0000000..7720182 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/MagneticSensorSC60228.h @@ -0,0 +1,20 @@ +#ifndef __MAGNETICSENSORSC60228_H__ +#define __MAGNETICSENSORSC60228_H__ + + +#include "common/base_classes/Sensor.h" +#include "./SC60228.h" + + +class MagneticSensorSC60228 : public Sensor, public SC60228 { +public: + MagneticSensorSC60228(int nCS = -1, SPISettings settings = SC60228SPISettings); + virtual ~MagneticSensorSC60228(); + + virtual float getSensorAngle() override; + + virtual void init(SPIClass* _spi = &SPI) override; +}; + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/README.md new file mode 100644 index 0000000..49f7901 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/README.md @@ -0,0 +1,47 @@ +# SC60228 SimpleFOC driver + +Driver for the Semiment 12bit magnetic encoder IC SC60288. According to specs it should support 12 bit accuracy, 10 bit effective accuracy and up to 20kRPM. + +Link to [Datasheet](https://semiment.com/wp-content/uploads/2021/04/SC60228_EN-VA1.0.pdf) + +The encoder and this driver were tested with a small gimbal motor and MKR1000 (SAMD21 MCU). + +## Hardware setup + +Connect as per normal for your SPI bus. No special hardware setup is needed to use this driver. + +## Software setup + +Its actually easier to use than the standard SPI sensor class, because it is less generic: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/sc60228/MagneticSensorSC60228.h" + +#define SENSOR1_CS 5 // some digital pin that you're using as the nCS pin +MagneticSensorSC60228 sensor1(SENSOR1_CS); + + +void setup() { + sensor1.init(); +} +``` + +Set some SPI options: + +```c++ +SPISettings mySPISettings(1000000, SC60228_BITORDER, SPI_MODE0); // lower speed to 1Mhz +MagneticSensorSC60228 sensor1(SENSOR1_CS, mySPISettings); +``` + +Use another SPI bus: + +```c++ +void setup() { + sensor1.init(SPI2); +} +``` diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.cpp new file mode 100644 index 0000000..4c63920 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.cpp @@ -0,0 +1,57 @@ + +#include "./SC60228.h" + + +SC60228::SC60228(SPISettings settings, int nCS) : settings(settings), nCS(nCS) { + // nix +}; + +SC60228::~SC60228() { }; + +void SC60228::init(SPIClass* _spi) { + spi = _spi; + if (nCS>=0) + pinMode(nCS, OUTPUT); + digitalWrite(nCS, HIGH); + spi->begin(); + readRawAngle(); +}; + + + +SC60228Angle SC60228::readRawAngle(){ + SC60228Angle result; + result.reg = spi_transfer16(0x0000); + errorflag = (result.err==1); + // TODO check parity + // Serial.print("0x"); + // Serial.print(result.angle, HEX); + // Serial.print(" - 0x"); + // Serial.println(result.reg, HEX); + return result; +}; + + + +bool SC60228::isError() { + return errorflag; +}; + + + +uint16_t SC60228::spi_transfer16(uint16_t outdata){ + uint16_t result; + if (nCS>=0) + digitalWrite(nCS, LOW); + // min delay here: 250ns + spi->beginTransaction(settings); + result = spi->transfer16(outdata); + // min delay here: clock period / 2 + spi->endTransaction(); + if (nCS>=0) + digitalWrite(nCS, HIGH); + // min delay until next read: 250ns + return result; +}; + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.h new file mode 100644 index 0000000..03b4e50 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/sc60228/SC60228.h @@ -0,0 +1,50 @@ + +#ifndef __SC60228_H__ +#define __SC60228_H__ + +#include "Arduino.h" +#include "SPI.h" + + +typedef union { + struct { + uint16_t parity:1; + uint16_t df2:1; + uint16_t df1:1; + uint16_t err:1; + uint16_t angle:12; + }; + uint16_t reg; +} SC60228Angle; + + +#define SC60228_CPR 4096 +#define SC60228_BITORDER MSBFIRST + +static SPISettings SC60228SPISettings(8000000, SC60228_BITORDER, SPI_MODE0); // @suppress("Invalid arguments") + + + +class SC60228 { +public: + SC60228(SPISettings settings = SC60228SPISettings, int nCS = -1); + virtual ~SC60228(); + + virtual void init(SPIClass* _spi = &SPI); + + SC60228Angle readRawAngle(); // 12bit angle value + error flag + bool isError(); // true if the last call to readRawAngle() returned an error + +protected: + uint16_t spi_transfer16(uint16_t outdata); + + SPIClass* spi; + SPISettings settings; + bool errorflag = false; + int nCS = -1; +}; + + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/README.md new file mode 100644 index 0000000..733284c --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/README.md @@ -0,0 +1,69 @@ +# Smoothing Sensor + +by [@dekutree64](https://github.com/dekutree64) + +A SimpleFOC Sensor wrapper implementation which adds angle extrapolation + +Please also see our [forum thread](https://community.simplefoc.com/t/smoothingsensor-experimental-sensor-angle-extrapoltion/3105) on this topic. + + +SmoothingSensor is a wrapper class which is inserted inbetween a sensor and motor to provide better quality angle readings from sensors that are low resolution or are slow to communicate. It provides no improvement for sensors that are high resolution and quick to update. It uses the timestamp of the last angle reading from the sensor and the low-pass filtered velocity from the motor to predict what the angle should be at the current time. + + +## Hardware setup + +Connect your sensor as usual. Make sure the sensor is working 'normally' i.e. without smoothing first. Once things are working and tuned without smoothing, you can add the SmoothingSensor to see if you get an improvement. + + +## Softwate setup + +The SmoothingSensor acts as a wrapper to the actual sensor class. When creating the SmoothingSensor object, provide the real sensor to the constructor of SmoothingSensor. Initialize the real sensor instance as normal. Then link the SmoothingSensor to the motor and call motor.initFOC(). + + +```c++ +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(PB4,PC7,PB10,PA9); +// real sensor instance +MagneticSensorPWM sensor = MagneticSensorPWM(2, 4, 904); +// instantiate the smoothing sensor, providing the real sensor as a constructor argument +SmoothingSensor smooth = SmoothingSensor(sensor, motor); + +void doPWM(){sensor.handlePWM();} + +void setup() { + sensor.init(); + sensor.enableInterrupt(doPWM); + // Link motor to sensor + motor.linkSensor(&smooth); + // power supply voltage + driver.voltage_power_supply = 20; + driver.init(); + motor.linkDriver(&driver); + // aligning voltage + motor.voltage_sensor_align = 8; + motor.voltage_limit = 20; + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_variables = _MON_VEL; + motor.monitor_downsample = 10; // default 10 + + // initialize motor + motor.init(); + motor.initFOC(); +} +``` + + +## Roadmap + +Possible future improvements we've thought about: + +- Add extrapolation of acceleration as well +- Switch to open loop control at very low speed with hall sensors, which otherwise move in steps even with smoothing. + diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.cpp new file mode 100644 index 0000000..ef0d322 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.cpp @@ -0,0 +1,57 @@ +#include "SmoothingSensor.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" + + +SmoothingSensor::SmoothingSensor(Sensor& s, const FOCMotor& m) : _wrapped(s), _motor(m) +{ +} + + +void SmoothingSensor::update() { + // Update sensor, with optional downsampling of update rate + if(sensor_cnt++ >= sensor_downsample) { + sensor_cnt = 0; + _wrapped.update(); + } + + // Copy state variables from the sensor + angle_prev = _wrapped.angle_prev; + angle_prev_ts = _wrapped.angle_prev_ts; + full_rotations = _wrapped.full_rotations; + + // Perform angle prediction, using low-pass filtered velocity. But don't advance more than + // pi/3 (equivalent to one step of block commutation) from the last true angle reading. + float dt = (_micros() - angle_prev_ts) * 1e-6f; + angle_prev += _motor.sensor_direction * _constrain(_motor.shaft_velocity * dt, -_PI_3 / _motor.pole_pairs, _PI_3 / _motor.pole_pairs); + + // Apply phase correction if needed + if (phase_correction != 0) { + if (_motor.shaft_velocity < -0) angle_prev -= _motor.sensor_direction * phase_correction / _motor.pole_pairs; + else if (_motor.shaft_velocity > 0) angle_prev += _motor.sensor_direction * phase_correction / _motor.pole_pairs; + } + + // Handle wraparound of the projected angle + if (angle_prev < 0) full_rotations -= 1, angle_prev += _2PI; + else if (angle_prev >= _2PI) full_rotations += 1, angle_prev -= _2PI; +} + + +float SmoothingSensor::getVelocity() { + return _wrapped.getVelocity(); +} + + +int SmoothingSensor::needsSearch() { + return _wrapped.needsSearch(); +} + + +float SmoothingSensor::getSensorAngle() { + return _wrapped.getSensorAngle(); +} + + +void SmoothingSensor::init() { + _wrapped.init(); +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.h new file mode 100644 index 0000000..c10c2a0 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/smoothing/SmoothingSensor.h @@ -0,0 +1,46 @@ +#ifndef SMOOTHING_SENSOR_H +#define SMOOTHING_SENSOR_H + +#include "Arduino.h" +#include "common/base_classes/FOCMotor.h" +#include "common/base_classes/Sensor.h" + +/** + SmoothingSensor is a wrapper class which is inserted inbetween a sensor and motor to provide better + quality angle readings from sensors that are low resolution or are slow to communicate. It provides + no improvement for sensors that are high resolution and quick to update. + It uses the timestamp of the last angle reading from the sensor and the low-pass filtered velocity + from the motor to predict what the angle should be at the current time. +*/ + +class SmoothingSensor : public Sensor +{ + public: + /** + SmoothingSensor class constructor + @param s Wrapped sensor + @param m Motor that the SmoothingSensor will be linked to + */ + SmoothingSensor(Sensor& s, const FOCMotor& m); + + void update() override; + float getVelocity() override; + int needsSearch() override; + + // For sensors with slow communication, use these to poll less often + unsigned int sensor_downsample = 0; // parameter defining the ratio of downsampling for sensor update + unsigned int sensor_cnt = 0; // counting variable for downsampling + + // For hall sensors, the predicted angle is always 0 to 60 electrical degrees ahead of where it would be without + // smoothing, so offset it backward by 30 degrees (set this to -PI_6) to get the average in phase with the rotor + float phase_correction = 0; + + protected: + float getSensorAngle() override; + void init() override; + + Sensor& _wrapped; + const FOCMotor& _motor; +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/README.md new file mode 100644 index 0000000..1bdb1ca --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/README.md @@ -0,0 +1,49 @@ +# SimpleFOC Driver for STM32 hardware encoder + +This encoder driver uses the STM32 timer hardware to track the A/B impulses, which is much more efficient (and will support higher speeds) than the generic interrupt-based solution used by the standard encoder driver. + +Big thank you to @conroy-cheers for originally contributing this code in pull request #114 to the simplefoc repository. Due its hardware-specific nature we moved the code to this drivers repository. + +## Warning + +This code has not been tested much! Use at your own risk, your milage may vary. +I have tested on: STM32F401CC/TIM4-PB6,PB7 + +## Hardware setup + +The ABI signals of your encoder will have to be connected to the STM32 MCU in such a way that all signals are connected to the same timer. Consult your STM32 chip's datasheet for more information on which pins connect to which timer. + +Not all of the timers support the encoder mode, so check the datasheet which timers can be used. + +An excellent option can be to use the STM32CubeIDE software's pin assignment view to quickly check which pins connect to which timer. + +Note that the index (I) pin is currently not used. + + +## Software setup + +There is no need for interrupt functions or their configuration with this encoder class, so usage is quite simple: + +```c++ +#include "Arduino.h" +#include "Wire.h" +#include "SPI.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "encoders/stm32hwencoder/STM32HWEncoder.h" + + +#define ENCODER_PPR 500 +#define ENCODER_PIN_A PB6 +#define ENCODER_PIN_B PB7 +#define ENCODER_PIN_I PC13 + + +STM32HWEncoder encoder = STM32HWEncoder(ENCODER_PPR, ENCODER_PIN_A, ENCODER_PIN_B, ENCODER_PIN_I); + + +void setup() { + encoder.init(); +} + +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.cpp new file mode 100644 index 0000000..0525e3f --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.cpp @@ -0,0 +1,78 @@ +#include "STM32HWEncoder.h" + +#if defined(_STM32_DEF_) + +/* + HardwareEncoder(int cpr) +*/ +STM32HWEncoder::STM32HWEncoder(unsigned int _ppr, int8_t pinA, int8_t pinB, int8_t pinI) { + cpr = _ppr * 4; // 4x for quadrature + _pinA = digitalPinToPinName(pinA); + _pinB = digitalPinToPinName(pinB); + _pinI = digitalPinToPinName(pinI); +} + +/* + Shaft angle calculation +*/ +float STM32HWEncoder::getSensorAngle() { + return _2PI * encoder_handle.Instance->CNT / static_cast(cpr); +} + +// getter for index pin +int STM32HWEncoder::needsSearch() { return false; } + +// private function used to determine if encoder has index +int STM32HWEncoder::hasIndex() { return 0; } + +// encoder initialisation of the hardware pins +void STM32HWEncoder::init() { + // GPIO configuration + TIM_TypeDef *InstanceA = (TIM_TypeDef *)pinmap_peripheral(_pinA, PinMap_TIM); + TIM_TypeDef *InstanceB = (TIM_TypeDef *)pinmap_peripheral(_pinB, PinMap_TIM); + if (InstanceA != InstanceB) { + initialized = false; + return; + } + pinmap_pinout(_pinA, PinMap_TIM); + pinmap_pinout(_pinB, PinMap_TIM); + + // set up timer for encoder + encoder_handle.Init.Period = cpr - 1; + encoder_handle.Init.Prescaler = 0; + encoder_handle.Init.ClockDivision = 0; + encoder_handle.Init.CounterMode = TIM_COUNTERMODE_UP; + encoder_handle.Init.RepetitionCounter = 0; + encoder_handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + + TIM_Encoder_InitTypeDef encoder_config; + + encoder_config.EncoderMode = TIM_ENCODERMODE_TI12; + + encoder_config.IC1Polarity = TIM_ICPOLARITY_RISING; + encoder_config.IC1Selection = TIM_ICSELECTION_DIRECTTI; + encoder_config.IC1Prescaler = TIM_ICPSC_DIV1; + encoder_config.IC1Filter = 0; + + encoder_config.IC2Polarity = TIM_ICPOLARITY_RISING; + encoder_config.IC2Selection = TIM_ICSELECTION_DIRECTTI; + encoder_config.IC2Prescaler = TIM_ICPSC_DIV1; + encoder_config.IC2Filter = 0; + + encoder_handle.Instance = InstanceA; // e.g. TIM4; + enableTimerClock(&encoder_handle); + + if (HAL_TIM_Encoder_Init(&encoder_handle, &encoder_config) != HAL_OK) { + initialized = false; + return; + } + + if (HAL_TIM_Encoder_Start(&encoder_handle, TIM_CHANNEL_1) != HAL_OK) { + initialized = false; + return; + } + + initialized = true; +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.h new file mode 100644 index 0000000..98b14e5 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32hwencoder/STM32HWEncoder.h @@ -0,0 +1,36 @@ + +#pragma once + +#include + + +#if defined(_STM32_DEF_) + +#include +#include "common/base_classes/Sensor.h" +#include "common/foc_utils.h" + +class STM32HWEncoder : public Sensor { + public: + /** + Encoder class constructor + @param ppr impulses per rotation (cpr=ppr*4) + */ + explicit STM32HWEncoder(unsigned int ppr, int8_t pinA, int8_t pinB, int8_t pinI=-1); + + void init() override; + int needsSearch() override; + int hasIndex(); // !< function returning 1 if encoder has index pin and 0 if not. + + bool initialized = false; + uint32_t cpr; //!< encoder cpr number + PinName _pinA, _pinB, _pinI; + + protected: + float getSensorAngle() override; + + TIM_HandleTypeDef encoder_handle; + +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/README.md new file mode 100644 index 0000000..fd98be9 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/README.md @@ -0,0 +1,46 @@ + +# STM32MagneticSensorPWM + +STM32 MCU specific PWM sensor class. This class uses the STM32's hardware timers to precisely capture the PWM input signal, and doesn't use interrupts or have MCU overhead. + +:warning: this code is not yet well tested. + +## Setup + +Please use an advanced control or general purpose timer pin on your STM32. Connect the sensor's PWM output to the MCU's input pin. Usually, pull-ups or pull-downs are not needed, but check your sensor's datasheet. + +:warning: only tested on 16 bit timers. Code changes may be needed to make it work on 32 but timers. Avoid using TIM2 and TIM5 unless you want to test it. + +The sensor needs the values `min_ticks` and `max-ticks` to be configured correctly to convert the PWM input into an angle. These values will depend on the sensor, but also on the MCU's timer clock speed. + +To print the current tick value, use: + +``` +sensor.getDutyCycleTicks(); +``` + +By rotating the motor through several full turns while printing the ticks to the screen you will be able to determine the correct values empirically. + +## Usage + +``` +STM32MagneticSensorPWM sensor = STM32MagneticSensorPWM(PB7, 412, 6917); // sample values, yours will be different + +void setup() { + ... + sensor.init(); + ... +} +``` + +To use alternate function timers, set the PinName directly: + +``` +sensor._pin = PB_7_ALT1; // manually set a PinName to use alternate timer function +``` + +PWM sensor may have a slow update time (not more often than once per PWM-period, e.g. at the PWM frequency): + +``` +sensor.min_elapsed_time = 0.001; // 1ms minimum sample time for velocity +``` diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.cpp new file mode 100644 index 0000000..3c3e1d6 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.cpp @@ -0,0 +1,35 @@ + +#include "./STM32MagneticSensorPWM.h" + +#if defined(_STM32_DEF_) + +#include "common/foc_utils.h" + + +STM32MagneticSensorPWM::STM32MagneticSensorPWM(int pin, uint32_t _min_ticks, uint32_t _max_ticks) : STM32PWMInput(pin), max_ticks(_max_ticks), min_ticks(_min_ticks) { + +}; + + + +STM32MagneticSensorPWM::~STM32MagneticSensorPWM(){}; + + + +void STM32MagneticSensorPWM::init(){ + initialized = (STM32PWMInput::initialize()==0); + if(initialized) + Sensor::init(); +}; + + + +float STM32MagneticSensorPWM::getSensorAngle(){ + uint32_t ticks = getDutyCycleTicks(); + return (ticks - min_ticks) * _2PI / (max_ticks - min_ticks); +}; + + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.h new file mode 100644 index 0000000..3e5d335 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/stm32pwmsensor/STM32MagneticSensorPWM.h @@ -0,0 +1,28 @@ + +#pragma once + + +#include + + +#if defined(_STM32_DEF_) + +#include "common/base_classes/Sensor.h" +#include "utilities/stm32pwm/STM32PWMInput.h" + + +class STM32MagneticSensorPWM : public Sensor, public STM32PWMInput { + public: + STM32MagneticSensorPWM(int pin, uint32_t _min_ticks = 0, uint32_t _max_ticks = 0x0FFF); + ~STM32MagneticSensorPWM(); + + void init() override; + + uint32_t max_ticks = 0x0FFF; + uint32_t min_ticks = 0; + bool initialized = false; + protected: + float getSensorAngle() override; +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.cpp new file mode 100644 index 0000000..5947209 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.cpp @@ -0,0 +1,18 @@ + +#include "./MagneticSensorTLE5012B.h" + +#if defined(_STM32_DEF_) + +MagneticSensorTLE5012B::MagneticSensorTLE5012B(int data, int sck, int nCS) : TLE5012B(data, sck, nCS) { }; +MagneticSensorTLE5012B::~MagneticSensorTLE5012B(){ }; + +void MagneticSensorTLE5012B::init() { + this->TLE5012B::init(); + this->Sensor::init(); +}; + +float MagneticSensorTLE5012B::getSensorAngle() { + return getCurrentAngle(); +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.h new file mode 100644 index 0000000..712c896 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/MagneticSensorTLE5012B.h @@ -0,0 +1,25 @@ + +#ifndef __MAGNETIC_SENSOR_TLE5012B_H__ +#define __MAGNETIC_SENSOR_TLE5012B_H__ + +#include "./STM32TLE5012B.h" + +#if defined(_STM32_DEF_) + +#include "common/base_classes/Sensor.h" + + + + +class MagneticSensorTLE5012B : public Sensor, public TLE5012B { + public: + MagneticSensorTLE5012B(int data, int sck, int nCS); + ~MagneticSensorTLE5012B(); + virtual void init() override; + virtual float getSensorAngle() override; +}; + + + +#endif +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/README.md b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/README.md new file mode 100644 index 0000000..3ce22c2 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/README.md @@ -0,0 +1,91 @@ +# SimpleFOC Driver for TLE5012B encoder for STM32 MCUs + +This driver code is compatible with STM32 MCUs. Based loosely on code from [here](https://github.com/xerootg/btt-s42b-simplefoc), with many thanks to @xerootg + +## Hardware setup + +Connect the data pin of the sensor to the MOSI (COPI) line of the MCU. The SCLK and nCS lines are connected as normal. + +## Software setup + +Sample code: + +``` +#include +#include +#include +#include "encoders/tle5012b/MagneticSensorTLE5012B.h" + +MagneticSensorTLE5012B sensor(PB15,PB13,PB12); + +long ts; + +void setup() { + Serial.begin(115200); + while (!Serial) ; + delay(2000); + + Serial.println("Initializing sensor..."); + + sensor.init(); + + Serial.println("Sensor initialized."); + + ts = millis(); +} + +void loop() { + sensor.update(); + if (millis() - ts > 1000) { + Serial.println(sensor.getAngle(), 3); + ts = millis(); + } + delay(1); +} +``` + +## Other MCUs + +Infineon provides a driver library compatible with Atmel AVR (Arduino UNO, Nano, etc...) and Infineon XMC MCUs. If you have one of those MCUs, you can use this library in conjunction with the GenericSensor class in SimpleFOC. + +``` +#include +#include + +Tle5012Ino Tle5012Sensor = Tle5012Ino(); +errorTypes checkError = NO_ERROR; + +float readMySensor(){ + // read my sensor + // return the angle value in radians in between 0 and 2PI + + Tle5012Sensor.getAngleValue(d); + d = (d + 180); + if ( d + 40.9 > 360 ) { + d = (d + 40.9) - 360; + } + else + d = d + 40.9; + + d = d * 0.0174533; + return d; +} +void initMySensor(){ + // do the init + checkError = Tle5012Sensor.begin(); +} + +// empty constructor +GenericSensor sensor = GenericSensor(readMySensor, initMySensor); + +void setup(){ +... + //init sensor and use it further with foc... + sensor.init(); +... +} +``` + +Other MCUs are currently not supported. The problem is that the sensor uses SPI in half-duplex mode, which is not supported by Arduino framework. So for each MCU type a custom driver has to be written to get the half-duplex SPI communication to work. There are currently no plans to support other MCUs on our side, but we will gladly accept pull requests :-) + +If you can find other libraries for other MCUs, you can use the GenericSensor approach to integrate them. \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.cpp b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.cpp new file mode 100644 index 0000000..7fd89c7 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.cpp @@ -0,0 +1,159 @@ + +#include "STM32TLE5012B.h" + +#if defined(_STM32_DEF_) + + +#include "utility/spi_com.h" +extern "C" uint32_t spi_getClkFreqInst(SPI_TypeDef *spi_inst); + + + +TLE5012B::TLE5012B(int data, int sck, int nCS, uint32_t freq) { + _data = data; + _sck = sck; + _nCS = nCS; + _freq = freq; +}; + +TLE5012B::~TLE5012B() { + +}; + + +void TLE5012B::init() { + pinMode(_nCS, OUTPUT); + digitalWrite(_nCS, HIGH); + + // initialize pins + GPIO_InitTypeDef gpio; + gpio.Pin = digitalPinToBitMask(_data); + gpio.Mode = GPIO_MODE_AF_PP; + gpio.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(digitalPinToPort(_data), &gpio); + gpio.Pin = digitalPinToBitMask(_sck); + gpio.Mode = GPIO_MODE_AF_PP; + gpio.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(digitalPinToPort(_sck), &gpio); + + SPI_TypeDef *spi_data = (SPI_TypeDef*)pinmap_peripheral(digitalPinToPinName(_data), PinMap_SPI_MOSI); + SPI_TypeDef *spi_sclk = (SPI_TypeDef*)pinmap_peripheral(digitalPinToPinName(_sck), PinMap_SPI_SCLK); + SPI_TypeDef *spi_inst = (SPI_TypeDef*)pinmap_merge_peripheral(spi_data, spi_sclk); + + pinmap_pinout(digitalPinToPinName(_data), PinMap_SPI_MOSI); + pinmap_pinout(digitalPinToPinName(_sck), PinMap_SPI_SCLK); + + #if defined SPI1_BASE + if (spi_inst == SPI1) { + __HAL_RCC_SPI1_CLK_ENABLE(); + __HAL_RCC_SPI1_FORCE_RESET(); + __HAL_RCC_SPI1_RELEASE_RESET(); + } + #endif + + #if defined SPI2_BASE + if (spi_inst == SPI2) { + __HAL_RCC_SPI2_CLK_ENABLE(); + __HAL_RCC_SPI2_FORCE_RESET(); + __HAL_RCC_SPI2_RELEASE_RESET(); + } + #endif + + #if defined SPI3_BASE + if (spi_inst == SPI3) { + __HAL_RCC_SPI3_CLK_ENABLE(); + __HAL_RCC_SPI3_FORCE_RESET(); + __HAL_RCC_SPI3_RELEASE_RESET(); + } + #endif + + #if defined SPI4_BASE + if (spi_inst == SPI4) { + __HAL_RCC_SPI4_CLK_ENABLE(); + __HAL_RCC_SPI4_FORCE_RESET(); + __HAL_RCC_SPI4_RELEASE_RESET(); + } + #endif + + #if defined SPI5_BASE + if (spi_inst == SPI5) { + __HAL_RCC_SPI5_CLK_ENABLE(); + __HAL_RCC_SPI5_FORCE_RESET(); + __HAL_RCC_SPI5_RELEASE_RESET(); + } + #endif + + #if defined SPI6_BASE + if (spi_inst == SPI6) { + __HAL_RCC_SPI6_CLK_ENABLE(); + __HAL_RCC_SPI6_FORCE_RESET(); + __HAL_RCC_SPI6_RELEASE_RESET(); + } + #endif + + _spi.Instance = spi_inst; + _spi.Init.Direction = SPI_DIRECTION_1LINE; + _spi.Init.Mode = SPI_MODE_MASTER; + _spi.Init.DataSize = SPI_DATASIZE_8BIT; + _spi.Init.CLKPolarity = SPI_POLARITY_LOW; + _spi.Init.CLKPhase = SPI_PHASE_2EDGE; + _spi.Init.NSS = SPI_NSS_SOFT; + _spi.Init.FirstBit = SPI_FIRSTBIT_MSB; + _spi.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; + _spi.Init.CRCPolynomial = 7; + _spi.Init.TIMode = SPI_TIMODE_DISABLE; + #if defined(SPI_NSS_PULSE_DISABLE) + _spi.Init.NSSPMode = SPI_NSS_PULSE_DISABLE; + #endif + + uint32_t spi_freq = spi_getClkFreqInst(spi_inst); + if (_freq >= (spi_freq / SPI_SPEED_CLOCK_DIV2_MHZ)) { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; + } else if (_freq >= (spi_freq / SPI_SPEED_CLOCK_DIV4_MHZ)) { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; + } else if (_freq >= (spi_freq / SPI_SPEED_CLOCK_DIV8_MHZ)) { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; + } else if (_freq >= (spi_freq / SPI_SPEED_CLOCK_DIV16_MHZ)) { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; + } else if (_freq >= (spi_freq / SPI_SPEED_CLOCK_DIV32_MHZ)) { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; + } else if (_freq >= (spi_freq / SPI_SPEED_CLOCK_DIV64_MHZ)) { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; + } else if (_freq >= (spi_freq / SPI_SPEED_CLOCK_DIV128_MHZ)) { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; + } else { + _spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; + } + + if (HAL_SPI_Init(&_spi) != HAL_OK) { + // setup error + Serial.println("TLE5012B setup error"); + } +}; + +uint16_t TLE5012B::readRawAngle() { + uint8_t data[4]; + readBytes(TLE5012B_ANGLE_REG, data, 2); + return (((uint16_t)data[0] << 8) | data[1]) & 0x7FFF; +}; + + +float TLE5012B::getCurrentAngle() { + return ((float)readRawAngle())/TLE5012B_CPR * _2PI; +}; // angle in radians, return current value + + +void TLE5012B::readBytes(uint16_t reg, uint8_t *data, uint8_t len) { + digitalWrite(_nCS, LOW); + + reg |= TLE5012B_READ_REGISTER + (len>>1); + uint8_t txbuffer[2] = { (uint8_t)(reg >> 8), (uint8_t)(reg & 0x00FF) }; + HAL_SPI_Transmit(&_spi, txbuffer, 2, 100); // TODO check return value for error, timeout + //delayMicroseconds(1); + HAL_SPI_Receive(&_spi, data, len + 2, 100); + + digitalWrite(_nCS, HIGH); +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.h b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.h new file mode 100644 index 0000000..6ae6c65 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/encoders/tle5012b/STM32TLE5012B.h @@ -0,0 +1,45 @@ +#ifndef __TLE5012B_H__ +#define __TLE5012B_H__ + +#include "Arduino.h" + +#if defined(_STM32_DEF_) + + +#define _2PI 6.28318530718f +#define TLE5012B_CPR 32768.0f + +#define TLE5012B_READ_REGISTER 0x8000 + +enum TLE5012B_Register : uint16_t { + TLE5012B_ANGLE_REG = 0x0020, + TLE5012B_SPEED_REG = 0x0030 +}; + + + +class TLE5012B { + public: + TLE5012B(int data, int sck, int nCS, uint32_t freq = 1000000); + ~TLE5012B(); + virtual void init(); + + uint16_t readRawAngle(); + float getCurrentAngle(); // angle in radians, return current value + private: + + void readBytes(uint16_t reg, uint8_t *data, uint8_t len); + + int _data; + int _sck; + int _nCS; + uint32_t _freq; + SPI_HandleTypeDef _spi; +}; + + + + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.cpp b/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.cpp new file mode 100644 index 0000000..b7fea27 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.cpp @@ -0,0 +1,548 @@ +#include "HybridStepperMotor.h" +#include "./communication/SimpleFOCDebug.h" + +// HybridStepperMotor(int pp) +// - pp - pole pair number +// - R - motor phase resistance +// - KV - motor kv rating (rmp/v) +// - L - motor phase inductance [H] +HybridStepperMotor::HybridStepperMotor(int pp, float _R, float _KV, float _inductance) + : FOCMotor() +{ + // number od pole pairs + pole_pairs = pp; + // save phase resistance number + phase_resistance = _R; + // save back emf constant KV = 1/K_bemf + // usually used rms + KV_rating = _KV * _SQRT2; + // save phase inductance + phase_inductance = _inductance; + + // torque control type is voltage by default + // current and foc_current not supported yet + torque_controller = TorqueControlType::voltage; +} + +/** + Link the driver which controls the motor +*/ +void HybridStepperMotor::linkDriver(BLDCDriver *_driver) +{ + driver = _driver; +} + +// init hardware pins +void HybridStepperMotor::init() +{ + if (!driver || !driver->initialized) + { + motor_status = FOCMotorStatus::motor_init_failed; + SIMPLEFOC_DEBUG("MOT: Init not possible, driver not initialized"); + return; + } + motor_status = FOCMotorStatus::motor_initializing; + SIMPLEFOC_DEBUG("MOT: Init"); + + // sanity check for the voltage limit configuration + if (voltage_limit > driver->voltage_limit) + voltage_limit = driver->voltage_limit; + // constrain voltage for sensor alignment + if (voltage_sensor_align > voltage_limit) + voltage_sensor_align = voltage_limit; + + // update the controller limits + if (_isset(phase_resistance)) + { + // velocity control loop controls current + PID_velocity.limit = current_limit; + } + else + { + PID_velocity.limit = voltage_limit; + } + P_angle.limit = velocity_limit; + + _delay(500); + // enable motor + SIMPLEFOC_DEBUG("MOT: Enable driver."); + enable(); + _delay(500); + + motor_status = FOCMotorStatus::motor_uncalibrated; +} + +// disable motor driver +void HybridStepperMotor::disable() +{ + // set zero to PWM + driver->setPwm(0, 0, 0); + // disable driver + driver->disable(); + // motor status update + enabled = 0; +} +// enable motor driver +void HybridStepperMotor::enable() +{ + // disable enable + driver->enable(); + // set zero to PWM + driver->setPwm(0, 0, 0); + // motor status update + enabled = 1; +} + +/** + * FOC functions + */ +int HybridStepperMotor::initFOC() +{ + int exit_flag = 1; + + motor_status = FOCMotorStatus::motor_calibrating; + + // sensor and motor alignment - can be skipped + // by setting motor.sensor_direction and motor.zero_electric_angle + _delay(500); + if (sensor) + { + exit_flag *= alignSensor(); + // added the shaft_angle update + sensor->update(); + shaft_angle = sensor->getAngle(); + } + else + SIMPLEFOC_DEBUG("MOT: No sensor."); + + if (exit_flag) + { + SIMPLEFOC_DEBUG("MOT: Ready."); + motor_status = FOCMotorStatus::motor_ready; + } + else + { + SIMPLEFOC_DEBUG("MOT: Init FOC failed."); + motor_status = FOCMotorStatus::motor_calib_failed; + disable(); + } + + return exit_flag; +} + +// Encoder alignment to electrical 0 angle +int HybridStepperMotor::alignSensor() +{ + int exit_flag = 1; // success + SIMPLEFOC_DEBUG("MOT: Align sensor."); + + // if unknown natural direction + if(sensor_direction==Direction::UNKNOWN) { + // check if sensor needs zero search + if (sensor->needsSearch()) + exit_flag = absoluteZeroSearch(); + // stop init if not found index + if (!exit_flag) + return exit_flag; + + // find natural direction + // move one electrical revolution forward + for (int i = 0; i <= 500; i++) + { + float angle = _3PI_2 + _2PI * i / 500.0f; + setPhaseVoltage(voltage_sensor_align, 0, angle); + sensor->update(); + _delay(2); + } + // take and angle in the middle + sensor->update(); + float mid_angle = sensor->getAngle(); + // move one electrical revolution backwards + for (int i = 500; i >= 0; i--) + { + float angle = _3PI_2 + _2PI * i / 500.0f; + setPhaseVoltage(voltage_sensor_align, 0, angle); + sensor->update(); + _delay(2); + } + sensor->update(); + float end_angle = sensor->getAngle(); + setPhaseVoltage(0, 0, 0); + _delay(200); + // determine the direction the sensor moved + if (mid_angle == end_angle) + { + SIMPLEFOC_DEBUG("MOT: Failed to notice movement"); + return 0; // failed calibration + } + else if (mid_angle < end_angle) + { + SIMPLEFOC_DEBUG("MOT: sensor_direction==CCW"); + sensor_direction = Direction::CCW; + } + else + { + SIMPLEFOC_DEBUG("MOT: sensor_direction==CW"); + sensor_direction = Direction::CW; + } + // check pole pair number + float moved = fabs(mid_angle - end_angle); + if (fabs(moved * pole_pairs - _2PI) > 0.5f) + { // 0.5f is arbitrary number it can be lower or higher! + SIMPLEFOC_DEBUG("MOT: PP check: fail - estimated pp: ", _2PI / moved); + } + else + SIMPLEFOC_DEBUG("MOT: PP check: OK!"); + } + else + SIMPLEFOC_DEBUG("MOT: Skip dir calib."); + + // zero electric angle not known + if (!_isset(zero_electric_angle)) + { + // align the electrical phases of the motor and sensor + // set angle -90(270 = 3PI/2) degrees + setPhaseVoltage(voltage_sensor_align, 0, _3PI_2); + _delay(700); + // read the sensor + sensor->update(); + // get the current zero electric angle + zero_electric_angle = 0; + zero_electric_angle = electricalAngle(); + _delay(20); + if (monitor_port) + { + SIMPLEFOC_DEBUG("MOT: Zero elec. angle: ", zero_electric_angle); + } + // stop everything + setPhaseVoltage(0, 0, 0); + _delay(200); + } + else + SIMPLEFOC_DEBUG("MOT: Skip offset calib."); + return exit_flag; +} + +// Encoder alignment the absolute zero angle +// - to the index +int HybridStepperMotor::absoluteZeroSearch() +{ + + SIMPLEFOC_DEBUG("MOT: Index search..."); + // search the absolute zero with small velocity + float limit_vel = velocity_limit; + float limit_volt = voltage_limit; + velocity_limit = velocity_index_search; + voltage_limit = voltage_sensor_align; + shaft_angle = 0; + while (sensor->needsSearch() && shaft_angle < _2PI) + { + angleOpenloop(1.5f * _2PI); + // call important for some sensors not to loose count + // not needed for the search + sensor->update(); + } + // disable motor + setPhaseVoltage(0, 0, 0); + // reinit the limits + velocity_limit = limit_vel; + voltage_limit = limit_volt; + // check if the zero found + if (monitor_port) + { + if (sensor->needsSearch()) + SIMPLEFOC_DEBUG("MOT: Error: Not found!"); + else + SIMPLEFOC_DEBUG("MOT: Success!"); + } + return !sensor->needsSearch(); +} + +// Iterative function looping FOC algorithm, setting Uq on the Motor +// The faster it can be run the better +void HybridStepperMotor::loopFOC() +{ + + // update sensor - do this even in open-loop mode, as user may be switching between modes and we could lose track + // of full rotations otherwise. + if (sensor) + sensor->update(); + + // if open-loop do nothing + if (controller == MotionControlType::angle_openloop || controller == MotionControlType::velocity_openloop) + return; + // shaft angle + shaft_angle = shaftAngle(); + + // if disabled do nothing + if (!enabled) + return; + + // Needs the update() to be called first + // This function will not have numerical issues because it uses Sensor::getMechanicalAngle() + // which is in range 0-2PI + electrical_angle = electricalAngle(); + + // set the phase voltage - FOC heart function :) + setPhaseVoltage(voltage.q, voltage.d, electrical_angle); +} + +// Iterative function running outer loop of the FOC algorithm +// Behavior of this function is determined by the motor.controller variable +// It runs either angle, velocity or voltage loop +// - needs to be called iteratively it is asynchronous function +// - if target is not set it uses motor.target value +void HybridStepperMotor::move(float new_target) +{ + + // downsampling (optional) + if (motion_cnt++ < motion_downsample) + return; + motion_cnt = 0; + + // shaft angle/velocity need the update() to be called first + // get shaft angle + // TODO sensor precision: the shaft_angle actually stores the complete position, including full rotations, as a float + // For this reason it is NOT precise when the angles become large. + // Additionally, the way LPF works on angle is a precision issue, and the angle-LPF is a problem + // when switching to a 2-component representation. + if (controller != MotionControlType::angle_openloop && controller != MotionControlType::velocity_openloop) + shaft_angle = shaftAngle(); // read value even if motor is disabled to keep the monitoring updated but not in openloop mode + // get angular velocity + shaft_velocity = shaftVelocity(); // read value even if motor is disabled to keep the monitoring updated + + // if disabled do nothing + if (!enabled) + return; + + // set internal target variable + if (_isset(new_target)) + target = new_target; + + // calculate the back-emf voltage if KV_rating available U_bemf = vel*(1/KV) + if (_isset(KV_rating)) + voltage_bemf = shaft_velocity / KV_rating / _RPM_TO_RADS; + // estimate the motor current if phase reistance available and current_sense not available + if (!current_sense && _isset(phase_resistance)) + current.q = (voltage.q - voltage_bemf) / phase_resistance; + + // choose control loop + switch (controller) + { + case MotionControlType::torque: + if (!_isset(phase_resistance)) + voltage.q = target; // if voltage torque control + else + voltage.q = target * phase_resistance + voltage_bemf; + voltage.q = _constrain(voltage.q, -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if (!_isset(phase_inductance)) + voltage.d = 0; + else + voltage.d = _constrain(-target * shaft_velocity * pole_pairs * phase_inductance, -voltage_limit, voltage_limit); + break; + case MotionControlType::angle: + // angle set point + shaft_angle_sp = target; + // calculate velocity set point + shaft_velocity_sp = P_angle(shaft_angle_sp - shaft_angle); + // calculate the torque command + current_sp = PID_velocity(shaft_velocity_sp - shaft_velocity); // if voltage torque control + // if torque controlled through voltage + // use voltage if phase-resistance not provided + if (!_isset(phase_resistance)) + voltage.q = current_sp; + else + voltage.q = _constrain(current_sp * phase_resistance + voltage_bemf, -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if (!_isset(phase_inductance)) + voltage.d = 0; + else + voltage.d = _constrain(-current_sp * shaft_velocity * pole_pairs * phase_inductance, -voltage_limit, voltage_limit); + break; + case MotionControlType::velocity: + // velocity set point + shaft_velocity_sp = target; + // calculate the torque command + current_sp = PID_velocity(shaft_velocity_sp - shaft_velocity); // if current/foc_current torque control + // if torque controlled through voltage control + // use voltage if phase-resistance not provided + if (!_isset(phase_resistance)) + voltage.q = current_sp; + else + voltage.q = _constrain(current_sp * phase_resistance + voltage_bemf, -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if (!_isset(phase_inductance)) + voltage.d = 0; + else + voltage.d = _constrain(-current_sp * shaft_velocity * pole_pairs * phase_inductance, -voltage_limit, voltage_limit); + break; + case MotionControlType::velocity_openloop: + // velocity control in open loop + shaft_velocity_sp = target; + voltage.q = velocityOpenloop(shaft_velocity_sp); // returns the voltage that is set to the motor + voltage.d = 0; // TODO d-component lag-compensation + break; + case MotionControlType::angle_openloop: + // angle control in open loop + shaft_angle_sp = target; + voltage.q = angleOpenloop(shaft_angle_sp); // returns the voltage that is set to the motor + voltage.d = 0; // TODO d-component lag-compensation + break; + } +} + +void HybridStepperMotor::setPhaseVoltage(float Uq, float Ud, float angle_el) +{ + angle_el = _normalizeAngle(angle_el); + float _ca = _cos(angle_el); + float _sa = _sin(angle_el); + float center; + + switch (foc_modulation) { + case FOCModulationType::Trapezoid_120: + case FOCModulationType::Trapezoid_150: + // not handled + Ua = 0; + Ub = 0; + Uc = 0; + break; + case FOCModulationType::SinePWM: + // C phase is fixed at half-rail to provide bias point for A, B legs + Ua = (_ca * Ud) - (_sa * Uq); + Ub = (_sa * Ud) + (_ca * Uq); + + center = driver->voltage_limit / 2; + + Ua += center; + Ub += center; + Uc = center; + break; + + case FOCModulationType::SpaceVectorPWM: + // C phase moves in order to increase max bias on coils + uint8_t sector = floor(4.0 * angle_el / _PI) + 1; + Ua = (_ca * Ud) - (_sa * Uq); + Ub = (_sa * Ud) + (_ca * Uq); + + // Determine max/ min of [Ua, Ub, 0] based on phase angle. + switch (sector) + { + case 1: + case 8: + center = (driver->voltage_limit - Ua - Ub) / 2; + break; + + case 2: + center = (driver->voltage_limit - Ua - 0) / 2; + break; + + case 3: + center = (driver->voltage_limit - Ub - 0) / 2; + break; + + case 4: + case 5: + center = (driver->voltage_limit - Ub - Ua) / 2; + break; + + case 6: + center = (driver->voltage_limit - 0 - Ua) / 2; + break; + + case 7: + center = (driver->voltage_limit - 0 - Ub) / 2; + break; + + default: // this case does not occur, but compilers complain about uninitialized variables + center = (driver->voltage_limit - 0) / 2; + break; + } + + Ua += center; + Ub += center; + Uc = center; + break; + } + + driver->setPwm(Ua, Ub, Uc); +} + +// Function (iterative) generating open loop movement for target velocity +// - target_velocity - rad/s +// it uses voltage_limit variable +float HybridStepperMotor::velocityOpenloop(float target_velocity) +{ + // get current timestamp + unsigned long now_us = _micros(); + // calculate the sample time from last call + float Ts = (now_us - open_loop_timestamp) * 1e-6f; + // quick fix for strange cases (micros overflow + timestamp not defined) + if (Ts <= 0 || Ts > 0.5f) + Ts = 1e-3f; + + // calculate the necessary angle to achieve target velocity + shaft_angle = _normalizeAngle(shaft_angle + target_velocity * Ts); + // for display purposes + shaft_velocity = target_velocity; + + // use voltage limit or current limit + float Uq = voltage_limit; + if (_isset(phase_resistance)) + { + Uq = _constrain(current_limit * phase_resistance + fabs(voltage_bemf), -voltage_limit, voltage_limit); + // recalculate the current + current.q = (Uq - fabs(voltage_bemf)) / phase_resistance; + } + + // set the maximal allowed voltage (voltage_limit) with the necessary angle + setPhaseVoltage(Uq, 0, _electricalAngle(shaft_angle, pole_pairs)); + + // save timestamp for next call + open_loop_timestamp = now_us; + + return Uq; +} + +// Function (iterative) generating open loop movement towards the target angle +// - target_angle - rad +// it uses voltage_limit and velocity_limit variables +float HybridStepperMotor::angleOpenloop(float target_angle) +{ + // get current timestamp + unsigned long now_us = _micros(); + // calculate the sample time from last call + float Ts = (now_us - open_loop_timestamp) * 1e-6f; + // quick fix for strange cases (micros overflow + timestamp not defined) + if (Ts <= 0 || Ts > 0.5f) + Ts = 1e-3f; + + // calculate the necessary angle to move from current position towards target angle + // with maximal velocity (velocity_limit) + if (abs(target_angle - shaft_angle) > abs(velocity_limit * Ts)) + { + shaft_angle += _sign(target_angle - shaft_angle) * abs(velocity_limit) * Ts; + shaft_velocity = velocity_limit; + } + else + { + shaft_angle = target_angle; + shaft_velocity = 0; + } + + // use voltage limit or current limit + float Uq = voltage_limit; + if (_isset(phase_resistance)) + { + Uq = _constrain(current_limit * phase_resistance + fabs(voltage_bemf), -voltage_limit, voltage_limit); + // recalculate the current + current.q = (Uq - fabs(voltage_bemf)) / phase_resistance; + } + // set the maximal allowed voltage (voltage_limit) with the necessary angle + setPhaseVoltage(Uq, 0, _electricalAngle((shaft_angle), pole_pairs)); + + // save timestamp for next call + open_loop_timestamp = now_us; + + return Uq; +} diff --git a/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.h b/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.h new file mode 100644 index 0000000..71e8792 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/HybridStepperMotor.h @@ -0,0 +1,112 @@ +/** + * @file HybridStepperMotor.h + * + */ + +#ifndef HybridStepperMotor_h +#define HybridStepperMotor_h + +#include "Arduino.h" +#include "common/base_classes/FOCMotor.h" +#include "common/base_classes/StepperDriver.h" +#include "common/base_classes/Sensor.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" +#include "common/defaults.h" + +/** + Stepper Motor class +*/ +class HybridStepperMotor : public FOCMotor +{ +public: + /** + HybridStepperMotor class constructor + @param pp pole pair number + @param R motor phase resistance - [Ohm] + @param KV motor KV rating (1/K_bemf) - rpm/V + @param L motor phase inductance - [H] + */ + HybridStepperMotor(int pp, float R = NOT_SET, float KV = NOT_SET, float L = NOT_SET); + + /** + * Function linking a motor and a foc driver + * + * @param driver BLDCDriver handle for hardware peripheral control + */ + void linkDriver(BLDCDriver *driver); + + /** + * BLDCDriver link: + */ + BLDCDriver *driver; + + /** Motor hardware init function */ + void init() override; + /** Motor disable function */ + void disable() override; + /** Motor enable function */ + void enable() override; + + /** + * Function initializing FOC algorithm + * and aligning sensor's and motors' zero position + */ + int initFOC() override; + + /** + * Function running FOC algorithm in real-time + * it calculates the gets motor angle and sets the appropriate voltages + * to the phase pwm signals + * - the faster you can run it the better Arduino UNO ~1ms, Bluepill ~ 100us + */ + void loopFOC() override; + + /** + * Function executing the control loops set by the controller parameter of the HybridStepperMotor. + * + * @param target Either voltage, angle or velocity based on the motor.controller + * If it is not set the motor will use the target set in its variable motor.target + * + * This function doesn't need to be run upon each loop execution - depends of the use case + */ + void move(float target = NOT_SET) override; + + float Ua, Ub, Uc; //!< Phase voltages used for inverse Park and Clarke transform + + /** + * Method using FOC to set Uq to the motor at the optimal angle + * Heart of the FOC algorithm + * + * @param Uq Current voltage in q axis to set to the motor + * @param Ud Current voltage in d axis to set to the motor + * @param angle_el current electrical angle of the motor + */ + void setPhaseVoltage(float Uq, float Ud, float angle_el) override; + +private: + /** Sensor alignment to electrical 0 angle of the motor */ + int alignSensor(); + /** Motor and sensor alignment to the sensors absolute 0 angle */ + int absoluteZeroSearch(); + + // Open loop motion control + /** + * Function (iterative) generating open loop movement for target velocity + * it uses voltage_limit variable + * + * @param target_velocity - rad/s + */ + float velocityOpenloop(float target_velocity); + /** + * Function (iterative) generating open loop movement towards the target angle + * it uses voltage_limit and velocity_limit variables + * + * @param target_angle - rad + */ + float angleOpenloop(float target_angle); + // open loop variables + long open_loop_timestamp; +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/README.md b/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/README.md new file mode 100644 index 0000000..4176539 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/motors/HybridStepperMotor/README.md @@ -0,0 +1,45 @@ +# Three Phase / Hybrid Stepper Motor Class + +By tying two phases together, you can use a standard bipolar stepper motor with three-phase drivers! +Of course, it requires some different math for commutation. Another limitation is that with SinePWM the motor voltage is limited to 50% of the supply voltage. Using some tricks in SpaceVectorPWM, this max bias can be increased to about 70%. + +## Warning + +This code has not been tested much! +It has killed one B-G431B-ESC1 board before. +However, it has been succesfully used on a few different hardware platforms, so it does work. +BEMF may be the danger here, so take caution with fast decelerations. +Keep in mind that potentially twice the current can be sunk in the shorted phase as the two other legs. + +## Hardware setup + +Tie two of the phases of the motor together. This is phase "C". The other two phases are A & B. Phase C must go last in the driver constructor. + + +## Software setup + +Usage is quite simple: + +```c++ +#include "Arduino.h" +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "motors/HybridStepperMotor/HybridStepperMotor.h" + +HybridStepperMotor motor = HybridStepperMotor(pole_pairs, phase_resistance, kv, winding_inductance); +BLDCDriver3PWM driver = BLDCDriver3PWM(phase_A, phase_B, phase_C, enable); + +void setup() { + driver.init(); + motor.linkDriver(&driver); + + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; //or SinePWM + motor.init(); + motor.initFOC(); +} + +void loop(){ + motor.loopFOC(); + motor.move(); +} +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/README.md b/firmware/lib/Arduino-FOC-drivers/src/settings/README.md new file mode 100644 index 0000000..9bd70fb --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/README.md @@ -0,0 +1,143 @@ +# SimpleFOC Settings Storage + +Code to persist calibration data and motor settings to and from storage. The SettingsStorage is abstract, and different implementations exist for different concete storage media. + +The SettingsStorage is based on the SimpleFOCRegisters abstraction, so this means you can load or store any of the registers (representing SimpleFOC settings) that is both readable and writeable (e.g. while the current shaft velocity is available as a register, you can't store it as a setting because its read-only). + +The SettingsStorage can save the settings for one or more motors, and you can customize which settings are saved. If you don't customize, only the motor +calibration will be stored (REG_ZERO_ELECTRIC_ANGLE, REG_SENSOR_DIRECTION). + +## Hardware requirements + +Obviously, to save settings you need a place to store them where they won't be lost when you power down. There can be many solutions to this question, and we attempt to provide some simple drivers for the common storage solutions people might want. + +But its also quite easy to extend the system to support your specific needs. + +Supported hardware: + +- [SAMD NVM](samd/) \ +Some SAMD chips have a built-in NVRAM flash, which can be written from user code. +- [CAT24 I2C Flash EEPROMs](i2c/) \ :warning: UNFINISHED +Simple programmable memories with I2C interface. Memory space is quite limited, but enough for storing settings. + +See Roadmap, below, for systems we may support in the future. + + +## Basic Usage + +Using SettingsStorage is simple. Just add a `settings.loadSettings()` after setting up your defaults, but before calling init() on the objects. And call `saveSettings()` after initialization of the motor has (successfully) completed. + +This example saves just the motor calibration, but you might want to add additional code to save other registers, or make your solution more user-friendly. See the other examples below. + +```c++ + +#include "settings/samd/SAMDNVMSettingsStorage.h" + +SAMDNVMSettingsStorage settings = SAMDNVMSettingsStorage(); +BLDCMotor motor = BLDCMotor(...); + +void setup() { + SimpleFOCDebug::enable(); // show debug messages from settings + + // initialize the settings early in the setup + settings.addMotor(&motor); + settings.init(); + + // first set your defaults + driver.voltage_power_supply = 12.0f; + driver.voltage_limit = 12.0f; // 12V driver limit, like PSU + motor.voltage_limit = 6.0f; // 6V motor limit + + // then try to load the settings + SettingsStatus loadStatus = settings.loadSettings(); + + // driver init code, etc... + ... + + // then init the motor + motor.init(); + motor.initFOC(); + + // and if the settings were not loaded earlier, then save them + if (motor.motor_status == FOCMotorStatus::motor_ready && loadStatus != SFOC_SETTINGS_SUCCESS) { + settings.saveSettings(); + } + + // any other initialization + ... +} + +``` + +### Choosing registers + +By default, only the calibration data (motor native direction, electrical zero position) are saved. To save additional registers, you can choose them before calling `SettingsStorage.init()`, as in the example below: + +```c++ + +SimpleFOCRegister settingsRegisters[] = { REG_ZERO_ELECTRIC_ANGLE, REG_SENSOR_DIRECTION, REG_VEL_PID_P, REG_VEL_PID_I, REG_VEL_PID_D, REG_VEL_LPF_T, REG_VEL_LIMIT, REG_VEL_MAX_RAMP, REG_VOLTAGE_LIMIT, REG_MOTION_DOWNSAMPLE, REG_CONTROL_MODE, REG_TORQUE_MODE, REG_PHASE_RESISTANCE, REG_KV, REG_INDUCTANCE }; +CAT24I2CFlashSettingsStorage settings = CAT24I2CFlashSettingsStorage(0xA0); +BLDCMotor motor = BLDCMotor(...); + +void setup() { + SimpleFOCDebug::enable(); // show debug messages from settings + + // initialize the settings early in the setup + settings.setRegisters(mySettingsRegisters, sizeof(mySettingsRegisters)); + settings.addMotor(&motor); + settings.init(); + ... +} +``` + + + +### Using settings with commander + +You can easily interact with the settings via the commander, for example to save your PID tuning values: + +```c++ + +SimpleFOCRegister settingsRegisters[] = { REG_ZERO_ELECTRIC_ANGLE, REG_SENSOR_DIRECTION, REG_VEL_PID_P, REG_VEL_PID_I, REG_VEL_PID_D, REG_VEL_LPF_T }; + +CAT24I2CFlashSettingsStorage settings = CAT24I2CFlashSettingsStorage(0xA0); + +Commander commander; + +void doSaveSettings(char *cmd) { settings.saveSettings(); } +void doLoadSettings(char *cmd) { settings.loadSettings(); } + + +void setup() { + ... + + settings.setRegisters(settingsRegisters, sizeof(settingsRegisters)); + settings.addMotor(&motor); + settings.init(); + + ... + + commander.addCommand('s', doSaveSettings, "Save settings"); + commander.addCommand('l', doLoadSettings, "Load settings"); + + ... + +} + + +void run() { + motor.move(); + motor.loopFOC(); + commander.run(); +} +``` + +## Roadmap + +The following ideas for storage backends are on the roadmap, with no definate schedule for implementation: + +- ESP32 SPIFFs Filesystem +- ESP32 Preferences +- Arduino EEPROM library +- In-Memory Buffer (for use with other libraries or abstractions) +- JSON String (for printing to console) diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.cpp b/firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.cpp new file mode 100644 index 0000000..5df2bcf --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.cpp @@ -0,0 +1,120 @@ + +#include "./SettingsStorage.h" +#include "communication/SimpleFOCDebug.h" + + +SettingsStorage::SettingsStorage() { + +}; + + +SettingsStorage::~SettingsStorage() { + +}; + + + +void SettingsStorage::addMotor(BLDCMotor* motor) { + if (numMotors < SIMPLEFOC_SETTINGS_MAX_MOTORS) { + motors[numMotors] = motor; + numMotors++; + } + else + SimpleFOCDebug::println("SS: too many motors"); +}; + + +void SettingsStorage::setRegisters(SimpleFOCRegister* registers, int numRegisters){ + this->registers = registers; + this->numRegisters = numRegisters; +}; + + +void SettingsStorage::init() { + // make sure we have motors and registers + if (numMotors < 1) { + SimpleFOCDebug::println("SS: no motors"); + return; + } + if (registers==NULL || numRegisters < 1) { + SimpleFOCDebug::println("SS: no registers"); + return; + } +}; + + + +SettingsStatus SettingsStorage::loadSettings() { + SimpleFOCDebug::println("Loading settings..."); + beforeLoad(); + uint8_t magic; readByte(&magic); + if (magic != SIMPLEFOC_SETTINGS_MAGIC_BYTE) { + SimpleFOCDebug::println("No settings found "); + return SFOC_SETTINGS_NONE; + } + uint8_t rversion; readByte(&rversion); + if (rversion != SIMPLEFOC_REGISTERS_VERSION) { + SimpleFOCDebug::println("Registers version mismatch"); + return SFOC_SETTINGS_OLD; + } + uint8_t version; readByte(&version); + if (version != settings_version) { + SimpleFOCDebug::println("Settings version mismatch"); + return SFOC_SETTINGS_OLD; + } + for (int m = 0; m < numMotors; m++) { + if (numMotors>1) + SimpleFOCDebug::println("Loading settings for motor ", m); + startLoadMotor(m); + for (int i = 0; i < numRegisters; i++) { + SimpleFOCRegister reg = registers[i]; + startLoadRegister(reg); + setRegister(reg, motors[m]); + endLoadRegister(); + } + endLoadMotor(); + } + afterLoad(); + SimpleFOCDebug::println("Settings loaded"); + return SFOC_SETTINGS_SUCCESS; +}; + + +SettingsStatus SettingsStorage::saveSettings() { + SimpleFOCDebug::println("Saving settings..."); + beforeSave(); + writeByte(SIMPLEFOC_SETTINGS_MAGIC_BYTE); + writeByte(SIMPLEFOC_REGISTERS_VERSION); + writeByte(settings_version); + for (int m = 0; m < numMotors; m++) { + if (numMotors>1) + SimpleFOCDebug::println("Saving settings for motor ", m); + startSaveMotor(m); + for (int i = 0; i < numRegisters; i++) { + SimpleFOCRegister reg = registers[i]; + startSaveRegister(reg); + sendRegister(reg, motors[m]); + endSaveRegister(); + } + endSaveMotor(); + } + afterSave(); + SimpleFOCDebug::println("Settings saved"); + return SFOC_SETTINGS_SUCCESS; +}; + +// empty implementation for these + +void SettingsStorage::startSaveMotor(uint8_t num) {}; +void SettingsStorage::endSaveMotor() {}; +void SettingsStorage::startSaveRegister(SimpleFOCRegister reg) {}; +void SettingsStorage::endSaveRegister() {}; +void SettingsStorage::startLoadMotor(uint8_t num) {}; +void SettingsStorage::endLoadMotor() {}; +void SettingsStorage::startLoadRegister(SimpleFOCRegister reg) {}; +void SettingsStorage::endLoadRegister() {}; + +void SettingsStorage::beforeLoad() {}; +void SettingsStorage::afterLoad() {}; +void SettingsStorage::beforeSave() {}; +void SettingsStorage::afterSave() {}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.h b/firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.h new file mode 100644 index 0000000..8506c3b --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/SettingsStorage.h @@ -0,0 +1,70 @@ + +#pragma once + + +#include "../comms/SimpleFOCRegisters.h" +#include "../comms/RegisterReceiver.h" +#include "../comms/RegisterSender.h" +#include "BLDCMotor.h" + +#define SIMPLEFOC_SETTINGS_MAGIC_BYTE 0x42 +#define SIMPLEFOC_SETTINGS_VERSION 0x01 + +#define SIMPLEFOC_SETTINGS_REGISTERS_MINIMAL { REG_ZERO_ELECTRIC_ANGLE, REG_SENSOR_DIRECTION } + + +#if !defined(SIMPLEFOC_SETTINGS_MAX_MOTORS) +#define SIMPLEFOC_SETTINGS_MAX_MOTORS 4 +#endif + + +typedef enum : uint8_t { + SFOC_SETTINGS_SUCCESS = 0, // settings loaded/saved successfully + SFOC_SETTINGS_NONE = 1, // no settings found to load + SFOC_SETTINGS_OLD = 2, // settings found, but version is old + SFOC_SETTINGS_ERROR = 3 // other error +} SettingsStatus; + + + + +class SettingsStorage : public RegisterReceiver, public RegisterSender { +public: + SettingsStorage(); + ~SettingsStorage(); + + void addMotor(BLDCMotor* motor); + void setRegisters(SimpleFOCRegister* registers, int numRegisters); + + virtual void init(); + + SettingsStatus loadSettings(); + SettingsStatus saveSettings(); + + /* + Change this value if you make changes to the registers saved in code, and have saved settings on existing devices. + This will cause the device to reset to defaults on the next boot. + */ + uint8_t settings_version = SIMPLEFOC_SETTINGS_VERSION; + +protected: + virtual void startSaveMotor(uint8_t num); + virtual void endSaveMotor(); + virtual void startSaveRegister(SimpleFOCRegister reg); + virtual void endSaveRegister(); + virtual void startLoadMotor(uint8_t num); + virtual void endLoadMotor(); + virtual void startLoadRegister(SimpleFOCRegister reg); + virtual void endLoadRegister(); + + + virtual void beforeLoad(); + virtual void afterLoad(); + virtual void beforeSave(); + virtual void afterSave(); + + FOCMotor* motors[SIMPLEFOC_SETTINGS_MAX_MOTORS]; + int numMotors = 0; + SimpleFOCRegister* registers = NULL; + int numRegisters = 0; +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.cpp b/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.cpp new file mode 100644 index 0000000..5d4b336 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.cpp @@ -0,0 +1,98 @@ + +#include "./CAT24I2CFlashSettingsStorage.h" + + +CAT24I2CFlashSettingsStorage::CAT24I2CFlashSettingsStorage(uint8_t address, uint16_t offset) { + _address = address; + _offset = offset; +}; + + + +CAT24I2CFlashSettingsStorage::~CAT24I2CFlashSettingsStorage() {}; + + + +void CAT24I2CFlashSettingsStorage::init(TwoWire* wire) { + SettingsStorage::init(); + _wire = wire; + reset(); +}; + + + +uint8_t CAT24I2CFlashSettingsStorage::readByte(uint8_t* valueToSet) { + return readBytes(valueToSet, 1); +}; + + + +uint8_t CAT24I2CFlashSettingsStorage::readFloat(float* valueToSet) { + return readBytes(valueToSet, 4); +}; + + + +uint8_t CAT24I2CFlashSettingsStorage::readInt(uint32_t* valueToSet) { + return readBytes(valueToSet, 4); +}; + + + +uint8_t CAT24I2CFlashSettingsStorage::writeByte(uint8_t value) { + return writeBytes(&value, 1); +}; + + + +uint8_t CAT24I2CFlashSettingsStorage::writeFloat(float value) { + return writeBytes(&value, 4); +}; + + + +uint8_t CAT24I2CFlashSettingsStorage::writeInt(uint32_t value) { + return writeBytes(&value, 4); +}; + + + +void CAT24I2CFlashSettingsStorage::beforeSave() { + reset(); +}; + + +void CAT24I2CFlashSettingsStorage::beforeLoad() { + reset(); + _wire->beginTransmission(_address); + _wire->write(_currptr >> 8); + _wire->write(_currptr & 0xFF); + _wire->endTransmission(false); +}; + + + +void CAT24I2CFlashSettingsStorage::reset() { + _currptr = _offset; +}; + + +int CAT24I2CFlashSettingsStorage::readBytes(void* valueToSet, int numBytes) { + int read = _wire->requestFrom((uint8_t)_address, (uint8_t)numBytes, (uint8_t)true); + _currptr += read; + if (read==numBytes) + _wire->readBytes((uint8_t*)valueToSet, numBytes); + return read; +}; + + +int CAT24I2CFlashSettingsStorage::writeBytes(void* value, int numBytes) { + _wire->beginTransmission(_address); + _wire->write(_currptr >> 8); + _wire->write(_currptr & 0xFF); + size_t written = _wire->write((uint8_t*)value, numBytes); + _wire->endTransmission(true); + _currptr += written; + delay(5); // write-cycle time + return written; +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.h b/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.h new file mode 100644 index 0000000..4f6c511 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/CAT24I2CFlashSettingsStorage.h @@ -0,0 +1,35 @@ + +#pragma once + +#include "../SettingsStorage.h" +#include "Wire.h" + +class CAT24I2CFlashSettingsStorage : public SettingsStorage { +public: + CAT24I2CFlashSettingsStorage(uint8_t address = 0xA0, uint16_t offset = 0x0); + ~CAT24I2CFlashSettingsStorage(); + + void init(TwoWire* wire = &Wire); + +protected: + uint8_t readByte(uint8_t* valueToSet) override; + uint8_t readFloat(float* valueToSet) override; + uint8_t readInt(uint32_t* valueToSet) override; + + uint8_t writeByte(uint8_t value) override; + uint8_t writeFloat(float value) override; + uint8_t writeInt(uint32_t value) override; + + void beforeSave() override; + void beforeLoad() override; + + void reset(); + int readBytes(void* valueToSet, int numBytes); + int writeBytes(void* value, int numBytes); + + TwoWire* _wire; + uint8_t _address; // i2c address + uint16_t _offset; // offset into NVRAM to store settings + uint16_t _currptr = 0; // pointer to current location in NVRAM + +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/README.md b/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/README.md new file mode 100644 index 0000000..9cb33bd --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/i2c/README.md @@ -0,0 +1,26 @@ + +# I2C memories settings drivers + +Store settings to I2C EEPROMs. + +## CAT24C64 I2C EEPROMs + +:warning: not yet finished or tested! + +Datasheet describes the CAT24C64 as: _The CAT24C64 is a 64 Kb CMOS Serial EEPROM device, internally organized as 8192 words of 8 bits each._ + +Provide I2C address in constructor: + +`CAT24I2CFlashSettingsStorage settings = CAT24I2CFlashSettingsStorage(0xA0);` + +If you want to use a different I2C bus than the default, you can pass it to the constructor: + +`settings.init(&Wire2);` + +You can use multiple settings objects in the same EEPROM, by providing an offset to the constructor: + +```c++ +CAT24I2CFlashSettingsStorage settings = CAT24I2CFlashSettingsStorage(0xA0); +CAT24I2CFlashSettingsStorage settings = CAT24I2CFlashSettingsStorage(0xA0, 80); +CAT24I2CFlashSettingsStorage settings = CAT24I2CFlashSettingsStorage(0xA0, 160); +``` diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/samd/README.md b/firmware/lib/Arduino-FOC-drivers/src/settings/samd/README.md new file mode 100644 index 0000000..7382751 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/samd/README.md @@ -0,0 +1,49 @@ +# SAMD21 settings driver + +Driver for storing settings on SAMD21 chips. + +There are two options: + +1. **RWW Flash** \ +Some SAMD21 chips have a seperate RWW flash area, of 2kB-8kB size. This area is seperate from the main flash array. \ +Note: this method is implemented and tested. + +2. **EEPROM emulation** \ +All SAMD21s support EEPROM emulation, where an area of the main flash is reserved for the application storage. \ +:warning: This method is not yet implemented fully, and untested. + +## Using RWW flash + +To use the RWW flash to store settings, you have to make sure the flash region is not locked (you can set the lock fuses using MCP Studio or other SAM development tools). + +Otherwise there is nothing special to do. When reprogramming the chip, be careful not to erase the RWW area. + +You can use multiple settings objects to store to different areas of the RWW. +To do so, specify an offset to the constructor: + +```c++ +SAMDNVMSettingsStorage settings0 = SAMDNVMSettingsStorage(); +SAMDNVMSettingsStorage settings1 = SAMDNVMSettingsStorage(NVMCTRL_ROW_SIZE); +SAMDNVMSettingsStorage settings2 = SAMDNVMSettingsStorage(NVMCTRL_ROW_SIZE*2); +``` + +Note: the offset must be a multiple of the flash memory row size, typically 256 bytes. + + +## Using EEPROM emulation + +TODO implement and test this method + +To use the EEPROM emulation, use a tool like MCP Studio to set the chip fuses to reserve an area of flash for EEPROM emulation: + +![](eeprom_emulation_screenshot.jpg) + +Normally 256 bytes (one flash page) should be plenty for SimpleFOC settings... Obviously, the area you reserve for EEPROM can't be used for your main program. + +Add a build-flag to your build to set the base address of your EEPROM memory: + +`-DSIMPLEFOC_SAMDNVMSETTINGS_BASE=0x003FF800` + +Then use the settings as normal. + +You'll have to adjust your board files to exclude the EEPROM area in the ldscript to prevent it being erased when you re-program, if you care to keep your settings when reflashing. diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/samd/SAMDNVMSettingsStorage.cpp b/firmware/lib/Arduino-FOC-drivers/src/settings/samd/SAMDNVMSettingsStorage.cpp new file mode 100644 index 0000000..5569600 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/settings/samd/SAMDNVMSettingsStorage.cpp @@ -0,0 +1,164 @@ + + + +#include "./SAMDNVMSettingsStorage.h" + + +#if defined(_SAMD21_) + +#include "communication/SimpleFOCDebug.h" + + +SAMDNVMSettingsStorage::SAMDNVMSettingsStorage(uint32_t offset) { + _offset = offset; +}; + +SAMDNVMSettingsStorage::~SAMDNVMSettingsStorage(){}; + +void SAMDNVMSettingsStorage::init(){ + SettingsStorage::init(); + reset(); +}; + + + +void SAMDNVMSettingsStorage::reset(){ + _currptr = (uint8_t*) SIMPLEFOC_SAMDNVMSETTINGS_BASE + _offset; // add offset to NVM base address +}; + + + +void SAMDNVMSettingsStorage::beforeLoad(){ + reset(); +}; + + +void SAMDNVMSettingsStorage::beforeSave(){ + reset(); + _writeIndex = 0; + + // set manual write mode + _ctlB = NVMCTRL->CTRLB.reg; + NVMCTRL->CTRLB.reg |= NVMCTRL_CTRLB_MANW; + while (NVMCTRL->INTFLAG.bit.READY == 0) {}; + // unlock region - user can do it with fuses + // erase rows + // TODO handle case that it is more than one row + NVMCTRL->ADDR.reg = ((uint32_t)_currptr - RWWEE_BASE) / 2; + NVMCTRL->STATUS.reg |= NVMCTRL_STATUS_MASK; + NVMCTRL->INTFLAG.bit.ERROR = 0; + NVMCTRL->CTRLA.reg = 0x1A | NVMCTRL_CTRLA_CMDEX_KEY; + delay(1); + while (NVMCTRL->INTFLAG.bit.READY == 0) {}; + if (NVMCTRL->INTFLAG.bit.ERROR == 1) + SimpleFOCDebug::println("NVM erase error ", NVMCTRL->STATUS.reg); + else + SimpleFOCDebug::println("NVM erased row @", (int)_currptr); +}; + + +void SAMDNVMSettingsStorage::afterSave() { + if (_writeIndex>0) + flushPage(); + // restore ctlb + delay(1); + NVMCTRL->CTRLB.reg =_ctlB; + while (NVMCTRL->INTFLAG.bit.READY == 0) {}; +} + + +void SAMDNVMSettingsStorage::flushPage(){ + // if we have an odd number of bytes, pad with 0xFF + if (_writeIndex%2==1) { + _writeBuffer[_writeIndex++] = 0xFF; + } + // erase page buffer + // NVMCTRL->ADDR.reg = ((uint32_t)_currptr - RWWEE_BASE) / 2; + // NVMCTRL->CTRLA.reg = NVMCTRL_CTRLA_CMD_PBC | NVMCTRL_CTRLA_CMDEX_KEY; + // while (NVMCTRL->INTFLAG.bit.READY == 0) {}; + // copy writeBuffer to NVM, using 16-bit writes + uint16_t* src = (uint16_t*)_writeBuffer; + uint16_t* dst = (uint16_t*)_currptr; + for (int i=0;i<_writeIndex/2;i++) { + *dst++ = *src++; + } + // write page + NVMCTRL->ADDR.reg = ((uint32_t)_currptr - RWWEE_BASE) / 2; + NVMCTRL->STATUS.reg |= NVMCTRL_STATUS_MASK; + NVMCTRL->INTFLAG.bit.ERROR = 0; + NVMCTRL->CTRLA.reg = 0x1C | NVMCTRL_CTRLA_CMDEX_KEY; + delay(1); + while (NVMCTRL->INTFLAG.bit.READY == 0) {}; + if (NVMCTRL->INTFLAG.bit.ERROR == 1) + SimpleFOCDebug::println("NVM write error ", NVMCTRL->STATUS.reg); + else + SimpleFOCDebug::println("NVM wrote page @", (int)_currptr); + // reset writeBuffer pointer and advance currptr to next page + _writeIndex = 0; + _currptr+=NVMCTRL_PAGE_SIZE; +} + + +int SAMDNVMSettingsStorage::readBytes(void* valueToSet, int numBytes) { + uint8_t* bytes = (uint8_t*)valueToSet; + for (int i=0;i + +#if defined(_SAMD21_) + +#include "../SettingsStorage.h" + +#define RWWEE_BASE 0x00400000 + +#if !defined(SIMPLEFOC_SAMDNVMSETTINGS_BASE) +#define SIMPLEFOC_SAMDNVMSETTINGS_BASE RWWEE_BASE +#endif + + +class SAMDNVMSettingsStorage : public SettingsStorage { +public: + SAMDNVMSettingsStorage(uint32_t offset = 0x0); + ~SAMDNVMSettingsStorage(); + + void init() override; + +protected: + uint8_t readByte(uint8_t* valueToSet) override; + uint8_t readFloat(float* valueToSet) override; + uint8_t readInt(uint32_t* valueToSet) override; + + uint8_t writeByte(uint8_t value) override; + uint8_t writeFloat(float value) override; + uint8_t writeInt(uint32_t value) override; + + void beforeSave() override; + void afterSave() override; + void beforeLoad() override; + + + void reset(); + int readBytes(void* valueToSet, int numBytes); + int writeBytes(void* value, int numBytes); + void flushPage(); + + uint32_t _offset; // offset into NVRAM to store settings + + uint32_t _ctlB; + uint8_t* _currptr; // pointer to current location in NVM + int _writeIndex; // index into current page being written + uint8_t _writeBuffer[NVMCTRL_PAGE_SIZE]; // buffer for writing to NVM +}; + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/settings/samd/eeprom_emulation_screenshot.jpg b/firmware/lib/Arduino-FOC-drivers/src/settings/samd/eeprom_emulation_screenshot.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c743439c8dba800f86f86fe7d46d77738cf713f8 GIT binary patch literal 73543 zcmc$_2UJu`(UIBubVvl0iU3B!`ilvj`|K0!MO20YO0|gMj2HNEQ)La*mQD z4S9fJcpJ{q^WFd6|E~M)dTYIgP1o+-UENh(RbAEHTuxjr0Hk+SHBe7?4ub(8j##4@}oE=QT(=!W1(Z4^(1qJjYAhLMR4ZE)j8PC@DejKhROt&{DZ3 zlZevN!@~ug6aZY^9(z4dQ)D$VHetnC1ILO9kO9&FxuvzYhr<2)T30xK=hyiE{5c-G zrVJPsxWe_P`2P$bv$6HI23d0-tZrrFZS4xe)!?&Z?cwzp05EdFa(3Ux9#`-e5T^73 z2MEG5SFruxF#HO(x`wa$K(*c*7hJCLS+yZcC&GG z17YwTkau-;w*ld55at2vc!2N~ekrT}z+?X(u%)HdADot!_J82NX#rb;9ViWN7Yi}ix zmw&glu~gRl4ZFGAyPEH7oOX_?R|0qqJ3iKU_#3wMR?+(nd$~XO)0dr>lEUwDOD_=m zr>&2({-1IOTa7>XpE^7={9WgXqrsKFT=(VetoLU;PaTy0lzaI+_%nW6H#NoI_3gY= z|IqI04VM0c$H7tKPus^153ls_8o#yWzvH)cQ}`FBx6z-m+1M(p{H|~7rvHatkH?CC z`toqO){SeNwk~Ra%DtcH{b~Cc6v*FrJRaZw!$T*_yH|35-4@US)Bsk{J}3hZz}yhf zy@r9uwtiPK3MjdI_Xv`Y z+;c%uJ_dCr@!vA5mjF-~1^~2E|CVuN0szTh08ra*?c??2Z+w_n85V#KkN}hb9l#8* z13Z8LAOc7LGQb@`1-J|701p9Uzyh!a8~|6q3-AR3fM6gDhz1gXS3o+D1>^vQKq*iO z)B(*v8_*5(0pEd9U>aBeR)9?a4jcpLXlQ6SXhdifXmn^SXq;$#Xd-A*X!2+(Xj*6w z(2UU@q1mIkq4}T%poOAEqa~rGqh+HNp;e$YptYg(qWwUdL|a7LK-)(76#XysIP^61_vjzcYth@#`_M{s9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|9a Oit0O1T}gDEcM||z$Zm}Q literal 0 HcmV?d00001 diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.cpp b/firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.cpp new file mode 100644 index 0000000..36271da --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.cpp @@ -0,0 +1,113 @@ +/* + * PreciseAngle.cpp + * + * Created on: 1 May 2021 + * Author: runger + */ + +#include +#include + +PreciseAngle::PreciseAngle() : angle(0), rotations(0) {} + +PreciseAngle::~PreciseAngle() {} + +PreciseAngle::PreciseAngle(const PreciseAngle &other) : angle(other.angle), rotations(other.rotations) {} + + +PreciseAngle::PreciseAngle(uint16_t count, int32_t rotations) : angle(count), rotations(rotations) {} + + +PreciseAngle::PreciseAngle(float radians) { + rotations = radians/_2PI; + angle = (radians - (rotations * _2PI)) * cpr / _2PI; +} + +PreciseAngle::PreciseAngle(double radians) { + rotations = radians/_2PI; + angle = (radians - (rotations * _2PI)) * cpr / _2PI; +} + +// returns the angle mod 2PI, i.e. the angle of the motor shaft, in radians +float PreciseAngle::getShaftAngle() { + return angle * _2PI / cpr; +} + + +// returns the angle mod 2PI, i.e. the angle of the motor shaft, in radians +int32_t PreciseAngle::getRotations() { + return rotations; +} + +// returns the angle mod 2PI, i.e. the angle of the motor shaft, in radians +uint16_t PreciseAngle::getShaftTicks() { + return angle; +} + + +// returns the total angle, including rotations, in radians +float PreciseAngle::asFloat() { + return (angle * _2PI / (float)cpr) + ((float)rotations * _2PI); +} + + +// returns the total angle, including rotations, in radians, as double precision +double PreciseAngle::asDouble() { + return (double)angle * _2PI / cpr + (double)rotations * _2PI; +} + + +// returns the total angle, including rotations, in ticks, as 64 bit integer +int64_t PreciseAngle::asTicks() { + return (int64_t)angle + (int64_t)rotations * cpr; +} + + + + +PreciseAngle PreciseAngle::operator+(const PreciseAngle &other) { + PreciseAngle result; + result.rotations = rotations + other.rotations; + uint32_t temp = angle + other.angle; + if (temp>=cpr) { + result.angle = temp-cpr; + result.rotations+=1; + } + else + result.angle = temp; + return result; +} + + +PreciseAngle PreciseAngle::operator-(const PreciseAngle &other) { + PreciseAngle result; + result.rotations = rotations - other.rotations; + int32_t temp = angle - other.angle; + if (temp<0) { + result.angle = temp+cpr; + result.rotations-=1; + } + else + result.angle = temp; + return result; +} + + +// velocity in rad/s +float PreciseAngle::velocity(const PreciseAngle &previous, uint32_t microseconds) { + PreciseAngle diff = (*this - previous); + return diff.asFloat() * (1e6/(float)microseconds); +} + + + +void PreciseAngle::update(uint16_t current_angle){ + int32_t diff = current_angle - angle; + if (abs(diff)>cpr_overflow_check){ + rotations += diff>0?-1:1; + } + angle = current_angle; +} + + + diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.h b/firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.h new file mode 100644 index 0000000..9b05d5e --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/PreciseAngle.h @@ -0,0 +1,57 @@ +/* + * PreciseAngle.h + * + * Created on: 1 May 2021 + * Author: runger + */ + +#ifndef LIBRARIES_ARDUNIO_FOC_DRIVERS_SRC_UTILITIES_PRECISEANGLE_H_ +#define LIBRARIES_ARDUNIO_FOC_DRIVERS_SRC_UTILITIES_PRECISEANGLE_H_ + +#include + +class PreciseAngle { +public: + PreciseAngle(); + virtual ~PreciseAngle(); + PreciseAngle(const PreciseAngle &other); + PreciseAngle(uint16_t count, int32_t rotations); + PreciseAngle(float radians); + PreciseAngle(double radians); + //PreciseAngle& operator=(const PreciseAngle &other); + + // returns the angle mod 2PI, i.e. the angle of the motor shaft, in radians + float getShaftAngle(); + // number of complete motor rotations + int32_t getRotations(); + uint16_t getShaftTicks(); + + // returns the total angle, including rotations, in radians + float asFloat(); + // returns the total angle, including rotations, in radians, as double precision + double asDouble(); + // returns the total angle, including rotations, in ticks, as 64 bit integer + int64_t asTicks(); + + + PreciseAngle operator+(const PreciseAngle &other); + PreciseAngle operator-(const PreciseAngle &other); + + // velocity in rad/s + float velocity(const PreciseAngle &previous, uint32_t microseconds); + + // update the angle with a new ticks value. this will increment the rotations + // if necessary, using a simple algorithm to detect overflows. + // if the motor turns too much between calls to update, the overflow could be missed + // and the rotations counted incorrectly. + void update(uint16_t current_angle); + + + const static uint16_t cpr = 16384; + const static uint16_t cpr_overflow_check = 13107; //cpr*0.8; +protected: + uint16_t angle; + int32_t rotations; +}; + +#endif /* LIBRARIES_ARDUNIO_FOC_DRIVERS_SRC_UTILITIES_PRECISEANGLE_H_ */ diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/README.md b/firmware/lib/Arduino-FOC-drivers/src/utilities/README.md new file mode 100644 index 0000000..7eb1796 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/README.md @@ -0,0 +1,25 @@ +# Utilities + +Some classes and functions you may find useful when working with SimpleFOC. + +### PreciseAngle + +:warning: work in progress! only velocity mode has been tested. + +SimpleFOC generally uses floats for calculations. This preserves compatibility with older MCUs which only support 32bit FP, and +can't do double precision, and ensures the maximum compatibilty for the library. + +When older MCUs become irrelevant, this may change, but in the meantime there is a problem representing the angles as floats. +On the one hand they have to be precise enough to accurately capture the electric position of the motor's rotor with respect to +the stator, so meybe even less than 0.1deg. Without this precision you can't do FOC. On the other hand, we need to support many +rotations of the motor shaft - a motor turning at 1000RPM for 1h will be at 60000 rotations or approx. 378,991.118radians. +Expressing these large numbers while also maintaining the required precision is too much for the humble float. + +PreciseAngle works in conjunction with PreciseXXXSensor classes [like this one](../encoders/as5048a/PreciseMagneticSensorAS5048A.h). +It solves the float problem by representing the angle as seperate components: angle within rotation and number of rotations, both as +integers. It maintains the complete precision of the sensor over a rotation range of +/- 2^31, i.e. about 2 billion rotations, before +overflowing. + +Even at 50000RPM (which would be a lot for SimpleFOC!) that's enough for about 30 days of continuous rotation. At 1000RPM it's enough +for 4 years. + diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/README.md b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/README.md new file mode 100644 index 0000000..614231d --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/README.md @@ -0,0 +1,41 @@ + +# SimpleFOC math functions for STM32 CORDIC + +Accellerated trigonometry functions are provided for STM32 MCUs having a CORDIC peripheral. The CORDIC hardware can compute sine and cosine values in just a few processor cycles. + +## Usage + +To use it, set the build-flag `-DHAL_CORDIC_MODULE_ENABLED` for the CORDIC to be enabled in the framework. + +Then, include the following in your code: + +```c++ +#include +#include "SimpleFOC.h" +#include "SimpleFOCDrivers.h" +#include "utilities/stm32math/STM32G4CORDICTrigFunctions.h" + +void setup() { + ... + + SimpleFOC_CORDIC_Config(); // initialize the CORDIC + + ... +} + +``` + +That's it. The faster trig functions will be used automatically by the SimpleFOC code. + +You can use them yourself in your own code too: + +```c++ + +float angle = 0.5f; // in radians +float s = _sin(angle); +float c = _cos(angle); + +// get both sine and cosine in one operation +_sincos(angle, &s, &c); + +``` \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.cpp b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.cpp new file mode 100644 index 0000000..2095ee8 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.cpp @@ -0,0 +1,83 @@ + +#include "./STM32G4CORDICTrigFunctions.h" + +#ifdef HAL_CORDIC_MODULE_ENABLED + +#include "Arduino.h" +//#include "stm32g4xx_hal_cordic.h" +#include "stm32g4xx_ll_cordic.h" +#include "stm32g4xx_ll_rcc.h" +#include "stm32g4xx_ll_bus.h" +#include "common/foc_utils.h" +#include "arm_math.h" + +CORDIC_HandleTypeDef thisCordic; + +bool SimpleFOC_CORDIC_Config(void){ + //__HAL_RCC_CORDIC_CLK_ENABLE(); + // CORDIC_ConfigTypeDef sConfig; + // thisCordic.Instance = CORDIC; + // if (HAL_CORDIC_Init(&thisCordic) != HAL_OK) { + // Error_Handler(); + // return false; + // } + + // sConfig.Function = CORDIC_FUNCTION_COSINE; + // sConfig.Precision = CORDIC_PRECISION_6CYCLES; + // sConfig.Scale = CORDIC_SCALE_0; + // sConfig.NbWrite = CORDIC_NBWRITE_1; + // sConfig.NbRead = CORDIC_NBREAD_2; + // sConfig.InSize = CORDIC_INSIZE_32BITS; + // sConfig.OutSize = CORDIC_OUTSIZE_32BITS; + // if (HAL_CORDIC_Configure(&thisCordic, &sConfig) != HAL_OK) { + // /* Channel Configuration Error */ + // Error_Handler(); + // return false; + // } + + LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_CORDIC); + LL_CORDIC_Config(CORDIC, LL_CORDIC_FUNCTION_COSINE, /* cosine function */ + LL_CORDIC_PRECISION_6CYCLES, /* max precision for q1.31 cosine */ + LL_CORDIC_SCALE_0, /* no scale */ + LL_CORDIC_NBWRITE_1, /* One input data: angle. Second input data (modulus) is 1 after cordic reset */ + LL_CORDIC_NBREAD_2, /* Two output data: cosine, then sine */ + LL_CORDIC_INSIZE_32BITS, /* q1.31 format for input data */ + LL_CORDIC_OUTSIZE_32BITS); /* q1.31 format for output data */ + return true; +}; + + + +float _sin(float a) { + a = fmod(a, _2PI); + if (a>_PI) a -= _2PI; + if (a<-_PI) a += _2PI; + CORDIC->WDATA = (q31_t)((a / _PI) * 0x80000000); + q31_t out_cos = (int32_t)CORDIC->RDATA; // read cosine result + q31_t out_sin = (int32_t)CORDIC->RDATA; // read sine result + return (float)out_sin / (float)0x80000000; +} + +float _cos(float a) { + a = fmod(a, _2PI); + if (a>_PI) a -= _2PI; + if (a<-_PI) a += _2PI; + CORDIC->WDATA = (q31_t)((a / _PI) * 0x80000000); + q31_t out_cos = (int32_t)CORDIC->RDATA; // read cosine result + q31_t out_sin = (int32_t)CORDIC->RDATA; // read sine result + return (float)out_cos / (float)0x80000000; +} + +void _sincos(float a, float* s, float* c) { + a = fmod(a, _2PI); + if (a>_PI) a -= _2PI; + if (a<-_PI) a += _2PI; + CORDIC->WDATA = (q31_t)((a / _PI) * 0x80000000); + q31_t out_cos = (int32_t)CORDIC->RDATA; // read cosine result + q31_t out_sin = (int32_t)CORDIC->RDATA; // read sine result + *c = (float)out_cos / (float)0x80000000; + *s = (float)out_sin / (float)0x80000000; +} + + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.h b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.h new file mode 100644 index 0000000..9277ac5 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32math/STM32G4CORDICTrigFunctions.h @@ -0,0 +1,10 @@ + +#pragma once + +#ifdef HAL_CORDIC_MODULE_ENABLED + + +bool SimpleFOC_CORDIC_Config(void); + + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/README.md b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/README.md new file mode 100644 index 0000000..20a641b --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/README.md @@ -0,0 +1,73 @@ + +# STM32 Utilities - PWM Input + +Using the `STM32PWMInput` class you can precisely read a PWM input signal on STM32 MCUs by using their timer's PWM-Input mode. This happens entirely in the timer hardware with zero MCU overhead, and is very precise. + +## Setup + +Connect the PWM input to either channel 1 or channel 2 of a general purpose or advanced control timer supporting PWM-Input mode. + +This should include the following timers: + +- Advanced control timers: TIM1, TIM8 +- General purpose timers (32 bit): TIM2, TIM5 +- General purpose timers (16 bit): TIM3, TIM4, TIM9, TIM12 + +The best to use are the 32 bit general purpose timers, although TIM1 may also be interesting because on some MCUs it can be clocked at a higher rate than the other timers. + +## Usage + +``` + STM32PWMInput pwmInput = STM32PWMInput(PA15); + pwmInput.init(); + + uint32_t periodTicks = pwmInput.getPeriodTicks(); + uint32_t dutyTicks = pwmInput.getDutyCycleTicks(); + float dutyPercent = pwmInput.getDutyCyclePercent(); +``` + +## Input signal + +The input signal should be a PWM signal (square wave) with a duty cycle that is >0% and <100%. The + +The behaviour if the input is not a square wave is not defined, although the MCU will continue to sample the input, and resumes correct measurement when the square wave input is restored. + +## Performance + +The range of PWM frequencies that can be measured and the resolution with which they can be sampled depends on the following: + +- timer clock speed - normally this is your MCU speed, but it can be lower, or in some cases even higher. +- timer prescaler - can divide the timer clock. + +The sample resolution for a PWM input signal of frequency _Fp_ is given by + +_R = Fc / Fp_ + +Where _R_ is the resolution in ticks, and _Fc_ is the timer tick frequency (timer clock with prescaler). + +This sample resolution is equal to the length of the PWM period in ticks. The timer needs to sample both the duty cycle and the full period, so the timer can't sample signals whose period would cause it to overflow. + +On a 16 bit timer this means the period (and sample resolution) must be less than 65536 ticks, while on a 32 bit timer it must be less than 4294967296 ticks. This places a lower limit on the PWM frequencies that can be sampled. + +On the other side, the minimum duty cycle that can be reliably captured is limited by the duration of one timer tick, e.g. the minimum on-time that can be measured reliably is equal to two timer ticks in duration. + +So as the frequency increases, the resolution decreases, and the minimum duty cycle increases. + +For example, on a 64MHz STM32 MCU, using TIM3 (16 bit) you could capture a PWM signal at 10kHz with a resolution of 6400 ticks. This fits in the 16 bit timer, so no problem. Assuming the signal is perfectly stable (it usually isn't) that would be 12 bits of accuracy on your input. + +If you lowered the PWM input frequency to 1kHz, you'd get a 64000 range - just fitting in the timer. But now the accuracy is greatly increased - almost 16 bits! + +If you increased the PWM frequency to 10Mhz, the resolution would be just 6 ticks, and the resulting accuracy very low - just 2 bits, with a minimum duty cycle of 33% and a maximum of 66%. + +Of course you could vary the 10MHz signal faster than the 1kHz one - so choosing the PWM input frequency is a tradeoff between accuracy and control bandwidth... + +Note: clock configuration is out of scope for this class. Set your clocks up in advance. + + + +## Roadmap + +- Support setting of the filtering function, this could help a lot against noise on the input +- Support setting of the timer prescaler (not the clock prescaler!) +- Support setting of the downsample function, this could help increase accuracy +- Support choosing of the alternate timers on pins with more than one diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.cpp b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.cpp new file mode 100644 index 0000000..c530c04 --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.cpp @@ -0,0 +1,108 @@ + +#include "./STM32PWMInput.h" + +#if defined(_STM32_DEF_) + + + +STM32PWMInput::STM32PWMInput(int pin){ + _pin = digitalPinToPinName(pin); +}; + + +STM32PWMInput::~STM32PWMInput(){}; + + + + + +int STM32PWMInput::initialize(){ + pinmap_pinout(_pin, PinMap_TIM); + uint32_t channel = STM_PIN_CHANNEL(pinmap_function(_pin, PinMap_TIM)); + timer.Instance = (TIM_TypeDef *)pinmap_peripheral(_pin, PinMap_TIM); + timer.Init.Prescaler = 0; + timer.Init.CounterMode = TIM_COUNTERMODE_UP; + timer.Init.Period = 4.294967295E9; // TODO max period, depends on which timer is used - 32 bits or 16 bits + timer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + timer.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (channel!=1 && channel!=2) // only channels 1 & 2 supported + return -10; + useChannel2 = (channel==2);// remember the channel + if (HAL_TIM_Base_Init(&timer) != HAL_OK) { + return -1; + } + TIM_ClockConfigTypeDef clkCfg = { .ClockSource=TIM_CLOCKSOURCE_INTERNAL }; + if (HAL_TIM_ConfigClockSource(&timer, &clkCfg) != HAL_OK) { + return -2; + } + if (HAL_TIM_IC_Init(&timer) != HAL_OK) { + return -3; + } + + TIM_SlaveConfigTypeDef slCfg = { + .SlaveMode = TIM_SLAVEMODE_RESET, + .InputTrigger = (channel==1)?TIM_TS_TI1FP1:TIM_TS_TI2FP2, + .TriggerPolarity = TIM_INPUTCHANNELPOLARITY_RISING, + .TriggerPrescaler = TIM_ICPSC_DIV1, + .TriggerFilter = 0 + }; + if (HAL_TIM_SlaveConfigSynchro(&timer, &slCfg) != HAL_OK) { + return -4; + } + TIM_IC_InitTypeDef icCfg = { + .ICPolarity = (channel==1)?TIM_INPUTCHANNELPOLARITY_RISING:TIM_INPUTCHANNELPOLARITY_FALLING, + .ICSelection = (channel==1)?TIM_ICSELECTION_DIRECTTI:TIM_ICSELECTION_INDIRECTTI, + .ICPrescaler = TIM_ICPSC_DIV1, + .ICFilter = 0 + }; + if (HAL_TIM_IC_ConfigChannel(&timer, &icCfg, TIM_CHANNEL_1) != HAL_OK) { + return -5; + } + icCfg.ICPolarity = (channel==1)?TIM_INPUTCHANNELPOLARITY_FALLING:TIM_INPUTCHANNELPOLARITY_RISING; + icCfg.ICSelection = (channel==1)?TIM_ICSELECTION_INDIRECTTI:TIM_ICSELECTION_DIRECTTI; + if (HAL_TIM_IC_ConfigChannel(&timer, &icCfg, TIM_CHANNEL_2) != HAL_OK) { + return -6; + } + TIM_MasterConfigTypeDef mCfg = { + .MasterOutputTrigger = TIM_TRGO_RESET, + .MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE + }; + if (HAL_TIMEx_MasterConfigSynchronization(&timer, &mCfg) != HAL_OK) { + return -7; + } + if (HAL_TIM_IC_Start(&timer, TIM_CHANNEL_1)!=HAL_OK) { + return -8; + } + if (HAL_TIM_IC_Start(&timer, TIM_CHANNEL_2)!=HAL_OK) { + return -9; + } + timer.Instance->CR1 |= TIM_CR1_CEN; + return 0; +}; + + +float STM32PWMInput::getDutyCyclePercent(){ + uint32_t period = getPeriodTicks(); + if (period<1) return 0.0f; + return getDutyCycleTicks() / (float)period * 100.0f; +}; + + +uint32_t STM32PWMInput::getDutyCycleTicks(){ + if (useChannel2) + return timer.Instance->CCR1; + else + return timer.Instance->CCR2; +}; + + +uint32_t STM32PWMInput::getPeriodTicks(){ + if (useChannel2) + return timer.Instance->CCR2; + else + return timer.Instance->CCR1; +}; + + + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.h b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.h new file mode 100644 index 0000000..fcf3acd --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/utilities/stm32pwm/STM32PWMInput.h @@ -0,0 +1,29 @@ +#pragma once + +#include "Arduino.h" + +#if defined(_STM32_DEF_) + + +class STM32PWMInput { + public: + STM32PWMInput(int pin); + ~STM32PWMInput(); + + int initialize(); + + float getDutyCyclePercent(); + uint32_t getDutyCycleTicks(); + uint32_t getPeriodTicks(); + + PinName _pin; + protected: + TIM_HandleTypeDef timer; + bool useChannel2 = false; +}; + + + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.cpp b/firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.cpp new file mode 100644 index 0000000..714a0cb --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.cpp @@ -0,0 +1,44 @@ + +#include "GenericVoltageSense.h" +#include "Arduino.h" + + + +GenericVoltageSense::GenericVoltageSense(int pin, float gain, float offset, float Tf, float fullScaleVoltage) : VoltageSense(gain, offset, Tf), fullScaleVoltage(fullScaleVoltage), pin(pin) { +}; + +#ifndef INPUT_ANALOG +#define INPUT_ANALOG INPUT +#endif + +#ifndef ADC_RESOLUTION +#define ADC_RESOLUTION 10 +#endif + + +bool GenericVoltageSense::init(int resolution){ + pinMode(pin, INPUT_ANALOG); +#if !defined(ARDUINO_ARCH_AVR) && !defined(ARDUINO_ARCH_MEGAAVR) + if (resolution>0) { + analogReadResolution(resolution); + maxValue = _powtwo(resolution); + } + else { + maxValue = _powtwo(ADC_RESOLUTION); + } +#else + maxValue = _powtwo(ADC_RESOLUTION); +#endif + return true; +}; + + + + + +float GenericVoltageSense::readRawVoltage(){ + float val = analogRead(pin); + val = (val / (float)maxValue) * fullScaleVoltage; + return val; +}; + diff --git a/firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.h b/firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.h new file mode 100644 index 0000000..673162a --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/voltage/GenericVoltageSense.h @@ -0,0 +1,23 @@ + +#ifndef __GENERICVOLTAGESENSE_H__ +#define __GENERICVOLTAGESENSE_H__ + +#include "./VoltageSense.h" +#include "common/foc_utils.h" + +class GenericVoltageSense : public VoltageSense { + public: + GenericVoltageSense(int pin, float gain = 1.0f, float offset = 0.0f, float Tf = 0.1f, float fullScaleVoltage = 3.3f); + bool init(int resolution = -1); + float fullScaleVoltage; + protected: + float readRawVoltage() override; + int maxValue; + int pin; +}; + + + + + +#endif diff --git a/firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.cpp b/firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.cpp new file mode 100644 index 0000000..725d16f --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.cpp @@ -0,0 +1,23 @@ + + +#include "./VoltageSense.h" + + + +VoltageSense::VoltageSense(float gain, float offset, float Tf) : filter(Tf), gain(gain), offset(offset) { + voltage = 0.0f; +}; + + + +float VoltageSense::getVoltage(){ + return voltage; +}; + + + +void VoltageSense::update(){ + float v = readRawVoltage(); + v = (v - offset) * gain; + voltage = filter(v); +}; diff --git a/firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.h b/firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.h new file mode 100644 index 0000000..08ebfec --- /dev/null +++ b/firmware/lib/Arduino-FOC-drivers/src/voltage/VoltageSense.h @@ -0,0 +1,24 @@ +#ifndef __VOLTAGESENSE_H__ +#define __VOLTAGESENSE_H__ + +#include "common/lowpass_filter.h" + +class VoltageSense { + public: + VoltageSense(float gain = 1.0f, float offset = 0.0f, float Tf = 0.1f); + float getVoltage(); + virtual void update(); + + LowPassFilter filter; + float gain; + float offset; + + protected: + virtual float readRawVoltage() = 0; + + float voltage; +}; + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/CITATION.cff b/firmware/lib/Arduino-FOC/CITATION.cff new file mode 100644 index 0000000..ec37686 --- /dev/null +++ b/firmware/lib/Arduino-FOC/CITATION.cff @@ -0,0 +1,48 @@ +cff-version: 1.0.0 +message: "If you use this software, please cite it as below." +authors: +- family-names: "Skuric" + given-names: "Antun" + orcid: "https://orcid.org/0000-0002-3323-4482" +- family-names: "Bank" + given-names: "Hasan Sinan" + orcid: "https://orcid.org/0000-0002-0626-2664" +- family-names: "Unger" + given-names: "Richard" +- family-names: "Williams" + given-names: "Owen" +- family-names: "González-Reyes" + given-names: "David" + orcid: "https://orcid.org/0000-0002-1535-3007" +title: "SimpleFOC: A Field Oriented Control (FOC) Library for Controlling Brushless Direct Current (BLDC) and Stepper Motors" +version: 2.2.2 +doi: 10.21105/joss.04232 +date-released: 2022-06-26 +url: "https://github.com/simplefoc/Arduino-FOC" + +preferred-citation: + type: article + authors: + - family-names: "Skuric" + given-names: "Antun" + orcid: "https://orcid.org/0000-0002-3323-4482" + - family-names: "Bank" + given-names: "Hasan Sinan" + orcid: "https://orcid.org/0000-0002-0626-2664" + - family-names: "Unger" + given-names: "Richard" + - family-names: "Williams" + given-names: "Owen" + - family-names: "González-Reyes" + given-names: "David" + orcid: "https://orcid.org/0000-0002-1535-3007" + doi: "10.21105/joss.04232" + journal: "Journal of Open Source Software" + url: "https://doi.org/10.21105/joss.04232" + month: 6 + start: 4232 # First page number + end: 4232 # Last page number + title: "SimpleFOC: A Field Oriented Control (FOC) Library for Controlling Brushless Direct Current (BLDC) and Stepper Motors" + volume: 7 + issue: 74 + year: 2022 diff --git a/firmware/lib/Arduino-FOC/CODE_OF_CONDUCT.md b/firmware/lib/Arduino-FOC/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..88763e9 --- /dev/null +++ b/firmware/lib/Arduino-FOC/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +info@simplefoc.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/firmware/lib/Arduino-FOC/LICENSE b/firmware/lib/Arduino-FOC/LICENSE new file mode 100644 index 0000000..4a32ba6 --- /dev/null +++ b/firmware/lib/Arduino-FOC/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Antun Skuric + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/firmware/lib/Arduino-FOC/README.md b/firmware/lib/Arduino-FOC/README.md new file mode 100644 index 0000000..747b0f3 --- /dev/null +++ b/firmware/lib/Arduino-FOC/README.md @@ -0,0 +1,223 @@ +# SimpleFOClibrary - **Simple** Field Oriented Control (FOC) **library**
+### A Cross-Platform FOC implementation for BLDC and Stepper motors
based on the Arduino IDE and PlatformIO + +![Library Compile](https://github.com/simplefoc/Arduino-FOC/workflows/Library%20Compile/badge.svg) +![GitHub release (latest by date)](https://img.shields.io/github/v/release/simplefoc/arduino-foc) +![GitHub Release Date](https://img.shields.io/github/release-date/simplefoc/arduino-foc?color=blue) +![GitHub commits since tagged version](https://img.shields.io/github/commits-since/simplefoc/arduino-foc/latest/dev) +![GitHub commit activity (branch)](https://img.shields.io/github/commit-activity/m/simplefoc/arduino-foc/dev) + +[![arduino-library-badge](https://www.ardu-badge.com/badge/Simple%20FOC.svg?)](https://www.ardu-badge.com/badge/Simple%20FOC.svg) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![status](https://joss.theoj.org/papers/4382445f249e064e9f0a7f6c1bb06b1d/status.svg)](https://joss.theoj.org/papers/4382445f249e064e9f0a7f6c1bb06b1d) + + +We live in very exciting times 😃! BLDC motors are entering the hobby community more and more and many great projects have already emerged leveraging their far superior dynamics and power capabilities. BLDC motors have numerous advantages over regular DC motors but they have one big disadvantage, the complexity of control. Even though it has become relatively easy to design and manufacture PCBs and create our own hardware solutions for driving BLDC motors the proper low-cost solutions are yet to come. One of the reasons for this is the apparent complexity of writing the BLDC driving algorithms, Field oriented control (FOC) being an example of one of the most efficient ones. +The solutions that can be found on-line are almost exclusively very specific for certain hardware configuration and the microcontroller architecture used. +Additionally, most of the efforts at this moment are still channeled towards the high-power applications of the BLDC motors and proper low-cost and low-power FOC supporting boards are very hard to find today and even may not exist.
+Therefore this is an attempt to: +- 🎯 Demystify FOC algorithm and make a robust but simple Arduino library: [Arduino *SimpleFOClibrary*](https://docs.simplefoc.com/arduino_simplefoc_library_showcase) + - Support as many motor + sensor + driver + mcu combinations out there +- 🎯 Develop a modular FOC supporting BLDC driver boards: + - ***NEW*** 📢: *Minimalistic* BLDC driver (<3Amps) : [SimpleFOCMini ](https://github.com/simplefoc/SimpleFOCMini). + - *Low-power* gimbal driver (<5Amps) : [*Arduino Simple**FOC**Shield*](https://docs.simplefoc.com/arduino_simplefoc_shield_showcase). + - *Medium-power* BLDC driver (<30Amps): [Arduino SimpleFOCPowerShield ](https://github.com/simplefoc/Arduino-SimpleFOC-PowerShield). + - See also [@byDagor](https://github.com/byDagor)'s *fully-integrated* ESP32 based board: [Dagor Brushless Controller](https://github.com/byDagor/Dagor-Brushless-Controller) + +> NEW RELEASE 📢 : SimpleFOClibrary v2.3.1 +> - Support for Arduino UNO R4 Minima (Renesas R7FA4M1 MCU - note UNO R4 WiFi is not yet supported) +> - Support setting PWM polarity on ESP32 (thanks to [@mcells](https://github.com/mcells)) +> - Expose I2C errors in MagneticSensorI2C (thanks to [@padok](https://github.com/padok)) +> - Improved default trig functions (sine, cosine) - faster, smaller +> - Overridable trig functions - plug in your own optimized versions +> - Bugfix: microseconds overflow in velocity mode [#287](https://github.com/simplefoc/Arduino-FOC/issues/287) +> - Bugfix: KV initialization ([5fc3128](https://github.com/simplefoc/Arduino-FOC/commit/5fc3128d282b65c141ca486327c6235089999627)) +> - And more bugfixes - see the [complete list of 2.3.1 fixes here](https://github.com/simplefoc/Arduino-FOC/issues?q=is%3Aissue+milestone%3A2.3.1_Release) +> - Change: simplify initFOC() API ([d57d32d](https://github.com/simplefoc/Arduino-FOC/commit/d57d32dd8715dbed4e476469bc3de0c052f1d531). [5231e5e](https://github.com/simplefoc/Arduino-FOC/commit/5231e5e1d044b0cc33ede67664b6ef2f9d0a8cdf), [10c5b87](https://github.com/simplefoc/Arduino-FOC/commit/10c5b872672cab72df16ddd738bbf09bcce95d28)) +> - Change: check for linked driver in currentsense and exit gracefully ([5ef4d9d](https://github.com/simplefoc/Arduino-FOC/commit/5ef4d9d5a92e03da0dd5af7f624243ab30f1b688)) +> - Compatibility with newest versions of Arduino framework for STM32, Renesas, ESP32, Atmel SAM, Atmel AVR, nRF52 and RP2040 + +## Arduino *SimpleFOClibrary* v2.3.1 + +
+ +This video demonstrates the *Simple**FOC**library* basic usage, electronic connections and shows its capabilities. + +### Features +- **Easy install**: + - Arduino IDE: Arduino Library Manager integration + - PlatformIO +- **Open-Source**: Full code and documentation available on github +- **Goal**: + - Support as many [sensor](https://docs.simplefoc.com/position_sensors) + [motor](https://docs.simplefoc.com/motors) + [driver](https://docs.simplefoc.com/drivers) + [current sense](https://docs.simplefoc.com/current_sense) combination as possible. + - Provide the up-to-date and in-depth documentation with API references and the examples +- **Easy to setup and configure**: + - Easy hardware configuration + - Each hardware component is a C++ object (easy to understand) + - Easy [tuning the control loops](https://docs.simplefoc.com/motion_control) + - [*Simple**FOC**Studio*](https://docs.simplefoc.com/studio) configuration GUI tool + - Built-in communication and monitoring +- **Cross-platform**: + - Seamless code transfer from one microcontroller family to another + - Supports multiple [MCU architectures](https://docs.simplefoc.com/microcontrollers): + - Arduino: UNO R4, UNO, MEGA, DUE, Leonardo, Nano, Nano33 .... + - STM32 + - ESP32 + - Teensy + - many more ... + +

+ + +## Documentation +Full API code documentation as well as example projects and step by step guides can be found on our [docs website](https://docs.simplefoc.com/). + +![image](https://user-images.githubusercontent.com/36178713/168475410-105e4e3d-082a-4015-98ff-d380c7992dfd.png) + + +## Getting Started +Depending on if you want to use this library as the plug and play Arduino library or you want to get insight in the algorithm and make changes there are two ways to install this code. + +- Full library installation [Docs](https://docs.simplefoc.com/library_download) +- PlatformIO [Docs](https://docs.simplefoc.com/library_platformio) + +### Arduino *SimpleFOClibrary* installation to Arduino IDE +#### Arduino Library Manager +The simplest way to get hold of the library is directly by using Arduino IDE and its integrated Library Manager. +- Open Arduino IDE and start Arduino Library Manager by clicking: `Tools > Manage Libraries...`. +- Search for `Simple FOC` library and install the latest version. +- Reopen Arduino IDE and you should have the library examples in `File > Examples > Simple FOC`. + +#### Using Github website +- Go to the [github repository](https://github.com/simplefoc/Arduino-FOC) +- Click first on `Clone or Download > Download ZIP`. +- Unzip it and place it in `Arduino Libraries` folder. Windows: `Documents > Arduino > libraries`. +- Reopen Arduino IDE and you should have the library examples in `File > Examples > Simple FOC`. + +#### Using terminal +- Open terminal and run +```sh +cd #Arduino libraries folder +git clone https://github.com/simplefoc/Arduino-FOC.git +``` +- Reopen Arduino IDE and you should have the library examples in `File > Examples > Simple FOC`. + +## Community and contributing + +For all the questions regarding the potential implementation, applications, supported hardware and similar please visit our [community forum](https://community.simplefoc.com) or our [discord server](https://discord.gg/kWBwuzY32n). + +It is always helpful to hear the stories/problems/suggestions of people implementing the code and you might find a lot of answered questions there already! + +### Github Issues & Pull requests + +Please do not hesitate to leave an issue if you have problems/advices/suggestions regarding the code! + +Pull requests are welcome, but let's first discuss them in [community forum](https://community.simplefoc.com)! + +If you'd like to contribute to this project but you are not very familiar with github, don't worry, let us know either by posting at the community forum , by posting a github issue or at our discord server. + +If you are familiar, we accept pull requests to the dev branch! + +## Arduino code example +This is a simple Arduino code example implementing the velocity control program of a BLDC motor with encoder. + +NOTE: This program uses all the default control parameters. + +```cpp +#include + +// BLDCMotor( pole_pairs ) +BLDCMotor motor = BLDCMotor(11); +// BLDCDriver( pin_pwmA, pin_pwmB, pin_pwmC, enable (optional) ) +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 10, 11, 8); +// Encoder(pin_A, pin_B, CPR) +Encoder encoder = Encoder(2, 3, 2048); +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + + +void setup() { + // initialize encoder hardware + encoder.init(); + // hardware interrupt enable + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // power supply voltage [V] + driver.voltage_power_supply = 12; + // initialise driver hardware + driver.init(); + // link driver + motor.linkDriver(&driver); + + // set control loop type to be used + motor.controller = MotionControlType::velocity; + // initialize motor + motor.init(); + + // align encoder and start FOC + motor.initFOC(); +} + +void loop() { + // FOC algorithm function + motor.loopFOC(); + + // velocity control loop function + // setting the target velocity or 2rad/s + motor.move(2); +} +``` +You can find more details in the [SimpleFOC documentation](https://docs.simplefoc.com/). + +## Example projects +Here are some of the *Simple**FOC**library* and *Simple**FOC**Shield* application examples. +

+ + + + + + + + + + + + +

+ + +## Citing the *SimpleFOC* + +We are very happy that *Simple**FOC**library* has been used as a component of several research project and has made its way to several scientific papers. We are hoping that this trend is going to continue as the project matures and becomes more robust! +A short resume paper about *Simple**FOC*** has been published in the Journal of Open Source Software: +

+ SimpleFOC: A Field Oriented Control (FOC) Library for Controlling Brushless Direct Current (BLDC) and Stepper Motors.
+ A. Skuric, HS. Bank, R. Unger, O. Williams, D. González-Reyes
+Journal of Open Source Software, 7(74), 4232, https://doi.org/10.21105/joss.04232 +

+ +If you are interested in citing *Simple**FOC**library* or some other component of *Simple**FOC**project* in your research, we suggest you to cite our paper: + +```bib +@article{simplefoc2022, + doi = {10.21105/joss.04232}, + url = {https://doi.org/10.21105/joss.04232}, + year = {2022}, + publisher = {The Open Journal}, + volume = {7}, + number = {74}, + pages = {4232}, + author = {Antun Skuric and Hasan Sinan Bank and Richard Unger and Owen Williams and David González-Reyes}, + title = {SimpleFOC: A Field Oriented Control (FOC) Library for Controlling Brushless Direct Current (BLDC) and Stepper Motors}, + journal = {Journal of Open Source Software} +} + +``` diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/B_G431B_ESC1.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/B_G431B_ESC1.ino new file mode 100644 index 0000000..51ac990 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/B_G431B_ESC1.ino @@ -0,0 +1,109 @@ +/** + * B-G431B-ESC1 position motion control example with encoder + * + */ +#include + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver6PWM driver = BLDCDriver6PWM(A_PHASE_UH, A_PHASE_UL, A_PHASE_VH, A_PHASE_VL, A_PHASE_WH, A_PHASE_WL); +LowsideCurrentSense currentSense = LowsideCurrentSense(0.003f, -64.0f/7.0f, A_OP1_OUT, A_OP2_OUT, A_OP3_OUT); + + +// encoder instance +Encoder encoder = Encoder(A_HALL2, A_HALL3, 2048, A_HALL1); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} +void doIndex(){encoder.handleIndex();} + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.motion(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + // link current sense and the driver + currentSense.linkDriver(&driver); + + // current sensing + currentSense.init(); + // no need for aligning + currentSense.skip_align = true; + motor.linkCurrentSense(¤tSense); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + // index search velocity [rad/s] + motor.velocity_index_search = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::velocity; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2; + motor.PID_velocity.I = 20; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 4; + + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + + // Motion control function + motor.move(); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/build_opt.h b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/build_opt.h new file mode 100644 index 0000000..6f547ec --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/B_G431B_ESC1/build_opt.h @@ -0,0 +1 @@ +-DHAL_OPAMP_MODULE_ENABLED \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/encoder/bluepill_position_control/bluepill_position_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/encoder/bluepill_position_control/bluepill_position_control.ino new file mode 100644 index 0000000..be853f0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/encoder/bluepill_position_control/bluepill_position_control.ino @@ -0,0 +1,115 @@ +/** + * + * STM32 Bluepill position motion control example with encoder + * + * The same example can be ran with any STM32 board - just make sure that put right pin numbers. + * + */ +#include + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +// BLDCDriver3PWM(IN1, IN2, IN3, enable(optional)) +BLDCDriver3PWM driver = BLDCDriver3PWM(PB6, PB7, PB8, PB5); +// BLDCDriver6PWM(IN1_H, IN1_L, IN2_H, IN2_L, IN3_H, IN3_L, enable(optional)) +//BLDCDriver6PWM driver = BLDCDriver6PWM(PA8, PB13, PA9, PB14, PA10, PB15, PB12); + +// encoder instance +Encoder encoder = Encoder(PA8, PA9, 8192, PA10); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} +void doI(){encoder.handleIndex();} + + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB, doI); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + // index search velocity [rad/s] + motor.velocity_index_search = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::velocity; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 4; + + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/magnetic_sensor/bluepill_position_control/bluepill_position_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/magnetic_sensor/bluepill_position_control/bluepill_position_control.ino new file mode 100644 index 0000000..e27f1e7 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Bluepill_examples/magnetic_sensor/bluepill_position_control/bluepill_position_control.ino @@ -0,0 +1,115 @@ +/** + * + * STM32 Bluepill position motion control example with magnetic sensor + * + * The same example can be ran with any STM32 board - just make sure that put right pin numbers. + * + */ +#include + +// SPI Magnetic sensor instance (AS5047U example) +// MISO PA7 +// MOSI PA6 +// SCK PA5 +MagneticSensorSPI sensor = MagneticSensorSPI(PA4, 14, 0x3FFF); + +// I2C Magnetic sensor instance (AS5600 example) +// make sure to use the pull-ups!! +// SDA PB7 +// SCL PB6 +//MagneticSensorI2C sensor = MagneticSensorI2C(0x36, 12, 0X0C, 4); + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +// BLDCDriver3PWM(IN1, IN2, IN3, enable(optional)) +BLDCDriver3PWM driver = BLDCDriver3PWM(PB6, PB7, PB8, PB5); +// BLDCDriver6PWM(IN1_H, IN1_L, IN2_H, IN2_L, IN3_H, IN3_L, enable(optional)) +//BLDCDriver6PWM driver = BLDCDriver6PWM(PA8, PB13, PA9, PB14, PA10, PB15, PB12); + + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // choose FOC modulation (optional) + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + // maximal voltage to be set to the motor + motor.voltage_limit = 6; + + // velocity low pass filtering time constant + // the lower the less filtered + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 40; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/3pwm_example/encoder/full_control_serial/full_control_serial.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/3pwm_example/encoder/full_control_serial/full_control_serial.ino new file mode 100644 index 0000000..842f383 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/3pwm_example/encoder/full_control_serial/full_control_serial.ino @@ -0,0 +1,130 @@ +/** + * Comprehensive BLDC motor control example using encoder and the DRV8302 board + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * check the https://docs.simplefoc.com for full list of motor commands + * + */ +#include + +// DRV8302 pins connections +// don't forget to connect the common ground pin +#define INH_A 9 +#define INH_B 10 +#define INH_C 11 + +#define EN_GATE 7 +#define M_PWM A1 +#define M_OC A2 +#define OC_ADJ A3 + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(INH_A, INH_B, INH_C, EN_GATE); + +// encoder instance +Encoder encoder = Encoder(2, 3, 8192); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // DRV8302 specific code + // M_OC - enable overcurrent protection + pinMode(M_OC,OUTPUT); + digitalWrite(M_OC,LOW); + // M_PWM - enable 3pwm mode + pinMode(M_PWM,OUTPUT); + digitalWrite(M_PWM,HIGH); + // OD_ADJ - set the maximum overcurrent limit possible + // Better option would be to use voltage divisor to set exact value + pinMode(OC_ADJ,OUTPUT); + digitalWrite(OC_ADJ,HIGH); + + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + + // choose FOC modulation + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 50; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // define the motor id + command.add('A', onMotor, "motor"); + + Serial.println(F("Full control example: ")); + Serial.println(F("Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) \n ")); + Serial.println(F("Initial motion control loop is voltage loop.")); + Serial.println(F("Initial target voltage 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + // velocity, position or voltage + // if tatget not set in parameter uses motor.target variable + motor.move(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/6pwm_example/encoder/full_control_serial/full_control_serial.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/6pwm_example/encoder/full_control_serial/full_control_serial.ino new file mode 100644 index 0000000..a5b72f8 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/6pwm_example/encoder/full_control_serial/full_control_serial.ino @@ -0,0 +1,129 @@ +/** + * Comprehensive BLDC motor control example using encoder and the DRV8302 board + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * check the https://docs.simplefoc.com for full list of motor commands + * + */ +#include + +// DRV8302 pins connections +// don't forget to connect the common ground pin +#define INH_A 3 +#define INH_B 5 +#define INH_C 9 +#define INL_A 11 +#define INL_B 6 +#define INL_C 10 + +#define EN_GATE 7 +#define M_PWM A1 +#define M_OC A2 +#define OC_ADJ A3 + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver6PWM driver = BLDCDriver6PWM(INH_A,INH_A, INH_B,INH_B, INH_C,INL_C, EN_GATE); + +// encoder instance +Encoder encoder = Encoder(2, 3, 8192); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // DRV8302 specific code + // M_OC - enable overcurrent protection + pinMode(M_OC,OUTPUT); + digitalWrite(M_OC,LOW); + // M_PWM - disable 3pwm mode + pinMode(M_PWM,OUTPUT); + digitalWrite(M_PWM, LOW); + // OD_ADJ - set the maximum overcurrent limit possible + // Better option would be to use voltage divisor to set exact value + pinMode(OC_ADJ,OUTPUT); + digitalWrite(OC_ADJ,HIGH); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // choose FOC modulation + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 50; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // define the motor id + command.add('M', onMotor, "motor"); + + Serial.println(F("Initial motion control loop is voltage loop.")); + Serial.println(F("Initial target voltage 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + // velocity, position or voltage + // if tatget not set in parameter uses motor.target variable + motor.move(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/esp32_current_control_low_side/esp32_current_control_low_side.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/esp32_current_control_low_side/esp32_current_control_low_side.ino new file mode 100644 index 0000000..84033b4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/esp32_current_control_low_side/esp32_current_control_low_side.ino @@ -0,0 +1,167 @@ +/** + * Comprehensive BLDC motor control example using encoder and the DRV8302 board + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * check the https://docs.simplefoc.com for full list of motor commands + * + */ +#include + +// DRV8302 pins connections +// don't forget to connect the common ground pin +#define INH_A 21 +#define INH_B 19 +#define INH_C 18 + +#define EN_GATE 5 +#define M_PWM 25 +#define M_OC 26 +#define OC_ADJ 12 +#define OC_GAIN 14 + +#define IOUTA 34 +#define IOUTB 35 +#define IOUTC 32 + +// Motor instance +BLDCMotor motor = BLDCMotor(7); +BLDCDriver3PWM driver = BLDCDriver3PWM(INH_A, INH_B, INH_C, EN_GATE); + +// DRV8302 board has 0.005Ohm shunt resistors and the gain of 12.22 V/V +LowsideCurrentSense cs = LowsideCurrentSense(0.005f, 12.22f, IOUTA, IOUTB, IOUTC); + +// encoder instance +Encoder encoder = Encoder(22, 23, 500); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // DRV8302 specific code + // M_OC - enable overcurrent protection + pinMode(M_OC,OUTPUT); + digitalWrite(M_OC,LOW); + // M_PWM - enable 3pwm mode + pinMode(M_PWM,OUTPUT); + digitalWrite(M_PWM,HIGH); + // OD_ADJ - set the maximum overcurrent limit possible + // Better option would be to use voltage divisor to set exact value + pinMode(OC_ADJ,OUTPUT); + digitalWrite(OC_ADJ,HIGH); + pinMode(OC_GAIN,OUTPUT); + digitalWrite(OC_GAIN,LOW); + + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.pwm_frequency = 15000; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + // link current sense and the driver + cs.linkDriver(&driver); + + // align voltage + motor.voltage_sensor_align = 0.5; + + // control loop type and torque mode + motor.torque_controller = TorqueControlType::voltage; + motor.controller = MotionControlType::torque; + motor.motion_downsample = 0.0; + + // velocity loop PID + motor.PID_velocity.P = 0.2; + motor.PID_velocity.I = 5.0; + // Low pass filtering time constant + motor.LPF_velocity.Tf = 0.02; + // angle loop PID + motor.P_angle.P = 20.0; + // Low pass filtering time constant + motor.LPF_angle.Tf = 0.0; + // current q loop PID + motor.PID_current_q.P = 3.0; + motor.PID_current_q.I = 100.0; + // Low pass filtering time constant + motor.LPF_current_q.Tf = 0.02; + // current d loop PID + motor.PID_current_d.P = 3.0; + motor.PID_current_d.I = 100.0; + // Low pass filtering time constant + motor.LPF_current_d.Tf = 0.02; + + // Limits + motor.velocity_limit = 100.0; // 100 rad/s velocity limit + motor.voltage_limit = 12.0; // 12 Volt limit + motor.current_limit = 2.0; // 2 Amp current limit + + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_variables = _MON_CURR_Q | _MON_CURR_D; // monitor the two currents d and q + motor.monitor_downsample = 1000; + + // initialise motor + motor.init(); + + cs.init(); + // driver 8302 has inverted gains on all channels + cs.gain_a *=-1; + cs.gain_b *=-1; + cs.gain_c *=-1; + motor.linkCurrentSense(&cs); + + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 0; + + // define the motor id + command.add('M', onMotor, "motor"); + + Serial.println(F("Full control example: ")); + Serial.println(F("Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) \n ")); + Serial.println(F("Initial motion control loop is voltage loop.")); + Serial.println(F("Initial target voltage 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + motor.move(); + + // monitoring the state variables + motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/stm32_current_control_low_side/stm32_current_control_low_side.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/stm32_current_control_low_side/stm32_current_control_low_side.ino new file mode 100644 index 0000000..3e3f04a --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/DRV8302_driver/stm32_current_control_low_side/stm32_current_control_low_side.ino @@ -0,0 +1,167 @@ +/** + * Comprehensive BLDC motor control example using encoder and the DRV8302 board + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * check the https://docs.simplefoc.com for full list of motor commands + * + */ +#include + +// DRV8302 pins connections +// don't forget to connect the common ground pin +#define INH_A PA8 +#define INH_B PA9 +#define INH_C PA10 + +#define EN_GATE PB7 +#define M_PWM PB4 +#define M_OC PB3 +#define OC_ADJ PB6 +#define OC_GAIN PB5 + +#define IOUTA PA0 +#define IOUTB PA1 +#define IOUTC PA2 + +// Motor instance +BLDCMotor motor = BLDCMotor(7); +BLDCDriver3PWM driver = BLDCDriver3PWM(INH_A, INH_B, INH_C, EN_GATE); + +// DRV8302 board has 0.005Ohm shunt resistors and the gain of 12.22 V/V +LowsideCurrentSense cs = LowsideCurrentSense(0.005f, 12.22f, IOUTA, IOUTB, IOUTC); + +// encoder instance +Encoder encoder = Encoder(PB14, PB15, 2048); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // DRV8302 specific code + // M_OC - enable overcurrent protection + pinMode(M_OC,OUTPUT); + digitalWrite(M_OC,LOW); + // M_PWM - enable 3pwm mode + pinMode(M_PWM,OUTPUT); + digitalWrite(M_PWM,HIGH); + // OD_ADJ - set the maximum overcurrent limit possible + // Better option would be to use voltage divisor to set exact value + pinMode(OC_ADJ,OUTPUT); + digitalWrite(OC_ADJ,HIGH); + pinMode(OC_GAIN,OUTPUT); + digitalWrite(OC_GAIN,LOW); + + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 19; + driver.pwm_frequency = 15000; // suggested under 18khz + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + // link current sense and the driver + cs.linkDriver(&driver); + + // align voltage + motor.voltage_sensor_align = 0.5; + + // control loop type and torque mode + motor.torque_controller = TorqueControlType::voltage; + motor.controller = MotionControlType::torque; + motor.motion_downsample = 0.0; + + // velocity loop PID + motor.PID_velocity.P = 0.2; + motor.PID_velocity.I = 5.0; + // Low pass filtering time constant + motor.LPF_velocity.Tf = 0.02; + // angle loop PID + motor.P_angle.P = 20.0; + // Low pass filtering time constant + motor.LPF_angle.Tf = 0.0; + // current q loop PID + motor.PID_current_q.P = 3.0; + motor.PID_current_q.I = 100.0; + // Low pass filtering time constant + motor.LPF_current_q.Tf = 0.02; + // current d loop PID + motor.PID_current_d.P = 3.0; + motor.PID_current_d.I = 100.0; + // Low pass filtering time constant + motor.LPF_current_d.Tf = 0.02; + + // Limits + motor.velocity_limit = 100.0; // 100 rad/s velocity limit + motor.voltage_limit = 12.0; // 12 Volt limit + motor.current_limit = 2.0; // 2 Amp current limit + + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_variables = _MON_CURR_Q | _MON_CURR_D; // monitor the two currents d and q + motor.monitor_downsample = 0; + + // initialise motor + motor.init(); + + cs.init(); + // driver 8302 has inverted gains on all channels + cs.gain_a *=-1; + cs.gain_b *=-1; + cs.gain_c *=-1; + motor.linkCurrentSense(&cs); + + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 0; + + // define the motor id + command.add('M', onMotor, "motor"); + + Serial.println(F("Full control example: ")); + Serial.println(F("Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) \n ")); + Serial.println(F("Initial motion control loop is voltage loop.")); + Serial.println(F("Initial target voltage 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + motor.move(); + + // monitoring the state variables + motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/encoder/esp32_position_control/esp32_position_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/encoder/esp32_position_control/esp32_position_control.ino new file mode 100644 index 0000000..f6dac94 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/encoder/esp32_position_control/esp32_position_control.ino @@ -0,0 +1,107 @@ +/** + * ESP32 position motion control example with encoder + * + */ +#include + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(25, 26, 27, 7); + +// encoder instance +Encoder encoder = Encoder(4, 2, 1024); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + // index search velocity [rad/s] + motor.velocity_index_search = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::velocity; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 4; + + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/magnetic_sensor/esp32_position_control/esp32_position_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/magnetic_sensor/esp32_position_control/esp32_position_control.ino new file mode 100644 index 0000000..f025895 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/ESP32/magnetic_sensor/esp32_position_control/esp32_position_control.ino @@ -0,0 +1,112 @@ +/** + * ESP32 position motion control example with magnetic sensor + */ +#include + +// SPI Magnetic sensor instance (AS5047U example) +// MISO 12 +// MOSI 9 +// SCK 14 +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, 15); + +// I2C Magnetic sensor instance (AS5600 example) +// make sure to use the pull-ups!! +// SDA 21 +// SCL 22 +// magnetic sensor instance - I2C +//MagneticSensorI2C sensor = MagneticSensorI2C(AS5600_I2C); + +// Analog output Magnetic sensor instance (AS5600) +// MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(25, 26, 27, 7); + + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // choose FOC modulation (optional) + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + // maximal voltage to be set to the motor + motor.voltage_limit = 6; + + // velocity low pass filtering time constant + // the lower the less filtered + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 40; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/position_control/position_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/position_control/position_control.ino new file mode 100644 index 0000000..5b5c8e4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/position_control/position_control.ino @@ -0,0 +1,127 @@ +/** + * + * HMBGC position motion control example with encoder + * + * - Motor is connected the MOT1 connector (MOT1 9,10,11; MOT2 3,5,6) + * - Encoder is connected to A0 and A1 + * + * This board doesn't have any interrupt pins so we need to run all the encoder channels with the software interrupt library + * - For this example we use: PciManager library : https://github.com/prampec/arduino-pcimanager + * + * See docs.simplefoc.com for more info. + * + */ +#include +// software interrupt library +#include +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 10, 11); + +// encoder instance +Encoder encoder = Encoder(A0, A1, 2048); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// encoder interrupt init +PciListenerImp listenerA(encoder.pinA, doA); +PciListenerImp listenerB(encoder.pinB, doB); + + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + +void setup() { + + // initialise encoder hardware + encoder.init(); + // interrupt initialization + PciManager.registerListener(&listenerA); + PciManager.registerListener(&listenerB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + // index search velocity [rad/s] + motor.velocity_index_search = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 4; + + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/voltage_control/voltage_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/voltage_control/voltage_control.ino new file mode 100644 index 0000000..9c9655f --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/HMBGC_example/voltage_control/voltage_control.ino @@ -0,0 +1,110 @@ +/** + * + * HMBGC torque control example using voltage control loop. + * + * - Motor is connected the MOT1 connector (MOT1 9,10,11; MOT2 3,5,6) + * - Encoder is connected to A0 and A1 + * + * Most of the low-end BLDC driver boards doesn't have current measurement therefore SimpleFOC offers + * you a way to control motor torque by setting the voltage to the motor instead hte current. + * + * This makes the BLDC motor effectively a DC motor, and you can use it in a same way. position motion control example with encoder + * + * NOTE: + * > HMBGC doesn't have any interrupt pins so we need to run all the encoder channels with the software interrupt library + * > - For this example we use: PciManager library : https://github.com/prampec/arduino-pcimanager + * + * See docs.simplefoc.com for more info. + * + */ +#include +// software interrupt library +#include +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 10, 11); + +// encoder instance +Encoder encoder = Encoder(A0, A1, 8192); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// encoder interrupt init +PciListenerImp listenerA(encoder.pinA, doA); +PciListenerImp listenerB(encoder.pinB, doB); + + +// voltage set point variable +float target_voltage = 2; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + // interrupt initialization + PciManager.registerListener(&listenerA); + PciManager.registerListener(&listenerB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // choose FOC modulation (optional) + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial for motor init + // comment out if not needed + motor.useMonitoring(Serial); + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target voltage using serial terminal:")); + _delay(1000); +} + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_encoder/odrive_example_encoder.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_encoder/odrive_example_encoder.ino new file mode 100644 index 0000000..b89c215 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_encoder/odrive_example_encoder.ino @@ -0,0 +1,134 @@ +/* + Odrive robotics' hardware is one of the best BLDC motor foc supporting hardware out there. + + This is an example code that can be directly uploaded to the Odrive using the SWD programmer. + This code uses an encoder with 500 cpr and a BLDC motor with 7 pole pairs connected to the M0 interface of the Odrive. + + This is a short template code and the idea is that you are able to adapt to your needs not to be a complete solution. :D +*/ +#include + +// Odrive M0 motor pinout +#define M0_INH_A PA8 +#define M0_INH_B PA9 +#define M0_INH_C PA10 +#define M0_INL_A PB13 +#define M0_INL_B PB14 +#define M0_INL_C PB15 +// M0 currnets +#define M0_IB PC0 +#define M0_IC PC1 +// Odrive M0 encoder pinout +#define M0_ENC_A PB4 +#define M0_ENC_B PB5 +#define M0_ENC_Z PC9 + + +// Odrive M1 motor pinout +#define M1_INH_A PC6 +#define M1_INH_B PC7 +#define M1_INH_C PC8 +#define M1_INL_A PA7 +#define M1_INL_B PB0 +#define M1_INL_C PB1 +// M0 currnets +#define M1_IB PC2 +#define M1_IC PC3 +// Odrive M1 encoder pinout +#define M1_ENC_A PB6 +#define M1_ENC_B PB7 +#define M1_ENC_Z PC15 + +// M1 & M2 common enable pin +#define EN_GATE PB12 + +// SPI pinout +#define SPI3_SCL PC10 +#define SPI3_MISO PC11 +#define SPI3_MOSO PC12 + +// Motor instance +BLDCMotor motor = BLDCMotor(7); +BLDCDriver6PWM driver = BLDCDriver6PWM(M0_INH_A,M0_INL_A, M0_INH_B,M0_INL_B, M0_INH_C,M0_INL_C, EN_GATE); + +// instantiate the commander +Commander command = Commander(Serial); +void doMotor(char* cmd) { command.motor(&motor, cmd); } + +// low side current sensing define +// 0.0005 Ohm resistor +// gain of 10x +// current sensing on B and C phases, phase A not connected +LowsideCurrentSense current_sense = LowsideCurrentSense(0.0005f, 10.0f, _NC, M0_IB, M0_IC); + +Encoder encoder = Encoder(M0_ENC_A, M0_ENC_B, 500,M0_ENC_Z); +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} +void doI(){encoder.handleIndex();} + +void setup(){ + + // pwm frequency to be used [Hz] + driver.pwm_frequency = 20000; + // power supply voltage [V] + driver.voltage_power_supply = 20; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 20; + // driver init + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB, doI); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // control loop type and torque mode + motor.torque_controller = TorqueControlType::voltage; + motor.controller = MotionControlType::torque; + + // max voltage allowed for motion control + motor.voltage_limit = 8.0; + // alignment voltage limit + motor.voltage_sensor_align = 0.5; + + + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_variables = _MON_CURR_Q | _MON_CURR_D; + motor.monitor_downsample = 1000; + + // add target command T + command.add('M', doMotor, "motor M0"); + + // initialise motor + motor.init(); + + // link the driver + current_sense.linkDriver(&driver); + // init the current sense + current_sense.init(); + current_sense.skip_align = true; + motor.linkCurrentSense(¤t_sense); + + // init FOC + motor.initFOC(); + delay(1000); +} + +void loop(){ + + // foc loop + motor.loopFOC(); + // motion control + motor.move(); + // monitoring + motor.monitor(); + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_spi/odrive_example_spi.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_spi/odrive_example_spi.ino new file mode 100644 index 0000000..2aed6bf --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Odrive_examples/odrive_example_spi/odrive_example_spi.ino @@ -0,0 +1,132 @@ +/* + Odrive robotics' hardware is one of the best BLDC motor foc supporting hardware out there. + + This is an example code that can be directly uploaded to the Odrive using the SWD programmer. + This code uses an magnetic spi sensor AS5047 and a BLDC motor with 11 pole pairs connected to the M0 interface of the Odrive. + + This is a short template code and the idea is that you are able to adapt to your needs not to be a complete solution. :D +*/ +#include + +// Odrive M0 motor pinout +#define M0_INH_A PA8 +#define M0_INH_B PA9 +#define M0_INH_C PA10 +#define M0_INL_A PB13 +#define M0_INL_B PB14 +#define M0_INL_C PB15 +// M0 currnets +#define M0_IB PC0 +#define M0_IC PC1 +// Odrive M0 encoder pinout +#define M0_ENC_A PB4 +#define M0_ENC_B PB5 +#define M0_ENC_Z PC9 + + +// Odrive M1 motor pinout +#define M1_INH_A PC6 +#define M1_INH_B PC7 +#define M1_INH_C PC8 +#define M1_INL_A PA7 +#define M1_INL_B PB0 +#define M1_INL_C PB1 +// M0 currnets +#define M1_IB PC2 +#define M1_IC PC3 +// Odrive M1 encoder pinout +#define M1_ENC_A PB6 +#define M1_ENC_B PB7 +#define M1_ENC_Z PC15 + +// M1 & M2 common enable pin +#define EN_GATE PB12 + +// SPI pinout +#define SPI3_SCL PC10 +#define SPI3_MISO PC11 +#define SPI3_MOSO PC12 + +// Motor instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver6PWM driver = BLDCDriver6PWM(M0_INH_A,M0_INL_A, M0_INH_B,M0_INL_B, M0_INH_C,M0_INL_C, EN_GATE); + +// instantiate the commander +Commander command = Commander(Serial); +void doMotor(char* cmd) { command.motor(&motor, cmd); } + +// low side current sensing define +// 0.0005 Ohm resistor +// gain of 10x +// current sensing on B and C phases, phase A not connected +LowsideCurrentSense current_sense = LowsideCurrentSense(0.0005f, 10.0f, _NC, M0_IB, M0_IC); + +// MagneticSensorSPI(int cs, float _cpr, int _angle_register) +// config - SPI config +// cs - SPI chip select pin +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, M0_ENC_A); +SPIClass SPI_3(SPI3_MOSO, SPI3_MISO, SPI3_SCL); + +void setup(){ + + // pwm frequency to be used [Hz] + driver.pwm_frequency = 20000; + // power supply voltage [V] + driver.voltage_power_supply = 20; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 20; + // driver init + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // initialise magnetic sensor hardware + sensor.init(&SPI_3); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // control loop type and torque mode + motor.torque_controller = TorqueControlType::voltage; + motor.controller = MotionControlType::torque; + + // max voltage allowed for motion control + motor.voltage_limit = 8.0; + // alignment voltage limit + motor.voltage_sensor_align = 0.5; + + + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_variables = _MON_CURR_Q | _MON_CURR_D; + motor.monitor_downsample = 1000; + + // add target command T + command.add('M', doMotor, "motor M0"); + + // initialise motor + motor.init(); + + // link the driver + current_sense.linkDriver(&driver); + // init the current sense + current_sense.init(); + current_sense.skip_align = true; + motor.linkCurrentSense(¤t_sense); + + // init FOC + motor.initFOC(); + delay(1000); +} + +void loop(){ + + // foc loop + motor.loopFOC(); + // motion control + motor.move(); + // monitoring + motor.monitor(); + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/README.md b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/README.md new file mode 100644 index 0000000..d1a5258 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/README.md @@ -0,0 +1,62 @@ + +# SAMD Support + +SimpleFOC supports many SAMD21 MCUs, really any SAMD21 supported by Arduino core should work. + +## Pin assignments + +The SAMD chips have some very powerful PWM features, but do not have flexible pin assignments. + +You should be able to use *most* (but not all!), pin combinations for attaching your motor's PWM pins. Please ignore the board descriptions and pinout diagrammes regarding PWM-pins on SAMD boards. They are pretty much all incorrect to varying degrees of awfulness. + +On SAMD we use TCC and TC timer peripherals (built into the SAMD chip) to control the PWM. Depending on the chip there are various timer units, whose PWM outputs are attached to various different pins, and it is all very complicated. Luckily SimpleFOC sets it all up automatically *if* there is a compatible configuration for those pins. + +Not all timers are created equal. The TCC timers are pretty awesome for PWM motor control, while the TC timers are just ok for the job. So to get best performance, you want to use just TCC timer pins if you can. + +By enabling + +``` + #define SIMPLEFOC_SAMD_DEBUG +``` + +in drivers/hardware_specific/samd_mcu.cpp
+you will see a table of pin assignments printed on the serial console, as well as the timers SimpleFOC was able to find and configure on the pins you specified. You can use this to optimize your choice of pins if you want. + +You can configure up to 12 pins for PWM motor control, i.e. 6x 2-PWM motors, 4x 3-PWM motors, 3x 4-PWM motors or 2x 6-PWM motors. + +## PWM control modes + +All modes (3-PWM, 6-PWM, Stepper 2-PWM and Stepper 4-PWM) are supported. + +For 2-, 3- amd 4- PWM, any valid pin-combinations can be used. If you stick to TCC timers rather than using TC timers, then you'll get getter PWM waveforms. If you use pins which are all on the same TCC unit, you'll get the best result, with the PWM signals all perfectly aligned as well. + +For 6-PWM, the situation is much more complicated:
+TC timers cannot be used for 6-PWM, only TCC timers. + +For Hardware Dead-Time insertion, you must use H and L pins for one phase from the same TCC unit, and on the same channel, but using complementary WOs (Waveform Outputs, i.e. PWM output pins). Check the table to find pins on the same channel (like TCC0-0) but complementary WOs (like TCC0-0[0] and TCC0-0[4] or TCC1-0[0] and TCC1-0[2]). + +For Software Dead-Time insertion, you must use the same TCC and different channels for the H and L pins of the same phase. + +Note: in all of the above note that you *cannot* set the timers or WOs used - they are fixed, and determined by the pins you selected. SimpleFOC will find the best combination of timers given the pins, trying to use TCC timers before TC, and trying to keep things on the same timers as much as possible. If you configure multiple motors, it will take into account the pins already assigned to other motors. +So it is matter of choosing the right pins, nothing else. + +Note also: Unfortunately you can't set the PWM frequency. It is currently fixed at 24KHz. This is a tradeoff between limiting PWM resolution vs +increasing frequency, and also due to keeping the pin assignemts flexible, which would not be possible if we ran the timers at different rates. + +## Status + +Currently, SAMD21 is supported, and SAMD51 is unsupported. SAMD51 support is in progress. + +Boards tested: + + * Arduino Nano 33 IoT + * Arduino MKR1000 + * Arduino MKR1010 Wifi + * Seeduino XIAO + * Feather M0 Basic + +Environments tested: + + * Arduino IDE + * Arduino Pro IDE + * Sloeber diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/nano33IoT/nano33IoT_velocity_control/nano33IoT_velocity_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/nano33IoT/nano33IoT_velocity_control/nano33IoT_velocity_control.ino new file mode 100644 index 0000000..70ec28b --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SAMD_examples/nano33IoT/nano33IoT_velocity_control/nano33IoT_velocity_control.ino @@ -0,0 +1,64 @@ + +// show the infos for SAMD pin assignment on serial console +// set this #define SIMPLEFOC_SAMD_DEBUG in drivers/hardware_specific/samd21_mcu.h + + +#include "Arduino.h" +#include +#include + +// this is for an AS5048B absolute magnetic encoder on I2C address 0x41 +MagneticSensorI2C sensor = MagneticSensorI2C(0x41, 14, 0xFE, 8); + +// small BLDC gimbal motor, 7 pole-pairs +BLDCMotor motor = BLDCMotor(7); +// 3-PWM driving on pins 6, 5 and 8 - these are all on the same timer unit (TCC0), but different channels +BLDCDriver3PWM driver = BLDCDriver3PWM(6,5,8); + +// velocity set point variable +float target_velocity = 2.0f; +// instantiate the commander +Commander command = Commander(SerialUSB); +void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } + + +void setup() { + Serial.begin(115200); + delay(1000); + Serial.println("Initializing..."); + + sensor.init(); + Wire.setClock(400000); + motor.linkSensor(&sensor); + driver.voltage_power_supply = 9; + driver.init(); + motor.linkDriver(&driver); + motor.controller = MotionControlType::velocity; + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0.001f; + motor.PID_velocity.output_ramp = 1000; + motor.LPF_velocity.Tf = 0.01f; + motor.voltage_limit = 9; + //motor.P_angle.P = 20; + motor.init(); + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target velocity"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target velocity using serial terminal:")); + delay(100); +} + + + +void loop() { +// Serial.print("Sensor: "); +// Serial.println(sensor.getAngle()); + motor.loopFOC(); + motor.move(target_velocity); + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOC-PowerShield/version_v02/single_full_control_example/single_full_control_example.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOC-PowerShield/version_v02/single_full_control_example/single_full_control_example.ino new file mode 100644 index 0000000..eb52f51 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOC-PowerShield/version_v02/single_full_control_example/single_full_control_example.ino @@ -0,0 +1,102 @@ + +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(7); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8, 4, 7); + +// encoder instance +Encoder encoder = Encoder(10, 11, 500); +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// inline current sensor instance +InlineCurrentSense current_sense = InlineCurrentSense(0.001f, 50.0f, A0, A1); + +// commander communication instance +Commander command = Commander(Serial); +// void doMotor(char* cmd){ command.motor(&motor, cmd); } +void doTarget(char* cmd){ command.scalar(&motor.target, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 20; + driver.init(); + // link driver + motor.linkDriver(&driver); + // link current sense and the driver + current_sense.linkDriver(&driver); + + motor.voltage_sensor_align = 1; + // set control loop type to be used + motor.torque_controller = TorqueControlType::foc_current; + motor.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor.PID_velocity.P = 0.05f; + motor.PID_velocity.I = 1; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 20; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_downsample = 0; // disable intially + motor.monitor_variables = _MON_TARGET | _MON_VEL | _MON_ANGLE; // monitor target velocity and angle + + // current sense init and linking + current_sense.init(); + motor.linkCurrentSense(¤t_sense); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 0; + + // subscribe motor to the commander + // command.add('M', doMotor, "motor"); + command.add('T', doTarget, "target"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println("Motor ready."); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + motor.move(); + + // motor monitoring + motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCMini/angle_control/angle_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCMini/angle_control/angle_control.ino new file mode 100644 index 0000000..9102c89 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCMini/angle_control/angle_control.ino @@ -0,0 +1,125 @@ +/** + * + * SimpleFOCMini motor control example + * + * For Arduino UNO, the most convenient way to use the board is to stack it to the pins: + * - 12 - GND + * - 11 - IN1 + * - 10 - IN2 + * - 9 - IN3 + * - 8 - EN + * + * For other boards with UNO headers but more PWM channles such as esp32, nucleo-64, samd51 metro etc, the best way to most convenient pinout is: + * - GND - GND + * - 13 - IN1 + * - 12 - IN2 + * - 11 - IN3 + * - 9 - EN + * + * For the boards without arduino uno headers, the choice of pinout is a lot less constrained. + * + */ +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(11, 10, 9, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 500); +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// instantiate the commander +Commander command = Commander(Serial); +void doMotor(char* cmd) { command.motor(&motor, cmd); } + +void setup() { + // if SimpleFOCMini is stacked in arduino headers + // on pins 12,11,10,9,8 + // pin 12 is used as ground + pinMode(12,OUTPUT); + pinMode(12,LOW); + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 4; + + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // add target command M + command.add('M', doMotor, "motor"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/double_full_control_example/double_full_control_example.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/double_full_control_example/double_full_control_example.ino new file mode 100644 index 0000000..c048956 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/double_full_control_example/double_full_control_example.ino @@ -0,0 +1,118 @@ + +#include + +// BLDC motor & driver instance +BLDCMotor motor1 = BLDCMotor(11); +BLDCDriver3PWM driver1 = BLDCDriver3PWM(9, 5, 6, 8); + +// BLDC motor & driver instance +BLDCMotor motor2 = BLDCMotor(11); +BLDCDriver3PWM driver2 = BLDCDriver3PWM(3, 10, 11, 7); + +// encoder instance +Encoder encoder1 = Encoder(2, A3, 500); +// channel A and B callbacks +void doA1(){encoder1.handleA();} +void doB1(){encoder1.handleB();} + +// encoder instance +Encoder encoder2 = Encoder(A1, A2, 500); +// channel A and B callbacks +void doA2(){encoder2.handleA();} +void doB2(){encoder2.handleB();} + +// commander communication instance +Commander command = Commander(Serial); +void doMotor1(char* cmd){ command.motor(&motor1, cmd); } +void doMotor2(char* cmd){ command.motor(&motor2, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder1.init(); + encoder1.enableInterrupts(doA1, doB1); + // initialize encoder sensor hardware + encoder2.init(); + encoder2.enableInterrupts(doA2, doB2); + // link the motor to the sensor + motor1.linkSensor(&encoder1); + motor2.linkSensor(&encoder2); + + + // driver config + // power supply voltage [V] + driver1.voltage_power_supply = 12; + driver1.init(); + // link driver + motor1.linkDriver(&driver1); + // power supply voltage [V] + driver2.voltage_power_supply = 12; + driver2.init(); + // link driver + motor2.linkDriver(&driver2); + + // set control loop type to be used + motor1.controller = MotionControlType::torque; + motor2.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor1.PID_velocity.P = 0.05f; + motor1.PID_velocity.I = 1; + motor1.PID_velocity.D = 0; + // default voltage_power_supply + motor1.voltage_limit = 12; + // contoller configuration based on the controll type + motor2.PID_velocity.P = 0.05f; + motor2.PID_velocity.I = 1; + motor2.PID_velocity.D = 0; + // default voltage_power_supply + motor2.voltage_limit = 12; + + // angle loop velocity limit + motor1.velocity_limit = 20; + motor2.velocity_limit = 20; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor1.useMonitoring(Serial); + motor2.useMonitoring(Serial); + + // initialise motor + motor1.init(); + // align encoder and start FOC + motor1.initFOC(); + + // initialise motor + motor2.init(); + // align encoder and start FOC + motor2.initFOC(); + + // set the inital target value + motor1.target = 2; + motor2.target = 2; + + // subscribe motor to the commander + command.add('A', doMotor1, "motor 1"); + command.add('B', doMotor2, "motor 2"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println(F("Double motor sketch ready.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor1.loopFOC(); + motor2.loopFOC(); + + // iterative function setting the outter loop target + motor1.move(); + motor2.move(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/single_full_control_example/single_full_control_example.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/single_full_control_example/single_full_control_example.ino new file mode 100644 index 0000000..10e26c9 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v1/single_full_control_example/single_full_control_example.ino @@ -0,0 +1,89 @@ + +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 500); +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// commander communication instance +Commander command = Commander(Serial); +void doMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor.PID_velocity.P = 0.05f; + motor.PID_velocity.I = 1; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 20; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_downsample = 0; // disable intially + motor.monitor_variables = _MON_TARGET | _MON_VEL | _MON_ANGLE; // monitor target velocity and angle + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // subscribe motor to the commander + command.add('M', doMotor, "motor"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println(F("Motor commands sketch | Initial motion control > torque/voltage : target 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + motor.move(); + + // motor monitoring + motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/double_full_control_example/double_full_control_example.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/double_full_control_example/double_full_control_example.ino new file mode 100644 index 0000000..b40ab62 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/double_full_control_example/double_full_control_example.ino @@ -0,0 +1,144 @@ + +#include + +// BLDC motor & driver instance +BLDCMotor motor1 = BLDCMotor(11); +BLDCDriver3PWM driver1 = BLDCDriver3PWM(5, 10, 6, 8); + +// BLDC motor & driver instance +BLDCMotor motor2 = BLDCMotor(11); +BLDCDriver3PWM driver2 = BLDCDriver3PWM(3, 9, 11, 7); + +// encoder instance +Encoder encoder1 = Encoder(12, 2, 500); +// channel A and B callbacks +void doA1(){encoder1.handleA();} +void doB1(){encoder1.handleB();} + +// encoder instance +Encoder encoder2 = Encoder(A5, A4, 500); +// channel A and B callbacks +void doA2(){encoder2.handleA();} +void doB2(){encoder2.handleB();} + + +// inline current sensor instance +// check if your board has R010 (0.01 ohm resistor) or R006 (0.006 mOhm resistor) +InlineCurrentSense current_sense1 = InlineCurrentSense(0.01f, 50.0f, A0, A2); + +// inline current sensor instance +// check if your board has R010 (0.01 ohm resistor) or R006 (0.006 mOhm resistor) +InlineCurrentSense current_sense2 = InlineCurrentSense(0.01f, 50.0f, A1, A3); + +// commander communication instance +Commander command = Commander(Serial); +// void doMotor1(char* cmd){ command.motor(&motor1, cmd); } +// void doMotor2(char* cmd){ command.motor(&motor2, cmd); } +void doTarget1(char* cmd){ command.scalar(&motor1.target, cmd); } +void doTarget2(char* cmd){ command.scalar(&motor2.target, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder1.init(); + encoder1.enableInterrupts(doA1, doB1); + // initialize encoder sensor hardware + encoder2.init(); + encoder2.enableInterrupts(doA2, doB2); + // link the motor to the sensor + motor1.linkSensor(&encoder1); + motor2.linkSensor(&encoder2); + + + // driver config + // power supply voltage [V] + driver1.voltage_power_supply = 12; + driver1.init(); + // link driver + motor1.linkDriver(&driver1); + // link current sense and the driver + current_sense1.linkDriver(&driver1); + + // power supply voltage [V] + driver2.voltage_power_supply = 12; + driver2.init(); + // link driver + motor2.linkDriver(&driver2); + // link current sense and the driver + current_sense2.linkDriver(&driver2); + + // set control loop type to be used + motor1.controller = MotionControlType::torque; + motor2.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor1.PID_velocity.P = 0.05f; + motor1.PID_velocity.I = 1; + motor1.PID_velocity.D = 0; + // default voltage_power_supply + motor1.voltage_limit = 12; + // contoller configuration based on the controll type + motor2.PID_velocity.P = 0.05f; + motor2.PID_velocity.I = 1; + motor2.PID_velocity.D = 0; + // default voltage_power_supply + motor2.voltage_limit = 12; + + // angle loop velocity limit + motor1.velocity_limit = 20; + motor2.velocity_limit = 20; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor1.useMonitoring(Serial); + motor2.useMonitoring(Serial); + + + // current sense init and linking + current_sense1.init(); + motor1.linkCurrentSense(¤t_sense1); + // current sense init and linking + current_sense2.init(); + motor2.linkCurrentSense(¤t_sense2); + + // initialise motor + motor1.init(); + // align encoder and start FOC + motor1.initFOC(); + + // initialise motor + motor2.init(); + // align encoder and start FOC + motor2.initFOC(); + + // set the inital target value + motor1.target = 2; + motor2.target = 2; + + // subscribe motor to the commander + // command.add('A', doMotor1, "motor 1"); + // command.add('B', doMotor2, "motor 2"); + command.add('A', doTarget1, "target 1"); + command.add('B', doTarget2, "target 2"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println("Motors ready."); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor1.loopFOC(); + motor2.loopFOC(); + + // iterative function setting the outter loop target + motor1.move(); + motor2.move(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/single_full_control_example/single_full_control_example.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/single_full_control_example/single_full_control_example.ino new file mode 100644 index 0000000..76a7296 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v2/single_full_control_example/single_full_control_example.ino @@ -0,0 +1,101 @@ + +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(5, 10, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 500); +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// inline current sensor instance +// check if your board has R010 (0.01 ohm resistor) or R006 (0.006 mOhm resistor) +InlineCurrentSense current_sense = InlineCurrentSense(0.01f, 50.0f, A0, A2); + +// commander communication instance +Commander command = Commander(Serial); +void doMotion(char* cmd){ command.motion(&motor, cmd); } +// void doMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + // link current sense and the driver + current_sense.linkDriver(&driver); + + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor.PID_velocity.P = 0.05f; + motor.PID_velocity.I = 1; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 20; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_downsample = 0; // disable intially + motor.monitor_variables = _MON_TARGET | _MON_VEL | _MON_ANGLE; // monitor target velocity and angle + + // current sense init and linking + current_sense.init(); + motor.linkCurrentSense(¤t_sense); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // subscribe motor to the commander + command.add('T', doMotion, "motion control"); + // command.add('M', doMotor, "motor"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println("Motor ready."); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + motor.move(); + + // motor monitoring + motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v3/single_full_control_example/single_full_control_example.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v3/single_full_control_example/single_full_control_example.ino new file mode 100644 index 0000000..0259328 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/SimpleFOCShield/version_v3/single_full_control_example/single_full_control_example.ino @@ -0,0 +1,101 @@ + +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(6, 10, 5, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 500); +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// inline current sensor instance +// ACS712-05B has the resolution of 0.185mV per Amp +InlineCurrentSense current_sense = InlineCurrentSense(1.0f, 0.185f, A0, A2); + +// commander communication instance +Commander command = Commander(Serial); +void doMotion(char* cmd){ command.motion(&motor, cmd); } +// void doMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + // link current sense and the driver + current_sense.linkDriver(&driver); + + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // controller configuration based on the control type + motor.PID_velocity.P = 0.05f; + motor.PID_velocity.I = 1; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 20; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + motor.monitor_downsample = 0; // disable intially + motor.monitor_variables = _MON_TARGET | _MON_VEL | _MON_ANGLE; // monitor target velocity and angle + + // current sense init and linking + current_sense.init(); + motor.linkCurrentSense(¤t_sense); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // subscribe motor to the commander + command.add('T', doMotion, "motion control"); + // command.add('M', doMotor, "motor"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println("Motor ready."); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + motor.move(); + + // motor monitoring + motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Smart_Stepper/smartstepper_control/smartstepper_control.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Smart_Stepper/smartstepper_control/smartstepper_control.ino new file mode 100644 index 0000000..80f2fe6 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Smart_Stepper/smartstepper_control/smartstepper_control.ino @@ -0,0 +1,61 @@ +/** + * Smart Stepper support with SimpleFOClibrary + */ +#include + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, A2); + +// Stepper motor & driver instance +StepperMotor motor = StepperMotor(50); +int in1[2] = {5, 6}; +int in2[2] = {A4, 7}; +StepperDriver2PWM driver = StepperDriver2PWM(4, in1, 9, in2); + +// instantiate the commander +Commander command = Commander(SerialUSB); +void doMotor(char* cmd) { command.motor(&motor, cmd); } + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // power supply voltage + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with SerialUSB + SerialUSB.begin(115200); + // comment out if not needed + motor.useMonitoring(SerialUSB); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command M + command.add('M', doMotor, "my motor"); + + SerialUSB.println(F("Motor ready.")); + SerialUSB.println(F("Set the target voltage using Serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + motor.loopFOC(); + + // Motion control function + motor.move(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino new file mode 100644 index 0000000..7f59551 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino @@ -0,0 +1,41 @@ +// 6pwm standalone example code for Teensy 3.x boards +#include + + +// BLDC driver instance +// using FTM0 timer +BLDCDriver6PWM driver = BLDCDriver6PWM(22,23, 9,10, 6,20, 8); +// using FTM3 timer - available on Teensy3.5 and Teensy3.6 +// BLDCDriver6PWM driver = BLDCDriver6PWM(2,14, 7,8, 35,36, 8); + +void setup() { + Serial.begin(115200); + // Enable debugging + // Driver init will show debugging output + SimpleFOCDebug::enable(&Serial); + + // pwm frequency to be used [Hz] + driver.pwm_frequency = 30000; + // dead zone percentage of the duty cycle - default 0.02 - 2% + driver.dead_zone=0.02; + // power supply voltage [V] + driver.voltage_power_supply = 12; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 12; + + // driver init + driver.init(); + + // enable driver + driver.enable(); + + _delay(1000); +} + +void loop() { + // setting pwm + // phase A: 3V + // phase B: 6V + // phase C: 5V + driver.setPwm(3,6,5); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino new file mode 100644 index 0000000..40924ee --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy3/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino @@ -0,0 +1,65 @@ +// 6pwm openloop velocity example +#include + + +// BLDC motor & driver instance +// BLDCMotor motor = BLDCMotor(pole pair number); +BLDCMotor motor = BLDCMotor(11); +// using FTM0 timer +// BLDCDriver6PWM(pwmA_H, pwmA_L, pwmB_H,pwmB_L, pwmC_H, pwmC_L) +BLDCDriver6PWM driver = BLDCDriver6PWM(22,23, 9,10, 6,20, 8); +// using FTM3 timer - available on Teensy3.5 and Teensy3.6 +// BLDCDriver6PWM driver = BLDCDriver6PWM(2,14, 7,8, 35,36, 8); + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&motor.target, cmd); } +void doLimit(char* cmd) { command.scalar(&motor.voltage_limit, cmd); } + +void setup() { + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + // limit the maximal dc voltage the driver can set + // as a protection measure for the low-resistance motors + // this value is fixed on startup + driver.voltage_limit = 6; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // limiting motor movements + // limit the voltage to be set to the motor + // start very low for high resistance motors + // currnet = resistance*voltage, so try to be well under 1Amp + motor.voltage_limit = 3; // [V] + + // open loop control config + motor.controller = MotionControlType::velocity_openloop; + + // init motor hardware + motor.init(); + + //initial motor target + motor.target=0; + + // add target command T + command.add('T', doTarget, "target velocity"); + command.add('L', doLimit, "voltage limit"); + + Serial.begin(115200); + Serial.println("Motor ready!"); + Serial.println("Set target velocity [rad/s]"); + _delay(1000); +} + +void loop() { + + // open loop velocity movement + // using motor.voltage_limit + motor.move(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino new file mode 100644 index 0000000..f3df3db --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino @@ -0,0 +1,57 @@ +// 6pwm standalone example code for Teensy 4.x boards +// +// Teensy4.x 6pwm driver generates a 6pwm signal using FlexTimers and it doesn't support the QuadTimers +// - Each high-low pair of the 6pwm has to be A and B channels of the same FlexTimer and to the same submodule +// +// List of available teensy 4.1 pins with their respective submodules and channels +// FlexPWM(timer number)_(submodule)_(channel) +// FlexPWM4_2_A pin 2 +// FlexPWM4_2_B pin 3 +// FlexPWM1_3_B pin 7 +// FlexPWM1_3_A pin 8 +// FlexPWM2_2_A pin 6 +// FlexPWM2_2_B pin 9 +// FlexPWM3_1_B pin 28 +// FlexPWM3_1_A pin 29 +// FlexPWM2_3_A pin 36 +// FlexPWM2_3_B pin 37 +#include + + +// BLDC driver instance +// make sure to provide channel A for high side and channel B for low side +// BLDCDriver6PWM(pwmA_H, pwmA_L, pwmB_H,pwmB_L, pwmC_H, pwmC_L) +// Example configuration +BLDCDriver6PWM driver = BLDCDriver6PWM(2,3, 6,9, 8,7); + +void setup() { + Serial.begin(115200); + // Enable debugging + // Driver init will show debugging output + SimpleFOCDebug::enable(&Serial); + + // pwm frequency to be used [Hz] + driver.pwm_frequency = 30000; + // dead zone percentage of the duty cycle - default 0.02 - 2% + driver.dead_zone=0.02; + // power supply voltage [V] + driver.voltage_power_supply = 12; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 12; + + // driver init + driver.init(); + + // enable driver + driver.enable(); + + _delay(1000); +} + +void loop() { + // setting pwm + // phase A: 3V + // phase B: 6V + // phase C: 5V + driver.setPwm(3,6,5); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino new file mode 100644 index 0000000..9c6eea0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/hardware_specific_examples/Teensy/Teensy4/open_loop_velocity_6pwm/open_loop_velocity_6pwm.ino @@ -0,0 +1,80 @@ +// 6pwm openloop velocity example +// +// Teensy4.x 6pwm driver generates a 6pwm signal using FlexTimers and it doesn't support the QuadTimers +// - Each high-low pair of the 6pwm has to be A and B channels of the same FlexTimer and to the same submodule +// +// List of available teensy 4.1 pins with their respective submodules and channels +// FlexPWM(timer number)_(submodule)_(channel) +// FlexPWM4_2_A pin 2 +// FlexPWM4_2_B pin 3 +// FlexPWM1_3_B pin 7 +// FlexPWM1_3_A pin 8 +// FlexPWM2_2_A pin 6 +// FlexPWM2_2_B pin 9 +// FlexPWM3_1_B pin 28 +// FlexPWM3_1_A pin 29 +// FlexPWM2_3_A pin 36 +// FlexPWM2_3_B pin 37 +#include + + +// BLDC motor & driver instance +// BLDCMotor motor = BLDCMotor(pole pair number); +BLDCMotor motor = BLDCMotor(11); +// make sure to provide channel A for high side and channel B for low side +// BLDCDriver6PWM(pwmA_H, pwmA_L, pwmB_H,pwmB_L, pwmC_H, pwmC_L) +// Example configuration +BLDCDriver6PWM driver = BLDCDriver6PWM(2,3, 6,9, 8,7); + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&motor.target, cmd); } +void doLimit(char* cmd) { command.scalar(&motor.voltage_limit, cmd); } + +void setup() { + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + // limit the maximal dc voltage the driver can set + // as a protection measure for the low-resistance motors + // this value is fixed on startup + driver.voltage_limit = 6; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // limiting motor movements + // limit the voltage to be set to the motor + // start very low for high resistance motors + // currnet = resistance*voltage, so try to be well under 1Amp + motor.voltage_limit = 3; // [V] + + // open loop control config + motor.controller = MotionControlType::velocity_openloop; + + // init motor hardware + motor.init(); + + //initial motor target + motor.target=0; + + // add target command T + command.add('T', doTarget, "target velocity"); + command.add('L', doLimit, "voltage limit"); + + Serial.begin(115200); + Serial.println("Motor ready!"); + Serial.println("Set target velocity [rad/s]"); + _delay(1000); +} + +void loop() { + + // open loop velocity movement + // using motor.voltage_limit + motor.move(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_position_example/open_loop_position_example.ino b/firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_position_example/open_loop_position_example.ino new file mode 100644 index 0000000..5a915dd --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_position_example/open_loop_position_example.ino @@ -0,0 +1,70 @@ +// Open loop motor control example + #include + + +// BLDC motor & driver instance +// BLDCMotor motor = BLDCMotor(pole pair number); +BLDCMotor motor = BLDCMotor(11); +// BLDCDriver3PWM driver = BLDCDriver3PWM(pwmA, pwmB, pwmC, Enable(optional)); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); + +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +//target variable +float target_position = 0; + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_position, cmd); } +void doLimit(char* cmd) { command.scalar(&motor.voltage_limit, cmd); } +void doVelocity(char* cmd) { command.scalar(&motor.velocity_limit, cmd); } + +void setup() { + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + // limit the maximal dc voltage the driver can set + // as a protection measure for the low-resistance motors + // this value is fixed on startup + driver.voltage_limit = 6; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // limiting motor movements + // limit the voltage to be set to the motor + // start very low for high resistance motors + // currnet = resistance*voltage, so try to be well under 1Amp + motor.voltage_limit = 3; // [V] + // limit/set the velocity of the transition in between + // target angles + motor.velocity_limit = 5; // [rad/s] cca 50rpm + // open loop control config + motor.controller = MotionControlType::angle_openloop; + + // init motor hardware + motor.init(); + + // add target command T + command.add('T', doTarget, "target angle"); + command.add('L', doLimit, "voltage limit"); + command.add('V', doLimit, "movement velocity"); + + Serial.begin(115200); + Serial.println("Motor ready!"); + Serial.println("Set target position [rad]"); + _delay(1000); +} + +void loop() { + // open loop angle movements + // using motor.voltage_limit and motor.velocity_limit + // angles can be positive or negative, negative angles correspond to opposite motor direction + motor.move(target_position); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_velocity_example/open_loop_velocity_example.ino b/firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_velocity_example/open_loop_velocity_example.ino new file mode 100644 index 0000000..43fc6f7 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/open_loop_motor_control/open_loop_velocity_example/open_loop_velocity_example.ino @@ -0,0 +1,68 @@ +// Open loop motor control example +#include + + +// BLDC motor & driver instance +// BLDCMotor motor = BLDCMotor(pole pair number); +BLDCMotor motor = BLDCMotor(11); +// BLDCDriver3PWM driver = BLDCDriver3PWM(pwmA, pwmB, pwmC, Enable(optional)); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); + +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + + +//target variable +float target_velocity = 0; + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } +void doLimit(char* cmd) { command.scalar(&motor.voltage_limit, cmd); } + +void setup() { + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + // limit the maximal dc voltage the driver can set + // as a protection measure for the low-resistance motors + // this value is fixed on startup + driver.voltage_limit = 6; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // limiting motor movements + // limit the voltage to be set to the motor + // start very low for high resistance motors + // current = voltage / resistance, so try to be well under 1Amp + motor.voltage_limit = 3; // [V] + + // open loop control config + motor.controller = MotionControlType::velocity_openloop; + + // init motor hardware + motor.init(); + + // add target command T + command.add('T', doTarget, "target velocity"); + command.add('L', doLimit, "voltage limit"); + + Serial.begin(115200); + Serial.println("Motor ready!"); + Serial.println("Set target velocity [rad/s]"); + _delay(1000); +} + +void loop() { + + // open loop velocity movement + // using motor.voltage_limit and motor.velocity_limit + // to turn the motor "backwards", just set a negative target_velocity + motor.move(target_velocity); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/encoder/angle_control/angle_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/encoder/angle_control/angle_control.ino new file mode 100644 index 0000000..ccb3980 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/encoder/angle_control/angle_control.ino @@ -0,0 +1,129 @@ +/** + * + * Position/angle motion control example + * Steps: + * 1) Configure the motor and encoder + * 2) Run the code + * 3) Set the target angle (in radians) from serial terminal + * + * + * NOTE : + * > Arduino UNO example code for running velocity motion control using an encoder with index significantly + * > Since Arduino UNO doesn't have enough interrupt pins we have to use software interrupt library PciManager. + * + * > If running this code with Nucleo or Bluepill or any other board which has more than 2 interrupt pins + * > you can supply doIndex directly to the encoder.enableInterrupts(doA,doB,doIndex) and avoid using PciManger + * + * > If you don't want to use index pin initialize the encoder class without index pin number: + * > For example: + * > - Encoder encoder = Encoder(2, 3, 8192); + * > and initialize interrupts like this: + * > - encoder.enableInterrupts(doA,doB) + * + * Check the docs.simplefoc.com for more info about the possible encoder configuration. + * + */ +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 8192); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 4; + + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/hall_sensor/angle_control/angle_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/hall_sensor/angle_control/angle_control.ino new file mode 100644 index 0000000..4bd7163 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/hall_sensor/angle_control/angle_control.ino @@ -0,0 +1,133 @@ +/** + * + * Position/angle motion control example + * Steps: + * 1) Configure the motor and hall sensor + * 2) Run the code + * 3) Set the target angle (in radians) from serial terminal + * + * + * NOTE : + * > This is for Arduino UNO example code for running angle motion control specifically + * > Since Arduino UNO doesn't have enough interrupt pins we have to use software interrupt library PciManager. + * + * > If running this code with Nucleo or Bluepill or any other board which has more than 2 interrupt pins + * > you can supply doIndex directly to the sensr.enableInterrupts(doA,doB,doC) and avoid using PciManger + * + * + */ +#include +// software interrupt library +#include +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// hall sensor instance +HallSensor sensor = HallSensor(2, 3, 4, 11); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} +// If no available hadware interrupt pins use the software interrupt +PciListenerImp listenC(sensor.pinC, doC); + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + +void setup() { + + // initialize sensor hardware + sensor.init(); + sensor.enableInterrupts(doA, doB); //, doC); + // software interrupts + PciManager.registerListener(&listenC); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + // index search velocity [rad/s] + motor.velocity_index_search = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 2; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 4; + + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/magnetic_sensor/angle_control/angle_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/magnetic_sensor/angle_control/angle_control.ino new file mode 100644 index 0000000..752030c --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/position_motion_control/magnetic_sensor/angle_control/angle_control.ino @@ -0,0 +1,112 @@ +/** + * + * Position/angle motion control example + * Steps: + * 1) Configure the motor and magnetic sensor + * 2) Run the code + * 3) Set the target angle (in radians) from serial terminal + * + */ +#include + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, 10); +// magnetic sensor instance - MagneticSensorI2C +//MagneticSensorI2C sensor = MagneticSensorI2C(AS5600_I2C); +// magnetic sensor instance - analog output +// MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// angle set point variable +float target_angle = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_angle, cmd); } + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // choose FOC modulation (optional) + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // maximal voltage to be set to the motor + motor.voltage_limit = 6; + + // velocity low pass filtering time constant + // the lower the less filtered + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 20; + // maximal velocity of the position control + motor.velocity_limit = 20; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target angle"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target angle using serial terminal:")); + _delay(1000); +} + + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_angle); + + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/current_control/current_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/current_control/current_control.ino new file mode 100644 index 0000000..c912340 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/current_control/current_control.ino @@ -0,0 +1,107 @@ +/** + * + * Torque control example using current control loop. + * + */ +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 500); +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// current sensor +InlineCurrentSense current_sense = InlineCurrentSense(0.01f, 50.0f, A0, A2); + +// current set point variable +float target_current = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_current, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + // link current sense and the driver + current_sense.linkDriver(&driver); + + // current sense init hardware + current_sense.init(); + // link the current sense to the motor + motor.linkCurrentSense(¤t_sense); + + // set torque mode: + // TorqueControlType::dc_current + // TorqueControlType::voltage + // TorqueControlType::foc_current + motor.torque_controller = TorqueControlType::foc_current; + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // foc currnet control parameters (Arduino UNO/Mega) + motor.PID_current_q.P = 5; + motor.PID_current_q.I= 300; + motor.PID_current_d.P= 5; + motor.PID_current_d.I = 300; + motor.LPF_current_q.Tf = 0.01f; + motor.LPF_current_d.Tf = 0.01f; + // foc currnet control parameters (stm/esp/due/teensy) + // motor.PID_current_q.P = 5; + // motor.PID_current_q.I= 1000; + // motor.PID_current_d.P= 5; + // motor.PID_current_d.I = 1000; + // motor.LPF_current_q.Tf = 0.002f; // 1ms default + // motor.LPF_current_d.Tf = 0.002f; // 1ms default + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target current"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target current using serial terminal:")); + _delay(1000); +} + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or torque (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_current); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/voltage_control/voltage_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/voltage_control/voltage_control.ino new file mode 100644 index 0000000..66ff456 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/encoder/voltage_control/voltage_control.ino @@ -0,0 +1,92 @@ +/** + * + * Torque control example using voltage control loop. + * + * Most of the low-end BLDC driver boards doesn't have current measurement therefore SimpleFOC offers + * you a way to control motor torque by setting the voltage to the motor instead hte current. + * + * This makes the BLDC motor effectively a DC motor, and you can use it in a same way. + */ +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 8192); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// voltage set point variable +float target_voltage = 2; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + + // aligning voltage + motor.voltage_sensor_align = 5; + // choose FOC modulation (optional) + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target voltage using serial terminal:")); + _delay(1000); +} + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/hall_sensor/voltage_control/voltage_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/hall_sensor/voltage_control/voltage_control.ino new file mode 100644 index 0000000..7273d15 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/hall_sensor/voltage_control/voltage_control.ino @@ -0,0 +1,95 @@ +/** + * + * Torque control example using voltage control loop. + * + * Most of the low-end BLDC driver boards doesn't have current measurement therefore SimpleFOC offers + * you a way to control motor torque by setting the voltage to the motor instead of the current. + * + * This makes the BLDC motor effectively a DC motor, and you can use it in a same way. + */ +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// hall sensor instance +HallSensor sensor = HallSensor(2, 3, 4, 11); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} + + +// voltage set point variable +float target_voltage = 2; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } + +void setup() { + + // initialize encoder sensor hardware + sensor.init(); + sensor.enableInterrupts(doA, doB, doC); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + // aligning voltage + motor.voltage_sensor_align = 3; + + // choose FOC modulation (optional) + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target voltage using serial terminal:")); + _delay(1000); +} + + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/magnetic_sensor/voltage_control/voltage_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/magnetic_sensor/voltage_control/voltage_control.ino new file mode 100644 index 0000000..d869f4d --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/torque_control/magnetic_sensor/voltage_control/voltage_control.ino @@ -0,0 +1,84 @@ +/** + * Torque control example using voltage control loop. + * + * Most of the low-end BLDC driver boards doesn't have current measurement therefore SimpleFOC offers + * you a way to control motor torque by setting the voltage to the motor instead hte current. + * + * This makes the BLDC motor effectively a DC motor, and you can use it in a same way. + */ +#include + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, 10); +// magnetic sensor instance - I2C +// MagneticSensorI2C sensor = MagneticSensorI2C(AS5600_I2C); +// magnetic sensor instance - analog output +// MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// voltage set point variable +float target_voltage = 2; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // power supply voltage + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + + // aligning voltage + motor.voltage_sensor_align = 5; + // choose FOC modulation (optional) + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target voltage using serial terminal:")); + _delay(1000); +} + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/encoder/velocity_control/velocity_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/encoder/velocity_control/velocity_control.ino new file mode 100644 index 0000000..f0f1e3e --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/encoder/velocity_control/velocity_control.ino @@ -0,0 +1,137 @@ +/** + * + * Velocity motion control example + * Steps: + * 1) Configure the motor and encoder + * 2) Run the code + * 3) Set the target velocity (in radians per second) from serial terminal + * + * + * + * NOTE : + * > Arduino UNO example code for running velocity motion control using an encoder with index significantly + * > Since Arduino UNO doesn't have enough interrupt pins we have to use software interrupt library PciManager. + * + * > If running this code with Nucleo or Bluepill or any other board which has more than 2 interrupt pins + * > you can supply doIndex directly to the encoder.enableInterrupts(doA,doB,doIndex) and avoid using PciManger + * + * > If you don't want to use index pin initialize the encoder class without index pin number: + * > For example: + * > - Encoder encoder = Encoder(2, 3, 8192); + * > and initialize interrupts like this: + * > - encoder.enableInterrupts(doA,doB) + * + * Check the docs.simplefoc.com for more info about the possible encoder configuration. + * + */ +#include +// software interrupt library +#include +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 8192, A0); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} +void doIndex(){encoder.handleIndex();} +// If no available hadware interrupt pins use the software interrupt +PciListenerImp listenerIndex(encoder.index_pin, doIndex); + + +// velocity set point variable +float target_velocity = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } + + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // software interrupts + PciManager.registerListener(&listenerIndex); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + // index search velocity [rad/s] + motor.velocity_index_search = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::velocity; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target velocity"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target velocity using serial terminal:")); + _delay(1000); +} + + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_velocity); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/hall_sensor/velocity_control/velocity_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/hall_sensor/velocity_control/velocity_control.ino new file mode 100644 index 0000000..1d39173 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/hall_sensor/velocity_control/velocity_control.ino @@ -0,0 +1,125 @@ +/** + * + * Velocity motion control example + * Steps: + * 1) Configure the motor and sensor + * 2) Run the code + * 3) Set the target velocity (in radians per second) from serial terminal + * + * + * + * NOTE : + * > Specifically for Arduino UNO example code for running velocity motion control using a hall sensor + * > Since Arduino UNO doesn't have enough interrupt pins we have to use software interrupt library PciManager. + * + * > If running this code with Nucleo or Bluepill or any other board which has more than 2 interrupt pins + * > you can supply doC directly to the sensor.enableInterrupts(doA,doB,doC) and avoid using PciManger + * + */ +#include +// software interrupt library +#include +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// hall sensor instance +HallSensor sensor = HallSensor(2, 3, 4, 11); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} +// If no available hadware interrupt pins use the software interrupt +PciListenerImp listenerIndex(sensor.pinC, doC); + +// velocity set point variable +float target_velocity = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } + +void setup() { + + // initialize sensor sensor hardware + sensor.init(); + sensor.enableInterrupts(doA, doB); //, doC); + // software interrupts + PciManager.registerListener(&listenerIndex); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::velocity; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 2; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target velocity using serial terminal:")); + _delay(1000); +} + + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_velocity); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/magnetic_sensor/velocity_control/velocity_control.ino b/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/magnetic_sensor/velocity_control/velocity_control.ino new file mode 100644 index 0000000..98e0942 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motion_control/velocity_motion_control/magnetic_sensor/velocity_control/velocity_control.ino @@ -0,0 +1,106 @@ +/** + * + * Velocity motion control example + * Steps: + * 1) Configure the motor and magnetic sensor + * 2) Run the code + * 3) Set the target velocity (in radians per second) from serial terminal + * + * + * By using the serial terminal set the velocity value you want to motor to obtain + * + */ +#include + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, 10); +// magnetic sensor instance - MagneticSensorI2C +//MagneticSensorI2C sensor = MagneticSensorI2C(AS5600_I2C); +// MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// velocity set point variable +float target_velocity = 0; +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // set motion control loop to be used + motor.controller = MotionControlType::velocity; + + // contoller configuration + // default parameters in defaults.h + + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 6; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering + // default 5ms - try different values to see what is the best. + // the lower the less filtered + motor.LPF_velocity.Tf = 0.01f; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target velocity"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target velocity using serial terminal:")); + _delay(1000); +} + +void loop() { + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_velocity); + + // function intended to be used with serial plotter to monitor motor variables + // significantly slowing the execution down!!!! + // motor.monitor(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/encoder/full_control_serial/full_control_serial.ino b/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/encoder/full_control_serial/full_control_serial.ino new file mode 100644 index 0000000..186d257 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/encoder/full_control_serial/full_control_serial.ino @@ -0,0 +1,106 @@ +/** + * Comprehensive BLDC motor control example using encoder + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * See more info in docs.simplefoc.com/commander_interface + */ +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 8192); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + + // choose FOC modulation + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // contoller configuration based on the controll type + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 50; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // define the motor id + command.add('A', onMotor, "motor"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println(F("Motor commands sketch | Initial motion control > torque/voltage : target 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + // velocity, position or voltage + // if tatget not set in parameter uses motor.target variable + motor.move(); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/hall_sensor/full_control_serial/full_control_serial.ino b/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/hall_sensor/full_control_serial/full_control_serial.ino new file mode 100644 index 0000000..df7b76a --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/hall_sensor/full_control_serial/full_control_serial.ino @@ -0,0 +1,114 @@ +/** + * Comprehensive BLDC motor control example using Hall sensor + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * See more info in docs.simplefoc.com/commander_interface + */ +#include +// software interrupt library +#include +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// hall sensor instance +HallSensor sensor = HallSensor(2, 3, 4, 11); + +// Interrupt routine intialisation +// channel A, B and C callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} +// If no available hadware interrupt pins use the software interrupt +PciListenerImp listenC(sensor.pinC, doC); + + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + + +void setup() { + + // initialize encoder sensor hardware + sensor.init(); + sensor.enableInterrupts(doA, doB); //, doC); + // software interrupts + PciManager.registerListener(&listenC); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + + // choose FOC modulation + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + // set control loop type to be used + motor.controller = MotionControlType::torque; + // contoller configuration based on the controll type + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 50; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // define the motor id + command.add('A', onMotor, "motor"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println(F("Motor commands sketch | Initial motion control > torque/voltage : target 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + // velocity, position or voltage + // if tatget not set in parameter uses motor.target variable + motor.move(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/magnetic_sensor/full_control_serial/full_control_serial.ino b/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/magnetic_sensor/full_control_serial/full_control_serial.ino new file mode 100644 index 0000000..098f688 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/motor_commands_serial_examples/magnetic_sensor/full_control_serial/full_control_serial.ino @@ -0,0 +1,104 @@ +/** + * Comprehensive BLDC motor control example using magnetic sensor + * + * Using serial terminal user can send motor commands and configure the motor and FOC in real-time: + * - configure PID controller constants + * - change motion control loops + * - monitor motor variabels + * - set target values + * - check all the configuration values + * + * See more info in docs.simplefoc.com/commander_interface + */ +#include + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, 10); +// magnetic sensor instance - MagneticSensorI2C +//MagneticSensorI2C sensor = MagneticSensorI2C(AS5600_I2C); +// magnetic sensor instance - analog output +// MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// commander interface +Commander command = Commander(Serial); +void onMotor(char* cmd){ command.motor(&motor, cmd); } + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + // choose FOC modulation + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + // set control loop type to be used + motor.controller = MotionControlType::torque; + + // contoller configuration based on the control type + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle loop controller + motor.P_angle.P = 20; + // angle loop velocity limit + motor.velocity_limit = 50; + + // use monitoring with serial for motor init + // monitoring port + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialise motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // set the inital target value + motor.target = 2; + + // define the motor id + command.add('A', onMotor, "motor"); + + // Run user commands to configure and the motor (find the full command list in docs.simplefoc.com) + Serial.println(F("Motor commands sketch | Initial motion control > torque/voltage : target 2V.")); + + _delay(1000); +} + + +void loop() { + // iterative setting FOC phase voltage + motor.loopFOC(); + + // iterative function setting the outter loop target + // velocity, position or voltage + // if tatget not set in parameter uses motor.target variable + motor.move(); + + // user communication + command.run(); +} diff --git a/firmware/lib/Arduino-FOC/examples/osc_control_examples/README.md b/firmware/lib/Arduino-FOC/examples/osc_control_examples/README.md new file mode 100644 index 0000000..bd6f776 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/osc_control_examples/README.md @@ -0,0 +1,28 @@ + +# OSC control examples + +OSC - opensoundcontrol.org is a simple message exchange protocol. Widely used in the Audio world it is being hailed as the successor to MIDI. But MIDI itself, and now OSC, has always been about sending and receiving fairly simple control messages, at medium speed, and that makes it well suited for the same kind of task in robotics or other control applications. + +As a protocol it is simple, making implementation quite easy, and while binary, simple enough to be fairly "human readable", which aids in debugging and reduces errors. + +The main advantage of using it is that there is a bunch of ready made software, and also libraries to use in your own programs, neaning you don't have to re-invent these things from scratch. + +## TouchOSC + +The first example shows how to set up control of a motor from TouchOSC. It's a super-fast way to set up a customizable GUI for your motor-project, that runs on your phone... + +## purr-Data + +The second example, "simplefoc\_osc\_esp32\_fullcontrol.ino" allows setting the variables and tuning the motor parameters, in the same way as the serial control but via OSC. The file "osc\_fullcontrol.pd" contains a sample GUI to go with that sketch, allowing the control and tuning of 2 BLDC motors. + +Here a screenshot of what it looks like in purr-Data: + +![Screenshot from pD](osc_fullcontrol_screenshot.png?raw=true "pD controlling 2 BLDC motors") + + +## Links to software used in examples + +- OSC - opensoundcontrol.org +- pD - https://puredata.info +- TouchOSC - https://hexler.net/products/touchosc + diff --git a/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_3pwm/layout1.touchosc b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_3pwm/layout1.touchosc new file mode 100644 index 0000000000000000000000000000000000000000..ba4d2afca30fa1bd295d514e07167c165edd5323 GIT binary patch literal 511 zcmWIWW@Zs#;Nak3sATmCWIzI(Kz3$cN@|5(MQ+Z~$-eoA40zi9dp)&Y-1<>f@Pgjt zvKx$?+a5pJwk(9((ChH?_48*>JAW{B`rJq68z&#nfAX+m`;~)jITJSr3fQ&^Oz^Zg z>$@z$tTy*cqK#D6ozJ&opL|t_DDvV`nV;)-Y~g2h?m%|2m5C-L66*~XA9xTH^!U8v z54%9FCM8GTVokmIpAVg!oA_eux&1D_>CHDys%}@#)i|Lu@#CTiSJLG-Hd(%E+S4Iw zv0E>B&&uPct8A`5PPLu)+WoN058c;N)!TF@mUCGNyb;~9dsAL2@6qPgrabwk7Sm|f zoQo+XdFu;vUT$;U9v}F#%&UyCacR=gWfNq3xUXfahd*)KQ#NHDhw#Q3IXerNxLZ4lzWC#CHU8*~n)GScpMBZo zGw&SlUDNfE{WDyy_Vm>;1bDM^1mvEnsb*wgxWvo=Cur~n>=0p6@^ RASp&5GzZd~fW|Q}002w5+d=>U literal 0 HcmV?d00001 diff --git a/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_3pwm/osc_esp32_3pwm.ino b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_3pwm/osc_esp32_3pwm.ino new file mode 100644 index 0000000..afb9529 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_3pwm/osc_esp32_3pwm.ino @@ -0,0 +1,183 @@ +/** + * Arduino SimpleFOC + OSC control example + * + * Simple example to show how you can control SimpleFOC via OSC. + * + * It's a nice way to work, easier than changing speeds via Seerial text input. It could also be the basis for + * a functional UI, for example in a lab, art-gallery or similar situation. + * + * For this example we used an ESP32 to run the code, a AS5048B I2C absolute encoder + * and a generic L298 driver board to drive a Emax 4114 gimbal motor. But there is no reason the OSC part will + * not work with any other setup. + * + * You will need: + * + * - a working SimpleFOC setup - motor, driver, encoder + * - a MCU with WiFi and UDP support, for example an ESP32, or an Arduino with Ethernet Shield + * - a device to run an OSC UI + * - a configured OSC UI + * - a WiFi network + * + * To do the OSC UI I used TouchOSC from https://hexler.net/products/touchosc + * There is an example UI file that works with this sketch, see "layout1.touchosc" + * You can open the UI file in 'TouchOSC Editor' (free program) and transfer it to the TouchOSC app on your device. + * + * Alternatively, there are other OSC UIs which may work, e.g. http://opensoundcontrol.org/implementations + * + * Using: + * + * Change the values below to match the WiFi ssid/password of your network. + * Load and run the code on your ESP32. Take a note of the IP address of your ESP32. + * Load and run the UI in TouchOSC. + * Configure TouchOSC to connect to your ESP32. + * The first command you send will cause the ESP32 to start sending responses to your TouchOSC device. + * After this you will see motor position and speed in the UI. + * Have fun controlling your SimpleFOC motors from your smartphone! + * + */ + + +#include "Arduino.h" +#include + +#include +#include + +#include +#include +#include +#include + + +const char ssid[] = "myssid"; // your network SSID (name) +const char pass[] = "mypassword"; // your network password +WiFiUDP Udp; +IPAddress outIp(192,168,1,17); // remote IP (not needed for receive) +const unsigned int outPort = 8000; // remote port (not needed for receive) +const unsigned int inPort = 8000; // local port to listen for UDP packets (here's where we send the packets) + + +OSCErrorCode error; + +MagneticSensorI2C sensor = MagneticSensorI2C(0x40, 14, 0xFE, 8); +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(25, 26, 27); + +// commander interface +Commander command = Commander(Serial); + +void setup() { + Serial.begin(115200); + + WiFi.begin(ssid, pass); + + Serial.print("Connecting WiFi "); + Serial.println(ssid); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Udp.begin(inPort); + Serial.println(); + Serial.print("WiFi connected. Local OSC address: "); + Serial.print(WiFi.localIP()); + Serial.print(":"); + Serial.println(inPort); + + delay(2000); + Serial.println("Initializing motor."); + + sensor.init(); + motor.linkSensor(&sensor); + driver.voltage_power_supply = 9; + driver.init(); + motor.linkDriver(&driver); + motor.controller = MotionControlType::velocity; + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0.001f; + motor.PID_velocity.output_ramp = 1000; + motor.LPF_velocity.Tf = 0.01f; + motor.voltage_limit = 8; + //motor.P_angle.P = 20; + motor.init(); + motor.initFOC(); + + Serial.println("All initialization complete."); +} + +// velocity set point variable +float target_velocity = 2.0f; +// angle set point variable +float target_angle = 1.0f; + + +void motorControl(OSCMessage &msg){ + if (msg.isInt(0)) + target_velocity = radians(msg.getInt(0)); + else if (msg.isFloat(0)) + target_velocity = radians(msg.getFloat(0)); + else if (msg.isDouble(0)) + target_velocity = radians(msg.getDouble(0)); + Serial.print("Velocity set to "); + Serial.println(target_velocity); +} + +void cmdControl(OSCMessage &msg){ + char cmdStr[16]; + if (msg.isString(0)) { + msg.getString(0,cmdStr,16); + command.motor(&motor,cmdStr); + } +} + +long lastSend = 0; +OSCMessage bundleIN; + +void loop() { + OSCBundle bundleOUT; + + // FOC algorithm function + motor.move(target_velocity); + motor.loopFOC(); + + + int size = Udp.parsePacket(); + if (size > 0) { + while (size--) { + bundleIN.fill(Udp.read()); + } + if (!bundleIN.hasError()) { + bundleIN.dispatch("/mot1/S", motorControl); + bundleIN.dispatch("/mot1/C", cmdControl); + IPAddress ip = Udp.remoteIP(); + if (!( ip==outIp )) { + Serial.print("New connection from "); + Serial.println(ip); + outIp = ip; + } + } + else { + error = bundleIN.getError(); + Serial.print("error: "); + Serial.println(error); + } + bundleIN.empty(); + } + else { // don't receive and send in the same loop... + long now = millis(); + if (now - lastSend > 100) { + int ang = (int)degrees(motor.shaftAngle()) % 360; + if (ang<0) ang = 360-abs(ang); + //BOSCBundle's add' returns the OSCMessage so the message's 'add' can be composed together + bundleOUT.add("/mot1/A").add((int)ang); + bundleOUT.add("/mot1/V").add((int)degrees(motor.shaftVelocity())); + Udp.beginPacket(outIp, outPort); + bundleOUT.send(Udp); + Udp.endPacket(); + bundleOUT.empty(); // empty the bundle to free room for a new one + lastSend = now; + } + } + +} diff --git a/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_esp32_fullcontrol.ino b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_esp32_fullcontrol.ino new file mode 100644 index 0000000..7c6aa4f --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_esp32_fullcontrol.ino @@ -0,0 +1,351 @@ +/** + * + * Control 2 motors on ESP32 using OSC + * + * In this example, all the commands available on the serial command interface are also available via OSC. + * Also, the example is for 2 motors. If you have only 1 motor, comment out the lines for the second motor. + * + * + * + * + */ + + +#include "Arduino.h" +#include +#include +#include "ssid.h" // create this file, which defines the constants MYSSID and MYPASS +#include +#include +#include + +#include +#include +#include + + +const char ssid[] = MYSSID; // your network SSID (name) +const char pass[] = MYPASS; // your network password +WiFiUDP Udp; +IPAddress outIp(192,168,1,13); // remote IP (not needed for receive) +const unsigned int outPort = 8000; // remote port (not needed for receive) +const unsigned int inPort = 8000; // local port to listen for UDP packets (here's where we send the packets) +#define POWER_SUPPLY 7.4f + + + +MagneticSensorI2C sensor2 = MagneticSensorI2C(0x40, 14, 0xFE, 8); +MagneticSensorI2C sensor1 = MagneticSensorI2C(0x41, 14, 0xFE, 8); +BLDCMotor motor1 = BLDCMotor(7); +BLDCMotor motor2 = BLDCMotor(7); +BLDCDriver3PWM driver1 = BLDCDriver3PWM(25, 26, 27); +BLDCDriver3PWM driver2 = BLDCDriver3PWM(0, 4, 16); + +String m1Prefix("/M1"); +String m2Prefix("/M2"); + + +// we store seperate set-points for each motor, of course +float set_point1 = 0.0f; +float set_point2 = 0.0f; + + +OSCErrorCode error; +OSCBundle bundleOUT; // outgoing message, gets re-used + + + +void setupOTA(const char* hostname) { + ArduinoOTA + .setPort(8266) + .onStart([]() { + String type; + if (ArduinoOTA.getCommand() == U_FLASH) + type = "sketch"; + else // U_SPIFFS + type = "filesystem"; + + // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() + Serial.println("Start updating " + type); + }) + .onEnd([]() { + Serial.println("\nEnd"); + }) + .onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("Progress: %u%%\n", (progress / (total / 100))); + }) + .onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + else if (error == OTA_END_ERROR) Serial.println("End Failed"); + }) + .setHostname(hostname) + .setMdnsEnabled(true); + ArduinoOTA.begin(); +} + + +void setup() { + // set pins low - motor initialization can take some time, + // and you don't want current flowing through the other motor while it happens... + pinMode(0,OUTPUT); + pinMode(4,OUTPUT); + pinMode(16,OUTPUT); + pinMode(25,OUTPUT); + pinMode(26,OUTPUT); + pinMode(27,OUTPUT); + digitalWrite(0, 0); + digitalWrite(4, 0); + digitalWrite(16, 0); + digitalWrite(25, 0); + digitalWrite(26, 0); + digitalWrite(27, 0); + + Serial.begin(115200); + delay(200); + + WiFi.begin(ssid, pass); + + Serial.print("Connecting WiFi "); + Serial.println(ssid); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Udp.begin(inPort); + Serial.println(); + Serial.print("WiFi connected. Local OSC address: "); + Serial.print(WiFi.localIP()); + Serial.print(":"); + Serial.println(inPort); + + setupOTA("smallrobot1"); + + Serial.println("Initializing motors."); + + Wire.setClock(400000); + + sensor1.init(); + motor1.linkSensor(&sensor1); + driver1.voltage_power_supply = POWER_SUPPLY; + driver1.init(); + motor1.linkDriver(&driver1); + motor1.foc_modulation = FOCModulationType::SpaceVectorPWM; + motor1.controller = MotionControlType::velocity; + motor1.PID_velocity.P = 0.2f; + motor1.PID_velocity.I = 20; + motor1.PID_velocity.D = 0.001f; + motor1.PID_velocity.output_ramp = 1000; + motor1.LPF_velocity.Tf = 0.01f; + motor1.voltage_limit = POWER_SUPPLY; + motor1.P_angle.P = 20; + motor1.init(); + motor1.initFOC(); + + sensor2.init(); + motor2.linkSensor(&sensor2); + driver2.voltage_power_supply = POWER_SUPPLY; + driver2.init(); + motor2.linkDriver(&driver2); + motor2.foc_modulation = FOCModulationType::SpaceVectorPWM; + motor2.controller = MotionControlType::velocity; + motor2.PID_velocity.P = 0.2f; + motor2.PID_velocity.I = 20; + motor2.PID_velocity.D = 0.001f; + motor2.PID_velocity.output_ramp = 1000; + motor2.LPF_velocity.Tf = 0.01f; + motor2.voltage_limit = POWER_SUPPLY; + motor2.P_angle.P = 20; + motor2.init(); + motor2.initFOC(); + + sendMotorParams(motor1, m1Prefix); + sendMotorParams(motor2, m2Prefix); + Serial.println("All initialization complete."); + _delay(1000); +} + + + + +template +void sendMessage(String& addr, T datum) { + bundleOUT.add(addr.c_str()).add(datum); + Udp.beginPacket(outIp, outPort); + bundleOUT.send(Udp); + Udp.endPacket(); + bundleOUT.empty(); // empty the bundle to free room for a new one +} + + + + +float getNumber(OSCMessage &msg, int index) { + if (msg.getType(index)=='i') + return msg.getInt(index); + if (msg.getType(index)=='f') + return msg.getFloat(index); + if (msg.getType(index)=='d') + return msg.getDouble(index); + return 0; +} + + + +void motorCmd(OSCMessage &msg, int offset, BLDCMotor& motor, float* set_point, String& prefix){ + Serial.print("Command for "); + Serial.println(prefix); + if (msg.fullMatch("/P", offset)) { + motor.PID_velocity.P = getNumber(msg,0); + sendMessage(prefix+"/P", motor.PID_velocity.P); + } + else if (msg.fullMatch("/I", offset)) { + motor.PID_velocity.I = getNumber(msg,0); + sendMessage(prefix+"/I", motor.PID_velocity.I); + } + else if (msg.fullMatch("/D", offset)) { + motor.PID_velocity.D = getNumber(msg,0); + sendMessage(prefix+"/D", motor.PID_velocity.D); + } + else if (msg.fullMatch("/R", offset)) { + motor.PID_velocity.output_ramp = getNumber(msg,0); + sendMessage(prefix+"/R", motor.PID_velocity.output_ramp); + } + else if (msg.fullMatch("/F", offset)) { + motor.LPF_velocity.Tf = getNumber(msg,0); + sendMessage(prefix+"/F", motor.LPF_velocity.Tf); + } + else if (msg.fullMatch("/K", offset)) { + motor.P_angle.P = getNumber(msg,0); + sendMessage(prefix+"/K", motor.P_angle.P); + } + else if (msg.fullMatch("/N", offset)) { + motor.velocity_limit = getNumber(msg,0); + sendMessage(prefix+"/N", motor.velocity_limit); + } + else if (msg.fullMatch("/L", offset)) { + motor.voltage_limit = getNumber(msg,0); + sendMessage(prefix+"/L", motor.voltage_limit); + } + else if (msg.fullMatch("/C", offset)) { + motor.controller = (MotionControlType)msg.getInt(0); + sendMessage(prefix+"/C", motor.controller); + } + else if (msg.fullMatch("/t", offset)) { + *set_point = getNumber(msg,0); + sendMessage(prefix+"/3", *set_point); // TODO is the set-point the same as motor.target? + Serial.print("Setting set-point to "); + Serial.println(*set_point); + } + else if (msg.fullMatch("/o", offset)) { + motor.disable(); + } + else if (msg.fullMatch("/e", offset)) { + motor.enable(); + } + else if (msg.fullMatch("/params", offset)) { + sendMotorParams(motor, prefix); + } + else if (msg.fullMatch("/reinit", offset)) { + motor.disable(); + motor.init(); + motor.initFOC(); + } + +} + + + + + + +void sendMotorMonitoring() { + //Serial.println("Sending monitoring..."); + bundleOUT.add("/M1/0").add(motor1.voltage.q); + bundleOUT.add("/M1/1").add(motor1.shaft_velocity); + bundleOUT.add("/M1/2").add(motor1.shaft_angle); + bundleOUT.add("/M1/3").add(motor1.target); + bundleOUT.add("/M2/0").add(motor2.voltage.q); + bundleOUT.add("/M2/1").add(motor2.shaft_velocity); + bundleOUT.add("/M2/2").add(motor2.shaft_angle); + bundleOUT.add("/M2/3").add(motor2.target); + // TODO pack it into one message bundleOUT.add("/M2/i").add(motor2.voltage_q).add(motor2.shaft_velocity).add(motor2.shaft_angle).add(motor2.target); + Udp.beginPacket(outIp, outPort); + bundleOUT.send(Udp); + Udp.endPacket(); + bundleOUT.empty(); // empty the bundle to free room for a new one +} + + + +void sendMotorParams(BLDCMotor& motor, String& prefix) { + bundleOUT.add((prefix+"/P").c_str()).add(motor.PID_velocity.P); + bundleOUT.add((prefix+"/I").c_str()).add(motor.PID_velocity.I); + bundleOUT.add((prefix+"/D").c_str()).add(motor.PID_velocity.D); + bundleOUT.add((prefix+"/R").c_str()).add(motor.PID_velocity.output_ramp); + bundleOUT.add((prefix+"/F").c_str()).add(motor.LPF_velocity.Tf); + bundleOUT.add((prefix+"/K").c_str()).add(motor.P_angle.P); + bundleOUT.add((prefix+"/N").c_str()).add(motor.velocity_limit); + bundleOUT.add((prefix+"/L").c_str()).add(motor.voltage_limit); + bundleOUT.add((prefix+"/C").c_str()).add(motor.controller); + Udp.beginPacket(outIp, outPort); + bundleOUT.send(Udp); + Udp.endPacket(); + bundleOUT.empty(); // empty the bundle to free room for a new one +} + + + + + +long lastSend = 0; +OSCMessage bundleIN; +int size; + + +void loop() { + + // FOC algorithm function + motor1.loopFOC(); + motor1.move(set_point1); + motor2.loopFOC(); + motor2.move(set_point2); + + + int size = Udp.parsePacket(); + if (size > 0) { + while (size--) { + bundleIN.fill(Udp.read()); + } + if (!bundleIN.hasError()) { + bundleIN.route("/M1", [](OSCMessage& msg, int offset){ motorCmd(msg, offset, motor1, &set_point1, m1Prefix); }, 0); + bundleIN.route("/M2", [](OSCMessage& msg, int offset){ motorCmd(msg, offset, motor2, &set_point2, m2Prefix); }, 0); + IPAddress ip = Udp.remoteIP(); + if (!( ip==outIp )) { + Serial.print("New connection from "); + Serial.println(ip); + outIp = ip; + sendMotorParams(motor1, m1Prefix); + sendMotorParams(motor2, m2Prefix); + } + } + else { + error = bundleIN.getError(); + Serial.print("error: "); + Serial.println(error); + } + bundleIN.empty(); + } + else { // don't receive and send in the same loop... + long now = millis(); + if (now - lastSend > 100) { + sendMotorMonitoring(); + lastSend = now; + } + } + + ArduinoOTA.handle(); +} diff --git a/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_fullcontrol.pd b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_fullcontrol.pd new file mode 100644 index 0000000..ddbf2f9 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/osc_fullcontrol.pd @@ -0,0 +1,384 @@ +#N struct text float x float y text t; +#N canvas 1842 146 1519 1052 12; +#X obj 501 697 cnv 15 193 209 empty empty Tuning\ M1 20 12 0 14 #e0e0e0 +#404040 0; +#X obj 787 477 mrpeach/unpackOSC; +#X obj 132 586 print oscin; +#X obj 787 504 print oscout; +#X obj 723 449 spigot; +#X obj 774 452 tgl 15 1 empty empty Debug 17 7 0 10 #fcfcfc #000000 +#000000 1 1; +#X msg 591 503 disconnect; +#X obj 132 558 spigot; +#X obj 114 562 tgl 15 1 empty empty Debug -34 6 0 10 #fcfcfc #000000 +#000000 0 1; +#X obj 132 531 mrpeach/unpackOSC; +#X obj 673 477 mrpeach/udpsend; +#X obj 132 496 mrpeach/udpreceive 8000; +#X obj 673 422 mrpeach/packOSC; +#X obj 1043 150 hsl 249 25 -5000 5000 0 0 empty empty Set\ Point\ M1 +-2 -8 0 10 #fcfcfc #000000 #000000 0 1; +#X obj 1044 197 hsl 247 25 -15 15 0 0 empty empty Set\ Point\ M2 -2 +-8 0 10 #fcfcfc #000000 #000000 12300 1; +#X obj 120 153 bng 53 250 50 0 empty empty STOP 14 26 0 10 #fc1204 +#000000 #ffffff; +#X obj 200 102 * 0.10472; +#X obj 202 169 hsl 235 30 -520 520 0 0 empty empty Set\ point\ (Velocity) +-2 -8 0 10 #fcfcfc #000000 #000000 11500 1; +#X obj 673 449 spigot; +#X obj 653 452 tgl 15 1 empty empty Enable\ send -71 6 0 10 #fcfcfc +#000000 #000000 1 1; +#X msg 484 478 connect 192.168.1.43 8000; +#X obj 673 395 speedlim 100; +#X obj 231 573 mrpeach/routeOSC /M1 /M2; +#X obj 231 610 mrpeach/routeOSC /0 /1 /2 /3 /P /I /D /R /F /K /N /L +/C; +#X obj 326 844 hsl 101 29 0 6.3 0 0 empty empty rad -2 -8 0 10 #fcfcfc +#000000 #000000 0 1; +#X obj 326 812 % 6.28319; +#X obj 326 704 nbx 7 27 -1e+37 1e+37 0 0 empty empty V -5 0 0 18 #fcfcfc +#000000 #000000 0.137548 256 3; +#X obj 113 804 nbx 7 27 -1e+37 1e+37 0 0 empty empty Set\ point 0 -15 +0 18 #fcfcfc #000000 #000000 0 256 3; +#X obj 326 776 nbx 7 27 -1e+37 1e+37 0 0 empty empty Position -80 0 +0 18 #fcfcfc #000000 #000000 -348.637 256 3; +#X obj 326 740 nbx 7 27 -1e+37 1e+37 0 0 empty empty Velocity -80 0 +0 18 #fcfcfc #000000 #000000 0.0649328 256 3; +#X obj 538 747 nbx 5 14 -1e+37 1e+37 0 0 empty empty P\ gain 0 -8 0 +10 #fcfcfc #000000 #000000 0.2 256 3; +#X obj 537 776 nbx 5 14 -1e+37 1e+37 0 0 empty empty I\ gain 0 -8 0 +10 #fcfcfc #000000 #000000 20 256 3; +#X obj 538 808 nbx 5 14 -1e+37 1e+37 0 0 empty empty D\ gain 0 -8 0 +10 #fcfcfc #000000 #000000 0.0001 256 3; +#X obj 539 838 nbx 5 14 -1e+37 1e+37 0 0 empty empty V\ Ramp 0 -8 0 +10 #fcfcfc #000000 #000000 1000 256 3; +#X obj 539 868 nbx 5 14 -1e+37 1e+37 0 0 empty empty LP\ time 0 -8 +0 10 #fcfcfc #000000 #000000 0.01 256 3; +#X obj 605 747 nbx 5 14 -1e+37 1e+37 0 0 empty empty angP\ gain 0 -8 +0 10 #fcfcfc #000000 #000000 20 256 3; +#X obj 608 779 nbx 5 14 -1e+37 1e+37 0 0 empty empty angP\ lim 0 -8 +0 10 #fcfcfc #000000 #000000 20 256 3; +#X obj 609 836 nbx 5 14 -1e+37 1e+37 0 0 empty empty V\ limit 0 -8 +0 10 #fcfcfc #000000 #000000 8 256 3; +#X obj 122 278 hradio 53 0 1 3 motorselect empty empty 0 -8 0 10 #fcfcfc +#000000 #000000 0; +#X scalar text 172 305 \; \;; +#X obj 122 372 select 0 1 2; +#X msg 122 399 prefix /M?; +#X msg 149 423 prefix /M1; +#X msg 178 445 prefix /M2; +#X obj 789 422 mrpeach/packOSC; +#X obj 789 395 speedlim 100; +#X msg 592 531 typetags \$1; +#X obj 571 535 tgl 15 1 empty empty OSC\ type\ tags -80 7 0 10 #ffffff +#000000 #000000 1 1; +#X text 63 286 Choose Motor, f 7; +#X text 137 339 All, f 4; +#X text 191 339 M1, f 4; +#X text 247 339 M2, f 4; +#X text 152 77 RPM; +#X obj 1008 148 bng 29 250 50 0 empty empty STOP 2 13 0 10 #fc1204 +#000000 #ffffff; +#X obj 1009 195 bng 29 250 50 0 empty empty STOP 2 13 0 10 #fc1204 +#000000 #ffffff; +#X obj 74 696 hradio 53 0 1 3 empty empty empty 0 -8 0 10 #fcfcfc #000000 +#000000 1; +#X text 8 711 Control; +#X text 67 752 Voltage; +#X text 124 753 Velocity; +#X text 189 754 Position; +#X obj 312 101 /; +#X obj 312 129 * 6.28319; +#X text 424 75 cm, f 4; +#X text 393 51 Wheel diameter; +#X obj 394 100 * 0.0314159; +#X msg 348 636 set \$1; +#X msg 376 637 set \$1; +#X msg 407 636 set \$1; +#X msg 435 636 set \$1; +#X msg 466 636 set \$1; +#X msg 495 636 set \$1; +#X msg 524 637 set \$1; +#X msg 554 637 set \$1; +#X msg 583 637 set \$1; +#X obj 75 898 s osctargetedout; +#X obj 75 866 prepend /M1/C; +#X obj 773 304 r osctargetedout; +#X obj 593 912 prepend /M1/K; +#X obj 602 925 prepend /M1/N; +#X obj 609 936 prepend /M1/L; +#X obj 564 976 s osctargetedout; +#X obj 1271 697 cnv 15 193 209 empty empty Tuning\ M2 20 12 0 14 #e0e0e0 +#404040 0; +#X obj 1001 610 mrpeach/routeOSC /0 /1 /2 /3 /P /I /D /R /F /K /N /L +/C; +#X obj 1096 844 hsl 101 29 0 6.3 0 0 empty empty rad -2 -8 0 10 #fcfcfc +#000000 #000000 0 1; +#X obj 1096 812 % 6.28319; +#X obj 1096 704 nbx 7 27 -1e+37 1e+37 0 0 empty empty V -5 0 0 18 #fcfcfc +#000000 #000000 -0.13018 256 3; +#X obj 883 804 nbx 7 27 -1e+37 1e+37 0 0 setpointin2 empty Set\ point +0 -15 0 18 #fcfcfc #000000 #000000 0 256 3; +#X obj 1096 776 nbx 7 27 -1e+37 1e+37 0 0 empty empty Position -80 +0 0 18 #fcfcfc #000000 #000000 -346.273 256 3; +#X obj 1096 740 nbx 7 27 -1e+37 1e+37 0 0 empty empty Velocity -80 +0 0 18 #fcfcfc #000000 #000000 0.0657255 256 3; +#X obj 1308 747 nbx 5 14 -1e+37 1e+37 0 0 empty empty P\ gain 0 -8 +0 10 #fcfcfc #000000 #000000 0.2 256 3; +#X obj 1308 778 nbx 5 14 -1e+37 1e+37 0 0 empty empty I\ gain 0 -8 +0 10 #fcfcfc #000000 #000000 20 256 3; +#X obj 1308 808 nbx 5 14 -1e+37 1e+37 0 0 empty empty D\ gain 0 -8 +0 10 #fcfcfc #000000 #000000 0.001 256 3; +#X obj 1309 838 nbx 5 14 -1e+37 1e+37 0 0 empty empty V\ Ramp 0 -8 +0 10 #fcfcfc #000000 #000000 1000 256 3; +#X obj 1309 868 nbx 5 14 -1e+37 1e+37 0 0 empty empty LP\ time 0 -8 +0 10 #fcfcfc #000000 #000000 0.01 256 3; +#X obj 1375 747 nbx 5 14 -1e+37 1e+37 0 0 empty empty angP\ gain 0 +-8 0 10 #fcfcfc #000000 #000000 20 256 3; +#X obj 1378 779 nbx 5 14 -1e+37 1e+37 0 0 empty empty angP\ lim 0 -8 +0 10 #fcfcfc #000000 #000000 20 256 3; +#X obj 1379 836 nbx 5 14 -1e+37 1e+37 0 0 empty empty V\ limit 0 -8 +0 10 #fcfcfc #000000 #000000 8 256 3; +#X obj 844 696 hradio 53 0 1 3 empty empty empty 0 -8 0 10 #fcfcfc +#000000 #000000 1; +#X text 778 711 Control; +#X text 837 752 Voltage; +#X text 894 753 Velocity; +#X text 959 754 Position; +#X msg 1118 636 set \$1; +#X msg 1146 637 set \$1; +#X msg 1177 636 set \$1; +#X msg 1205 636 set \$1; +#X msg 1236 636 set \$1; +#X msg 1265 636 set \$1; +#X msg 1294 637 set \$1; +#X msg 1324 637 set \$1; +#X msg 1353 637 set \$1; +#X obj 845 898 s osctargetedout; +#X obj 1325 976 s osctargetedout; +#X obj 1379 936 prepend /M2/L; +#X obj 1372 925 prepend /M2/N; +#X obj 1364 912 prepend /M2/K; +#X obj 1296 947 prepend /M2/F; +#X obj 1291 940 prepend /M2/R; +#X obj 1287 933 prepend /M2/D; +#X obj 1281 925 prepend /M2/I; +#X obj 1276 917 prepend /M2/P; +#X obj 526 947 prepend /M1/F; +#X obj 521 940 prepend /M1/R; +#X obj 517 933 prepend /M1/D; +#X obj 511 925 prepend /M1/I; +#X obj 506 917 prepend /M1/P; +#X obj 393 78 nbx 2 14 0 50 0 1 empty empty empty 0 -8 0 10 #fcfcfc +#000000 #000000 6 256 2; +#X obj 299 71 nbx 5 24 -20 20 0 0 empty empty empty 0 -8 0 10 #fcfcfc +#000000 #000000 -0.266666 256 2; +#X obj 179 74 nbx 7 23 -5000 5000 0 0 empty empty empty 0 -8 0 10 #fcfcfc +#000000 #000000 -84.8824 256 2; +#X obj 577 169 hsl 104 30 -3.1415 3.1415 0 0 empty empty Set\ point\ (Position) +-2 -8 0 10 #fcfcfc #000000 #000000 10300 1; +#X obj 708 68 vsl 31 122 0 12 0 0 empty empty Set\ point\ (Voltage) +0 -9 0 10 #fcfcfc #000000 #000000 0 1; +#X obj 246 13 / 0.10472; +#X msg 318 13 set \$1; +#X obj 457 11 *; +#X obj 384 11 / 6.28319; +#X obj 547 96 /; +#X obj 547 125 * 6.28319; +#X obj 547 66 nbx 5 24 -100 100 0 0 empty empty empty 0 -8 0 10 #fcfcfc +#000000 #000000 0.0599999 256 2; +#X text 534 68 m; +#X obj 20 6 r setpointin; +#X obj 17 36 r setpointin2; +#X obj 120 6 spigot; +#X obj 120 42 spigot; +#X obj 16 63 r motorselect; +#X obj 1339 99 r setpointin; +#X obj 1345 150 r setpointin2; +#X msg 493 11 set \$1; +#X obj 22 103 > 1; +#X obj 59 103 <= 1; +#X msg 1110 529 /M?/params; +#X obj 1110 502 loadbang; +#X msg 1339 126 set \$1; +#X msg 1343 174 set \$1; +#X obj 639 9 *; +#X obj 566 9 / 6.28319; +#X msg 675 9 set \$1; +#X obj 483 448 loadbang; +#X text 284 74 m/s; +#X obj 845 866 prepend /M2/C; +#X msg 163 226 sendtyped /M?/t f 0; +#X obj 458 224 prepend sendtyped /t f; +#X msg 991 301 sendtyped /M2/t f 0; +#X msg 983 274 sendtyped /M1/t f 0; +#X obj 1051 286 prepend sendtyped /M1/t f; +#X obj 1047 322 prepend sendtyped /M2/t f; +#X obj 475 171 nbx 7 21 -1e+37 1e+37 0 0 empty empty rad 0 -8 0 10 +#fcfcfc #000000 #000000 2 256 2; +#X connect 1 0 3 0; +#X connect 4 0 1 0; +#X connect 5 0 4 1; +#X connect 6 0 10 0; +#X connect 7 0 2 0; +#X connect 8 0 7 1; +#X connect 9 0 7 0; +#X connect 9 0 22 0; +#X connect 11 0 9 0; +#X connect 12 0 18 0; +#X connect 12 0 4 0; +#X connect 13 0 163 0; +#X connect 14 0 164 0; +#X connect 15 0 159 0; +#X connect 16 0 17 0; +#X connect 17 0 131 0; +#X connect 17 0 134 0; +#X connect 17 0 160 0; +#X connect 18 0 10 0; +#X connect 19 0 18 1; +#X connect 20 0 10 0; +#X connect 21 0 12 0; +#X connect 22 0 23 0; +#X connect 22 1 82 0; +#X connect 23 0 26 0; +#X connect 23 1 29 0; +#X connect 23 2 28 0; +#X connect 23 3 27 0; +#X connect 23 4 65 0; +#X connect 23 5 66 0; +#X connect 23 6 67 0; +#X connect 23 7 68 0; +#X connect 23 8 69 0; +#X connect 23 9 70 0; +#X connect 23 10 71 0; +#X connect 23 11 72 0; +#X connect 23 12 73 0; +#X connect 25 0 24 0; +#X connect 28 0 25 0; +#X connect 30 0 125 0; +#X connect 31 0 124 0; +#X connect 32 0 123 0; +#X connect 33 0 122 0; +#X connect 34 0 121 0; +#X connect 35 0 77 0; +#X connect 36 0 78 0; +#X connect 37 0 79 0; +#X connect 38 0 40 0; +#X connect 40 0 41 0; +#X connect 40 1 42 0; +#X connect 40 2 43 0; +#X connect 41 0 12 0; +#X connect 42 0 12 0; +#X connect 43 0 12 0; +#X connect 44 0 18 0; +#X connect 44 0 4 0; +#X connect 45 0 44 0; +#X connect 46 0 12 0; +#X connect 47 0 46 0; +#X connect 53 0 162 0; +#X connect 54 0 161 0; +#X connect 55 0 75 0; +#X connect 60 0 61 0; +#X connect 61 0 17 0; +#X connect 64 0 60 1; +#X connect 64 0 133 1; +#X connect 64 0 135 1; +#X connect 64 0 153 1; +#X connect 65 0 30 0; +#X connect 66 0 31 0; +#X connect 67 0 32 0; +#X connect 68 0 33 0; +#X connect 69 0 34 0; +#X connect 70 0 35 0; +#X connect 71 0 36 0; +#X connect 72 0 37 0; +#X connect 73 0 55 0; +#X connect 75 0 74 0; +#X connect 76 0 45 0; +#X connect 77 0 80 0; +#X connect 78 0 80 0; +#X connect 79 0 80 0; +#X connect 82 0 85 0; +#X connect 82 1 88 0; +#X connect 82 2 87 0; +#X connect 82 3 86 0; +#X connect 82 4 102 0; +#X connect 82 5 103 0; +#X connect 82 6 104 0; +#X connect 82 7 105 0; +#X connect 82 8 106 0; +#X connect 82 9 107 0; +#X connect 82 10 108 0; +#X connect 82 11 109 0; +#X connect 82 12 110 0; +#X connect 84 0 83 0; +#X connect 87 0 84 0; +#X connect 89 0 120 0; +#X connect 90 0 119 0; +#X connect 91 0 118 0; +#X connect 92 0 117 0; +#X connect 93 0 116 0; +#X connect 94 0 115 0; +#X connect 95 0 114 0; +#X connect 96 0 113 0; +#X connect 97 0 158 0; +#X connect 102 0 89 0; +#X connect 103 0 90 0; +#X connect 104 0 91 0; +#X connect 105 0 92 0; +#X connect 106 0 93 0; +#X connect 107 0 94 0; +#X connect 108 0 95 0; +#X connect 109 0 96 0; +#X connect 110 0 97 0; +#X connect 113 0 112 0; +#X connect 114 0 112 0; +#X connect 115 0 112 0; +#X connect 116 0 112 0; +#X connect 117 0 112 0; +#X connect 118 0 112 0; +#X connect 119 0 112 0; +#X connect 120 0 112 0; +#X connect 121 0 80 0; +#X connect 122 0 80 0; +#X connect 123 0 80 0; +#X connect 124 0 80 0; +#X connect 125 0 80 0; +#X connect 126 0 64 0; +#X connect 127 0 60 0; +#X connect 128 0 16 0; +#X connect 129 0 165 0; +#X connect 130 0 160 0; +#X connect 131 0 132 0; +#X connect 132 0 128 0; +#X connect 133 0 146 0; +#X connect 134 0 133 0; +#X connect 135 0 136 0; +#X connect 136 0 165 0; +#X connect 137 0 135 0; +#X connect 139 0 141 0; +#X connect 140 0 142 0; +#X connect 143 0 147 0; +#X connect 143 0 148 0; +#X connect 144 0 151 0; +#X connect 145 0 152 0; +#X connect 146 0 127 0; +#X connect 147 0 142 1; +#X connect 148 0 141 1; +#X connect 149 0 44 0; +#X connect 150 0 149 0; +#X connect 151 0 13 0; +#X connect 152 0 14 0; +#X connect 153 0 155 0; +#X connect 154 0 153 0; +#X connect 155 0 137 0; +#X connect 156 0 20 0; +#X connect 158 0 111 0; +#X connect 159 0 44 0; +#X connect 160 0 21 0; +#X connect 161 0 44 0; +#X connect 162 0 44 0; +#X connect 163 0 45 0; +#X connect 164 0 45 0; +#X connect 165 0 160 0; +#X connect 165 0 154 0; diff --git a/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/ssid.h_rename_me b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/ssid.h_rename_me new file mode 100644 index 0000000..9d3b03c --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_esp32_fullcontrol/ssid.h_rename_me @@ -0,0 +1,4 @@ + +#define MYSSID "yourssid" +#define MYPASS "yourpassword" + diff --git a/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_fullcontrol_screenshot.png b/firmware/lib/Arduino-FOC/examples/osc_control_examples/osc_fullcontrol_screenshot.png new file mode 100644 index 0000000000000000000000000000000000000000..214d2a81e5d105692bd0400d1aacd1498525f839 GIT binary patch literal 261643 zcma%i1z42b);8UeA|Tx&4bmMFlF}U_-7z!+(%sz>iqhSkf`oL=(A_n_5dXaAjdQ*e z|2fRX^~Bz5uN|xQUiTBBsx12q<0S?h9NaT`IcYUGIOGdBI3#W~6xf?Vl!iq(IE)o* zDJfNXDJd#d7e@Mj>sE7JwA0tV#Kj;A;8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{0&%(Ww|s%5yOP+(q>Nf2!YeGeHZLPpbB8=Xk0}*x&V@|9YX2;U1hR z@z&{DtG<`@op|R3K`>YpI zf3Md6dhB{swtE_>3fXTp?3Q4{GoSwFWc>z~H~#16FU#;nmqLuvXKS&#|H<6{exQHv zONa;2c42$GgueQiBQemWrz*ruJN)kq`oCTz^c}s}pzoo7cM#7JexjmA4eWmoE;izJ z*@(w^uwIMvk#(}u|5}hJ;1S`+YlAWlwWLb_V=O4_Q9`L_E`_5>6{Il#=iWhbwRZ>} z&d?k@U}9q8G!kX_UvG<^fjFB-Fpt4DR#g8 zW1rpEzn9MbHj>re7hAJ){_*R-YhH!?E~xwS_uj{q_sw5EtDX67>5sCHPwVFYteWpX zH%tDV{X6^p@{%g+B*I~inITvxt${JZZn*MI+c zW#zYr{~rJQTz!0b-TfuAzo+h+{^<76>A!2Ay{@$@T~)i||BnBE28os5SGqk~9bfnG qP-|F3L +#include + +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 10, 11, 8); +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); +MagneticSensorI2C sensor = MagneticSensorI2C(0x36, 12, 0X0C, 4); + + +/** + * This measures how closely sensor and electrical angle agree and how much your motor is affected by 'cogging'. + * It can be used to investigate how much non linearity there is between what we set (electrical angle) and what we read (sensor angle) + * This non linearity could be down to magnet placement, coil winding differences or simply that the magnetic field when travelling through a pole pair is not linear + * An alignment error of ~10 degrees and cogging of ~4 degrees is normal for small gimbal. + * The following article is an interesting read + * https://hackaday.com/2016/02/23/anti-cogging-algorithm-brings-out-the-best-in-your-hobby-brushless-motors/ + */ +void testAlignmentAndCogging(int direction) { + + motor.move(0); + _delay(200); + + sensor.update(); + float initialAngle = sensor.getAngle(); + + const int shaft_rotation = 720; // 720 deg test - useful to see repeating cog pattern + int sample_count = int(shaft_rotation * motor.pole_pairs); // test every electrical degree + + float stDevSum = 0; + + float mean = 0.0f; + float prev_mean = 0.0f; + + + for (int i = 0; i < sample_count; i++) { + + float shaftAngle = (float) direction * i * shaft_rotation / sample_count; + float electricAngle = (float) shaftAngle * motor.pole_pairs; + // move and wait + motor.move(shaftAngle * PI / 180); + _delay(5); + + // measure + sensor.update(); + float sensorAngle = (sensor.getAngle() - initialAngle) * 180 / PI; + float sensorElectricAngle = sensorAngle * motor.pole_pairs; + float electricAngleError = electricAngle - sensorElectricAngle; + + // plot this - especially electricAngleError + Serial.print(electricAngle); + Serial.print("\t"); + Serial.print(sensorElectricAngle ); + Serial.print("\t"); + Serial.println(electricAngleError); + + // use knuth standard deviation algorithm so that we don't need an array too big for an Uno + prev_mean = mean; + mean = mean + (electricAngleError-mean)/(i+1); + stDevSum = stDevSum + (electricAngleError-mean)*(electricAngleError-prev_mean); + + } + + Serial.println(); + Serial.println(F("ALIGNMENT AND COGGING REPORT")); + Serial.println(); + Serial.print(F("Direction: ")); + Serial.println(direction); + Serial.print(F("Mean error (alignment): ")); + Serial.print(mean); + Serial.println(" deg (electrical)"); + Serial.print(F("Standard Deviation (cogging): ")); + Serial.print(sqrt(stDevSum/sample_count)); + Serial.println(F(" deg (electrical)")); + Serial.println(); + Serial.println(F("Plotting 3rd column of data (electricAngleError) will likely show sinusoidal cogging pattern with a frequency of 4xpole_pairs per rotation")); + Serial.println(); + +} + +void setup() { + + Serial.begin(115200); + while (!Serial) ; + + // driver config + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + + motor.voltage_sensor_align = 3; + motor.foc_modulation = FOCModulationType::SpaceVectorPWM; + + motor.controller = MotionControlType::angle_openloop; + motor.voltage_limit=motor.voltage_sensor_align; + + sensor.init(); + motor.linkSensor(&sensor); + + motor.useMonitoring(Serial); + motor.init(); + motor.initFOC(); + + testAlignmentAndCogging(1); + + motor.move(0); + Serial.println(F("Press any key to test in CCW direction")); + while (!Serial.available()) { } + + testAlignmentAndCogging(-1); + + Serial.println(F("Complete")); + + motor.voltage_limit = 0; + motor.move(0); + while (true) ; //do nothing; + +} + + + + +void loop() { + +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/encoder/find_kv_rating/find_kv_rating.ino b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/encoder/find_kv_rating/find_kv_rating.ino new file mode 100644 index 0000000..76fb46b --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/encoder/find_kv_rating/find_kv_rating.ino @@ -0,0 +1,102 @@ +/** + * + * Find KV rating for motor with encoder + * + * Motor KV rating is defiend as the increase of the motor velocity expressed in rotations per minute [rpm] per each 1 Volt int voltage control mode. + * + * This example will set your motor in the torque control mode using voltage and set 1 volt to the motor. By reading the velocity it will calculat the motors KV rating. + * - To make this esimation more credible you can try increasing the target voltage (or decrease in some cases) + * - The KV rating should be realatively static number - it should not change considerably with the increase in the voltage + * + */ +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// encoder instance +Encoder sensor = Encoder(2, 3, 8192); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} + + +// voltage set point variable +float target_voltage = 1; + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } +void calcKV(char* cmd) { + // calculate the KV + Serial.println(motor.shaft_velocity/motor.target*30.0f/_PI); + +} + +void setup() { + + // initialize encoder sensor hardware + sensor.init(); + sensor.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // IMPORTANT! + // make sure to set the correct power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + // aligning voltage + motor.voltage_sensor_align = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + command.add('K', calcKV, "calculate KV rating"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target voltage : - commnad T")); + Serial.println(F("Calculate the motor KV : - command K")); + _delay(1000); +} + + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/hall_sensor/find_kv_rating/find_kv_rating.ino b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/hall_sensor/find_kv_rating/find_kv_rating.ino new file mode 100644 index 0000000..3abef46 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/hall_sensor/find_kv_rating/find_kv_rating.ino @@ -0,0 +1,99 @@ +/** + * + * Find KV rating for motor with Hall sensors + * + * Motor KV rating is defiend as the increase of the motor velocity expressed in rotations per minute [rpm] per each 1 Volt int voltage control mode. + * + * This example will set your motor in the torque control mode using voltage and set 1 volt to the motor. By reading the velocity it will calculat the motors KV rating. + * - To make this esimation more credible you can try increasing the target voltage (or decrease in some cases) + * - The KV rating should be realatively static number - it should not change considerably with the increase in the voltage + */ +#include + + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); + +// hall sensor instance +HallSensor sensor = HallSensor(2, 3, 4, 11); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} + + +// voltage set point variable +float target_voltage = 1; + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } +void calcKV(char* cmd) { + // calculate the KV + Serial.println(motor.shaft_velocity/motor.target*30.0f/_PI); + +} + +void setup() { + + // initialize encoder sensor hardware + sensor.init(); + sensor.enableInterrupts(doA, doB, doC); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // IMPORTANT! + // make sure to set the correct power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + // aligning voltage + motor.voltage_sensor_align = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + command.add('K', calcKV, "calculate KV rating"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target voltage : - commnad T")); + Serial.println(F("Calculate the motor KV : - command K")); + _delay(1000); +} + + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/magnetic_sensor/find_kv_rating/find_kv_rating.ino b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/magnetic_sensor/find_kv_rating/find_kv_rating.ino new file mode 100644 index 0000000..f3dd74a --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_kv_rating/magnetic_sensor/find_kv_rating/find_kv_rating.ino @@ -0,0 +1,96 @@ +/** + * Find KV rating for motor with magnetic sensors + * + * Motor KV rating is defiend as the increase of the motor velocity expressed in rotations per minute [rpm] per each 1 Volt int voltage control mode. + * + * This example will set your motor in the torque control mode using voltage and set 1 volt to the motor. By reading the velocity it will calculat the motors KV rating. + * - To make this esimation more credible you can try increasing the target voltage (or decrease in some cases) + * - The KV rating should be realatively static number - it should not change considerably with the increase in the voltage + */ +#include + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, 10); +// magnetic sensor instance - I2C +// MagneticSensorI2C sensor = MagneticSensorI2C(AS5600_I2C); +// magnetic sensor instance - analog output +// MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// voltage set point variable +float target_voltage = 1; + +// instantiate the commander +Commander command = Commander(Serial); +void doTarget(char* cmd) { command.scalar(&target_voltage, cmd); } +void calcKV(char* cmd) { + // calculate the KV + Serial.println(motor.shaft_velocity/motor.target*30.0f/_PI); + +} + +void setup() { + + // initialize encoder sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // driver config + // IMPORTANT! + // make sure to set the correct power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link driver + motor.linkDriver(&driver); + + // aligning voltage + motor.voltage_sensor_align = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // add target command T + command.add('T', doTarget, "target voltage"); + command.add('K', calcKV, "calculate KV rating"); + + Serial.println(F("Motor ready.")); + Serial.println(F("Set the target voltage : - commnad T")); + Serial.println(F("Calculate the motor KV : - command K")); + _delay(1000); +} + + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/encoder/find_pole_pairs_number/find_pole_pairs_number.ino b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/encoder/find_pole_pairs_number/find_pole_pairs_number.ino new file mode 100644 index 0000000..aac879c --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/encoder/find_pole_pairs_number/find_pole_pairs_number.ino @@ -0,0 +1,173 @@ +/** + * Utility arduino sketch which finds pole pair number of the motor + * + * To run it just set the correct pin numbers for the BLDC driver and encoder A and B channel as well as the encoder PPR value. + * + * The program will rotate your motor a specific amount and check how much it moved, and by doing a simple calculation calculate your pole pair number. + * The pole pair number will be outputted to the serial terminal. + * + * If the pole pair number is well estimated your motor will start to spin in voltage mode with 2V target. + * + * If the code calculates negative pole pair number please invert your encoder A and B channel pins or motor connector. + * + * Try running this code several times to avoid statistical errors. + * > But in general if your motor spins, you have a good pole pairs number. + */ +#include + +// BLDC motor instance +// its important to put pole pairs number as 1!!! +BLDCMotor motor = BLDCMotor(1); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor instance +// its important to put pole pairs number as 1!!! +//StepperMotor motor = StepperMotor(1); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// Encoder(int encA, int encB , int cpr, int index) +Encoder encoder = Encoder(2, 3, 2048); +// interrupt routine intialisation +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +void setup() { + + // initialise encoder hardware + encoder.init(); + // hardware interrupt enable + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // power supply voltage + // default 12V + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + + + // initialize motor + motor.init(); + // monitoring port + Serial.begin(115200); + + // pole pairs calculation routine + Serial.println("Pole pairs (PP) estimator"); + Serial.println("-\n"); + + float pp_search_voltage = 4; // maximum power_supply_voltage/2 + float pp_search_angle = 6*_PI; // search electrical angle to turn + + // move motor to the electrical angle 0 + motor.controller = MotionControlType::angle_openloop; + motor.voltage_limit=pp_search_voltage; + motor.move(0); + _delay(1000); + // read the encoder angle + encoder.update(); + float angle_begin = encoder.getAngle(); + _delay(50); + + // move the motor slowly to the electrical angle pp_search_angle + float motor_angle = 0; + while(motor_angle <= pp_search_angle){ + motor_angle += 0.01f; + motor.move(motor_angle); + _delay(1); + } + _delay(1000); + // read the encoder value for 180 + encoder.update(); + float angle_end = encoder.getAngle(); + _delay(50); + // turn off the motor + motor.move(0); + _delay(1000); + + // calculate the pole pair number + int pp = round((pp_search_angle)/(angle_end-angle_begin)); + + Serial.print(F("Estimated PP : ")); + Serial.println(pp); + Serial.println(F("PP = Electrical angle / Encoder angle ")); + Serial.print(pp_search_angle*180/_PI); + Serial.print("/"); + Serial.print((angle_end-angle_begin)*180/_PI); + Serial.print(" = "); + Serial.println((pp_search_angle)/(angle_end-angle_begin)); + Serial.println(); + + + // a bit of monitoring the result + if(pp <= 0 ){ + Serial.println(F("PP number cannot be negative")); + Serial.println(F(" - Try changing the search_voltage value or motor/encoder configuration.")); + return; + }else if(pp > 30){ + Serial.println(F("PP number very high, possible error.")); + }else{ + Serial.println(F("If PP is estimated well your motor should turn now!")); + Serial.println(F(" - If it is not moving try to relaunch the program!")); + Serial.println(F(" - You can also try to adjust the target voltage using serial terminal!")); + } + + + // set FOC loop to be used + motor.controller = MotionControlType::torque; + // set the pole pair number to the motor + motor.pole_pairs = pp; + //align encoder and start FOC + motor.initFOC(); + _delay(1000); + + Serial.println(F("\n Motor ready.")); + Serial.println(F("Set the target voltage using serial terminal:")); +} + +// uq voltage +float target_voltage = 2; + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // communicate with the user + serialReceiveUserCommand(); +} + + +// utility function enabling serial communication with the user to set the target values +// this function can be implemented in serialEvent function as well +void serialReceiveUserCommand() { + + // a string to hold incoming data + static String received_chars; + + while (Serial.available()) { + // get the new byte: + char inChar = (char)Serial.read(); + // add it to the string buffer: + received_chars += inChar; + // end of user input + if (inChar == '\n') { + + // change the motor target + target_voltage = received_chars.toFloat(); + Serial.print("Target voltage: "); + Serial.println(target_voltage); + + // reset the command buffer + received_chars = ""; + } + } +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/magnetic_sensor/find_pole_pairs_number/find_pole_pairs_number.ino b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/magnetic_sensor/find_pole_pairs_number/find_pole_pairs_number.ino new file mode 100644 index 0000000..e98a452 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_pole_pair_number/magnetic_sensor/find_pole_pairs_number/find_pole_pairs_number.ino @@ -0,0 +1,173 @@ +/** + * Utility arduino sketch which finds pole pair number of the motor + * + * To run it just set the correct pin numbers for the BLDC driver and sensor CPR value and chip select pin. + * + * The program will rotate your motor a specific amount and check how much it moved, and by doing a simple calculation calculate your pole pair number. + * The pole pair number will be outputted to the serial terminal. + * + * If the pole pair number is well estimated your motor will start to spin in voltage mode with 2V target. + * + * If the code calculates negative pole pair number please invert your motor connector. + * + * Try running this code several times to avoid statistical errors. + * > But in general if your motor spins, you have a good pole pairs number. + */ +#include + +// BLDC motor instance +// its important to put pole pairs number as 1!!! +BLDCMotor motor = BLDCMotor(1); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor instance +// its important to put pole pairs number as 1!!! +//StepperMotor motor = StepperMotor(1); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(10, 14, 0x3FFF); +// magnetic sensor instance - I2C +//MagneticSensorI2C sensor = MagneticSensorI2C(0x36, 12, 0X0C, 4); +// magnetic sensor instance - analog output +// MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +void setup() { + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // power supply voltage + // default 12V + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + + // initialize motor hardware + motor.init(); + + // monitoring port + Serial.begin(115200); + + // pole pairs calculation routine + Serial.println("Pole pairs (PP) estimator"); + Serial.println("-\n"); + + float pp_search_voltage = 4; // maximum power_supply_voltage/2 + float pp_search_angle = 6*_PI; // search electrical angle to turn + + // move motor to the electrical angle 0 + motor.controller = MotionControlType::angle_openloop; + motor.voltage_limit=pp_search_voltage; + motor.move(0); + _delay(1000); + // read the sensor angle + sensor.update(); + float angle_begin = sensor.getAngle(); + _delay(50); + + // move the motor slowly to the electrical angle pp_search_angle + float motor_angle = 0; + while(motor_angle <= pp_search_angle){ + motor_angle += 0.01f; + sensor.update(); // keep track of the overflow + motor.move(motor_angle); + _delay(1); + } + _delay(1000); + // read the sensor value for 180 + sensor.update(); + float angle_end = sensor.getAngle(); + _delay(50); + // turn off the motor + motor.move(0); + _delay(1000); + + // calculate the pole pair number + int pp = round((pp_search_angle)/(angle_end-angle_begin)); + + Serial.print(F("Estimated PP : ")); + Serial.println(pp); + Serial.println(F("PP = Electrical angle / Encoder angle ")); + Serial.print(pp_search_angle*180/_PI); + Serial.print(F("/")); + Serial.print((angle_end-angle_begin)*180/_PI); + Serial.print(F(" = ")); + Serial.println((pp_search_angle)/(angle_end-angle_begin)); + Serial.println(); + + + // a bit of monitoring the result + if(pp <= 0 ){ + Serial.println(F("PP number cannot be negative")); + Serial.println(F(" - Try changing the search_voltage value or motor/sensor configuration.")); + return; + }else if(pp > 30){ + Serial.println(F("PP number very high, possible error.")); + }else{ + Serial.println(F("If PP is estimated well your motor should turn now!")); + Serial.println(F(" - If it is not moving try to relaunch the program!")); + Serial.println(F(" - You can also try to adjust the target voltage using serial terminal!")); + } + + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + // set the pole pair number to the motor + motor.pole_pairs = pp; + //align sensor and start FOC + motor.initFOC(); + _delay(1000); + + Serial.println(F("\n Motor ready.")); + Serial.println(F("Set the target voltage using serial terminal:")); +} + +// uq voltage +float target_voltage = 2; + +void loop() { + + // main FOC algorithm function + // the faster you run this function the better + // Arduino UNO loop ~1kHz + // Bluepill loop ~10kHz + motor.loopFOC(); + + // Motion control function + // velocity, position or voltage (defined in motor.controller) + // this function can be run at much lower frequency than loopFOC() function + // You can also use motor.move() and set the motor.target in the code + motor.move(target_voltage); + + // communicate with the user + serialReceiveUserCommand(); +} + + +// utility function enabling serial communication with the user to set the target values +// this function can be implemented in serialEvent function as well +void serialReceiveUserCommand() { + + // a string to hold incoming data + static String received_chars; + + while (Serial.available()) { + // get the new byte: + char inChar = (char)Serial.read(); + // add it to the string buffer: + received_chars += inChar; + // end of user input + if (inChar == '\n') { + + // change the motor target + target_voltage = received_chars.toFloat(); + Serial.print("Target voltage: "); + Serial.println(target_voltage); + + // reset the command buffer + received_chars = ""; + } + } +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/calibration/find_sensor_offset_and_direction/find_sensor_offset_and_direction.ino b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_sensor_offset_and_direction/find_sensor_offset_and_direction.ino new file mode 100644 index 0000000..27163df --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/calibration/find_sensor_offset_and_direction/find_sensor_offset_and_direction.ino @@ -0,0 +1,84 @@ +/** + * Simple example intended to help users find the zero offset and natural direction of the sensor. + * + * These values can further be used to avoid motor and sensor alignment procedure. + * To use these values add them to the code:"); + * motor.sensor_direction=Direction::CW; // or Direction::CCW + * motor.zero_electric_angle=1.2345; // use the real value! + * + * This will only work for abosolute value sensors - magnetic sensors. + * Bypassing the alignment procedure is not possible for the encoders and for the current implementation of the Hall sensors. + * library version 1.4.2. + * + */ +#include + +// magnetic sensor instance - SPI +//MagneticSensorSPI sensor = MagneticSensorSPI(10, 14, 0x3FFF); +// magnetic sensor instance - I2C +//MagneticSensorI2C sensor = MagneticSensorI2C(0x36, 12, 0X0C, 4); +// magnetic sensor instance - analog output +MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +// BLDC motor instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); +// Stepper motor instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +void setup() { + + // power supply voltage + driver.voltage_power_supply = 12; + driver.init(); + motor.linkDriver(&driver); + + // initialise magnetic sensor hardware + sensor.init(); + // link the motor to the sensor + motor.linkSensor(&sensor); + + // aligning voltage + motor.voltage_sensor_align = 7; + + // set motion control loop to be used + motor.controller = MotionControlType::torque; + + // force direction search - because default is CW + motor.sensor_direction = Direction::UNKNOWN; + + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + + Serial.begin(115200); + Serial.println("Sensor zero offset is:"); + Serial.println(motor.zero_electric_angle, 4); + Serial.println("Sensor natural direction is: "); + Serial.println(motor.sensor_direction == Direction::CW ? "Direction::CW" : "Direction::CCW"); + + Serial.println("To use these values add them to the code:"); + Serial.print(" motor.sensor_direction="); + Serial.print(motor.sensor_direction == Direction::CW ? "Direction::CW" : "Direction::CCW"); + Serial.println(";"); + Serial.print(" motor.zero_electric_angle="); + Serial.print(motor.zero_electric_angle, 4); + Serial.println(";"); + + _delay(1000); + Serial.println("If motor is not moving the alignment procedure was not successfull!!"); +} + + +void loop() { + + // main FOC algorithm function + motor.loopFOC(); + + // Motion control function + motor.move(2); +} + diff --git a/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_extend_example/commander_extend_example.ino b/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_extend_example/commander_extend_example.ino new file mode 100644 index 0000000..60bbcf1 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_extend_example/commander_extend_example.ino @@ -0,0 +1,53 @@ +/** + * Simple example of custom commands that have nothing to do with the simple foc library + */ + +#include + +// instantiate the commander +Commander command = Commander(Serial); + +// led control function +void doLed(char* cmd){ + if(atoi(cmd)) digitalWrite(LED_BUILTIN, HIGH); + else digitalWrite(LED_BUILTIN, LOW); +}; +// get analog input +void doAnalog(char* cmd){ + if (cmd[0] == '0') Serial.println(analogRead(A0)); + else if (cmd[0] == '1') Serial.println(analogRead(A1)); + else if (cmd[0] == '2') Serial.println(analogRead(A2)); + else if (cmd[0] == '3') Serial.println(analogRead(A3)); + else if (cmd[0] == '4') Serial.println(analogRead(A4)); +}; + +void setup() { + // define pins + pinMode(LED_BUILTIN, OUTPUT); + pinMode(A0, INPUT); + pinMode(A1, INPUT); + pinMode(A2, INPUT); + pinMode(A3, INPUT); + pinMode(A4, INPUT); + + // Serial port to be used + Serial.begin(115200); + + // add new commands + command.add('L', doLed, "led on/off"); + command.add('A', doAnalog, "analog read A0-A4"); + + Serial.println(F("Commander listening")); + Serial.println(F(" - Send ? to see the node list...")); + Serial.println(F(" - Send L0 to turn the led off and L1 to turn it off")); + Serial.println(F(" - Send A0-A4 to read the analog pins")); + _delay(1000); +} + + +void loop() { + + // user communication + command.run(); + _delay(10); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_no_serial/commander_no_serial.ino b/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_no_serial/commander_no_serial.ino new file mode 100644 index 0000000..1381515 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_no_serial/commander_no_serial.ino @@ -0,0 +1,51 @@ +/** + * Simple example of how to use the commander without serial - using just strings + */ + +#include + +// instantiate the commander +Commander command = Commander(); + +// led control function +void doLed(char* cmd){ + if(atoi(cmd)) digitalWrite(LED_BUILTIN, HIGH); + else digitalWrite(LED_BUILTIN, LOW); +}; +// get analog input +void doAnalog(char* cmd){ + if (cmd[0] == '0') Serial.println(analogRead(A0)); + else if (cmd[0] == '1') Serial.println(analogRead(A1)); +}; + +void setup() { + // define pins + pinMode(LED_BUILTIN, OUTPUT); + pinMode(A0, INPUT); + pinMode(A1, INPUT); + + // Serial port to be used + Serial.begin(115200); + + // add new commands + command.add('L', doLed, "led control"); + command.add('A', doAnalog, "analog read A0-A1"); + + Serial.println(F("Commander running")); + _delay(1000); +} + + +void loop() { + // user communication + command.run("?"); + _delay(2000); + command.run("L0"); + _delay(1000); + command.run("A0"); + _delay(1000); + command.run("A1"); + _delay(1000); + command.run("L1"); + _delay(1000); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_tune_custom_loop/commander_tune_custom_loop.ino b/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_tune_custom_loop/commander_tune_custom_loop.ino new file mode 100644 index 0000000..cbeb6ec --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/communication_test/commander/commander_tune_custom_loop/commander_tune_custom_loop.ino @@ -0,0 +1,79 @@ +/** + * A simple example to show how to use the commander with the control loops outside of the scope of the SimpleFOC library +*/ +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(5, 10, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 500); +// channel A and B callbacks +void doA() { encoder.handleA(); } +void doB() { encoder.handleB(); } + +// target voltage to be set to the motor +float target_velocity = 0; + +// PID controllers and low pass filters +PIDController PIDv{0.05, 1, 0, 100000000, 12}; +LowPassFilter LPFv{0.01}; + +//add communication +Commander command = Commander(Serial); +void doController(char* cmd) { command.pid(&PIDv, cmd); } +void doFilter(char* cmd) { command.lpf(&LPFv, cmd); } +void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } + + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.init(); + // link driver + motor.linkDriver(&driver); + + // set motion control loop to be used ( doing nothing ) + motor.torque_controller = TorqueControlType::voltage; + motor.controller = MotionControlType::torque; + + // use monitoring with serial + Serial.begin(115200); + motor.useMonitoring(Serial); + // initialize motor + motor.init(); + // align sensor and start FOC + motor.initFOC(); + + // subscribe the new commands + command.add('C', doController, "tune velocity pid"); + command.add('F', doFilter, "tune velocity LPF"); + command.add('T', doTarget, "motor target"); + + _delay(1000); + Serial.println(F("Commander listening")); + Serial.println(F(" - Send ? to see the node list...")); +} + + + +void loop() { + // looping foc + motor.loopFOC(); + + // calculate voltage + float target_voltage = PIDv(target_velocity - LPFv(motor.shaft_velocity)); + // set the voltage + motor.move(target_voltage); + + // user communication + command.run(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_simple/step_dir_listener_simple.ino b/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_simple/step_dir_listener_simple.ino new file mode 100644 index 0000000..a0bebc3 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_simple/step_dir_listener_simple.ino @@ -0,0 +1,36 @@ +/** + * A simple example of reading step/dir communication + * - this example uses hadware interrupts +*/ + +#include + +// angle +float received_angle = 0; + +// StepDirListener( step_pin, dir_pin, counter_to_value) +StepDirListener step_dir = StepDirListener(2, 3, 360.0/200.0); // receive the angle in degrees +void onStep() { step_dir.handle(); } + +void setup() { + + Serial.begin(115200); + + // init step and dir pins + step_dir.init(); + // enable interrupts + step_dir.enableInterrupt(onStep); + // attach the variable to be updated on each step (optional) + // the same can be done asynchronously by caling step_dir.getValue(); + step_dir.attach(&received_angle); + + Serial.println(F("Step/Dir listenning.")); + _delay(1000); +} + +void loop() { + Serial.print(received_angle); + Serial.print("\t"); + Serial.println(step_dir.getValue()); + _delay(500); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_software_interrupt/step_dir_listener_software_interrupt.ino b/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_software_interrupt/step_dir_listener_software_interrupt.ino new file mode 100644 index 0000000..b6f0ea5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_listener_software_interrupt/step_dir_listener_software_interrupt.ino @@ -0,0 +1,44 @@ +/** + * A simple example of reading step/dir communication + * - this example uses software interrupts - this code is intended primarily + * for Arduino UNO/Mega and similar boards with very limited number of interrupt pins +*/ + +#include +// software interrupt library +#include +#include + + +// angle +float received_angle = 0; + +// StepDirListener( step_pin, dir_pin, counter_to_value) +StepDirListener step_dir = StepDirListener(4, 5, 2.0f*_PI/200.0); // receive the angle in radians +void onStep() { step_dir.handle(); } + +// If no available hadware interrupt pins use the software interrupt +PciListenerImp listenStep(step_dir.pin_step, onStep); + +void setup() { + + Serial.begin(115200); + + // init step and dir pins + step_dir.init(); + // enable software interrupts + PciManager.registerListener(&listenStep); + // attach the variable to be updated on each step (optional) + // the same can be done asynchronously by caling step_dir.getValue(); + step_dir.attach(&received_angle); + + Serial.println(F("Step/Dir listenning.")); + _delay(1000); +} + +void loop() { + Serial.print(received_angle); + Serial.print("\t"); + Serial.println(step_dir.getValue()); + _delay(500); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_motor_example/step_dir_motor_example.ino b/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_motor_example/step_dir_motor_example.ino new file mode 100644 index 0000000..f897857 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/communication_test/step_dir/step_dir_motor_example/step_dir_motor_example.ino @@ -0,0 +1,98 @@ +/** + * A position control example using step/dir interface to update the motor position + */ + +#include + +// BLDC motor & driver instance +BLDCMotor motor = BLDCMotor(11); +BLDCDriver3PWM driver = BLDCDriver3PWM(10, 5, 6, 8); + +// Stepper motor & driver instance +//StepperMotor motor = StepperMotor(50); +//StepperDriver4PWM driver = StepperDriver4PWM(9, 5, 10, 6, 8); + +// encoder instance +Encoder encoder = Encoder(2, 3, 500); +// channel A and B callbacks +void doA() { encoder.handleA(); } +void doB() { encoder.handleB(); } + +// StepDirListener( step_pin, dir_pin, counter_to_value) +StepDirListener step_dir = StepDirListener(A4, A5, 2.0f*_PI/200.0); +void onStep() { step_dir.handle(); } + +void setup() { + + // initialize encoder sensor hardware + encoder.init(); + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // driver config + // power supply voltage [V] + driver.voltage_power_supply = 12; + driver.init(); + // link the motor and the driver + motor.linkDriver(&driver); + + // aligning voltage [V] + motor.voltage_sensor_align = 3; + // index search velocity [rad/s] + motor.velocity_index_search = 3; + + // set motion control loop to be used + motor.controller = MotionControlType::angle; + + // contoller configuration + // default parameters in defaults.h + // velocity PI controller parameters + motor.PID_velocity.P = 0.2f; + motor.PID_velocity.I = 20; + motor.PID_velocity.D = 0; + // default voltage_power_supply + motor.voltage_limit = 12; + // jerk control using voltage voltage ramp + // default value is 300 volts per sec ~ 0.3V per millisecond + motor.PID_velocity.output_ramp = 1000; + + // velocity low pass filtering time constant + motor.LPF_velocity.Tf = 0.01f; + + // angle P controller + motor.P_angle.P = 10; + // maximal velocity of the position control + motor.velocity_limit = 100; + + // use monitoring with serial + Serial.begin(115200); + // comment out if not needed + motor.useMonitoring(Serial); + + // initialize motor + motor.init(); + // align encoder and start FOC + motor.initFOC(); + + // init step and dir pins + step_dir.init(); + // enable interrupts + step_dir.enableInterrupt(onStep); + // attach the variable to be updated on each step (optional) + // the same can be done asynchronously by caling motor.move(step_dir.getValue()); + step_dir.attach(&motor.target); + + Serial.println(F("Motor ready.")); + Serial.println(F("Listening to step/dir commands!")); + _delay(1000); +} + +void loop() { + + // main FOC algorithm function + motor.loopFOC(); + + // Motion control function + motor.move(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/current_sense_test/generic_current_sense/generic_current_sense.ino b/firmware/lib/Arduino-FOC/examples/utils/current_sense_test/generic_current_sense/generic_current_sense.ino new file mode 100644 index 0000000..e999de2 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/current_sense_test/generic_current_sense/generic_current_sense.ino @@ -0,0 +1,59 @@ +/** + * An example code for the generic current sensing implementation +*/ +#include + + +// user defined function for reading the phase currents +// returning the value per phase in amps +PhaseCurrent_s readCurrentSense(){ + PhaseCurrent_s c; + // dummy example only reading analog pins + c.a = analogRead(A0); + c.b = analogRead(A1); + c.c = analogRead(A2); // if no 3rd current sense set it to 0 + return(c); +} + +// user defined function for intialising the current sense +// it is optional and if provided it will be called in current_sense.init() +void initCurrentSense(){ + pinMode(A0,INPUT); + pinMode(A1,INPUT); + pinMode(A2,INPUT); +} + + +// GenericCurrentSense class constructor +// it receives the user defined callback for reading the current sense +// and optionally the user defined callback for current sense initialisation +GenericCurrentSense current_sense = GenericCurrentSense(readCurrentSense, initCurrentSense); + + +void setup() { + // if callbacks are not provided in the constructor + // they can be assigned directly: + //current_sense.readCallback = readCurrentSense; + //current_sense.initCallback = initCurrentSense; + + // initialise the current sensing + current_sense.init(); + + + Serial.begin(115200); + Serial.println("Current sense ready."); +} + +void loop() { + + PhaseCurrent_s currents = current_sense.getPhaseCurrents(); + float current_magnitude = current_sense.getDCCurrent(); + + Serial.print(currents.a); // milli Amps + Serial.print("\t"); + Serial.print(currents.b); // milli Amps + Serial.print("\t"); + Serial.print(currents.c); // milli Amps + Serial.print("\t"); + Serial.println(current_magnitude); // milli Amps +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/current_sense_test/inline_current_sense_test/inline_current_sense_test.ino b/firmware/lib/Arduino-FOC/examples/utils/current_sense_test/inline_current_sense_test/inline_current_sense_test.ino new file mode 100644 index 0000000..c1a5139 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/current_sense_test/inline_current_sense_test/inline_current_sense_test.ino @@ -0,0 +1,36 @@ +/** + * Testing example code for the Inline current sensing class +*/ +#include + +// current sensor +// shunt resistor value +// gain value +// pins phase A,B, (C optional) +InlineCurrentSense current_sense = InlineCurrentSense(0.01f, 50.0f, A0, A2); + + +void setup() { + // initialise the current sensing + current_sense.init(); + + // for SimpleFOCShield v2.01/v2.0.2 + current_sense.gain_b *= -1; + + Serial.begin(115200); + Serial.println("Current sense ready."); +} + +void loop() { + + PhaseCurrent_s currents = current_sense.getPhaseCurrents(); + float current_magnitude = current_sense.getDCCurrent(); + + Serial.print(currents.a*1000); // milli Amps + Serial.print("\t"); + Serial.print(currents.b*1000); // milli Amps + Serial.print("\t"); + Serial.print(currents.c*1000); // milli Amps + Serial.print("\t"); + Serial.println(current_magnitude*1000); // milli Amps +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_3pwm_standalone/bldc_driver_3pwm_standalone.ino b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_3pwm_standalone/bldc_driver_3pwm_standalone.ino new file mode 100644 index 0000000..1235fcc --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_3pwm_standalone/bldc_driver_3pwm_standalone.ino @@ -0,0 +1,34 @@ +// BLDC driver standalone example +#include + + +// BLDC driver instance +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 5, 6, 8); + +void setup() { + + // pwm frequency to be used [Hz] + // for atmega328 fixed to 32kHz + // esp32/stm32/teensy configurable + driver.pwm_frequency = 50000; + // power supply voltage [V] + driver.voltage_power_supply = 12; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 12; + + // driver init + driver.init(); + + // enable driver + driver.enable(); + + _delay(1000); +} + +void loop() { + // setting pwm + // phase A: 3V + // phase B: 6V + // phase C: 5V + driver.setPwm(3,6,5); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino new file mode 100644 index 0000000..478d397 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/bldc_driver_6pwm_standalone/bldc_driver_6pwm_standalone.ino @@ -0,0 +1,35 @@ +// BLDC driver standalone example +#include + +// BLDC driver instance +BLDCDriver6PWM driver = BLDCDriver6PWM(5, 6, 9,10, 3, 11, 8); + +void setup() { + + // pwm frequency to be used [Hz] + // for atmega328 fixed to 32kHz + // esp32/stm32/teensy configurable + driver.pwm_frequency = 50000; + // power supply voltage [V] + driver.voltage_power_supply = 12; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 12; + // daad_zone [0,1] - default 0.02f - 2% + driver.dead_zone = 0.05f; + + // driver init + driver.init(); + + // enable driver + driver.enable(); + + _delay(1000); +} + +void loop() { + // setting pwm + // phase A: 3V + // phase B: 6V + // phase C: 5V + driver.setPwm(3,6,5); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_2pwm_standalone/stepper_driver_2pwm_standalone.ino b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_2pwm_standalone/stepper_driver_2pwm_standalone.ino new file mode 100644 index 0000000..4627efa --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_2pwm_standalone/stepper_driver_2pwm_standalone.ino @@ -0,0 +1,39 @@ +// Stepper driver standalone example +#include + + +// Stepper driver instance +// StepperDriver2PWM(pwm1, in1, pwm2, in2, (en1, en2 optional)) +int in1[] = {4,5}; +int in2[] = {9,8}; +StepperDriver2PWM driver = StepperDriver2PWM(3, in1, 10 , in2, 11, 12); + +// StepperDriver2PWM(pwm1, dir1, pwm2, dir2,(en1, en2 optional)) +// StepperDriver2PWM driver = StepperDriver2PWM(3, 4, 5, 6, 11, 12); + +void setup() { + + // pwm frequency to be used [Hz] + // for atmega328 fixed to 32kHz + // esp32/stm32/teensy configurable + driver.pwm_frequency = 30000; + // power supply voltage [V] + driver.voltage_power_supply = 12; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 12; + + // driver init + driver.init(); + + // enable driver + driver.enable(); + + _delay(1000); +} + +void loop() { + // setting pwm + // phase A: 3V + // phase B: 6V + driver.setPwm(3,6); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_4pwm_standalone/stepper_driver_4pwm_standalone.ino b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_4pwm_standalone/stepper_driver_4pwm_standalone.ino new file mode 100644 index 0000000..e028a73 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_4pwm_standalone/stepper_driver_4pwm_standalone.ino @@ -0,0 +1,34 @@ +// Stepper driver standalone example +#include + + +// Stepper driver instance +// StepperDriver4PWM(ph1A, ph1B, ph2A, ph2B, (en1, en2 optional)) +StepperDriver4PWM driver = StepperDriver4PWM(5, 6, 9,10, 7, 8); + +void setup() { + + // pwm frequency to be used [Hz] + // for atmega328 fixed to 32kHz + // esp32/stm32/teensy configurable + driver.pwm_frequency = 30000; + // power supply voltage [V] + driver.voltage_power_supply = 12; + // Max DC voltage allowed - default voltage_power_supply + driver.voltage_limit = 12; + + // driver init + driver.init(); + + // enable driver + driver.enable(); + + _delay(1000); +} + +void loop() { + // setting pwm + // phase A: 3V + // phase B: 6V + driver.setPwm(3,6); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_example/encoder_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_example/encoder_example.ino new file mode 100644 index 0000000..f105f5b --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_example/encoder_example.ino @@ -0,0 +1,44 @@ +/** + * Encoder example code + * + * This is a code intended to test the encoder connections and to demonstrate the encoder setup. + * + */ + +#include + + +Encoder encoder = Encoder(2, 3, 8192); +// interrupt routine intialisation +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +void setup() { + // monitoring port + Serial.begin(115200); + + // enable/disable quadrature mode + encoder.quadrature = Quadrature::ON; + + // check if you need internal pullups + encoder.pullup = Pullup::USE_EXTERN; + + // initialise encoder hardware + encoder.init(); + // hardware interrupt enable + encoder.enableInterrupts(doA, doB); + + Serial.println("Encoder ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // not doing much for the encoder though + encoder.update(); + // display the angle and the angular velocity to the terminal + Serial.print(encoder.getAngle()); + Serial.print("\t"); + Serial.println(encoder.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_software_interrupts_example/encoder_software_interrupts_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_software_interrupts_example/encoder_software_interrupts_example.ino new file mode 100644 index 0000000..ebf2dd4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/encoder/encoder_software_interrupts_example/encoder_software_interrupts_example.ino @@ -0,0 +1,57 @@ +/** + * Encoder example code using only software interrupts + * + * This is a code intended to test the encoder connections and to + * demonstrate the encoder setup fully using software interrupts. + * - We use PciManager library: https://github.com/prampec/arduino-pcimanager + * + * This code will work on Arduino devices but not on STM32 devices + * + */ + +#include +// software interrupt library +#include +#include + +// encoder instance +Encoder encoder = Encoder(A0, A1, 2048); +// interrupt routine intialisation +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + +// encoder interrupt init +PciListenerImp listenerA(encoder.pinA, doA); +PciListenerImp listenerB(encoder.pinB, doB); + +void setup() { + // monitoring port + Serial.begin(115200); + + // enable/disable quadrature mode + encoder.quadrature = Quadrature::ON; + + // check if you need internal pullups + encoder.pullup = Pullup::USE_EXTERN; + + // initialise encoder hardware + encoder.init(); + + // interrupt initialization + PciManager.registerListener(&listenerA); + PciManager.registerListener(&listenerB); + + Serial.println("Encoder ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // not doing much for the encoder though + encoder.update(); + // display the angle and the angular velocity to the terminal + Serial.print(encoder.getAngle()); + Serial.print("\t"); + Serial.println(encoder.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/generic_sensor/generic_sensor.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/generic_sensor/generic_sensor.ino new file mode 100644 index 0000000..4a470e5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/generic_sensor/generic_sensor.ino @@ -0,0 +1,51 @@ +/** + * Generic sensor example code + * + * This is a code intended to demonstrate how to implement the generic sensor class + * + */ + +#include + +// sensor reading function example +// for the magnetic sensor with analog communication +// returning an angle in radians in between 0 and 2PI +float readSensor(){ + return analogRead(A0)*_2PI/1024.0; +} + +// sensor intialising function +void initSensor(){ + pinMode(A0,INPUT); +} + +// generic sensor class contructor +// - read sensor callback +// - init sensor callback (optional) +GenericSensor sensor = GenericSensor(readSensor, initSensor); + +void setup() { + // monitoring port + Serial.begin(115200); + + // if callbacks are not provided in the constructor + // they can be assigned directly: + //sensor.readCallback = readSensor; + //sensor.initCallback = initSensor; + + sensor.init(); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + sensor.update(); + + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_example/hall_sensor_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_example/hall_sensor_example.ino new file mode 100644 index 0000000..c4777ba --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_example/hall_sensor_example.ino @@ -0,0 +1,48 @@ +/** + * Hall sensor example code + * + * This is a code intended to test the hall sensors connections and to demonstrate the hall sensor setup. + * + */ + +#include + +// Hall sensor instance +// HallSensor(int hallA, int hallB , int cpr, int index) +// - hallA, hallB, hallC - HallSensor A, B and C pins +// - pp - pole pairs +HallSensor sensor = HallSensor(2, 3, 4, 14); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} + + +void setup() { + // monitoring port + Serial.begin(115200); + + // check if you need internal pullups + sensor.pullup = Pullup::USE_EXTERN; + + // initialise encoder hardware + sensor.init(); + // hardware interrupt enable + sensor.enableInterrupts(doA, doB, doC); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); + delay(100); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_software_interrupts_example/hall_sensor_software_interrupts_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_software_interrupts_example/hall_sensor_software_interrupts_example.ino new file mode 100644 index 0000000..238eb2c --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/hall_sensors/hall_sensor_software_interrupts_example/hall_sensor_software_interrupts_example.ino @@ -0,0 +1,59 @@ +/** + * Hall sensors example code using only software interrupts + * + * This is a code intended to test the hall sensor connections and to + * demonstrate the hall sensor setup fully using software interrupts. + * - We use PciManager library: https://github.com/prampec/arduino-pcimanager + * + * This code will work on Arduino devices but not on STM32 devices + */ + +#include +// software interrupt library +#include +#include + +// Hall sensor instance +// HallSensor(int hallA, int hallB , int cpr, int index) +// - hallA, hallB, hallC - HallSensor A, B and C pins +// - pp - pole pairs +HallSensor sensor = HallSensor(2, 3, 4, 11); + +// Interrupt routine intialisation +// channel A and B callbacks +void doA(){sensor.handleA();} +void doB(){sensor.handleB();} +void doC(){sensor.handleC();} +// If no available hadware interrupt pins use the software interrupt +PciListenerImp listenA(sensor.pinA, doA); +PciListenerImp listenB(sensor.pinB, doB); +PciListenerImp listenC(sensor.pinC, doC); + +void setup() { + // monitoring port + Serial.begin(115200); + + // check if you need internal pullups + sensor.pullup = Pullup::USE_EXTERN; + + // initialise encoder hardware + sensor.init(); + + // software interrupts + PciManager.registerListener(&listenA); + PciManager.registerListener(&listenB); + PciManager.registerListener(&listenC); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/linear_hall_sensors/find_raw_centers/find_raw_centers.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/linear_hall_sensors/find_raw_centers/find_raw_centers.ino new file mode 100644 index 0000000..5fda5f5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/linear_hall_sensors/find_raw_centers/find_raw_centers.ino @@ -0,0 +1,62 @@ +/** + * An example to find the center offsets for both ADC channels used in the LinearHall sensor constructor + * Spin your motor through at least one full revolution to average out all of the variations in magnet strength. + */ + +//Change these defines to match the analog input pins that your hall sensors are connected to +#define LINEAR_HALL_CHANNEL_A 39 +#define LINEAR_HALL_CHANNEL_B 33 + + +//program variables +int minA, maxA, minB, maxB, centerA, centerB; +unsigned long timestamp; + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + pinMode(LINEAR_HALL_CHANNEL_A, INPUT); + pinMode(LINEAR_HALL_CHANNEL_B, INPUT); + + minA = analogRead(LINEAR_HALL_CHANNEL_A); + maxA = minA; + centerA = (minA + maxA) / 2; + minB = analogRead(LINEAR_HALL_CHANNEL_B); + maxB = minB; + centerB = (minB + maxB) / 2; + + Serial.println("Sensor ready"); + delay(1000); + timestamp = millis(); +} + +void loop() { + //read sensors and update variables + int tempA = analogRead(LINEAR_HALL_CHANNEL_A); + if (tempA < minA) minA = tempA; + if (tempA > maxA) maxA = tempA; + centerA = (minA + maxA) / 2; + int tempB = analogRead(LINEAR_HALL_CHANNEL_B); + if (tempB < minB) minB = tempB; + if (tempB > maxB) maxB = tempB; + centerB = (minB + maxB) / 2; + + if (millis() > timestamp + 100) { + timestamp = millis(); + // display the center counts, and max and min count + Serial.print("A:"); + Serial.print(centerA); + Serial.print("\t, B:"); + Serial.print(centerB); + Serial.print("\t, min A:"); + Serial.print(minA); + Serial.print("\t, max A:"); + Serial.print(maxA); + Serial.print("\t, min B:"); + Serial.print(minB); + Serial.print("\t, max B:"); + Serial.println(maxB); + } +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/find_raw_min_max/find_raw_min_max.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/find_raw_min_max/find_raw_min_max.ino new file mode 100644 index 0000000..34e68a1 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/find_raw_min_max/find_raw_min_max.ino @@ -0,0 +1,56 @@ +#include + +/** + * An example to find out the raw max and min count to be provided to the constructor + * Spin your motor/sensor/magnet to see what is the maximum output of the sensor and what is the minimum value + * And replace values 14 and 1020 with new values. Once when you replace them make sure there is no jump in the angle reading sensor.getAngle(). + * If there is a jump that means you can still find better values. + */ + +/** + * Magnetic sensor reading analog voltage on pin A1. This voltage is proportional to rotation position. + * Tested on AS5600 magnetic sensor running in 'analog mode'. Note AS5600 works better in 'i2C mode' (less noise) but only supports one sensor per i2c bus. + * + * MagneticSensorAnalog(uint8_t _pinAnalog, int _min, int _max) + * - pinAnalog - the pin that is reading the pwm from magnetic sensor + * - min_raw_count - the smallest expected reading. Whilst you might expect it to be 0 it is often ~15. Getting this wrong results in a small click once per revolution + * - max_raw_count - the largest value read. whilst you might expect it to be 2^10 = 1023 it is often ~ 1020. Note ESP32 will be closer to 4096 with its 12bit ADC + */ +MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + sensor.init(); + + Serial.println("Sensor ready"); + _delay(1000); +} + +int max_count = 0; +int min_count = 100000; + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + + // keep track of min and max + if(sensor.raw_count > max_count) max_count = sensor.raw_count; + else if(sensor.raw_count < min_count) min_count = sensor.raw_count; + + // display the raw count, and max and min raw count + Serial.print("angle:"); + Serial.print(sensor.getAngle()); + Serial.print("\t, raw:"); + Serial.print(sensor.raw_count); + Serial.print("\t, min:"); + Serial.print(min_count); + Serial.print("\t, max:"); + Serial.println(max_count); + delay(100); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/magnetic_sensor_analog_example/magnetic_sensor_analog_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/magnetic_sensor_analog_example/magnetic_sensor_analog_example.ino new file mode 100644 index 0000000..2496151 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_analog/magnetic_sensor_analog_example/magnetic_sensor_analog_example.ino @@ -0,0 +1,37 @@ +#include + + + +/** + * Magnetic sensor reading analog voltage on pin A1. This voltage is proportional to rotation position. + * Tested on AS5600 magnetic sensor running in 'analog mode'. Note AS5600 works better in 'i2C mode' (less noise) but only supports one sensor per i2c bus. + * + * MagneticSensorAnalog(uint8_t _pinAnalog, int _min, int _max) + * - pinAnalog - the pin that is reading the pwm from magnetic sensor + * - min_raw_count - the smallest expected reading. Whilst you might expect it to be 0 it is often ~15. Getting this wrong results in a small click once per revolution + * - max_raw_count - the largest value read. whilst you might expect it to be 2^10 = 1023 it is often ~ 1020. Note ESP32 will be closer to 4096 with its 12bit ADC + */ +MagneticSensorAnalog sensor = MagneticSensorAnalog(A1, 14, 1020); + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + sensor.init(); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/esp32_i2c_dual_bus_example/esp32_i2c_dual_bus_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/esp32_i2c_dual_bus_example/esp32_i2c_dual_bus_example.ino new file mode 100644 index 0000000..0516ede --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/esp32_i2c_dual_bus_example/esp32_i2c_dual_bus_example.ino @@ -0,0 +1,40 @@ +#include + +/** Annoyingly some i2c sensors (e.g. AS5600) have a fixed chip address. This means only one of these devices can be addressed on a single bus + * This example shows how a second i2c bus can be used to communicate with a second sensor. + */ + +MagneticSensorI2C sensor0 = MagneticSensorI2C(AS5600_I2C); +MagneticSensorI2C sensor1 = MagneticSensorI2C(AS5600_I2C); + + +void setup() { + + Serial.begin(115200); + _delay(750); + + Wire.setClock(400000); + Wire1.setClock(400000); + + // Normally SimpleFOC will call begin for i2c but with esp32 begin() is the only way to set pins! + // It seems safe to call begin multiple times + Wire1.begin(19, 23, (uint32_t)400000); + + sensor0.init(); + sensor1.init(&Wire1); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor0.update(); + sensor1.update(); + + _delay(200); + Serial.print(sensor0.getAngle()); + Serial.print(" - "); + Serial.print(sensor1.getAngle()); + Serial.println(); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/stm32_i2c_dual_bus_example/stm32_i2c_dual_bus_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/stm32_i2c_dual_bus_example/stm32_i2c_dual_bus_example.ino new file mode 100644 index 0000000..08fb145 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_dual_bus_examples/stm32_i2c_dual_bus_example/stm32_i2c_dual_bus_example.ino @@ -0,0 +1,39 @@ +#include + +/** Annoyingly some i2c sensors (e.g. AS5600) have a fixed chip address. This means only one of these devices can be addressed on a single bus + * This example shows how a second i2c bus can be used to communicate with a second sensor. + */ + +MagneticSensorI2C sensor0 = MagneticSensorI2C(AS5600_I2C); +MagneticSensorI2C sensor1 = MagneticSensorI2C(AS5600_I2C); + +// example of stm32 defining 2nd bus +TwoWire Wire1(PB11, PB10); + + +void setup() { + + Serial.begin(115200); + _delay(750); + + Wire.setClock(400000); + Wire1.setClock(400000); + + sensor0.init(); + sensor1.init(&Wire1); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor0.update(); + sensor1.update(); + + _delay(200); + Serial.print(sensor0.getAngle()); + Serial.print(" - "); + Serial.print(sensor1.getAngle()); + Serial.println(); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_example/magnetic_sensor_i2c_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_example/magnetic_sensor_i2c_example.ino new file mode 100644 index 0000000..4e060c0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_i2c/magnetic_sensor_i2c_example/magnetic_sensor_i2c_example.ino @@ -0,0 +1,43 @@ +#include + +// MagneticSensorI2C(uint8_t _chip_address, float _cpr, uint8_t _angle_register_msb) +// chip_address I2C chip address +// bit_resolution resolution of the sensor +// angle_register_msb angle read register msb +// bits_used_msb number of used bits in msb register +// +// make sure to read the chip address and the chip angle register msb value from the datasheet +// also in most cases you will need external pull-ups on SDA and SCL lines!!!!! +// +// For AS5058B +// MagneticSensorI2C sensor = MagneticSensorI2C(0x40, 14, 0xFE, 8); + +// Example of AS5600 configuration +MagneticSensorI2C sensor = MagneticSensorI2C(AS5600_I2C); + + +void setup() { + // monitoring port + Serial.begin(115200); + + // configure i2C + Wire.setClock(400000); + // initialise magnetic sensor hardware + sensor.init(); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/find_raw_min_max/find_raw_min_max.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/find_raw_min_max/find_raw_min_max.ino new file mode 100644 index 0000000..ac9bf04 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/find_raw_min_max/find_raw_min_max.ino @@ -0,0 +1,49 @@ +#include + + +/** + * An example to find out the raw max and min count to be provided to the constructor + * SPin your motor/sensor/magnet to see what is the maximum output of the sensor and what is the minimum value + * And replace values 4 and 904 with new values. Once when you replace them make sure there is no jump in the angle reading sensor.getAngle(). + * If there is a jump that means you can still find better values. + */ +MagneticSensorPWM sensor = MagneticSensorPWM(2, 4, 904); +void doPWM(){sensor.handlePWM();} + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + sensor.init(); + // comment out to use sensor in blocking (non-interrupt) way + sensor.enableInterrupt(doPWM); + + Serial.println("Sensor ready"); + _delay(1000); +} + +int max_pulse= 0; +int min_pulse = 10000; + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + + // keep track of min and max + if(sensor.pulse_length_us > max_pulse) max_pulse = sensor.pulse_length_us; + else if(sensor.pulse_length_us < min_pulse) min_pulse = sensor.pulse_length_us; + + // display the raw count, and max and min raw count + Serial.print("angle:"); + Serial.print(sensor.getAngle()); + Serial.print("\t, raw:"); + Serial.print(sensor.pulse_length_us); + Serial.print("\t, min:"); + Serial.print(min_pulse); + Serial.print("\t, max:"); + Serial.println(max_pulse); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_example/magnetic_sensor_pwm_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_example/magnetic_sensor_pwm_example.ino new file mode 100644 index 0000000..6ae0a3e --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_example/magnetic_sensor_pwm_example.ino @@ -0,0 +1,38 @@ +#include + + +/** + * Magnetic sensor reading pwm signal on pin 2. The pwm duty cycle is proportional to the sensor angle. + * + * MagneticSensorPWM(uint8_t MagneticSensorPWM, int _min, int _max) + * - pinPWM - the pin that is reading the pwm from magnetic sensor + * - min_raw_count - the smallest expected reading. Whilst you might expect it to be 0 it is often ~5. Getting this wrong results in a small click once per revolution + * - max_raw_count - the largest value read. whilst you might expect it to be 1kHz = 1000 it is often ~910. depending on the exact frequency and saturation + */ +MagneticSensorPWM sensor = MagneticSensorPWM(2, 4, 904); +void doPWM(){sensor.handlePWM();} + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + sensor.init(); + // comment out to use sensor in blocking (non-interrupt) way + sensor.enableInterrupt(doPWM); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_software_interrupt/magnetic_sensor_pwm_software_interrupt.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_software_interrupt/magnetic_sensor_pwm_software_interrupt.ino new file mode 100644 index 0000000..10dc8a6 --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_pwm/magnetic_sensor_pwm_software_interrupt/magnetic_sensor_pwm_software_interrupt.ino @@ -0,0 +1,44 @@ +#include + +// software interrupt library +#include +#include + +/** + * Magnetic sensor reading analog voltage on pin which does not have hardware interrupt support. Such as A0. + * + * MagneticSensorPWM(uint8_t MagneticSensorPWM, int _min, int _max) + * - pinPWM - the pin that is reading the pwm from magnetic sensor + * - min_raw_count - the smallest expected reading. Whilst you might expect it to be 0 it is often ~5. Getting this wrong results in a small click once per revolution + * - max_raw_count - the largest value read. whilst you might expect it to be 1kHz = 1000 it is often ~910. depending on the exact frequency and saturation + */ +MagneticSensorPWM sensor = MagneticSensorPWM(A0, 4, 904); +void doPWM(){sensor.handlePWM();} + +// encoder interrupt init +PciListenerImp listenerPWM(sensor.pinPWM, doPWM); + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + sensor.init(); + // comment out to use sensor in blocking (non-interrupt) way + PciManager.registerListener(&listenerPWM); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/esp32_spi_alt_example/esp32_spi_alt_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/esp32_spi_alt_example/esp32_spi_alt_example.ino new file mode 100644 index 0000000..cbb72af --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/esp32_spi_alt_example/esp32_spi_alt_example.ino @@ -0,0 +1,41 @@ +#include + +// alternative pinout +#define HSPI_MISO 12 +#define HSPI_MOSI 13 +#define HSPI_SCLK 14 +#define HSPI_SS 15 + +// MagneticSensorSPI(int cs, float _cpr, int _angle_register) +// config - SPI config +// cs - SPI chip select pin +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, HSPI_SS); + +// for esp 32, it has 2 spi interfaces VSPI (default) and HPSI as the second one +// to enable it instatiate the object +SPIClass SPI_2(HSPI); + +void setup() { + // monitoring port + Serial.begin(115200); + + // start the newly defined spi communication + SPI_2.begin(HSPI_SCLK, HSPI_MISO, HSPI_MOSI, HSPI_SS); //SCLK, MISO, MOSI, SS + // initialise magnetic sensor hardware + sensor.init(&SPI_2); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/stm32_spi_alt_example/stm32_spi_alt_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/stm32_spi_alt_example/stm32_spi_alt_example.ino new file mode 100644 index 0000000..713a19b --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_alternative_examples/stm32_spi_alt_example/stm32_spi_alt_example.ino @@ -0,0 +1,32 @@ +#include + +// MagneticSensorSPI(int cs, float _cpr, int _angle_register) +// config - SPI config +// cs - SPI chip select pin +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, PA15); + +// these are valid pins (mosi, miso, sclk) for 2nd SPI bus on storm32 board (stm32f107rc) +SPIClass SPI_2(PB15, PB14, PB13); + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + sensor.init(&SPI_2); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_example/magnetic_sensor_spi_example.ino b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_example/magnetic_sensor_spi_example.ino new file mode 100644 index 0000000..048620a --- /dev/null +++ b/firmware/lib/Arduino-FOC/examples/utils/sensor_test/magnetic_sensors/magnetic_sensor_spi/magnetic_sensor_spi_example/magnetic_sensor_spi_example.ino @@ -0,0 +1,32 @@ +#include + +// MagneticSensorSPI(MagneticSensorSPIConfig_s config, int cs) +// config - SPI config +// cs - SPI chip select pin +// magnetic sensor instance - SPI +MagneticSensorSPI sensor = MagneticSensorSPI(AS5147_SPI, 10); +// alternative constructor (chipselsect, bit_resolution, angle_read_register, ) +// MagneticSensorSPI sensor = MagneticSensorSPI(10, 14, 0x3FFF); + +void setup() { + // monitoring port + Serial.begin(115200); + + // initialise magnetic sensor hardware + sensor.init(); + + Serial.println("Sensor ready"); + _delay(1000); +} + +void loop() { + // iterative function updating the sensor internal variables + // it is usually called in motor.loopFOC() + // this function reads the sensor hardware and + // has to be called before getAngle nad getVelocity + sensor.update(); + // display the angle and the angular velocity to the terminal + Serial.print(sensor.getAngle()); + Serial.print("\t"); + Serial.println(sensor.getVelocity()); +} diff --git a/firmware/lib/Arduino-FOC/keywords.txt b/firmware/lib/Arduino-FOC/keywords.txt new file mode 100644 index 0000000..1f200e5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/keywords.txt @@ -0,0 +1,251 @@ +ArduinoFOC KEYWORD1 +SimpleFOC KEYWORD1 +BLDCMotor KEYWORD1 +FOCMotor KEYWORD1 +StepperMotor KEYWORD1 +Encoder KEYWORD1 +HallSensors KEYWORD1 +MagneticSensorSPI KEYWORD1 +MagneticSensorI2C KEYWORD1 +MagneticSensorAnalog KEYWORD1 +MagneticSensorPWM KEYWORD1 +BLDCDriver3PWM KEYWORD1 +BLDCDriver6PWM KEYWORD1 +BLDCDriver KEYWORD1 +StepperDriver4PWM KEYWORD1 +StepperDriver2PWM KEYWORD1 +StepperDriver KEYWORD1 +PIDController KEYWORD1 +LowPassFilter KEYWORD1 +InlineCurrentSense KEYWORD1 +LowsideCurrentSense KEYWORD1 +CurrentSense KEYWORD1 +Commander KEYWORD1 +StepDirListener KEYWORD1 +GenericCurrentSense KEYWORD1 +GenericSensor KEYWORD1 +SimpleFOCDebug KEYWORD1 + +initFOC KEYWORD2 +loopFOC KEYWORD2 +disable KEYWORD2 + +_delay KEYWORD3 +_sqrt KEYWORD3 +_micros KEYWORD3 +_sin KEYWORD3 +_cos KEYWORD3 +_setPwmFrequency KEYWORD3 +_writeDutyCycle KEYWORD3 +_round KEYWORD3 +_sign KEYWORD3 +_constrain KEYWORD3 +monitor KEYWORD3 +command KEYWORD3 + +PID_velocity KEYWORD2 +PID_current_q KEYWORD2 +PID_current_d KEYWORD2 +LPF_velocity KEYWORD2 +LPF_current_q KEYWORD2 +LPF_current_d KEYWORD2 +P_angle KEYWORD2 +LPF_angle KEYWORD2 +lpf_a KEYWORD2 +lpf_b KEYWORD2 +lpf_c KEYWORD2 + +MotionControlType KEYWORD1 +TorqueControlType KEYWORD1 +FOCModulationType KEYWORD2 +Quadrature KEYWORD1 +Pullup KEYWORD1 +Direction KEYWORD1 +MagneticSensorI2CConfig_s KEYWORD1 +MagneticSensorSPIConfig_s KEYWORD1 +DQVoltage_s KEYWORD1 +DQCurrent_s KEYWORD1 +PhaseCurrent_s KEYWORD1 + +linkDriver KEYWORD2 +linkSensor KEYWORD2 +linkCurrentSense KEYWORD2 +handleA KEYWORD2 +handleB KEYWORD2 +handleIndex KEYWORD2 +handleC KEYWORD2 +enableInterrupts KEYWORD2 +ISR KEYWORD2 +getVelocity KEYWORD2 +setPhaseVoltage KEYWORD2 +getAngle KEYWORD2 +getMechanicalAngle KEYWORD2 +getSensorAngle KEYWORD2 +update KEYWORD2 +needsSearch KEYWORD2 +useMonitoring KEYWORD2 +angleOpenloop KEYWORD2 +velocityOpenloop KEYWORD2 +getPhaseCurrents KEYWORD2 +getFOCCurrents KEYWORD2 +getDCCurrent KEYWORD2 +setPwm KEYWORD2 +driverAlign KEYWORD2 +linkDriver KEYWORD2 +add KEYWORD2 +run KEYWORD2 +attach KEYWORD2 +enableInterrupt KEYWORD2 +getValue KEYWORD2 +handle KEYWORD2 +scalar KEYWORD2 +pid KEYWORD2 +lpf KEYWORD2 +motor KEYWORD2 +handlePWM KEYWORD2 +enableInterrupt KEYWORD2 +readCallback KEYWORD2 +initCallback KEYWORD2 + + + +current KEYWORD2 +current_measured KEYWORD2 +shaft_angle_sp KEYWORD2 +electrical_angle KEYWORD2 +shaft_velocity_sp KEYWORD2 +shaft_angle KEYWORD2 +shaft_velocity KEYWORD2 +torque_controller KEYWORD2 +controller KEYWORD2 +pullup KEYWORD2 +quadrature KEYWORD2 +foc_modulation KEYWORD2 +target KEYWORD2 +motion KEYWORD2 +pwm_frequency KEYWORD2 +dead_zone KEYWORD2 +gain_a KEYWORD2 +gain_b KEYWORD2 +gain_c KEYWORD2 +skip_align KEYWORD2 +sensor_direction KEYWORD2 +sensor_offset KEYWORD2 +zero_electric_angle KEYWORD2 +verbose KEYWORD2 +decimal_places KEYWORD2 +phase_resistance KEYWORD2 +phase_inductance KEYWORD2 +modulation_centered KEYWORD2 + + + +voltage KEYWORD2 +velocity KEYWORD2 +velocity_openloop KEYWORD2 +angle KEYWORD2 +angle_openloop KEYWORD2 +torque KEYWORD2 +dc_current KEYWORD2 +foc_current KEYWORD2 + + +ON KEYWORD2 +OFF KEYWORD2 +CW KEYWORD2 +CCW KEYWORD2 +UNKNOWN KEYWORD2 + +P KEYWORD2 +I KEYWORD2 +D KEYWORD2 +Tf KEYWORD2 +voltage_limit KEYWORD2 +current_limit KEYWORD2 +output_ramp KEYWORD2 +limit KEYWORD2 +velocity_limit KEYWORD2 +voltage_power_supply KEYWORD2 +voltage_sensor_align KEYWORD2 +velocity_index_search KEYWORD2 +monitor_downsample KEYWORD2 +monitor_start_char KEYWORD2 +monitor_end_char KEYWORD2 +monitor_separator KEYWORD2 +monitor_decimals KEYWORD2 +monitor_variables KEYWORD2 +motion_downsample KEYWORD2 + +pinA KEYWORD2 +pinB KEYWORD2 +pinC KEYWORD2 +index_pin KEYWORD2 + +USE_INTERN KEYWORD2 +USE_EXTERN KEYWORD2 +DISABLE KEYWORD2 +ENABLE KEYWORD2 +SpaceVectorPWM KEYWORD2 +SinePWM KEYWORD2 +Trapezoid_120 KEYWORD2 +Trapezoid_150 KEYWORD2 + +pwmA KEYWORD2 +pwmB KEYWORD2 +pwmC KEYWORD2 +pwm1A KEYWORD2 +pwm1B KEYWORD2 +pwm2A KEYWORD2 +pwm2B KEYWORD2 +Ualpha KEYWORD2 +Ubeta KEYWORD2 +Ua KEYWORD2 +Ub KEYWORD2 +Uc KEYWORD2 +enable_pin KEYWORD2 +enable_pin1 KEYWORD2 +enable_pin2 KEYWORD2 +pole_pairs KEYWORD2 +dc_a KEYWORD2 +dc_b KEYWORD2 +dc_c KEYWORD2 + +DEF_POWER_SUPPLY LITERAL1 +DEF_PID_VEL_P LITERAL1 +DEF_PID_VEL_I LITERAL1 +DEF_PID_VEL_D LITERAL1 +DEF_PID_VEL_RAMP LITERAL1 +DEF_P_ANGLE_P LITERAL1 +DEF_PID_VEL_LIMIT LITERAL1 +DEF_INDEX_SEARCH_TARGET_VELOCITY LITERAL1 +DEF_VOLTAGE_SENSOR_ALIGN LITERAL1 +DEF_VEL_FILTER_Tf LITERAL1 +DEF_CURRENT_LIM LITERAL1 +DEF_CURR_FILTER_Tf LITERAL1 +DEF_PID_CURR_LIMIT LITERAL1 +DEF_PID_CURR_RAMP LITERAL1 +DEF_PID_CURR_D LITERAL1 +DEF_PID_CURR_I LITERAL1 +DEF_PID_CURR_P LITERAL1 +_2_SQRT3 LITERAL1 +_1_SQRT3 LITERAL1 +_SQRT3_2 LITERAL1 +_SQRT2 LITERAL1 +_120_D2R LITERAL1 +_PI_2 LITERAL1 +_PI_6 LITERAL1 +_2PI LITERAL1 +_3PI_2 LITERAL1 +_PI_3 LITERAL1 +_SQRT3 LITERAL1 +_PI LITERAL1 +_HIGH_Z LITERAL1 +_NC LITERAL1 + +_MON_TARGET LITERAL1 +_MON_VOLT_Q LITERAL1 +_MON_VOLT_D LITERAL1 +_MON_CURR_Q LITERAL1 +_MON_CURR_D LITERAL1 +_MON_VEL LITERAL1 +_MON_ANGLE LITERAL1 \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/library.properties b/firmware/lib/Arduino-FOC/library.properties new file mode 100644 index 0000000..6904387 --- /dev/null +++ b/firmware/lib/Arduino-FOC/library.properties @@ -0,0 +1,10 @@ +name=Simple FOC +version=2.3.1 +author=Simplefoc +maintainer=Simplefoc +sentence=A library demistifying FOC for BLDC motors +paragraph=Simple library intended for hobby comunity to run the BLDC and Stepper motor using FOC algorithm. It is intended to support as many BLDC/Stepper motor+sensor+driver combinations as possible and in the same time maintain simplicity of usage. Library supports Arudino devices such as Arduino UNO, MEGA, NANO and similar, stm32 boards such as Nucleo and Bluepill, ESP32 and Teensy boards. +category=Device Control +url=https://docs.simplefoc.com +architectures=* +includes=SimpleFOC.h diff --git a/firmware/lib/Arduino-FOC/src/BLDCMotor.cpp b/firmware/lib/Arduino-FOC/src/BLDCMotor.cpp new file mode 100644 index 0000000..b72728b --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/BLDCMotor.cpp @@ -0,0 +1,736 @@ +#include "BLDCMotor.h" +#include "./communication/SimpleFOCDebug.h" + + +// see https://www.youtube.com/watch?v=InzXA7mWBWE Slide 5 +// each is 60 degrees with values for 3 phases of 1=positive -1=negative 0=high-z +int trap_120_map[6][3] = { + {_HIGH_IMPEDANCE,1,-1}, + {-1,1,_HIGH_IMPEDANCE}, + {-1,_HIGH_IMPEDANCE,1}, + {_HIGH_IMPEDANCE,-1,1}, + {1,-1,_HIGH_IMPEDANCE}, + {1,_HIGH_IMPEDANCE,-1} +}; + +// see https://www.youtube.com/watch?v=InzXA7mWBWE Slide 8 +// each is 30 degrees with values for 3 phases of 1=positive -1=negative 0=high-z +int trap_150_map[12][3] = { + {_HIGH_IMPEDANCE,1,-1}, + {-1,1,-1}, + {-1,1,_HIGH_IMPEDANCE}, + {-1,1,1}, + {-1,_HIGH_IMPEDANCE,1}, + {-1,-1,1}, + {_HIGH_IMPEDANCE,-1,1}, + {1,-1,1}, + {1,-1,_HIGH_IMPEDANCE}, + {1,-1,-1}, + {1,_HIGH_IMPEDANCE,-1}, + {1,1,-1} +}; + +// BLDCMotor( int pp , float R) +// - pp - pole pair number +// - R - motor phase resistance +// - KV - motor kv rating (rmp/v) +// - L - motor phase inductance +BLDCMotor::BLDCMotor(int pp, float _R, float _KV, float _inductance) +: FOCMotor() +{ + // save pole pairs number + pole_pairs = pp; + // save phase resistance number + phase_resistance = _R; + // save back emf constant KV = 1/KV + // 1/sqrt(2) - rms value + KV_rating = NOT_SET; + if (_isset(_KV)) + KV_rating = _KV*_SQRT2; + // save phase inductance + phase_inductance = _inductance; + + // torque control type is voltage by default + torque_controller = TorqueControlType::voltage; +} + + +/** + Link the driver which controls the motor +*/ +void BLDCMotor::linkDriver(BLDCDriver* _driver) { + driver = _driver; +} + +// init hardware pins +void BLDCMotor::init() { + if (!driver || !driver->initialized) { + motor_status = FOCMotorStatus::motor_init_failed; + SIMPLEFOC_DEBUG("MOT: Init not possible, driver not initialized"); + return; + } + motor_status = FOCMotorStatus::motor_initializing; + SIMPLEFOC_DEBUG("MOT: Init"); + + // sanity check for the voltage limit configuration + if(voltage_limit > driver->voltage_limit) voltage_limit = driver->voltage_limit; + // constrain voltage for sensor alignment + if(voltage_sensor_align > voltage_limit) voltage_sensor_align = voltage_limit; + + // update the controller limits + if(current_sense){ + // current control loop controls voltage + PID_current_q.limit = voltage_limit; + PID_current_d.limit = voltage_limit; + } + if(_isset(phase_resistance) || torque_controller != TorqueControlType::voltage){ + // velocity control loop controls current + PID_velocity.limit = current_limit; + }else{ + // velocity control loop controls the voltage + PID_velocity.limit = voltage_limit; + } + P_angle.limit = velocity_limit; + + // if using open loop control, set a CW as the default direction if not already set + if ((controller==MotionControlType::angle_openloop + ||controller==MotionControlType::velocity_openloop) + && (sensor_direction == Direction::UNKNOWN)) { + sensor_direction = Direction::CW; + } + + _delay(500); + // enable motor + SIMPLEFOC_DEBUG("MOT: Enable driver."); + enable(); + _delay(500); + motor_status = FOCMotorStatus::motor_uncalibrated; +} + + +// disable motor driver +void BLDCMotor::disable() +{ + // set zero to PWM + driver->setPwm(0, 0, 0); + // disable the driver + driver->disable(); + // motor status update + enabled = 0; +} +// enable motor driver +void BLDCMotor::enable() +{ + // enable the driver + driver->enable(); + // set zero to PWM + driver->setPwm(0, 0, 0); + // motor status update + enabled = 1; +} + +/** + FOC functions +*/ +// FOC initialization function +int BLDCMotor::initFOC() { + int exit_flag = 1; + + motor_status = FOCMotorStatus::motor_calibrating; + + // align motor if necessary + // alignment necessary for encoders! + // sensor and motor alignment - can be skipped + // by setting motor.sensor_direction and motor.zero_electric_angle + _delay(500); + if(sensor){ + exit_flag *= alignSensor(); + // added the shaft_angle update + sensor->update(); + shaft_angle = shaftAngle(); + }else { + exit_flag = 0; // no FOC without sensor + SIMPLEFOC_DEBUG("MOT: No sensor."); + } + + // aligning the current sensor - can be skipped + // checks if driver phases are the same as current sense phases + // and checks the direction of measuremnt. + _delay(500); + if(exit_flag){ + if(current_sense){ + if (!current_sense->initialized) { + motor_status = FOCMotorStatus::motor_calib_failed; + SIMPLEFOC_DEBUG("MOT: Init FOC error, current sense not initialized"); + exit_flag = 0; + }else{ + exit_flag *= alignCurrentSense(); + } + } + else { SIMPLEFOC_DEBUG("MOT: No current sense."); } + } + + if(exit_flag){ + SIMPLEFOC_DEBUG("MOT: Ready."); + motor_status = FOCMotorStatus::motor_ready; + }else{ + SIMPLEFOC_DEBUG("MOT: Init FOC failed."); + motor_status = FOCMotorStatus::motor_calib_failed; + disable(); + } + + return exit_flag; +} + +// Calibarthe the motor and current sense phases +int BLDCMotor::alignCurrentSense() { + int exit_flag = 1; // success + + SIMPLEFOC_DEBUG("MOT: Align current sense."); + + // align current sense and the driver + exit_flag = current_sense->driverAlign(voltage_sensor_align); + if(!exit_flag){ + // error in current sense - phase either not measured or bad connection + SIMPLEFOC_DEBUG("MOT: Align error!"); + exit_flag = 0; + }else{ + // output the alignment status flag + SIMPLEFOC_DEBUG("MOT: Success: ", exit_flag); + } + + return exit_flag > 0; +} + +// Encoder alignment to electrical 0 angle +int BLDCMotor::alignSensor() { + int exit_flag = 1; //success + SIMPLEFOC_DEBUG("MOT: Align sensor."); + + // check if sensor needs zero search + if(sensor->needsSearch()) exit_flag = absoluteZeroSearch(); + // stop init if not found index + if(!exit_flag) return exit_flag; + + // if unknown natural direction + if(sensor_direction==Direction::UNKNOWN){ + + // find natural direction + // move one electrical revolution forward + for (int i = 0; i <=500; i++ ) { + float angle = _3PI_2 + _2PI * i / 500.0f; + setPhaseVoltage(voltage_sensor_align, 0, angle); + sensor->update(); + _delay(2); + } + // take and angle in the middle + sensor->update(); + float mid_angle = sensor->getAngle(); + // move one electrical revolution backwards + for (int i = 500; i >=0; i-- ) { + float angle = _3PI_2 + _2PI * i / 500.0f ; + setPhaseVoltage(voltage_sensor_align, 0, angle); + sensor->update(); + _delay(2); + } + sensor->update(); + float end_angle = sensor->getAngle(); + setPhaseVoltage(0, 0, 0); + _delay(200); + // determine the direction the sensor moved + float moved = fabs(mid_angle - end_angle); + if (moved 0.5f ) { // 0.5f is arbitrary number it can be lower or higher! + SIMPLEFOC_DEBUG("MOT: PP check: fail - estimated pp: ", _2PI/moved); + } else { + SIMPLEFOC_DEBUG("MOT: PP check: OK!"); + } + + } else { SIMPLEFOC_DEBUG("MOT: Skip dir calib."); } + + // zero electric angle not known + if(!_isset(zero_electric_angle)){ + // align the electrical phases of the motor and sensor + // set angle -90(270 = 3PI/2) degrees + setPhaseVoltage(voltage_sensor_align, 0, _3PI_2); + _delay(700); + // read the sensor + sensor->update(); + // get the current zero electric angle + zero_electric_angle = 0; + zero_electric_angle = electricalAngle(); + //zero_electric_angle = _normalizeAngle(_electricalAngle(sensor_direction*sensor->getAngle(), pole_pairs)); + _delay(20); + if(monitor_port){ + SIMPLEFOC_DEBUG("MOT: Zero elec. angle: ", zero_electric_angle); + } + // stop everything + setPhaseVoltage(0, 0, 0); + _delay(200); + } else { SIMPLEFOC_DEBUG("MOT: Skip offset calib."); } + return exit_flag; +} + +// Encoder alignment the absolute zero angle +// - to the index +int BLDCMotor::absoluteZeroSearch() { + // sensor precision: this is all ok, as the search happens near the 0-angle, where the precision + // of float is sufficient. + SIMPLEFOC_DEBUG("MOT: Index search..."); + // search the absolute zero with small velocity + float limit_vel = velocity_limit; + float limit_volt = voltage_limit; + velocity_limit = velocity_index_search; + voltage_limit = voltage_sensor_align; + shaft_angle = 0; + while(sensor->needsSearch() && shaft_angle < _2PI){ + angleOpenloop(1.5f*_2PI); + // call important for some sensors not to loose count + // not needed for the search + sensor->update(); + } + // disable motor + setPhaseVoltage(0, 0, 0); + // reinit the limits + velocity_limit = limit_vel; + voltage_limit = limit_volt; + // check if the zero found + if(monitor_port){ + if(sensor->needsSearch()) { SIMPLEFOC_DEBUG("MOT: Error: Not found!"); } + else { SIMPLEFOC_DEBUG("MOT: Success!"); } + } + return !sensor->needsSearch(); +} + +// Iterative function looping FOC algorithm, setting Uq on the Motor +// The faster it can be run the better +void BLDCMotor::loopFOC() { + // update sensor - do this even in open-loop mode, as user may be switching between modes and we could lose track + // of full rotations otherwise. + if (sensor) sensor->update(); + + // if open-loop do nothing + if( controller==MotionControlType::angle_openloop || controller==MotionControlType::velocity_openloop ) return; + + // if disabled do nothing + if(!enabled) return; + + // Needs the update() to be called first + // This function will not have numerical issues because it uses Sensor::getMechanicalAngle() + // which is in range 0-2PI + electrical_angle = electricalAngle(); + switch (torque_controller) { + case TorqueControlType::voltage: + // no need to do anything really + break; + case TorqueControlType::dc_current: + if(!current_sense) return; + // read overall current magnitude + current.q = current_sense->getDCCurrent(electrical_angle); + // filter the value values + current.q = LPF_current_q(current.q); + // calculate the phase voltage + voltage.q = PID_current_q(current_sp - current.q); + // d voltage - lag compensation + if(_isset(phase_inductance)) voltage.d = _constrain( -current_sp*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + else voltage.d = 0; + break; + case TorqueControlType::foc_current: + if(!current_sense) return; + // read dq currents + current = current_sense->getFOCCurrents(electrical_angle); + // filter values + current.q = LPF_current_q(current.q); + current.d = LPF_current_d(current.d); + // calculate the phase voltages + voltage.q = PID_current_q(current_sp - current.q); + voltage.d = PID_current_d(-current.d); + // d voltage - lag compensation - TODO verify + // if(_isset(phase_inductance)) voltage.d = _constrain( voltage.d - current_sp*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + break; + default: + // no torque control selected + SIMPLEFOC_DEBUG("MOT: no torque control selected!"); + break; + } + + // set the phase voltage - FOC heart function :) + setPhaseVoltage(voltage.q, voltage.d, electrical_angle); +} + +// Iterative function running outer loop of the FOC algorithm +// Behavior of this function is determined by the motor.controller variable +// It runs either angle, velocity or torque loop +// - needs to be called iteratively it is asynchronous function +// - if target is not set it uses motor.target value +void BLDCMotor::move(float new_target) { + + // downsampling (optional) + if(motion_cnt++ < motion_downsample) return; + motion_cnt = 0; + + // shaft angle/velocity need the update() to be called first + // get shaft angle + // TODO sensor precision: the shaft_angle actually stores the complete position, including full rotations, as a float + // For this reason it is NOT precise when the angles become large. + // Additionally, the way LPF works on angle is a precision issue, and the angle-LPF is a problem + // when switching to a 2-component representation. + if( controller!=MotionControlType::angle_openloop && controller!=MotionControlType::velocity_openloop ) + shaft_angle = shaftAngle(); // read value even if motor is disabled to keep the monitoring updated but not in openloop mode + // get angular velocity TODO the velocity reading probably also shouldn't happen in open loop modes? + shaft_velocity = shaftVelocity(); // read value even if motor is disabled to keep the monitoring updated + + // if disabled do nothing + if(!enabled) return; + // set internal target variable + if(_isset(new_target)) target = new_target; + + // calculate the back-emf voltage if KV_rating available U_bemf = vel*(1/KV) + if (_isset(KV_rating)) voltage_bemf = shaft_velocity/KV_rating/_RPM_TO_RADS; + // estimate the motor current if phase reistance available and current_sense not available + if(!current_sense && _isset(phase_resistance)) current.q = (voltage.q - voltage_bemf)/phase_resistance; + + // upgrade the current based voltage limit + switch (controller) { + case MotionControlType::torque: + if(torque_controller == TorqueControlType::voltage){ // if voltage torque control + if(!_isset(phase_resistance)) voltage.q = target; + else voltage.q = target*phase_resistance + voltage_bemf; + voltage.q = _constrain(voltage.q, -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if(!_isset(phase_inductance)) voltage.d = 0; + else voltage.d = _constrain( -target*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + }else{ + current_sp = target; // if current/foc_current torque control + } + break; + case MotionControlType::angle: + // TODO sensor precision: this calculation is not numerically precise. The target value cannot express precise positions when + // the angles are large. This results in not being able to command small changes at high position values. + // to solve this, the delta-angle has to be calculated in a numerically precise way. + // angle set point + shaft_angle_sp = target; + // calculate velocity set point + shaft_velocity_sp = feed_forward_velocity + P_angle( shaft_angle_sp - shaft_angle ); + shaft_angle_sp = _constrain(shaft_angle_sp,-velocity_limit, velocity_limit); + // calculate the torque command - sensor precision: this calculation is ok, but based on bad value from previous calculation + current_sp = PID_velocity(shaft_velocity_sp - shaft_velocity); // if voltage torque control + // if torque controlled through voltage + if(torque_controller == TorqueControlType::voltage){ + // use voltage if phase-resistance not provided + if(!_isset(phase_resistance)) voltage.q = current_sp; + else voltage.q = _constrain( current_sp*phase_resistance + voltage_bemf , -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if(!_isset(phase_inductance)) voltage.d = 0; + else voltage.d = _constrain( -current_sp*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + } + break; + case MotionControlType::velocity: + // velocity set point - sensor precision: this calculation is numerically precise. + shaft_velocity_sp = target; + // calculate the torque command + current_sp = PID_velocity(shaft_velocity_sp - shaft_velocity); // if current/foc_current torque control + // if torque controlled through voltage control + if(torque_controller == TorqueControlType::voltage){ + // use voltage if phase-resistance not provided + if(!_isset(phase_resistance)) voltage.q = current_sp; + else voltage.q = _constrain( current_sp*phase_resistance + voltage_bemf , -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if(!_isset(phase_inductance)) voltage.d = 0; + else voltage.d = _constrain( -current_sp*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + } + break; + case MotionControlType::velocity_openloop: + // velocity control in open loop - sensor precision: this calculation is numerically precise. + shaft_velocity_sp = target; + voltage.q = velocityOpenloop(shaft_velocity_sp); // returns the voltage that is set to the motor + voltage.d = 0; + break; + case MotionControlType::angle_openloop: + // angle control in open loop - + // TODO sensor precision: this calculation NOT numerically precise, and subject + // to the same problems in small set-point changes at high angles + // as the closed loop version. + shaft_angle_sp = target; + voltage.q = angleOpenloop(shaft_angle_sp); // returns the voltage that is set to the motor + voltage.d = 0; + break; + } +} + + +// Method using FOC to set Uq and Ud to the motor at the optimal angle +// Function implementing Space Vector PWM and Sine PWM algorithms +// +// Function using sine approximation +// regular sin + cos ~300us (no memory usage) +// approx _sin + _cos ~110us (400Byte ~ 20% of memory) +void BLDCMotor::setPhaseVoltage(float Uq, float Ud, float angle_el) { + + float center; + int sector; + float _ca,_sa; + + switch (foc_modulation) + { + case FOCModulationType::Trapezoid_120 : + // see https://www.youtube.com/watch?v=InzXA7mWBWE Slide 5 + // determine the sector + sector = 6 * (_normalizeAngle(angle_el + _PI_6 ) / _2PI); // adding PI/6 to align with other modes + // centering the voltages around either + // modulation_centered == true > driver.voltage_limit/2 + // modulation_centered == false > or Adaptable centering, all phases drawn to 0 when Uq=0 + center = modulation_centered ? (driver->voltage_limit)/2 : Uq; + + if(trap_120_map[sector][0] == _HIGH_IMPEDANCE){ + Ua= center; + Ub = trap_120_map[sector][1] * Uq + center; + Uc = trap_120_map[sector][2] * Uq + center; + driver->setPhaseState(PhaseState::PHASE_OFF, PhaseState::PHASE_ON, PhaseState::PHASE_ON); // disable phase if possible + }else if(trap_120_map[sector][1] == _HIGH_IMPEDANCE){ + Ua = trap_120_map[sector][0] * Uq + center; + Ub = center; + Uc = trap_120_map[sector][2] * Uq + center; + driver->setPhaseState(PhaseState::PHASE_ON, PhaseState::PHASE_OFF, PhaseState::PHASE_ON);// disable phase if possible + }else{ + Ua = trap_120_map[sector][0] * Uq + center; + Ub = trap_120_map[sector][1] * Uq + center; + Uc = center; + driver->setPhaseState(PhaseState::PHASE_ON, PhaseState::PHASE_ON, PhaseState::PHASE_OFF);// disable phase if possible + } + + break; + + case FOCModulationType::Trapezoid_150 : + // see https://www.youtube.com/watch?v=InzXA7mWBWE Slide 8 + // determine the sector + sector = 12 * (_normalizeAngle(angle_el + _PI_6 ) / _2PI); // adding PI/6 to align with other modes + // centering the voltages around either + // modulation_centered == true > driver.voltage_limit/2 + // modulation_centered == false > or Adaptable centering, all phases drawn to 0 when Uq=0 + center = modulation_centered ? (driver->voltage_limit)/2 : Uq; + + if(trap_150_map[sector][0] == _HIGH_IMPEDANCE){ + Ua= center; + Ub = trap_150_map[sector][1] * Uq + center; + Uc = trap_150_map[sector][2] * Uq + center; + driver->setPhaseState(PhaseState::PHASE_OFF, PhaseState::PHASE_ON, PhaseState::PHASE_ON); // disable phase if possible + }else if(trap_150_map[sector][1] == _HIGH_IMPEDANCE){ + Ua = trap_150_map[sector][0] * Uq + center; + Ub = center; + Uc = trap_150_map[sector][2] * Uq + center; + driver->setPhaseState(PhaseState::PHASE_ON, PhaseState::PHASE_OFF, PhaseState::PHASE_ON); // disable phase if possible + }else if(trap_150_map[sector][2] == _HIGH_IMPEDANCE){ + Ua = trap_150_map[sector][0] * Uq + center; + Ub = trap_150_map[sector][1] * Uq + center; + Uc = center; + driver->setPhaseState(PhaseState::PHASE_ON, PhaseState::PHASE_ON, PhaseState::PHASE_OFF); // disable phase if possible + }else{ + Ua = trap_150_map[sector][0] * Uq + center; + Ub = trap_150_map[sector][1] * Uq + center; + Uc = trap_150_map[sector][2] * Uq + center; + driver->setPhaseState(PhaseState::PHASE_ON, PhaseState::PHASE_ON, PhaseState::PHASE_ON); // enable all phases + } + + break; + + case FOCModulationType::SinePWM : + // Sinusoidal PWM modulation + // Inverse Park + Clarke transformation + _sincos(angle_el, &_sa, &_ca); + + // Inverse park transform + Ualpha = _ca * Ud - _sa * Uq; // -sin(angle) * Uq; + Ubeta = _sa * Ud + _ca * Uq; // cos(angle) * Uq; + + // center = modulation_centered ? (driver->voltage_limit)/2 : Uq; + center = driver->voltage_limit/2; + // Clarke transform + Ua = Ualpha + center; + Ub = -0.5f * Ualpha + _SQRT3_2 * Ubeta + center; + Uc = -0.5f * Ualpha - _SQRT3_2 * Ubeta + center; + + if (!modulation_centered) { + float Umin = min(Ua, min(Ub, Uc)); + Ua -= Umin; + Ub -= Umin; + Uc -= Umin; + } + + break; + + case FOCModulationType::SpaceVectorPWM : + // Nice video explaining the SpaceVectorModulation (SVPWM) algorithm + // https://www.youtube.com/watch?v=QMSWUMEAejg + + // the algorithm goes + // 1) Ualpha, Ubeta + // 2) Uout = sqrt(Ualpha^2 + Ubeta^2) + // 3) angle_el = atan2(Ubeta, Ualpha) + // + // equivalent to 2) because the magnitude does not change is: + // Uout = sqrt(Ud^2 + Uq^2) + // equivalent to 3) is + // angle_el = angle_el + atan2(Uq,Ud) + + float Uout; + // a bit of optitmisation + if(Ud){ // only if Ud and Uq set + // _sqrt is an approx of sqrt (3-4% error) + Uout = _sqrt(Ud*Ud + Uq*Uq) / driver->voltage_limit; + // angle normalisation in between 0 and 2pi + // only necessary if using _sin and _cos - approximation functions + angle_el = _normalizeAngle(angle_el + atan2(Uq, Ud)); + }else{// only Uq available - no need for atan2 and sqrt + Uout = Uq / driver->voltage_limit; + // angle normalisation in between 0 and 2pi + // only necessary if using _sin and _cos - approximation functions + angle_el = _normalizeAngle(angle_el + _PI_2); + } + // find the sector we are in currently + sector = floor(angle_el / _PI_3) + 1; + // calculate the duty cycles + float T1 = _SQRT3*_sin(sector*_PI_3 - angle_el) * Uout; + float T2 = _SQRT3*_sin(angle_el - (sector-1.0f)*_PI_3) * Uout; + // two versions possible + float T0 = 0; // pulled to 0 - better for low power supply voltage + if (modulation_centered) { + T0 = 1 - T1 - T2; // modulation_centered around driver->voltage_limit/2 + } + + // calculate the duty cycles(times) + float Ta,Tb,Tc; + switch(sector){ + case 1: + Ta = T1 + T2 + T0/2; + Tb = T2 + T0/2; + Tc = T0/2; + break; + case 2: + Ta = T1 + T0/2; + Tb = T1 + T2 + T0/2; + Tc = T0/2; + break; + case 3: + Ta = T0/2; + Tb = T1 + T2 + T0/2; + Tc = T2 + T0/2; + break; + case 4: + Ta = T0/2; + Tb = T1+ T0/2; + Tc = T1 + T2 + T0/2; + break; + case 5: + Ta = T2 + T0/2; + Tb = T0/2; + Tc = T1 + T2 + T0/2; + break; + case 6: + Ta = T1 + T2 + T0/2; + Tb = T0/2; + Tc = T1 + T0/2; + break; + default: + // possible error state + Ta = 0; + Tb = 0; + Tc = 0; + } + + // calculate the phase voltages and center + Ua = Ta*driver->voltage_limit; + Ub = Tb*driver->voltage_limit; + Uc = Tc*driver->voltage_limit; + break; + + } + + // set the voltages in driver + driver->setPwm(Ua, Ub, Uc); +} + + + +// Function (iterative) generating open loop movement for target velocity +// - target_velocity - rad/s +// it uses voltage_limit variable +float BLDCMotor::velocityOpenloop(float target_velocity){ + // get current timestamp + unsigned long now_us = _micros(); + // calculate the sample time from last call + float Ts = (now_us - open_loop_timestamp) * 1e-6f; + // quick fix for strange cases (micros overflow + timestamp not defined) + if(Ts <= 0 || Ts > 0.5f) Ts = 1e-3f; + + // calculate the necessary angle to achieve target velocity + shaft_angle = _normalizeAngle(shaft_angle + target_velocity*Ts); + // for display purposes + shaft_velocity = target_velocity; + + // use voltage limit or current limit + float Uq = voltage_limit; + if(_isset(phase_resistance)){ + Uq = _constrain(current_limit*phase_resistance + fabs(voltage_bemf),-voltage_limit, voltage_limit); + // recalculate the current + current.q = (Uq - fabs(voltage_bemf))/phase_resistance; + } + // set the maximal allowed voltage (voltage_limit) with the necessary angle + setPhaseVoltage(Uq, 0, _electricalAngle(shaft_angle, pole_pairs)); + + // save timestamp for next call + open_loop_timestamp = now_us; + + return Uq; +} + +// Function (iterative) generating open loop movement towards the target angle +// - target_angle - rad +// it uses voltage_limit and velocity_limit variables +float BLDCMotor::angleOpenloop(float target_angle){ + // get current timestamp + unsigned long now_us = _micros(); + // calculate the sample time from last call + float Ts = (now_us - open_loop_timestamp) * 1e-6f; + // quick fix for strange cases (micros overflow + timestamp not defined) + if(Ts <= 0 || Ts > 0.5f) Ts = 1e-3f; + + // calculate the necessary angle to move from current position towards target angle + // with maximal velocity (velocity_limit) + // TODO sensor precision: this calculation is not numerically precise. The angle can grow to the point + // where small position changes are no longer captured by the precision of floats + // when the total position is large. + if(abs( target_angle - shaft_angle ) > abs(velocity_limit*Ts)){ + shaft_angle += _sign(target_angle - shaft_angle) * abs( velocity_limit )*Ts; + shaft_velocity = velocity_limit; + }else{ + shaft_angle = target_angle; + shaft_velocity = 0; + } + + // use voltage limit or current limit + float Uq = voltage_limit; + if(_isset(phase_resistance)){ + Uq = _constrain(current_limit*phase_resistance + fabs(voltage_bemf),-voltage_limit, voltage_limit); + // recalculate the current + current.q = (Uq - fabs(voltage_bemf))/phase_resistance; + } + // set the maximal allowed voltage (voltage_limit) with the necessary angle + // sensor precision: this calculation is OK due to the normalisation + setPhaseVoltage(Uq, 0, _electricalAngle(_normalizeAngle(shaft_angle), pole_pairs)); + + // save timestamp for next call + open_loop_timestamp = now_us; + + return Uq; +} diff --git a/firmware/lib/Arduino-FOC/src/BLDCMotor.h b/firmware/lib/Arduino-FOC/src/BLDCMotor.h new file mode 100644 index 0000000..a1f196a --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/BLDCMotor.h @@ -0,0 +1,115 @@ +#ifndef BLDCMotor_h +#define BLDCMotor_h + +#include "Arduino.h" +#include "common/base_classes/FOCMotor.h" +#include "common/base_classes/Sensor.h" +#include "common/base_classes/BLDCDriver.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" +#include "common/defaults.h" + +/** + BLDC motor class +*/ +class BLDCMotor: public FOCMotor +{ + public: + /** + BLDCMotor class constructor + @param pp pole pairs number + @param R motor phase resistance - [Ohm] + @param KV motor KV rating (1/K_bemf) - rpm/V + @param L motor phase inductance - [H] + */ + BLDCMotor(int pp, float R = NOT_SET, float KV = NOT_SET, float L = NOT_SET); + + /** + * Function linking a motor and a foc driver + * + * @param driver BLDCDriver class implementing all the hardware specific functions necessary PWM setting + */ + virtual void linkDriver(BLDCDriver* driver); + + /** + * BLDCDriver link: + * - 3PWM + * - 6PWM + */ + BLDCDriver* driver; + + /** Motor hardware init function */ + void init() override; + /** Motor disable function */ + void disable() override; + /** Motor enable function */ + void enable() override; + + /** + * Function initializing FOC algorithm + * and aligning sensor's and motors' zero position + */ + int initFOC() override; + /** + * Function running FOC algorithm in real-time + * it calculates the gets motor angle and sets the appropriate voltages + * to the phase pwm signals + * - the faster you can run it the better Arduino UNO ~1ms, Bluepill ~ 100us + */ + void loopFOC() override; + + /** + * Function executing the control loops set by the controller parameter of the BLDCMotor. + * + * @param target Either voltage, angle or velocity based on the motor.controller + * If it is not set the motor will use the target set in its variable motor.target + * + * This function doesn't need to be run upon each loop execution - depends of the use case + */ + void move(float target = NOT_SET) override; + + float Ua, Ub, Uc;//!< Current phase voltages Ua,Ub and Uc set to motor + float Ualpha, Ubeta; //!< Phase voltages U alpha and U beta used for inverse Park and Clarke transform + + /** + * Method using FOC to set Uq to the motor at the optimal angle + * Heart of the FOC algorithm + * + * @param Uq Current voltage in q axis to set to the motor + * @param Ud Current voltage in d axis to set to the motor + * @param angle_el current electrical angle of the motor + */ + void setPhaseVoltage(float Uq, float Ud, float angle_el) override; + + private: + // FOC methods + + /** Sensor alignment to electrical 0 angle of the motor */ + int alignSensor(); + /** Current sense and motor phase alignment */ + int alignCurrentSense(); + /** Motor and sensor alignment to the sensors absolute 0 angle */ + int absoluteZeroSearch(); + + + // Open loop motion control + /** + * Function (iterative) generating open loop movement for target velocity + * it uses voltage_limit variable + * + * @param target_velocity - rad/s + */ + float velocityOpenloop(float target_velocity); + /** + * Function (iterative) generating open loop movement towards the target angle + * it uses voltage_limit and velocity_limit variables + * + * @param target_angle - rad + */ + float angleOpenloop(float target_angle); + // open loop variables + long open_loop_timestamp; +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/SimpleFOC.h b/firmware/lib/Arduino-FOC/src/SimpleFOC.h new file mode 100644 index 0000000..4e6815e --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/SimpleFOC.h @@ -0,0 +1,119 @@ +/*! + * @file SimpleFOC.h + * + * @mainpage Simple Field Oriented Control BLDC motor control library + * + * @section intro_sec Introduction + * + * Proper low-cost and low-power FOC supporting boards are very hard to find these days and even may not exist.
Even harder to find is a stable and simple FOC algorithm code capable of running on Arduino devices. Therefore this is an attempt to: + * - Demystify FOC algorithm and make a robust but simple Arduino library: Arduino SimpleFOC library + * - Develop a modular BLDC driver board: Arduino SimpleFOC shield. + * + * @section features Features + * - Arduino compatible: Arduino library code + * - Easy to setup and configure: + * - Easy hardware configuration + * - Easy tuning the control loops + * - Modular: + * - Supports as many sensors , BLDC motors and driver boards as possible + * - Supports as many application requirements as possible + * - Plug & play: Arduino SimpleFOC shield + * + * @section dependencies Supported Hardware + * - Motors + * - BLDC motors + * - Stepper motors + * - Drivers + * - BLDC drivers + * - Gimbal drivers + * - Stepper drivers + * - Position sensors + * - Encoders + * - Magnetic sensors + * - Hall sensors + * - Open-loop control + * - Microcontrollers + * - Arduino + * - STM32 + * - ESP32 + * - Teensy + * + * @section example_code Example code + * @code +#include + +// BLDCMotor( pole_pairs ) +BLDCMotor motor = BLDCMotor(11); +// BLDCDriver( pin_pwmA, pin_pwmB, pin_pwmC, enable (optional) ) +BLDCDriver3PWM driver = BLDCDriver3PWM(9, 10, 11, 8); +// Encoder(pin_A, pin_B, CPR) +Encoder encoder = Encoder(2, 3, 2048); +// channel A and B callbacks +void doA(){encoder.handleA();} +void doB(){encoder.handleB();} + + +void setup() { + // initialize encoder hardware + encoder.init(); + // hardware interrupt enable + encoder.enableInterrupts(doA, doB); + // link the motor to the sensor + motor.linkSensor(&encoder); + + // power supply voltage [V] + driver.voltage_power_supply = 12; + // initialise driver hardware + driver.init(); + // link driver + motor.linkDriver(&driver); + + // set control loop type to be used + motor.controller = MotionControlType::velocity; + // initialize motor + motor.init(); + + // align encoder and start FOC + motor.initFOC(); +} + +void loop() { + // FOC algorithm function + motor.loopFOC(); + + // velocity control loop function + // setting the target velocity or 2rad/s + motor.move(2); +} + * @endcode + * + * @section license License + * + * MIT license, all text here must be included in any redistribution. + * + */ + +#ifndef SIMPLEFOC_H +#define SIMPLEFOC_H + +#include "BLDCMotor.h" +#include "StepperMotor.h" +#include "sensors/Encoder.h" +#include "sensors/MagneticSensorSPI.h" +#include "sensors/MagneticSensorI2C.h" +#include "sensors/MagneticSensorAnalog.h" +#include "sensors/MagneticSensorPWM.h" +#include "sensors/HallSensor.h" +#include "sensors/GenericSensor.h" +#include "drivers/BLDCDriver3PWM.h" +#include "drivers/BLDCDriver6PWM.h" +#include "drivers/StepperDriver4PWM.h" +#include "drivers/StepperDriver2PWM.h" +#include "current_sense/InlineCurrentSense.h" +#include "current_sense/LowsideCurrentSense.h" +#include "current_sense/GenericCurrentSense.h" +#include "communication/Commander.h" +#include "communication/StepDirListener.h" +#include "communication/SimpleFOCDebug.h" + +#endif diff --git a/firmware/lib/Arduino-FOC/src/StepperMotor.cpp b/firmware/lib/Arduino-FOC/src/StepperMotor.cpp new file mode 100644 index 0000000..c53e1a4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/StepperMotor.cpp @@ -0,0 +1,463 @@ +#include "StepperMotor.h" +#include "./communication/SimpleFOCDebug.h" + + +// StepperMotor(int pp) +// - pp - pole pair number +// - R - motor phase resistance +// - KV - motor kv rating (rmp/v) +// - L - motor phase inductance [H] +StepperMotor::StepperMotor(int pp, float _R, float _KV, float _inductance) +: FOCMotor() +{ + // number od pole pairs + pole_pairs = pp; + // save phase resistance number + phase_resistance = _R; + // save back emf constant KV = 1/K_bemf + // usually used rms + KV_rating = _KV*_SQRT2; + // save phase inductance + phase_inductance = _inductance; + + // torque control type is voltage by default + // current and foc_current not supported yet + torque_controller = TorqueControlType::voltage; +} + +/** + Link the driver which controls the motor +*/ +void StepperMotor::linkDriver(StepperDriver* _driver) { + driver = _driver; +} + +// init hardware pins +void StepperMotor::init() { + if (!driver || !driver->initialized) { + motor_status = FOCMotorStatus::motor_init_failed; + SIMPLEFOC_DEBUG("MOT: Init not possible, driver not initialized"); + return; + } + motor_status = FOCMotorStatus::motor_initializing; + SIMPLEFOC_DEBUG("MOT: Init"); + + // sanity check for the voltage limit configuration + if(voltage_limit > driver->voltage_limit) voltage_limit = driver->voltage_limit; + // constrain voltage for sensor alignment + if(voltage_sensor_align > voltage_limit) voltage_sensor_align = voltage_limit; + + // update the controller limits + if(_isset(phase_resistance)){ + // velocity control loop controls current + PID_velocity.limit = current_limit; + }else{ + PID_velocity.limit = voltage_limit; + } + P_angle.limit = velocity_limit; + + // if using open loop control, set a CW as the default direction if not already set + if ((controller==MotionControlType::angle_openloop + ||controller==MotionControlType::velocity_openloop) + && (sensor_direction == Direction::UNKNOWN)) { + sensor_direction = Direction::CW; + } + + _delay(500); + // enable motor + SIMPLEFOC_DEBUG("MOT: Enable driver."); + enable(); + _delay(500); + + motor_status = FOCMotorStatus::motor_uncalibrated; +} + + +// disable motor driver +void StepperMotor::disable() +{ + // set zero to PWM + driver->setPwm(0, 0); + // disable driver + driver->disable(); + // motor status update + enabled = 0; +} +// enable motor driver +void StepperMotor::enable() +{ + // disable enable + driver->enable(); + // set zero to PWM + driver->setPwm(0, 0); + // motor status update + enabled = 1; +} + + +/** + FOC functions +*/ +// FOC initialization function +int StepperMotor::initFOC() { + int exit_flag = 1; + + motor_status = FOCMotorStatus::motor_calibrating; + + // align motor if necessary + // alignment necessary for encoders! + // sensor and motor alignment - can be skipped + // by setting motor.sensor_direction and motor.zero_electric_angle + _delay(500); + if(sensor){ + exit_flag *= alignSensor(); + // added the shaft_angle update + sensor->update(); + shaft_angle = sensor->getAngle(); + } else { SIMPLEFOC_DEBUG("MOT: No sensor."); } + + if(exit_flag){ + SIMPLEFOC_DEBUG("MOT: Ready."); + motor_status = FOCMotorStatus::motor_ready; + }else{ + SIMPLEFOC_DEBUG("MOT: Init FOC failed."); + motor_status = FOCMotorStatus::motor_calib_failed; + disable(); + } + + return exit_flag; +} + +// Encoder alignment to electrical 0 angle +int StepperMotor::alignSensor() { + int exit_flag = 1; //success + SIMPLEFOC_DEBUG("MOT: Align sensor."); + + // if unknown natural direction + if(sensor_direction == Direction::UNKNOWN){ + // check if sensor needs zero search + if(sensor->needsSearch()) exit_flag = absoluteZeroSearch(); + // stop init if not found index + if(!exit_flag) return exit_flag; + + // find natural direction + // move one electrical revolution forward + for (int i = 0; i <=500; i++ ) { + float angle = _3PI_2 + _2PI * i / 500.0f; + setPhaseVoltage(voltage_sensor_align, 0, angle); + sensor->update(); + _delay(2); + } + // take and angle in the middle + sensor->update(); + float mid_angle = sensor->getAngle(); + // move one electrical revolution backwards + for (int i = 500; i >=0; i-- ) { + float angle = _3PI_2 + _2PI * i / 500.0f ; + setPhaseVoltage(voltage_sensor_align, 0, angle); + sensor->update(); + _delay(2); + } + sensor->update(); + float end_angle = sensor->getAngle(); + setPhaseVoltage(0, 0, 0); + _delay(200); + // determine the direction the sensor moved + if (mid_angle == end_angle) { + SIMPLEFOC_DEBUG("MOT: Failed to notice movement"); + return 0; // failed calibration + } else if (mid_angle < end_angle) { + SIMPLEFOC_DEBUG("MOT: sensor_direction==CCW"); + sensor_direction = Direction::CCW; + } else{ + SIMPLEFOC_DEBUG("MOT: sensor_direction==CW"); + sensor_direction = Direction::CW; + } + // check pole pair number + float moved = fabs(mid_angle - end_angle); + if( fabs(moved*pole_pairs - _2PI) > 0.5f ) { // 0.5f is arbitrary number it can be lower or higher! + SIMPLEFOC_DEBUG("MOT: PP check: fail - estimated pp: ", _2PI/moved); + } else { + SIMPLEFOC_DEBUG("MOT: PP check: OK!"); + } + + } else { + SIMPLEFOC_DEBUG("MOT: Skip dir calib."); + } + + // zero electric angle not known + if(zero_electric_angle == NOT_SET){ + // align the electrical phases of the motor and sensor + // set angle -90(270 = 3PI/2) degrees + setPhaseVoltage(voltage_sensor_align, 0, _3PI_2); + _delay(700); + // read the sensor + sensor->update(); + // get the current zero electric angle + zero_electric_angle = 0; + zero_electric_angle = electricalAngle(); + _delay(20); + if(monitor_port){ + SIMPLEFOC_DEBUG("MOT: Zero elec. angle: ", zero_electric_angle); + } + // stop everything + setPhaseVoltage(0, 0, 0); + _delay(200); + } else { SIMPLEFOC_DEBUG("MOT: Skip offset calib."); } + return exit_flag; +} + +// Calibrate the motor and current sense phases +int StepperMotor::alignCurrentSense() { + int exit_flag = 1; // success + + SIMPLEFOC_DEBUG("MOT: Align current sense."); + + // align current sense and the driver + exit_flag = current_sense->driverAlign(voltage_sensor_align); + if(!exit_flag){ + // error in current sense - phase either not measured or bad connection + SIMPLEFOC_DEBUG("MOT: Align error!"); + exit_flag = 0; + }else{ + // output the alignment status flag + SIMPLEFOC_DEBUG("MOT: Success: ", exit_flag); + } + + return exit_flag > 0; +} + +// Encoder alignment the absolute zero angle +// - to the index +int StepperMotor::absoluteZeroSearch() { + + SIMPLEFOC_DEBUG("MOT: Index search..."); + // search the absolute zero with small velocity + float limit_vel = velocity_limit; + float limit_volt = voltage_limit; + velocity_limit = velocity_index_search; + voltage_limit = voltage_sensor_align; + shaft_angle = 0; + while(sensor->needsSearch() && shaft_angle < _2PI){ + angleOpenloop(1.5f*_2PI); + // call important for some sensors not to loose count + // not needed for the search + sensor->update(); + } + // disable motor + setPhaseVoltage(0, 0, 0); + // reinit the limits + velocity_limit = limit_vel; + voltage_limit = limit_volt; + // check if the zero found + if(monitor_port){ + if(sensor->needsSearch()) SIMPLEFOC_DEBUG("MOT: Error: Not found!"); + else { SIMPLEFOC_DEBUG("MOT: Success!"); } + } + return !sensor->needsSearch(); +} + + +// Iterative function looping FOC algorithm, setting Uq on the Motor +// The faster it can be run the better +void StepperMotor::loopFOC() { + + // update sensor - do this even in open-loop mode, as user may be switching between modes and we could lose track + // of full rotations otherwise. + if (sensor) sensor->update(); + + // if open-loop do nothing + if( controller==MotionControlType::angle_openloop || controller==MotionControlType::velocity_openloop ) return; + // shaft angle + shaft_angle = shaftAngle(); + + // if disabled do nothing + if(!enabled) return; + + // Needs the update() to be called first + // This function will not have numerical issues because it uses Sensor::getMechanicalAngle() + // which is in range 0-2PI + electrical_angle = electricalAngle(); + + // set the phase voltage - FOC heart function :) + setPhaseVoltage(voltage.q, voltage.d, electrical_angle); +} + +// Iterative function running outer loop of the FOC algorithm +// Behavior of this function is determined by the motor.controller variable +// It runs either angle, velocity or voltage loop +// - needs to be called iteratively it is asynchronous function +// - if target is not set it uses motor.target value +void StepperMotor::move(float new_target) { + + // downsampling (optional) + if(motion_cnt++ < motion_downsample) return; + motion_cnt = 0; + + // shaft angle/velocity need the update() to be called first + // get shaft angle + // TODO sensor precision: the shaft_angle actually stores the complete position, including full rotations, as a float + // For this reason it is NOT precise when the angles become large. + // Additionally, the way LPF works on angle is a precision issue, and the angle-LPF is a problem + // when switching to a 2-component representation. + if( controller!=MotionControlType::angle_openloop && controller!=MotionControlType::velocity_openloop ) + shaft_angle = shaftAngle(); // read value even if motor is disabled to keep the monitoring updated but not in openloop mode + // get angular velocity + shaft_velocity = shaftVelocity(); // read value even if motor is disabled to keep the monitoring updated + + // if disabled do nothing + if(!enabled) return; + + // set internal target variable + if(_isset(new_target) ) target = new_target; + + // calculate the back-emf voltage if KV_rating available U_bemf = vel*(1/KV) + if (_isset(KV_rating)) voltage_bemf = shaft_velocity/KV_rating/_RPM_TO_RADS; + // estimate the motor current if phase reistance available and current_sense not available + if(!current_sense && _isset(phase_resistance)) current.q = (voltage.q - voltage_bemf)/phase_resistance; + + // choose control loop + switch (controller) { + case MotionControlType::torque: + if(!_isset(phase_resistance)) voltage.q = target; // if voltage torque control + else voltage.q = target*phase_resistance + voltage_bemf; + voltage.q = _constrain(voltage.q, -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if(!_isset(phase_inductance)) voltage.d = 0; + else voltage.d = _constrain( -target*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + break; + case MotionControlType::angle: + // angle set point + shaft_angle_sp = target; + // calculate velocity set point + shaft_velocity_sp = feed_forward_velocity + P_angle( shaft_angle_sp - shaft_angle ); + shaft_angle_sp = _constrain(shaft_angle_sp, -velocity_limit, velocity_limit); + // calculate the torque command + current_sp = PID_velocity(shaft_velocity_sp - shaft_velocity); // if voltage torque control + // if torque controlled through voltage + // use voltage if phase-resistance not provided + if(!_isset(phase_resistance)) voltage.q = current_sp; + else voltage.q = _constrain( current_sp*phase_resistance + voltage_bemf , -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if(!_isset(phase_inductance)) voltage.d = 0; + else voltage.d = _constrain( -current_sp*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + break; + case MotionControlType::velocity: + // velocity set point + shaft_velocity_sp = target; + // calculate the torque command + current_sp = PID_velocity(shaft_velocity_sp - shaft_velocity); // if current/foc_current torque control + // if torque controlled through voltage control + // use voltage if phase-resistance not provided + if(!_isset(phase_resistance)) voltage.q = current_sp; + else voltage.q = _constrain( current_sp*phase_resistance + voltage_bemf , -voltage_limit, voltage_limit); + // set d-component (lag compensation if known inductance) + if(!_isset(phase_inductance)) voltage.d = 0; + else voltage.d = _constrain( -current_sp*shaft_velocity*pole_pairs*phase_inductance, -voltage_limit, voltage_limit); + break; + case MotionControlType::velocity_openloop: + // velocity control in open loop + shaft_velocity_sp = target; + voltage.q = velocityOpenloop(shaft_velocity_sp); // returns the voltage that is set to the motor + voltage.d = 0; // TODO d-component lag-compensation + break; + case MotionControlType::angle_openloop: + // angle control in open loop + shaft_angle_sp = target; + voltage.q = angleOpenloop(shaft_angle_sp); // returns the voltage that is set to the motor + voltage.d = 0; // TODO d-component lag-compensation + break; + } +} + + +// Method using FOC to set Uq and Ud to the motor at the optimal angle +// Function implementing Sine PWM algorithms +// - space vector not implemented yet +// +// Function using sine approximation +// regular sin + cos ~300us (no memory usaage) +// approx _sin + _cos ~110us (400Byte ~ 20% of memory) +void StepperMotor::setPhaseVoltage(float Uq, float Ud, float angle_el) { + // Sinusoidal PWM modulation + // Inverse Park transformation + float _sa, _ca; + _sincos(angle_el, &_sa, &_ca); + + // Inverse park transform + Ualpha = _ca * Ud - _sa * Uq; // -sin(angle) * Uq; + Ubeta = _sa * Ud + _ca * Uq; // cos(angle) * Uq; + + // set the voltages in hardware + driver->setPwm(Ualpha, Ubeta); +} + +// Function (iterative) generating open loop movement for target velocity +// - target_velocity - rad/s +// it uses voltage_limit variable +float StepperMotor::velocityOpenloop(float target_velocity){ + // get current timestamp + unsigned long now_us = _micros(); + // calculate the sample time from last call + float Ts = (now_us - open_loop_timestamp) * 1e-6f; + // quick fix for strange cases (micros overflow + timestamp not defined) + if(Ts <= 0 || Ts > 0.5f) Ts = 1e-3f; + + // calculate the necessary angle to achieve target velocity + shaft_angle = _normalizeAngle(shaft_angle + target_velocity*Ts); + // for display purposes + shaft_velocity = target_velocity; + + // use voltage limit or current limit + float Uq = voltage_limit; + if(_isset(phase_resistance)){ + Uq = _constrain(current_limit*phase_resistance + fabs(voltage_bemf),-voltage_limit, voltage_limit); + // recalculate the current + current.q = (Uq - fabs(voltage_bemf))/phase_resistance; + } + + // set the maximal allowed voltage (voltage_limit) with the necessary angle + setPhaseVoltage(Uq, 0, _electricalAngle(shaft_angle, pole_pairs)); + + // save timestamp for next call + open_loop_timestamp = now_us; + + return Uq; +} + +// Function (iterative) generating open loop movement towards the target angle +// - target_angle - rad +// it uses voltage_limit and velocity_limit variables +float StepperMotor::angleOpenloop(float target_angle){ + // get current timestamp + unsigned long now_us = _micros(); + // calculate the sample time from last call + float Ts = (now_us - open_loop_timestamp) * 1e-6f; + // quick fix for strange cases (micros overflow + timestamp not defined) + if(Ts <= 0 || Ts > 0.5f) Ts = 1e-3f; + + // calculate the necessary angle to move from current position towards target angle + // with maximal velocity (velocity_limit) + if(abs( target_angle - shaft_angle ) > abs(velocity_limit*Ts)){ + shaft_angle += _sign(target_angle - shaft_angle) * abs( velocity_limit )*Ts; + shaft_velocity = velocity_limit; + }else{ + shaft_angle = target_angle; + shaft_velocity = 0; + } + + // use voltage limit or current limit + float Uq = voltage_limit; + if(_isset(phase_resistance)){ + Uq = _constrain(current_limit*phase_resistance + fabs(voltage_bemf),-voltage_limit, voltage_limit); + // recalculate the current + current.q = (Uq - fabs(voltage_bemf))/phase_resistance; + } + // set the maximal allowed voltage (voltage_limit) with the necessary angle + setPhaseVoltage(Uq, 0, _electricalAngle((shaft_angle), pole_pairs)); + + // save timestamp for next call + open_loop_timestamp = now_us; + + return Uq; +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/StepperMotor.h b/firmware/lib/Arduino-FOC/src/StepperMotor.h new file mode 100644 index 0000000..1662b54 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/StepperMotor.h @@ -0,0 +1,117 @@ +/** + * @file StepperMotor.h + * + */ + +#ifndef StepperMotor_h +#define StepperMotor_h + +#include "Arduino.h" +#include "common/base_classes/FOCMotor.h" +#include "common/base_classes/StepperDriver.h" +#include "common/base_classes/Sensor.h" +#include "common/foc_utils.h" +#include "common/time_utils.h" +#include "common/defaults.h" + +/** + Stepper Motor class +*/ +class StepperMotor: public FOCMotor +{ + public: + /** + StepperMotor class constructor + @param pp pole pair number + @param R motor phase resistance - [Ohm] + @param KV motor KV rating (1/K_bemf) - rpm/V + @param L motor phase inductance - [H] + */ + StepperMotor(int pp, float R = NOT_SET, float KV = NOT_SET, float L = NOT_SET); + + /** + * Function linking a motor and a foc driver + * + * @param driver StepperDriver class implementing all the hardware specific functions necessary PWM setting + */ + void linkDriver(StepperDriver* driver); + + /** + * StepperDriver link: + * - 4PWM - L298N for example + */ + StepperDriver* driver; + + /** Motor hardware init function */ + void init() override; + /** Motor disable function */ + void disable() override; + /** Motor enable function */ + void enable() override; + + /** + * Function initializing FOC algorithm + * and aligning sensor's and motors' zero position + * + * - If zero_electric_offset parameter is set the alignment procedure is skipped + */ + int initFOC() override; + /** + * Function running FOC algorithm in real-time + * it calculates the gets motor angle and sets the appropriate voltages + * to the phase pwm signals + * - the faster you can run it the better Arduino UNO ~1ms, Bluepill ~ 100us + */ + void loopFOC() override; + /** + * Function executing the control loops set by the controller parameter of the StepperMotor. + * + * @param target Either voltage, angle or velocity based on the motor.controller + * If it is not set the motor will use the target set in its variable motor.target + * + * This function doesn't need to be run upon each loop execution - depends of the use case + */ + void move(float target = NOT_SET) override; + + float Ualpha,Ubeta; //!< Phase voltages U alpha and U beta used for inverse Park and Clarke transform + + /** + * Method using FOC to set Uq to the motor at the optimal angle + * Heart of the FOC algorithm + * + * @param Uq Current voltage in q axis to set to the motor + * @param Ud Current voltage in d axis to set to the motor + * @param angle_el current electrical angle of the motor + */ + void setPhaseVoltage(float Uq, float Ud, float angle_el) override; + + private: + + /** Sensor alignment to electrical 0 angle of the motor */ + int alignSensor(); + /** Current sense and motor phase alignment */ + int alignCurrentSense(); + /** Motor and sensor alignment to the sensors absolute 0 angle */ + int absoluteZeroSearch(); + + // Open loop motion control + /** + * Function (iterative) generating open loop movement for target velocity + * it uses voltage_limit variable + * + * @param target_velocity - rad/s + */ + float velocityOpenloop(float target_velocity); + /** + * Function (iterative) generating open loop movement towards the target angle + * it uses voltage_limit and velocity_limit variables + * + * @param target_angle - rad + */ + float angleOpenloop(float target_angle); + // open loop variables + long open_loop_timestamp; +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/BLDCDriver.h b/firmware/lib/Arduino-FOC/src/common/base_classes/BLDCDriver.h new file mode 100644 index 0000000..8d6747e --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/BLDCDriver.h @@ -0,0 +1,42 @@ +#ifndef BLDCDRIVER_H +#define BLDCDRIVER_H + +#include "Arduino.h" +#include "FOCDriver.h" + + +enum PhaseState : uint8_t { + PHASE_OFF = 0, // both sides of the phase are off + PHASE_ON = 1, // both sides of the phase are driven with PWM, dead time is applied in 6-PWM mode + PHASE_HI = 2, // only the high side of the phase is driven with PWM (6-PWM mode only) + PHASE_LO = 3, // only the low side of the phase is driven with PWM (6-PWM mode only) +}; + + +class BLDCDriver: public FOCDriver{ + public: + + float dc_a; //!< currently set duty cycle on phaseA + float dc_b; //!< currently set duty cycle on phaseB + float dc_c; //!< currently set duty cycle on phaseC + + /** + * Set phase voltages to the harware + * + * @param Ua - phase A voltage + * @param Ub - phase B voltage + * @param Uc - phase C voltage + */ + virtual void setPwm(float Ua, float Ub, float Uc) = 0; + + /** + * Set phase state, enable/disable + * + * @param sc - phase A state : active / disabled ( high impedance ) + * @param sb - phase B state : active / disabled ( high impedance ) + * @param sa - phase C state : active / disabled ( high impedance ) + */ + virtual void setPhaseState(PhaseState sa, PhaseState sb, PhaseState sc) = 0; +}; + +#endif diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.cpp b/firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.cpp new file mode 100644 index 0000000..7a74447 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.cpp @@ -0,0 +1,121 @@ +#include "CurrentSense.h" + +// get current magnitude +// - absolute - if no electrical_angle provided +// - signed - if angle provided +float CurrentSense::getDCCurrent(float motor_electrical_angle) +{ + // read current phase currents + PhaseCurrent_s current = getPhaseCurrents(); + // currnet sign - if motor angle not provided the magnitude is always positive + float sign = 1; + + // calculate clarke transform + float i_alpha, i_beta; + if (!current.c) + { + // if only two measured currents + i_alpha = current.a; + i_beta = _1_SQRT3 * current.a + _2_SQRT3 * current.b; + } + if (!current.a) + { + // if only two measured currents + float a = -current.c - current.b; + i_alpha = a; + i_beta = _1_SQRT3 * a + _2_SQRT3 * current.b; + } + if (!current.b) + { + // if only two measured currents + float b = -current.a - current.c; + i_alpha = current.a; + i_beta = _1_SQRT3 * current.a + _2_SQRT3 * b; + } + else + { + // signal filtering using identity a + b + c = 0. Assumes measurement error is normally distributed. + float mid = (1.f / 3) * (current.a + current.b + current.c); + float a = current.a - mid; + float b = current.b - mid; + i_alpha = a; + i_beta = _1_SQRT3 * a + _2_SQRT3 * b; + } + + // if motor angle provided function returns signed value of the current + // determine the sign of the current + // sign(atan2(current.q, current.d)) is the same as c.q > 0 ? 1 : -1 + if (motor_electrical_angle) + { + float ct; + float st; + _sincos(motor_electrical_angle, &st, &ct); + sign = (i_beta * ct - i_alpha * st) > 0 ? 1 : -1; + } + // return current magnitude + return sign * _sqrt(i_alpha * i_alpha + i_beta * i_beta); +} + +// function used with the foc algorihtm +// calculating DQ currents from phase currents +// - function calculating park and clarke transform of the phase currents +// - using getPhaseCurrents internally +DQCurrent_s CurrentSense::getFOCCurrents(float angle_el) +{ + // read current phase currents + PhaseCurrent_s current = getPhaseCurrents(); + + // calculate clarke transform + float i_alpha, i_beta; + if (!current.c) + { + // if only two measured currents + i_alpha = current.a; + i_beta = _1_SQRT3 * current.a + _2_SQRT3 * current.b; + } + if (!current.a) + { + // if only two measured currents + float a = -current.c - current.b; + i_alpha = a; + i_beta = _1_SQRT3 * a + _2_SQRT3 * current.b; + } + if (!current.b) + { + // if only two measured currents + float b = -current.a - current.c; + i_alpha = current.a; + i_beta = _1_SQRT3 * current.a + _2_SQRT3 * b; + } + else + { + // signal filtering using identity a + b + c = 0. Assumes measurement error is normally distributed. + float mid = (1.f / 3) * (current.a + current.b + current.c); + float a = current.a - mid; + float b = current.b - mid; + i_alpha = a; + i_beta = _1_SQRT3 * a + _2_SQRT3 * b; + } + + // calculate park transform + float ct; + float st; + _sincos(angle_el, &st, &ct); + DQCurrent_s return_current; + return_current.d = i_alpha * ct + i_beta * st; + return_current.q = i_beta * ct - i_alpha * st; + return return_current; +} + +/** + Driver linking to the current sense +*/ +void CurrentSense::linkDriver(BLDCDriver *_driver) +{ + driver = _driver; +} + +void CurrentSense::linkDriver(StepperDriver *_driver) +{ + driver = _driver; +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.h b/firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.h new file mode 100644 index 0000000..00fa0cf --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/CurrentSense.h @@ -0,0 +1,75 @@ +#ifndef CURRENTSENSE_H +#define CURRENTSENSE_H + +#include "BLDCDriver.h" +#include "StepperDriver.h" +#include "../foc_utils.h" + +/** + * Current sensing abstract class defintion + * Each current sensoring implementation needs to extend this interface + */ +class CurrentSense{ + public: + + /** + * Function intialising the CurrentSense class + * - All the necessary intialisations of adc and sync should be implemented here + * + * @returns - 0 - for failure & 1 - for success + */ + virtual int init() = 0; + + /** + * Linking the current sense with the motor driver + * Only necessary if synchronisation in between the two is required + */ + void linkDriver(BLDCDriver *driver); + void linkDriver(StepperDriver *driver); + + // variables + bool skip_align = false; //!< variable signaling that the phase current direction should be verified during initFOC() + + FOCDriver* driver = nullptr; //!< driver link + bool initialized = false; // true if current sense was successfully initialized + void* params = 0; //!< pointer to hardware specific parameters of current sensing + + /** + * Function intended to verify if: + * - phase current are oriented properly + * - if their order is the same as driver phases + * + * This function corrects the alignment errors if possible ans if no such thing is needed it can be left empty (return 1) + * @returns - 0 - for failure & positive number (with status) - for success + */ + virtual int driverAlign(float align_voltage) = 0; + + /** + * Function rading the phase currents a, b and c + * This function will be used with the foc control throught the function + * CurrentSense::getFOCCurrents(electrical_angle) + * - it returns current c equal to 0 if only two phase measurements available + * + * @return PhaseCurrent_s current values + */ + virtual PhaseCurrent_s getPhaseCurrents() = 0; + /** + * Function reading the magnitude of the current set to the motor + * It returns the abosolute or signed magnitude if possible + * It can receive the motor electrical angle to help with calculation + * This function is used with the current control (not foc) + * + * @param angle_el - electrical angle of the motor (optional) + */ + virtual float getDCCurrent(float angle_el = 0); + + /** + * Function used for FOC contorl, it reads the DQ currents of the motor + * It uses the function getPhaseCurrents internally + * + * @param angle_el - motor electrical angle + */ + DQCurrent_s getFOCCurrents(float angle_el); +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/FOCDriver.h b/firmware/lib/Arduino-FOC/src/common/base_classes/FOCDriver.h new file mode 100644 index 0000000..67343f7 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/FOCDriver.h @@ -0,0 +1,21 @@ +#ifndef FOCMOTOR_H +#define FOTMOTOR_H + +#include "Arduino.h" + +class FOCDriver{ + public: + virtual int init() = 0; + + virtual void enable() = 0; + + virtual void disable() = 0; + + long pwm_frequency; + float voltage_power_supply; + float voltage_limit; + bool initialized = false; + void* params = 0; +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.cpp b/firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.cpp new file mode 100644 index 0000000..d1427bc --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.cpp @@ -0,0 +1,155 @@ +#include "FOCMotor.h" +#include "../../communication/SimpleFOCDebug.h" + +/** + * Default constructor - setting all variabels to default values + */ +FOCMotor::FOCMotor() +{ + // maximum angular velocity to be used for positioning + velocity_limit = DEF_VEL_LIM; + // maximum voltage to be set to the motor + voltage_limit = DEF_POWER_SUPPLY; + // not set on the begining + current_limit = DEF_CURRENT_LIM; + + // index search velocity + velocity_index_search = DEF_INDEX_SEARCH_TARGET_VELOCITY; + // sensor and motor align voltage + voltage_sensor_align = DEF_VOLTAGE_SENSOR_ALIGN; + + // default modulation is SinePWM + foc_modulation = FOCModulationType::SinePWM; + + // default target value + target = 0; + voltage.d = 0; + voltage.q = 0; + // current target values + current_sp = 0; + current.q = 0; + current.d = 0; + + // voltage bemf + voltage_bemf = 0; + + //monitor_port + monitor_port = nullptr; + //sensor + sensor_offset = 0.0f; + sensor = nullptr; + //current sensor + current_sense = nullptr; +} + + +/** + Sensor linking method +*/ +void FOCMotor::linkSensor(Sensor* _sensor) { + sensor = _sensor; +} + +/** + CurrentSense linking method +*/ +void FOCMotor::linkCurrentSense(CurrentSense* _current_sense) { + current_sense = _current_sense; +} + +// shaft angle calculation +float FOCMotor::shaftAngle() { + // if no sensor linked return previous value ( for open loop ) + if(!sensor) return shaft_angle; + return sensor_direction*LPF_angle(sensor->getAngle()) - sensor_offset; +} +// shaft velocity calculation +float FOCMotor::shaftVelocity() { + // if no sensor linked return previous value ( for open loop ) + if(!sensor) return shaft_velocity; + return sensor_direction*LPF_velocity(sensor->getVelocity()); +} + +float FOCMotor::electricalAngle(){ + // if no sensor linked return previous value ( for open loop ) + if(!sensor) return electrical_angle; + return _normalizeAngle( (float)(sensor_direction * pole_pairs) * sensor->getMechanicalAngle() - zero_electric_angle ); +} + +/** + * Monitoring functions + */ +// function implementing the monitor_port setter +void FOCMotor::useMonitoring(Print &print){ + monitor_port = &print; //operate on the address of print + #ifndef SIMPLEFOC_DISABLE_DEBUG + SimpleFOCDebug::enable(&print); + SIMPLEFOC_DEBUG("MOT: Monitor enabled!"); + #endif +} + +// utility function intended to be used with serial plotter to monitor motor variables +// significantly slowing the execution down!!!! +void FOCMotor::monitor() { + if( !monitor_downsample || monitor_cnt++ < monitor_downsample ) return; + monitor_cnt = 0; + if(!monitor_port) return; + bool printed = 0; + + if(monitor_variables & _MON_TARGET){ + if(!printed && monitor_start_char) monitor_port->print(monitor_start_char); + monitor_port->print(target,monitor_decimals); + printed= true; + } + if(monitor_variables & _MON_VOLT_Q) { + if(!printed && monitor_start_char) monitor_port->print(monitor_start_char); + else if(printed) monitor_port->print(monitor_separator); + monitor_port->print(voltage.q,monitor_decimals); + printed= true; + } + if(monitor_variables & _MON_VOLT_D) { + if(!printed && monitor_start_char) monitor_port->print(monitor_start_char); + else if(printed) monitor_port->print(monitor_separator); + monitor_port->print(voltage.d,monitor_decimals); + printed= true; + } + // read currents if possible - even in voltage mode (if current_sense available) + if(monitor_variables & _MON_CURR_Q || monitor_variables & _MON_CURR_D) { + DQCurrent_s c = current; + if( current_sense && torque_controller != TorqueControlType::foc_current ){ + c = current_sense->getFOCCurrents(electrical_angle); + c.q = LPF_current_q(c.q); + c.d = LPF_current_d(c.d); + } + if(monitor_variables & _MON_CURR_Q) { + if(!printed && monitor_start_char) monitor_port->print(monitor_start_char); + else if(printed) monitor_port->print(monitor_separator); + monitor_port->print(c.q*1000, monitor_decimals); // mAmps + printed= true; + } + if(monitor_variables & _MON_CURR_D) { + if(!printed && monitor_start_char) monitor_port->print(monitor_start_char); + else if(printed) monitor_port->print(monitor_separator); + monitor_port->print(c.d*1000, monitor_decimals); // mAmps + printed= true; + } + } + + if(monitor_variables & _MON_VEL) { + if(!printed && monitor_start_char) monitor_port->print(monitor_start_char); + else if(printed) monitor_port->print(monitor_separator); + monitor_port->print(shaft_velocity,monitor_decimals); + printed= true; + } + if(monitor_variables & _MON_ANGLE) { + if(!printed && monitor_start_char) monitor_port->print(monitor_start_char); + else if(printed) monitor_port->print(monitor_separator); + monitor_port->print(shaft_angle,monitor_decimals); + printed= true; + } + if(printed){ + if(monitor_end_char) monitor_port->println(monitor_end_char); + else monitor_port->println(""); + } +} + diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.h b/firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.h new file mode 100644 index 0000000..318be99 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/FOCMotor.h @@ -0,0 +1,251 @@ +#ifndef FOCMOTOR_H +#define FOCMOTOR_H + +#include "Arduino.h" +#include "Sensor.h" +#include "CurrentSense.h" + +#include "../time_utils.h" +#include "../foc_utils.h" +#include "../defaults.h" +#include "../pid.h" +#include "../lowpass_filter.h" + + +// monitoring bitmap +#define _MON_TARGET 0b1000000 // monitor target value +#define _MON_VOLT_Q 0b0100000 // monitor voltage q value +#define _MON_VOLT_D 0b0010000 // monitor voltage d value +#define _MON_CURR_Q 0b0001000 // monitor current q value - if measured +#define _MON_CURR_D 0b0000100 // monitor current d value - if measured +#define _MON_VEL 0b0000010 // monitor velocity value +#define _MON_ANGLE 0b0000001 // monitor angle value + +/** + * Motiron control type + */ +enum MotionControlType : uint8_t { + torque = 0x00, //!< Torque control + velocity = 0x01, //!< Velocity motion control + angle = 0x02, //!< Position/angle motion control + velocity_openloop = 0x03, + angle_openloop = 0x04 +}; + +/** + * Motiron control type + */ +enum TorqueControlType : uint8_t { + voltage = 0x00, //!< Torque control using voltage + dc_current = 0x01, //!< Torque control using DC current (one current magnitude) + foc_current = 0x02, //!< torque control using dq currents +}; + +/** + * FOC modulation type + */ +enum FOCModulationType : uint8_t { + SinePWM = 0x00, //!< Sinusoidal PWM modulation + SpaceVectorPWM = 0x01, //!< Space vector modulation method + Trapezoid_120 = 0x02, + Trapezoid_150 = 0x03, +}; + + + +enum FOCMotorStatus : uint8_t { + motor_uninitialized = 0x00, //!< Motor is not yet initialized + motor_initializing = 0x01, //!< Motor intiialization is in progress + motor_uncalibrated = 0x02, //!< Motor is initialized, but not calibrated (open loop possible) + motor_calibrating = 0x03, //!< Motor calibration in progress + motor_ready = 0x04, //!< Motor is initialized and calibrated (closed loop possible) + motor_error = 0x08, //!< Motor is in error state (recoverable, e.g. overcurrent protection active) + motor_calib_failed = 0x0E, //!< Motor calibration failed (possibly recoverable) + motor_init_failed = 0x0F, //!< Motor initialization failed (not recoverable) +}; + + + +/** + Generic motor class +*/ +class FOCMotor +{ + public: + /** + * Default constructor - setting all variabels to default values + */ + FOCMotor(); + + /** Motor hardware init function */ + virtual void init()=0; + /** Motor disable function */ + virtual void disable()=0; + /** Motor enable function */ + virtual void enable()=0; + + /** + * Function linking a motor and a sensor + * + * @param sensor Sensor class wrapper for the FOC algorihtm to read the motor angle and velocity + */ + void linkSensor(Sensor* sensor); + + /** + * Function linking a motor and current sensing + * + * @param current_sense CurrentSense class wrapper for the FOC algorihtm to read the motor current measurements + */ + void linkCurrentSense(CurrentSense* current_sense); + + + /** + * Function initializing FOC algorithm + * and aligning sensor's and motors' zero position + * + * - If zero_electric_offset parameter is set the alignment procedure is skipped + */ + virtual int initFOC()=0; + /** + * Function running FOC algorithm in real-time + * it calculates the gets motor angle and sets the appropriate voltages + * to the phase pwm signals + * - the faster you can run it the better Arduino UNO ~1ms, Bluepill ~ 100us + */ + virtual void loopFOC()=0; + /** + * Function executing the control loops set by the controller parameter of the BLDCMotor. + * + * @param target Either voltage, angle or velocity based on the motor.controller + * If it is not set the motor will use the target set in its variable motor.target + * + * This function doesn't need to be run upon each loop execution - depends of the use case + */ + virtual void move(float target = NOT_SET)=0; + + /** + * Method using FOC to set Uq to the motor at the optimal angle + * Heart of the FOC algorithm + * + * @param Uq Current voltage in q axis to set to the motor + * @param Ud Current voltage in d axis to set to the motor + * @param angle_el current electrical angle of the motor + */ + virtual void setPhaseVoltage(float Uq, float Ud, float angle_el)=0; + + // State calculation methods + /** Shaft angle calculation in radians [rad] */ + float shaftAngle(); + /** + * Shaft angle calculation function in radian per second [rad/s] + * It implements low pass filtering + */ + float shaftVelocity(); + + + + /** + * Electrical angle calculation + */ + float electricalAngle(); + + // state variables + float target; //!< current target value - depends of the controller + float feed_forward_velocity = 0.0f; //!< current feed forward velocity + float shaft_angle;//!< current motor angle + float electrical_angle;//!< current electrical angle + float shaft_velocity;//!< current motor velocity + float current_sp;//!< target current ( q current ) + float shaft_velocity_sp;//!< current target velocity + float shaft_angle_sp;//!< current target angle + DQVoltage_s voltage;//!< current d and q voltage set to the motor + DQCurrent_s current;//!< current d and q current measured + float voltage_bemf; //!< estimated backemf voltage (if provided KV constant) + + // motor configuration parameters + float voltage_sensor_align;//!< sensor and motor align voltage parameter + float velocity_index_search;//!< target velocity for index search + + // motor physical parameters + float phase_resistance; //!< motor phase resistance + int pole_pairs;//!< motor pole pairs number + float KV_rating; //!< motor KV rating + float phase_inductance; //!< motor phase inductance + + // limiting variables + float voltage_limit; //!< Voltage limiting variable - global limit + float current_limit; //!< Current limiting variable - global limit + float velocity_limit; //!< Velocity limiting variable - global limit + + // motor status vairables + int8_t enabled = 0;//!< enabled or disabled motor flag + FOCMotorStatus motor_status = FOCMotorStatus::motor_uninitialized; //!< motor status + + // pwm modulation related variables + FOCModulationType foc_modulation;//!< parameter determining modulation algorithm + int8_t modulation_centered = 1;//!< flag (1) centered modulation around driver limit /2 or (0) pulled to 0 + + + // configuration structures + TorqueControlType torque_controller; //!< parameter determining the torque control type + MotionControlType controller; //!< parameter determining the control loop to be used + + // controllers and low pass filters + PIDController PID_current_q{DEF_PID_CURR_P,DEF_PID_CURR_I,DEF_PID_CURR_D,DEF_PID_CURR_RAMP, DEF_POWER_SUPPLY};//!< parameter determining the q current PID config + PIDController PID_current_d{DEF_PID_CURR_P,DEF_PID_CURR_I,DEF_PID_CURR_D,DEF_PID_CURR_RAMP, DEF_POWER_SUPPLY};//!< parameter determining the d current PID config + LowPassFilter LPF_current_q{DEF_CURR_FILTER_Tf};//!< parameter determining the current Low pass filter configuration + LowPassFilter LPF_current_d{DEF_CURR_FILTER_Tf};//!< parameter determining the current Low pass filter configuration + PIDController PID_velocity{DEF_PID_VEL_P,DEF_PID_VEL_I,DEF_PID_VEL_D,DEF_PID_VEL_RAMP,DEF_PID_VEL_LIMIT};//!< parameter determining the velocity PID configuration + PIDController P_angle{DEF_P_ANGLE_P,0,0,0,DEF_VEL_LIM}; //!< parameter determining the position PID configuration + LowPassFilter LPF_velocity{DEF_VEL_FILTER_Tf};//!< parameter determining the velocity Low pass filter configuration + LowPassFilter LPF_angle{0.0};//!< parameter determining the angle low pass filter configuration + unsigned int motion_downsample = DEF_MOTION_DOWNSMAPLE; //!< parameter defining the ratio of downsampling for move commad + unsigned int motion_cnt = 0; //!< counting variable for downsampling for move commad + + // sensor related variabels + float sensor_offset; //!< user defined sensor zero offset + float zero_electric_angle = NOT_SET;//!< absolute zero electric angle - if available + Direction sensor_direction = Direction::UNKNOWN; //!< default is CW. if sensor_direction == Direction::CCW then direction will be flipped compared to CW. Set to UNKNOWN to set by calibration + + /** + * Function providing BLDCMotor class with the + * Serial interface and enabling monitoring mode + * + * @param serial Monitoring Serial class reference + */ + void useMonitoring(Print &serial); + + /** + * Utility function intended to be used with serial plotter to monitor motor variables + * significantly slowing the execution down!!!! + */ + void monitor(); + unsigned int monitor_downsample = DEF_MON_DOWNSMAPLE; //!< show monitor outputs each monitor_downsample calls + char monitor_start_char = '\0'; //!< monitor starting character + char monitor_end_char = '\0'; //!< monitor outputs ending character + char monitor_separator = '\t'; //!< monitor outputs separation character + unsigned int monitor_decimals = 4; //!< monitor outputs decimal places + // initial monitoring will display target, voltage, velocity and angle + uint8_t monitor_variables = _MON_TARGET | _MON_VOLT_Q | _MON_VEL | _MON_ANGLE; //!< Bit array holding the map of variables the user wants to monitor + + /** + * Sensor link: + * - Encoder + * - MagneticSensor* + * - HallSensor + */ + Sensor* sensor; + /** + * CurrentSense link + */ + CurrentSense* current_sense; + + // monitoring functions + Print* monitor_port; //!< Serial terminal variable if provided + private: + // monitor counting variable + unsigned int monitor_cnt = 0 ; //!< counting variable +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.cpp b/firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.cpp new file mode 100644 index 0000000..a80fa43 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.cpp @@ -0,0 +1,78 @@ +#include "Sensor.h" +#include "../foc_utils.h" +#include "../time_utils.h" + + + +void Sensor::update() { + float val = getSensorAngle(); + angle_prev_ts = _micros(); + float d_angle = val - angle_prev; + // if overflow happened track it as full rotation + if(abs(d_angle) > (0.8f*_2PI) ) full_rotations += ( d_angle > 0 ) ? -1 : 1; + angle_prev = val; +} + + + /** get current angular velocity (rad/s) */ +float Sensor::getVelocity() { + // calculate sample time + float Ts = (angle_prev_ts - vel_angle_prev_ts)*1e-6; + if (Ts < 0.0f) { // handle micros() overflow - we need to reset vel_angle_prev_ts + vel_angle_prev = angle_prev; + vel_full_rotations = full_rotations; + vel_angle_prev_ts = angle_prev_ts; + return velocity; + } + if (Ts < min_elapsed_time) return velocity; // don't update velocity if deltaT is too small + + velocity = ( (float)(full_rotations - vel_full_rotations)*_2PI + (angle_prev - vel_angle_prev) ) / Ts; + vel_angle_prev = angle_prev; + vel_full_rotations = full_rotations; + vel_angle_prev_ts = angle_prev_ts; + return velocity; +} + + + +void Sensor::init() { + // initialize all the internal variables of Sensor to ensure a "smooth" startup (without a 'jump' from zero) + getSensorAngle(); // call once + delayMicroseconds(1); + vel_angle_prev = getSensorAngle(); // call again + vel_angle_prev_ts = _micros(); + delay(1); + getSensorAngle(); // call once + delayMicroseconds(1); + angle_prev = getSensorAngle(); // call again + angle_prev_ts = _micros(); +} + + +float Sensor::getMechanicalAngle() { + return angle_prev; +} + + + +float Sensor::getAngle(){ + return (float)full_rotations * _2PI + angle_prev; +} + + + +double Sensor::getPreciseAngle() { + return (double)full_rotations * (double)_2PI + (double)angle_prev; +} + + + +int32_t Sensor::getFullRotations() { + return full_rotations; +} + + + +int Sensor::needsSearch() { + return 0; // default false +} diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.h b/firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.h new file mode 100644 index 0000000..c77eb91 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/Sensor.h @@ -0,0 +1,139 @@ +#ifndef SENSOR_H +#define SENSOR_H + +#include + +/** + * Direction structure + */ +enum Direction : int8_t { + CW = 1, // clockwise + CCW = -1, // counter clockwise + UNKNOWN = 0 // not yet known or invalid state +}; + + +/** + * Pullup configuration structure + */ +enum Pullup : uint8_t { + USE_INTERN = 0x00, //!< Use internal pullups + USE_EXTERN = 0x01 //!< Use external pullups +}; + +/** + * Sensor abstract class defintion + * + * This class is purposefully kept simple, as a base for all kinds of sensors. Currently we have + * Encoders, Magnetic Encoders and Hall Sensor implementations. This base class extracts the + * most basic common features so that a FOC driver can obtain the data it needs for operation. + * + * To implement your own sensors, create a sub-class of this class, and implement the getSensorAngle() + * method. getSensorAngle() returns a float value, in radians, representing the current shaft angle in the + * range 0 to 2*PI (one full turn). + * + * To function correctly, the sensor class update() method has to be called sufficiently quickly. Normally, + * the BLDCMotor's loopFOC() function calls it once per iteration, so you must ensure to call loopFOC() quickly + * enough, both for correct motor and sensor operation. + * + * The Sensor base class provides an implementation of getVelocity(), and takes care of counting full + * revolutions in a precise way, but if you wish you can additionally override these methods to provide more + * optimal implementations for your hardware. + * + */ +class Sensor{ + friend class SmoothingSensor; + public: + /** + * Get mechanical shaft angle in the range 0 to 2PI. This value will be as precise as possible with + * the hardware. Base implementation uses the values returned by update() so that + * the same values are returned until update() is called again. + */ + virtual float getMechanicalAngle(); + + /** + * Get current position (in rad) including full rotations and shaft angle. + * Base implementation uses the values returned by update() so that the same + * values are returned until update() is called again. + * Note that this value has limited precision as the number of rotations increases, + * because the limited precision of float can't capture the large angle of the full + * rotations and the small angle of the shaft angle at the same time. + */ + virtual float getAngle(); + + /** + * On architectures supporting it, this will return a double precision position value, + * which should have improved precision for large position values. + * Base implementation uses the values returned by update() so that the same + * values are returned until update() is called again. + */ + virtual double getPreciseAngle(); + + /** + * Get current angular velocity (rad/s) + * Can be overridden in subclasses. Base implementation uses the values + * returned by update() so that it only makes sense to call this if update() + * has been called in the meantime. + */ + virtual float getVelocity(); + + /** + * Get the number of full rotations + * Base implementation uses the values returned by update() so that the same + * values are returned until update() is called again. + */ + virtual int32_t getFullRotations(); + + /** + * Updates the sensor values by reading the hardware sensor. + * Some implementations may work with interrupts, and not need this. + * The base implementation calls getSensorAngle(), and updates internal + * fields for angle, timestamp and full rotations. + * This method must be called frequently enough to guarantee that full + * rotations are not "missed" due to infrequent polling. + * Override in subclasses if alternative behaviours are required for your + * sensor hardware. + */ + virtual void update(); + + /** + * returns 0 if it does need search for absolute zero + * 0 - magnetic sensor (& encoder with index which is found) + * 1 - ecoder with index (with index not found yet) + */ + virtual int needsSearch(); + + /** + * Minimum time between updates to velocity. If time elapsed is lower than this, the velocity is not updated. + */ + float min_elapsed_time = 0.000100; // default is 100 microseconds, or 10kHz + + protected: + /** + * Get current shaft angle from the sensor hardware, and + * return it as a float in radians, in the range 0 to 2PI. + * + * This method is pure virtual and must be implemented in subclasses. + * Calling this method directly does not update the base-class internal fields. + * Use update() when calling from outside code. + */ + virtual float getSensorAngle()=0; + /** + * Call Sensor::init() from your sensor subclass's init method if you want smoother startup + * The base class init() method calls getSensorAngle() several times to initialize the internal fields + * to current values, ensuring there is no discontinuity ("jump from zero") during the first calls + * to sensor.getAngle() and sensor.getVelocity() + */ + virtual void init(); + + // velocity calculation variables + float velocity=0.0f; + float angle_prev=0.0f; // result of last call to getSensorAngle(), used for full rotations and velocity + long angle_prev_ts=0; // timestamp of last call to getAngle, used for velocity + float vel_angle_prev=0.0f; // angle at last call to getVelocity, used for velocity + long vel_angle_prev_ts=0; // last velocity calculation timestamp + int32_t full_rotations=0; // full rotation tracking + int32_t vel_full_rotations=0; // previous full rotation value for velocity calculation +}; + +#endif diff --git a/firmware/lib/Arduino-FOC/src/common/base_classes/StepperDriver.h b/firmware/lib/Arduino-FOC/src/common/base_classes/StepperDriver.h new file mode 100644 index 0000000..f0369ec --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/base_classes/StepperDriver.h @@ -0,0 +1,18 @@ +#ifndef STEPPERDRIVER_H +#define STEPPERDRIVER_H + +#include "drivers/hardware_api.h" +#include "FOCDriver.h" + +class StepperDriver: public FOCDriver{ + public: + /** + * Set phase voltages to the harware + * + * @param Ua phase A voltage + * @param Ub phase B voltage + */ + virtual void setPwm(float Ua, float Ub) = 0; +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/common/defaults.h b/firmware/lib/Arduino-FOC/src/common/defaults.h new file mode 100644 index 0000000..c0a4618 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/defaults.h @@ -0,0 +1,49 @@ +// default configuration values +// change this file to optimal values for your application + +#define DEF_POWER_SUPPLY 12.0f //!< default power supply voltage +// velocity PI controller params +#define DEF_PID_VEL_P 0.5f //!< default PID controller P value +#define DEF_PID_VEL_I 10.0f //!< default PID controller I value +#define DEF_PID_VEL_D 0.0f //!< default PID controller D value +#define DEF_PID_VEL_RAMP 1000.0f //!< default PID controller voltage ramp value +#define DEF_PID_VEL_LIMIT (DEF_POWER_SUPPLY) //!< default PID controller voltage limit + +// current sensing PID values +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328PB__) || defined(__AVR_ATmega2560__) +// for 16Mhz controllers like Arduino uno and mega +#define DEF_PID_CURR_P 2 //!< default PID controller P value +#define DEF_PID_CURR_I 100 //!< default PID controller I value +#define DEF_PID_CURR_D 0.0f //!< default PID controller D value +#define DEF_PID_CURR_RAMP 1000.0f //!< default PID controller voltage ramp value +#define DEF_PID_CURR_LIMIT (DEF_POWER_SUPPLY) //!< default PID controller voltage limit +#define DEF_CURR_FILTER_Tf 0.01f //!< default velocity filter time constant +#else +// for stm32, due, teensy, esp32 and similar +#define DEF_PID_CURR_P 3 //!< default PID controller P value +#define DEF_PID_CURR_I 300.0f //!< default PID controller I value +#define DEF_PID_CURR_D 0.0f //!< default PID controller D value +#define DEF_PID_CURR_RAMP 0 //!< default PID controller voltage ramp value +#define DEF_PID_CURR_LIMIT (DEF_POWER_SUPPLY) //!< default PID controller voltage limit +#define DEF_CURR_FILTER_Tf 0.005f //!< default currnet filter time constant +#endif +// default current limit values +#define DEF_CURRENT_LIM 2.0f //!< 2Amps current limit by default + +// default monitor downsample +#define DEF_MON_DOWNSMAPLE 100 //!< default monitor downsample +#define DEF_MOTION_DOWNSMAPLE 0 //!< default motion downsample - disable + +// angle P params +#define DEF_P_ANGLE_P 20.0f //!< default P controller P value +#define DEF_VEL_LIM 20.0f //!< angle velocity limit default + +// index search +#define DEF_INDEX_SEARCH_TARGET_VELOCITY 1.0f //!< default index search velocity +// align voltage +#define DEF_VOLTAGE_SENSOR_ALIGN 3.0f //!< default voltage for sensor and motor zero alignemt +// low pass filter velocity +#define DEF_VEL_FILTER_Tf 0.005 //!< default velocity filter time constant + +// current sense default parameters +#define DEF_LPF_PER_PHASE_CURRENT_SENSE_Tf 0.0f //!< default currnet sense per phase low pass filter time constant diff --git a/firmware/lib/Arduino-FOC/src/common/foc_utils.cpp b/firmware/lib/Arduino-FOC/src/common/foc_utils.cpp new file mode 100644 index 0000000..4cb0986 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/foc_utils.cpp @@ -0,0 +1,73 @@ +#include "foc_utils.h" + + +// function approximating the sine calculation by using fixed size array +// uses a 65 element lookup table and interpolation +// thanks to @dekutree for his work on optimizing this +__attribute__((weak)) float _sin(float a){ + // 16bit integer array for sine lookup. interpolation is used for better precision + // 16 bit precision on sine value, 8 bit fractional value for interpolation, 6bit LUT size + // resulting precision compared to stdlib sine is 0.00006480 (RMS difference in range -PI,PI for 3217 steps) + static uint16_t sine_array[65] = {0,804,1608,2411,3212,4011,4808,5602,6393,7180,7962,8740,9512,10279,11039,11793,12540,13279,14010,14733,15447,16151,16846,17531,18205,18868,19520,20160,20788,21403,22006,22595,23170,23732,24279,24812,25330,25833,26320,26791,27246,27684,28106,28511,28899,29269,29622,29957,30274,30572,30853,31114,31357,31581,31786,31972,32138,32286,32413,32522,32610,32679,32729,32758,32768}; + unsigned int i = (unsigned int)(a * (64*4*256.0 /_2PI)); + int t1, t2, frac = i & 0xff; + i = (i >> 8) & 0xff; + if (i < 64) { + t1 = sine_array[i]; t2 = sine_array[i+1]; + } + else if(i < 128) { + t1 = sine_array[128 - i]; t2 = sine_array[127 - i]; + } + else if(i < 192) { + t1 = -sine_array[-128 + i]; t2 = -sine_array[-127 + i]; + } + else { + t1 = -sine_array[256 - i]; t2 = -sine_array[255 - i]; + } + return (1.0f/32768.0f) * (t1 + (((t2 - t1) * frac) >> 8)); +} + +// function approximating cosine calculation by using fixed size array +// ~55us (float array) +// ~56us (int array) +// precision +-0.005 +// it has to receive an angle in between 0 and 2PI +__attribute__((weak)) float _cos(float a){ + float a_sin = a + _PI_2; + a_sin = a_sin > _2PI ? a_sin - _2PI : a_sin; + return _sin(a_sin); +} + + +__attribute__((weak)) void _sincos(float a, float* s, float* c){ + *s = _sin(a); + *c = _cos(a); +} + + +// normalizing radian angle to [0,2PI] +__attribute__((weak)) float _normalizeAngle(float angle){ + float a = fmod(angle, _2PI); + return a >= 0 ? a : (a + _2PI); +} + +// Electrical angle calculation +float _electricalAngle(float shaft_angle, int pole_pairs) { + return (shaft_angle * pole_pairs); +} + +// square root approximation function using +// https://reprap.org/forum/read.php?147,219210 +// https://en.wikipedia.org/wiki/Fast_inverse_square_root +__attribute__((weak)) float _sqrtApprox(float number) {//low in fat + // float x; + // const float f = 1.5F; // better precision + + // x = number * 0.5F; + float y = number; + long i = * ( long * ) &y; + i = 0x5f375a86 - ( i >> 1 ); + y = * ( float * ) &i; + // y = y * ( f - ( x * y * y ) ); // better precision + return number * y; +} diff --git a/firmware/lib/Arduino-FOC/src/common/foc_utils.h b/firmware/lib/Arduino-FOC/src/common/foc_utils.h new file mode 100644 index 0000000..0efe3b5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/foc_utils.h @@ -0,0 +1,106 @@ +#ifndef FOCUTILS_LIB_H +#define FOCUTILS_LIB_H + +#include "Arduino.h" + +// sign function +#define _sign(a) ( ( (a) < 0 ) ? -1 : ( (a) > 0 ) ) +#ifndef _round +#define _round(x) ((x)>=0?(long)((x)+0.5f):(long)((x)-0.5f)) +#endif +#define _constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt))) +#define _sqrt(a) (_sqrtApprox(a)) +#define _isset(a) ( (a) != (NOT_SET) ) +#define _UNUSED(v) (void) (v) +#define _powtwo(x) (1 << (x)) + +// utility defines +#define _2_SQRT3 1.15470053838f +#define _SQRT3 1.73205080757f +#define _1_SQRT3 0.57735026919f +#define _SQRT3_2 0.86602540378f +#define _SQRT2 1.41421356237f +#define _120_D2R 2.09439510239f +#define _PI 3.14159265359f +#define _PI_2 1.57079632679f +#define _PI_3 1.0471975512f +#define _2PI 6.28318530718f +#define _3PI_2 4.71238898038f +#define _PI_6 0.52359877559f +#define _RPM_TO_RADS 0.10471975512f + +#define NOT_SET -12345.0f +#define _HIGH_IMPEDANCE 0 +#define _HIGH_Z _HIGH_IMPEDANCE +#define _ACTIVE 1 +#define _NC (NOT_SET) + +#define MIN_ANGLE_DETECT_MOVEMENT (_2PI/101.0f) + +// dq current structure +struct DQCurrent_s +{ + float d; + float q; +}; +// phase current structure +struct PhaseCurrent_s +{ + float a; + float b; + float c; +}; +// dq voltage structs +struct DQVoltage_s +{ + float d; + float q; +}; + + +/** + * Function approximating the sine calculation by using fixed size array + * - execution time ~40us (Arduino UNO) + * + * @param a angle in between 0 and 2PI + */ +float _sin(float a); +/** + * Function approximating cosine calculation by using fixed size array + * - execution time ~50us (Arduino UNO) + * + * @param a angle in between 0 and 2PI + */ +float _cos(float a); +/** + * Function returning both sine and cosine of the angle in one call. + * Internally it uses the _sin and _cos functions, but you may wish to + * provide your own implementation which is more optimized. + */ +void _sincos(float a, float* s, float* c); + + +/** + * normalizing radian angle to [0,2PI] + * @param angle - angle to be normalized + */ +float _normalizeAngle(float angle); + + +/** + * Electrical angle calculation + * + * @param shaft_angle - shaft angle of the motor + * @param pole_pairs - number of pole pairs + */ +float _electricalAngle(float shaft_angle, int pole_pairs); + +/** + * Function approximating square root function + * - using fast inverse square root + * + * @param value - number + */ +float _sqrtApprox(float value); + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/common/lowpass_filter.cpp b/firmware/lib/Arduino-FOC/src/common/lowpass_filter.cpp new file mode 100644 index 0000000..ffb15cf --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/lowpass_filter.cpp @@ -0,0 +1,28 @@ +#include "lowpass_filter.h" + +LowPassFilter::LowPassFilter(float time_constant) + : Tf(time_constant) + , y_prev(0.0f) +{ + timestamp_prev = _micros(); +} + + +float LowPassFilter::operator() (float x) +{ + unsigned long timestamp = _micros(); + float dt = (timestamp - timestamp_prev)*1e-6f; + + if (dt < 0.0f ) dt = 1e-3f; + else if(dt > 0.3f) { + y_prev = x; + timestamp_prev = timestamp; + return x; + } + + float alpha = Tf/(Tf + dt); + float y = alpha*y_prev + (1.0f - alpha)*x; + y_prev = y; + timestamp_prev = timestamp; + return y; +} diff --git a/firmware/lib/Arduino-FOC/src/common/lowpass_filter.h b/firmware/lib/Arduino-FOC/src/common/lowpass_filter.h new file mode 100644 index 0000000..1f24e80 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/lowpass_filter.h @@ -0,0 +1,28 @@ +#ifndef LOWPASS_FILTER_H +#define LOWPASS_FILTER_H + + +#include "time_utils.h" +#include "foc_utils.h" + +/** + * Low pass filter class + */ +class LowPassFilter +{ +public: + /** + * @param Tf - Low pass filter time constant + */ + LowPassFilter(float Tf); + ~LowPassFilter() = default; + + float operator() (float x); + float Tf; //!< Low pass filter time constant + +protected: + unsigned long timestamp_prev; //!< Last execution timestamp + float y_prev; //!< filtered value in previous execution step +}; + +#endif // LOWPASS_FILTER_H \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/common/pid.cpp b/firmware/lib/Arduino-FOC/src/common/pid.cpp new file mode 100644 index 0000000..da1bee1 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/pid.cpp @@ -0,0 +1,64 @@ +#include "pid.h" + +PIDController::PIDController(float P, float I, float D, float ramp, float limit) + : P(P) + , I(I) + , D(D) + , output_ramp(ramp) // output derivative limit [volts/second] + , limit(limit) // output supply limit [volts] + , error_prev(0.0f) + , output_prev(0.0f) + , integral_prev(0.0f) +{ + timestamp_prev = _micros(); +} + +// PID controller function +float PIDController::operator() (float error){ + // calculate the time from the last call + unsigned long timestamp_now = _micros(); + float Ts = (timestamp_now - timestamp_prev) * 1e-6f; + // quick fix for strange cases (micros overflow) + if(Ts <= 0 || Ts > 0.5f) Ts = 1e-3f; + + // u(s) = (P + I/s + Ds)e(s) + // Discrete implementations + // proportional part + // u_p = P *e(k) + float proportional = P * error; + // Tustin transform of the integral part + // u_ik = u_ik_1 + I*Ts/2*(ek + ek_1) + float integral = integral_prev + I*Ts*0.5f*(error + error_prev); + // antiwindup - limit the output + integral = _constrain(integral, -limit, limit); + // Discrete derivation + // u_dk = D(ek - ek_1)/Ts + float derivative = D*(error - error_prev)/Ts; + + // sum all the components + float output = proportional + integral + derivative; + // antiwindup - limit the output variable + output = _constrain(output, -limit, limit); + + // if output ramp defined + if(output_ramp > 0){ + // limit the acceleration by ramping the output + float output_rate = (output - output_prev)/Ts; + if (output_rate > output_ramp) + output = output_prev + output_ramp*Ts; + else if (output_rate < -output_ramp) + output = output_prev - output_ramp*Ts; + } + // saving for the next pass + integral_prev = integral; + output_prev = output; + error_prev = error; + timestamp_prev = timestamp_now; + return output; +} + +void PIDController::reset(){ + integral_prev = 0.0f; + output_prev = 0.0f; + error_prev = 0.0f; +} diff --git a/firmware/lib/Arduino-FOC/src/common/pid.h b/firmware/lib/Arduino-FOC/src/common/pid.h new file mode 100644 index 0000000..acd68d6 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/pid.h @@ -0,0 +1,41 @@ +#ifndef PID_H +#define PID_H + + +#include "time_utils.h" +#include "foc_utils.h" + +/** + * PID controller class + */ +class PIDController +{ +public: + /** + * + * @param P - Proportional gain + * @param I - Integral gain + * @param D - Derivative gain + * @param ramp - Maximum speed of change of the output value + * @param limit - Maximum output value + */ + PIDController(float P, float I, float D, float ramp, float limit); + ~PIDController() = default; + + float operator() (float error); + void reset(); + + float P; //!< Proportional gain + float I; //!< Integral gain + float D; //!< Derivative gain + float output_ramp; //!< Maximum speed of change of the output value + float limit; //!< Maximum output value + +protected: + float error_prev; //!< last tracking error value + float output_prev; //!< last pid output value + float integral_prev; //!< last integral component value + unsigned long timestamp_prev; //!< Last execution timestamp +}; + +#endif // PID_H \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/common/time_utils.cpp b/firmware/lib/Arduino-FOC/src/common/time_utils.cpp new file mode 100644 index 0000000..2acb47a --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/time_utils.cpp @@ -0,0 +1,31 @@ +#include "time_utils.h" + +// function buffering delay() +// arduino uno function doesn't work well with interrupts +void _delay(unsigned long ms){ +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328PB__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) + // if arduino uno and other atmega328p chips + // use while instad of delay, + // due to wrong measurement based on changed timer0 + unsigned long t = _micros() + ms*1000; + while( _micros() < t ){}; +#else + // regular micros + delay(ms); +#endif +} + + +// function buffering _micros() +// arduino function doesn't work well with interrupts +unsigned long _micros(){ +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328PB__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) +// if arduino uno and other atmega328p chips + //return the value based on the prescaler + if((TCCR0B & 0b00000111) == 0x01) return (micros()/32); + else return (micros()); +#else + // regular micros + return micros(); +#endif +} diff --git a/firmware/lib/Arduino-FOC/src/common/time_utils.h b/firmware/lib/Arduino-FOC/src/common/time_utils.h new file mode 100644 index 0000000..143d485 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/common/time_utils.h @@ -0,0 +1,22 @@ +#ifndef TIME_UTILS_H +#define TIME_UTILS_H + +#include "foc_utils.h" + +/** + * Function implementing delay() function in milliseconds + * - blocking function + * - hardware specific + + * @param ms number of milliseconds to wait + */ +void _delay(unsigned long ms); + +/** + * Function implementing timestamp getting function in microseconds + * hardware specific + */ +unsigned long _micros(); + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/communication/Commander.cpp b/firmware/lib/Arduino-FOC/src/communication/Commander.cpp new file mode 100644 index 0000000..ee6be9f --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/communication/Commander.cpp @@ -0,0 +1,685 @@ +#include "Commander.h" + +Commander::Commander(Stream& serial, char eol, bool echo){ + com_port = &serial; + this->eol = eol; + this->echo = echo; +} +Commander::Commander(char eol, bool echo){ + this->eol = eol; + this->echo = echo; +} + + +void Commander::add(char id, CommandCallback onCommand, char* label ){ + call_list[call_count] = onCommand; + call_ids[call_count] = id; + call_label[call_count] = label; + call_count++; +} + + +void Commander::run(){ + if(!com_port) return; + run(*com_port, eol); +} + +void Commander::run(Stream& serial, char eol){ + Stream* tmp = com_port; // save the serial instance + char eol_tmp = this->eol; + this->eol = eol; + com_port = &serial; + + // a string to hold incoming data + while (serial.available()) { + // get the new byte: + int ch = serial.read(); + received_chars[rec_cnt++] = (char)ch; + // end of user input + if(echo) + print((char)ch); + if (isSentinel(ch)) { + // execute the user command + run(received_chars); + + // reset the command buffer + received_chars[0] = 0; + rec_cnt=0; + } + if (rec_cnt>=MAX_COMMAND_LENGTH) { // prevent buffer overrun if message is too long + received_chars[0] = 0; + rec_cnt=0; + } + } + + com_port = tmp; // reset the instance to the internal value + this->eol = eol_tmp; +} + +void Commander::run(char* user_input){ + // execute the user command + char id = user_input[0]; + switch(id){ + case CMD_SCAN: + for(int i=0; i < call_count; i++){ + printMachineReadable(CMD_SCAN); + print(call_ids[i]); + print(":"); + if(call_label[i]) println(call_label[i]); + else println(""); + } + break; + case CMD_VERBOSE: + if(!isSentinel(user_input[1])) verbose = (VerboseMode)atoi(&user_input[1]); + printVerbose(F("Verb:")); + printMachineReadable(CMD_VERBOSE); + switch (verbose){ + case VerboseMode::nothing: + println(F("off!")); + break; + case VerboseMode::on_request: + case VerboseMode::user_friendly: + println(F("on!")); + break; + case VerboseMode::machine_readable: + printlnMachineReadable(F("machine")); + break; + } + break; + case CMD_DECIMAL: + if(!isSentinel(user_input[1])) decimal_places = atoi(&user_input[1]); + printVerbose(F("Decimal:")); + printMachineReadable(CMD_DECIMAL); + println(decimal_places); + break; + default: + for(int i=0; i < call_count; i++){ + if(id == call_ids[i]){ + printMachineReadable(user_input[0]); + call_list[i](&user_input[1]); + break; + } + } + break; + } +} + +void Commander::motor(FOCMotor* motor, char* user_command) { + + // if target setting + if(isDigit(user_command[0]) || user_command[0] == '-' || user_command[0] == '+' || isSentinel(user_command[0])){ + target(motor, user_command); + return; + } + + // parse command letter + char cmd = user_command[0]; + char sub_cmd = user_command[1]; + // check if there is a subcommand or not + int value_index = (sub_cmd >= 'A' && sub_cmd <= 'Z') || (sub_cmd == '#') ? 2 : 1; + // check if get command + bool GET = isSentinel(user_command[value_index]); + // parse command values + float value = atof(&user_command[value_index]); + printMachineReadable(cmd); + if (sub_cmd >= 'A' && sub_cmd <= 'Z') { + printMachineReadable(sub_cmd); + } + + // a bit of optimisation of variable memory for Arduino UNO (atmega328) + switch(cmd){ + case CMD_C_Q_PID: // + printVerbose(F("PID curr q| ")); + if(sub_cmd == SCMD_LPF_TF) lpf(&motor->LPF_current_q, &user_command[1]); + else pid(&motor->PID_current_q,&user_command[1]); + break; + case CMD_C_D_PID: // + printVerbose(F("PID curr d| ")); + if(sub_cmd == SCMD_LPF_TF) lpf(&motor->LPF_current_d, &user_command[1]); + else pid(&motor->PID_current_d, &user_command[1]); + break; + case CMD_V_PID: // + printVerbose(F("PID vel| ")); + if(sub_cmd == SCMD_LPF_TF) lpf(&motor->LPF_velocity, &user_command[1]); + else pid(&motor->PID_velocity, &user_command[1]); + break; + case CMD_A_PID: // + printVerbose(F("PID angle| ")); + if(sub_cmd == SCMD_LPF_TF) lpf(&motor->LPF_angle, &user_command[1]); + else pid(&motor->P_angle, &user_command[1]); + break; + case CMD_LIMITS: // + printVerbose(F("Limits| ")); + switch (sub_cmd){ + case SCMD_LIM_VOLT: // voltage limit change + printVerbose(F("volt: ")); + if(!GET) { + motor->voltage_limit = value; + motor->PID_current_d.limit = value; + motor->PID_current_q.limit = value; + // change velocity pid limit if in voltage mode and no phase resistance set + if( !_isset(motor->phase_resistance) && motor->torque_controller==TorqueControlType::voltage) motor->PID_velocity.limit = value; + } + println(motor->voltage_limit); + break; + case SCMD_LIM_CURR: // current limit + printVerbose(F("curr: ")); + if(!GET){ + motor->current_limit = value; + // if phase resistance specified or the current control is on set the current limit to the velocity PID + if(_isset(motor->phase_resistance) || motor->torque_controller != TorqueControlType::voltage ) motor->PID_velocity.limit = value; + } + println(motor->current_limit); + break; + case SCMD_LIM_VEL: // velocity limit + printVerbose(F("vel: ")); + if(!GET){ + motor->velocity_limit = value; + motor->P_angle.limit = value; + } + println(motor->velocity_limit); + break; + default: + printError(); + break; + } + break; + case CMD_MOTION_TYPE: + case CMD_TORQUE_TYPE: + case CMD_STATUS: + motion(motor, &user_command[0]); + break; + case CMD_PWMMOD: + // PWM modulation change + printVerbose(F("PWM Mod | ")); + switch (sub_cmd){ + case SCMD_PWMMOD_TYPE: // zero offset + printVerbose(F("type: ")); + if(!GET) motor->foc_modulation = (FOCModulationType)value; + switch(motor->foc_modulation){ + case FOCModulationType::SinePWM: + println(F("SinePWM")); + break; + case FOCModulationType::SpaceVectorPWM: + println(F("SVPWM")); + break; + case FOCModulationType::Trapezoid_120: + println(F("Trap 120")); + break; + case FOCModulationType::Trapezoid_150: + println(F("Trap 150")); + break; + } + break; + case SCMD_PWMMOD_CENTER: // centered modulation + printVerbose(F("center: ")); + if(!GET) motor->modulation_centered = value; + println(motor->modulation_centered); + break; + default: + printError(); + break; + } + break; + case CMD_RESIST: + printVerbose(F("R phase: ")); + if(!GET){ + motor->phase_resistance = value; + if(motor->torque_controller==TorqueControlType::voltage) + motor->PID_velocity.limit= motor->current_limit; + } + if(_isset(motor->phase_resistance)) println(motor->phase_resistance); + else println(0); + break; + case CMD_INDUCTANCE: + printVerbose(F("L phase: ")); + if(!GET){ + motor->phase_inductance = value; + } + if(_isset(motor->phase_inductance)) println(motor->phase_inductance); + else println(0); + break; + case CMD_KV_RATING: + printVerbose(F("Motor KV: ")); + if(!GET){ + motor->KV_rating = value; + } + if(_isset(motor->KV_rating)) println(motor->KV_rating); + else println(0); + break; + case CMD_SENSOR: + // Sensor zero offset + printVerbose(F("Sensor | ")); + switch (sub_cmd){ + case SCMD_SENS_MECH_OFFSET: // zero offset + printVerbose(F("offset: ")); + if(!GET) motor->sensor_offset = value; + println(motor->sensor_offset); + break; + case SCMD_SENS_ELEC_OFFSET: // electrical zero offset - not suggested to touch + printVerbose(F("el. offset: ")); + if(!GET) motor->zero_electric_angle = value; + println(motor->zero_electric_angle); + break; + default: + printError(); + break; + } + break; + case CMD_MONITOR: // get current values of the state variables + printVerbose(F("Monitor | ")); + switch (sub_cmd){ + case SCMD_GET: // get command + switch((uint8_t)value){ + case 0: // get target + printVerbose(F("target: ")); + println(motor->target); + break; + case 1: // get voltage q + printVerbose(F("Vq: ")); + println(motor->voltage.q); + break; + case 2: // get voltage d + printVerbose(F("Vd: ")); + println(motor->voltage.d); + break; + case 3: // get current q + printVerbose(F("Cq: ")); + println(motor->current.q); + break; + case 4: // get current d + printVerbose(F("Cd: ")); + println(motor->current.d); + break; + case 5: // get velocity + printVerbose(F("vel: ")); + println(motor->shaft_velocity); + break; + case 6: // get angle + printVerbose(F("angle: ")); + println(motor->shaft_angle); + break; + case 7: // get all states + printVerbose(F("all: ")); + print(motor->target); + print(";"); + print(motor->voltage.q); + print(";"); + print(motor->voltage.d); + print(";"); + print(motor->current.q); + print(";"); + print(motor->current.d); + print(";"); + print(motor->shaft_velocity); + print(";"); + println(motor->shaft_angle); + break; + default: + printError(); + break; + } + break; + case SCMD_DOWNSAMPLE: + printVerbose(F("downsample: ")); + if(!GET) motor->monitor_downsample = value; + println((int)motor->monitor_downsample); + break; + case SCMD_CLEAR: + motor->monitor_variables = (uint8_t) 0; + println(F("clear")); + break; + case CMD_DECIMAL: + printVerbose(F("decimal: ")); + motor->monitor_decimals = value; + println((int)motor->monitor_decimals); + break; + case SCMD_SET: + if(!GET){ + // set the variables + motor->monitor_variables = (uint8_t) 0; + for(int i = 0; i < 7; i++){ + if(isSentinel(user_command[value_index+i])) break; + motor->monitor_variables |= (user_command[value_index+i] - '0') << (6-i); + } + } + // print the variables + for(int i = 0; i < 7; i++){ + print( (motor->monitor_variables & (1 << (6-i))) >> (6-i)); + } + println(""); + break; + default: + printError(); + break; + } + break; + default: // unknown cmd + printVerbose(F("unknown cmd ")); + printError(); + } +} + +void Commander::motion(FOCMotor* motor, char* user_cmd, char* separator){ + char cmd = user_cmd[0]; + char sub_cmd = user_cmd[1]; + bool GET = isSentinel(user_cmd[1]); + float value = atof(&user_cmd[(sub_cmd >= 'A' && sub_cmd <= 'Z') ? 2 : 1]); + + switch(cmd){ + case CMD_MOTION_TYPE: + printVerbose(F("Motion:")); + switch(sub_cmd){ + case SCMD_DOWNSAMPLE: + printVerbose(F(" downsample: ")); + if(!GET) motor->motion_downsample = value; + println((int)motor->motion_downsample); + break; + default: + // change control type + if(!GET && value >= 0 && (int)value < 5) // if set command + motor->controller = (MotionControlType)value; + switch(motor->controller){ + case MotionControlType::torque: + println(F("torque")); + break; + case MotionControlType::velocity: + println(F("vel")); + break; + case MotionControlType::angle: + println(F("angle")); + break; + case MotionControlType::velocity_openloop: + println(F("vel open")); + break; + case MotionControlType::angle_openloop: + println(F("angle open")); + break; + } + break; + } + break; + case CMD_TORQUE_TYPE: + // change control type + printVerbose(F("Torque: ")); + if(!GET && (int8_t)value >= 0 && (int8_t)value < 3)// if set command + motor->torque_controller = (TorqueControlType)value; + switch(motor->torque_controller){ + case TorqueControlType::voltage: + println(F("volt")); + // change the velocity control limits if necessary + if( !_isset(motor->phase_resistance) ) motor->PID_velocity.limit = motor->voltage_limit; + break; + case TorqueControlType::dc_current: + println(F("dc curr")); + // change the velocity control limits if necessary + motor->PID_velocity.limit = motor->current_limit; + break; + case TorqueControlType::foc_current: + println(F("foc curr")); + // change the velocity control limits if necessary + motor->PID_velocity.limit = motor->current_limit; + break; + } + break; + case CMD_STATUS: + // enable/disable + printVerbose(F("Status: ")); + if(!GET) (bool)value ? motor->enable() : motor->disable(); + println(motor->enabled); + break; + default: + target(motor, user_cmd, separator); + break; + } +} + +void Commander::pid(PIDController* pid, char* user_cmd){ + char cmd = user_cmd[0]; + bool GET = isSentinel(user_cmd[1]); + float value = atof(&user_cmd[1]); + + switch (cmd){ + case SCMD_PID_P: // P gain change + printVerbose("P: "); + if(!GET) pid->P = value; + println(pid->P); + break; + case SCMD_PID_I: // I gain change + printVerbose("I: "); + if(!GET) pid->I = value; + println(pid->I); + break; + case SCMD_PID_D: // D gain change + printVerbose("D: "); + if(!GET) pid->D = value; + println(pid->D); + break; + case SCMD_PID_RAMP: // ramp change + printVerbose("ramp: "); + if(!GET) pid->output_ramp = value; + println(pid->output_ramp); + break; + case SCMD_PID_LIM: // limit change + printVerbose("limit: "); + if(!GET) pid->limit = value; + println(pid->limit); + break; + default: + printError(); + break; + } +} + +void Commander::lpf(LowPassFilter* lpf, char* user_cmd){ + char cmd = user_cmd[0]; + bool GET = isSentinel(user_cmd[1]); + float value = atof(&user_cmd[1]); + + switch (cmd){ + case SCMD_LPF_TF: // Tf value change + printVerbose(F("Tf: ")); + if(!GET) lpf->Tf = value; + println(lpf->Tf); + break; + default: + printError(); + break; + } +} + +void Commander::scalar(float* value, char* user_cmd){ + bool GET = isSentinel(user_cmd[0]); + if(!GET) *value = atof(user_cmd); + println(*value); +} + + +void Commander::target(FOCMotor* motor, char* user_cmd, char* separator){ + // if no values sent + if(isSentinel(user_cmd[0])) { + printlnMachineReadable(motor->target); + return; + }; + + float pos, vel, torque; + char* next_value; + switch(motor->controller){ + case MotionControlType::torque: // setting torque target + torque = atof(strtok (user_cmd, separator)); + motor->target = torque; + break; + case MotionControlType::velocity: // setting velocity target + torque limit + // set the target + vel= atof(strtok (user_cmd, separator)); + motor->target = vel; + + // allow for setting only the target velocity without chaning the torque limit + next_value = strtok (NULL, separator); + if (next_value){ + torque = atof(next_value); + motor->PID_velocity.limit = torque; + // torque command can be voltage or current + if(!_isset(motor->phase_resistance) && motor->torque_controller == TorqueControlType::voltage) motor->voltage_limit = torque; + else motor->current_limit = torque; + } + break; + case MotionControlType::angle: // setting angle target + torque, velocity limit + // setting the target position + pos= atof(strtok (user_cmd, separator)); + motor->target = pos; + + // allow for setting only the target position without chaning the velocity/torque limits + next_value = strtok (NULL, separator); + if( next_value ){ + vel = atof(next_value); + motor->velocity_limit = vel; + motor->P_angle.limit = vel; + + // allow for setting only the target position and velocity limit without the torque limit + next_value = strtok (NULL, separator); + if( next_value ){ + torque= atof(next_value); + motor->PID_velocity.limit = torque; + // torque command can be voltage or current + if(!_isset(motor->phase_resistance) && motor->torque_controller == TorqueControlType::voltage) motor->voltage_limit = torque; + else motor->current_limit = torque; + } + } + break; + case MotionControlType::velocity_openloop: // setting velocity target + torque limit + // set the target + vel= atof(strtok (user_cmd, separator)); + motor->target = vel; + // allow for setting only the target velocity without chaning the torque limit + next_value = strtok (NULL, separator); + if (next_value ){ + torque = atof(next_value); + // torque command can be voltage or current + if(!_isset(motor->phase_resistance)) motor->voltage_limit = torque; + else motor->current_limit = torque; + } + break; + case MotionControlType::angle_openloop: // setting angle target + torque, velocity limit + // set the target + pos= atof(strtok (user_cmd, separator)); + motor->target = pos; + + // allow for setting only the target position without chaning the velocity/torque limits + next_value = strtok (NULL, separator); + if( next_value ){ + vel = atof(next_value); + motor->velocity_limit = vel; + // allow for setting only the target velocity without chaning the torque limit + next_value = strtok (NULL, separator); + if (next_value ){ + torque = atof(next_value); + // torque command can be voltage or current + if(!_isset(motor->phase_resistance)) motor->voltage_limit = torque; + else motor->current_limit = torque; + } + } + break; + } + printVerbose(F("Target: ")); + println(motor->target); +} + + +bool Commander::isSentinel(char ch) +{ + if(ch == eol) + return true; + else if (ch == '\r') + { + printVerbose(F("Warn: \\r detected! \n")); + return true; // lets still consider it to end the line... + } + return false; +} + +void Commander::print(const int number){ + if( !com_port || verbose == VerboseMode::nothing ) return; + com_port->print(number); +} +void Commander::print(const float number){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->print((float)number,(int)decimal_places); +} +void Commander::print(const char* message){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->print(message); +} +void Commander::print(const __FlashStringHelper *message){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->print(message); +} +void Commander::print(const char message){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->print(message); +} + +void Commander::println(const int number){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->println(number); +} +void Commander::println(const float number){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->println((float)number, (int)decimal_places); +} +void Commander::println(const char* message){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->println(message); +} +void Commander::println(const __FlashStringHelper *message){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->println(message); +} +void Commander::println(const char message){ + if(!com_port || verbose == VerboseMode::nothing ) return; + com_port->println(message); +} + + +void Commander::printVerbose(const char* message){ + if(verbose == VerboseMode::user_friendly) print(message); +} +void Commander::printVerbose(const __FlashStringHelper *message){ + if(verbose == VerboseMode::user_friendly) print(message); +} + +void Commander::printMachineReadable(const int number){ + if(verbose == VerboseMode::machine_readable) print(number); +} +void Commander::printMachineReadable(const float number){ + if(verbose == VerboseMode::machine_readable) print(number); +} +void Commander::printMachineReadable(const char* message){ + if(verbose == VerboseMode::machine_readable) print(message); +} +void Commander::printMachineReadable(const __FlashStringHelper *message){ + if(verbose == VerboseMode::machine_readable) print(message); +} +void Commander::printMachineReadable(const char message){ + if(verbose == VerboseMode::machine_readable) print(message); +} + +void Commander::printlnMachineReadable(const int number){ + if(verbose == VerboseMode::machine_readable) println(number); +} +void Commander::printlnMachineReadable(const float number){ + if(verbose == VerboseMode::machine_readable) println(number); +} +void Commander::printlnMachineReadable(const char* message){ + if(verbose == VerboseMode::machine_readable) println(message); +} +void Commander::printlnMachineReadable(const __FlashStringHelper *message){ + if(verbose == VerboseMode::machine_readable) println(message); +} +void Commander::printlnMachineReadable(const char message){ + if(verbose == VerboseMode::machine_readable) println(message); +} + +void Commander::printError(){ + println(F("err")); +} diff --git a/firmware/lib/Arduino-FOC/src/communication/Commander.h b/firmware/lib/Arduino-FOC/src/communication/Commander.h new file mode 100644 index 0000000..91e3dc4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/communication/Commander.h @@ -0,0 +1,301 @@ +#ifndef COMMANDS_H +#define COMMANDS_H + +#include "Arduino.h" +#include "../common/base_classes/FOCMotor.h" +#include "../common/pid.h" +#include "../common/lowpass_filter.h" +#include "commands.h" + + +#define MAX_COMMAND_LENGTH 20 + + +// Commander verbose display to the user type +enum VerboseMode : uint8_t { + nothing = 0x00, // display nothing - good for monitoring + on_request = 0x01, // display only on user request + user_friendly = 0x02, // display textual messages to the user + machine_readable = 0x03 // display machine readable commands, matching commands to set each settings +}; + + +// callback function pointer definiton +typedef void (* CommandCallback)(char*); //!< command callback function pointer + +/** + * Commander class implementing string communication protocol based on IDvalue (ex AB5.321 - command id `A`, sub-command id `B`,value `5.321`) + * + * - This class can be used in combination with HardwareSerial instance which it would read and write + * or it can be used to parse strings that have been received from the user outside this library + * - Commander class implements command protocol for few standard components of the SimpleFOC library + * - FOCMotor + * - PIDController + * - LowPassFilter + * - Commander also provides a very simple command > callback interface that enables user to + * attach a callback function to certain command id - see function add() + */ +class Commander +{ + public: + /** + * Default constructor receiving a serial interface that it uses to output the values to + * Also if the function run() is used it uses this serial instance to read the serial for user commands + * + * @param serial - Serial com port instance + * @param eol - the end of line sentinel character + * @param echo - echo last typed character (for command line feedback) + */ + Commander(Stream &serial, char eol = '\n', bool echo = false); + Commander(char eol = '\n', bool echo = false); + + /** + * Function reading the serial port and firing callbacks that have been added to the commander + * once the user has requested them - when he sends the command + * + * - It has default commands (the letters can be changed in the commands.h file) + * '@' - Verbose mode + * '#' - Number of decimal places + * '?' - Scan command - displays all the labels of attached nodes + */ + void run(); + /** + * Function reading the string of user input and firing callbacks that have been added to the commander + * once the user has requested them - when he sends the command + * + * - It has default commands (the letters can be changed in the commands.h file) + * '@' - Verbose mode + * '#' - Number of decimal places + * '?' - Scan command - displays all the labels of attached nodes + * + * @param reader - temporary stream to read user input + * @param eol - temporary end of line sentinel + */ + void run(Stream &reader, char eol = '\n'); + /** + * Function reading the string of user input and firing callbacks that have been added to the commander + * once the user has requested them - when he sends the command + * + * - It has default commands (the letters can be changed in the commands.h file) + * '@' - Verbose mode + * '#' - Number of decimal places + * '?' - Scan command - displays all the labels of attached nodes + * + * @param user_input - string of user inputs + */ + void run(char* user_input); + + /** + * Function adding a callback to the coomander withe the command id + * @param id - char command letter + * @param onCommand - function pointer void function(char*) + * @param label - string label to be displayed when scan command sent + */ + void add(char id , CommandCallback onCommand, char* label = nullptr); + + // printing variables + VerboseMode verbose = VerboseMode::user_friendly; //!< flag signaling that the commands should output user understanable text + uint8_t decimal_places = 3; //!< number of decimal places to be used when displaying numbers + + // monitoring functions + Stream* com_port = nullptr; //!< Serial terminal variable if provided + char eol = '\n'; //!< end of line sentinel character + bool echo = false; //!< echo last typed character (for command line feedback) + + /** + * + * FOC motor (StepperMotor and BLDCMotor) command interface + * @param motor - FOCMotor (BLDCMotor or StepperMotor) instance + * @param user_cmd - the string command + * + * - It has several paramters (the letters can be changed in the commands.h file) + * 'Q' - Q current PID controller & LPF (see function pid and lpf for commands) + * 'D' - D current PID controller & LPF (see function pid and lpf for commands) + * 'V' - Velocity PID controller & LPF (see function pid and lpf for commands) + * 'A' - Angle PID controller & LPF (see function pid and lpf for commands) + * 'L' - Limits + * sub-commands: + * 'C' - Current + * 'U' - Voltage + * 'V' - Velocity + * 'C' - Motion control type config + * sub-commands: + * 'D' - downsample motiron loop + * '0' - torque + * '1' - velocity + * '2' - angle + * 'T' - Torque control type + * sub-commands: + * '0' - voltage + * '1' - current + * '2' - foc_current + * 'E' - Motor status (enable/disable) + * sub-commands: + * '0' - enable + * '1' - disable + * 'R' - Motor resistance + * 'S' - Sensor offsets + * sub-commands: + * 'M' - sensor offset + * 'E' - sensor electrical zero + * 'M' - Monitoring control + * sub-commands: + * 'D' - downsample monitoring + * 'C' - clear monitor + * 'S' - set monitoring variables + * 'G' - get variable value + * '' - Target setting interface + * Depends of the motion control mode: + * - torque : torque (ex. M2.5) + * - velocity (open and closed loop) : velocity torque (ex.M10 2.5 or M10 to only chanage the target witout limits) + * - angle (open and closed loop) : angle velocity torque (ex.M3.5 10 2.5 or M3.5 to only chanage the target witout limits) + * + * - Each of them can be get by sening the command letter -(ex. 'R' - to get the phase resistance) + * - Each of them can be set by sending 'IdSubidValue' - (ex. SM1.5 for setting sensor zero offset to 1.5f) + * + */ + void motor(FOCMotor* motor, char* user_cmd); + + /** + * Low pass fileter command interface + * @param lpf - LowPassFilter instance + * @param user_cmd - the string command + * + * - It only has one property - filtering time constant Tf + * - It can be get by sending 'F' + * - It can be set by sending 'Fvalue' - (ex. F0.01 for settin Tf=0.01) + */ + void lpf(LowPassFilter* lpf, char* user_cmd); + /** + * PID controller command interface + * @param pid - PIDController instance + * @param user_cmd - the string command + * + * - It has several paramters (the letters can be changed in the commands.h file) + * - P gain - 'P' + * - I gain - 'I' + * - D gain - 'D' + * - output ramp - 'R' + * - output limit - 'L' + * - Each of them can be get by sening the command letter -(ex. 'D' - to get the D gain) + * - Each of them can be set by sending 'IDvalue' - (ex. I1.5 for setting I=1.5) + */ + void pid(PIDController* pid, char* user_cmd); + /** + * Float variable scalar command interface + * @param value - float variable pointer + * @param user_cmd - the string command + * + * - It only has one property - one float value + * - It can be get by sending an empty string '\n' + * - It can be set by sending 'value' - (ex. 0.01f for settin *value=0.01) + */ + void scalar(float* value, char* user_cmd); + /** + * Target setting interface, enables setting the target and limiting variables at once. + * The values are sent separated by a separator specified as the third argument. The default separator is the space. + * + * @param motor - FOCMotor (BLDCMotor or StepperMotor) instance + * @param user_cmd - the string command + * @param separator - the string separator in between target and limit values, default is space - " " + * + * Example: P2.34 70 2 + * `P` is the user defined command, `2.34` is the target angle `70` is the target + * velocity and `2` is the desired max current. + * + * It depends of the motion control mode: + * - torque : torque (ex. P2.5) + * - velocity : velocity torque (ex.P10 2.5 or P10 to only chanage the target witout limits) + * - angle : angle velocity torque (ex.P3.5 10 2.5 or P3.5 to only chanage the target witout limits) + */ + void target(FOCMotor* motor, char* user_cmd, char* separator = (char *)" "); + + /** + * FOC motor (StepperMotor and BLDCMotor) motion control interfaces + * @param motor - FOCMotor (BLDCMotor or StepperMotor) instance + * @param user_cmd - the string command + * @param separator - the string separator in between target and limit values, default is space - " " + * + * Commands: + * 'C' - Motion control type config + * sub-commands: + * 'D' - downsample motiron loop + * '0' - torque + * '1' - velocity + * '2' - angle + * 'T' - Torque control type + * sub-commands: + * '0' - voltage + * '1' - current + * '2' - foc_current + * 'E' - Motor status (enable/disable) + * sub-commands: + * '0' - enable + * '1' - disable + * '' - Target setting interface + * Depends of the motion control mode: + * - torque : torque (ex. M2.5) + * - velocity (open and closed loop) : velocity torque (ex.M10 2.5 or M10 to only chanage the target witout limits) + * - angle (open and closed loop) : angle velocity torque (ex.M3.5 10 2.5 or M3.5 to only chanage the target witout limits) + */ + void motion(FOCMotor* motor, char* user_cmd, char* separator = (char *)" "); + + bool isSentinel(char ch); + private: + // Subscribed command callback variables + CommandCallback call_list[20];//!< array of command callback pointers - 20 is an arbitrary number + char call_ids[20]; //!< added callback commands + char* call_label[20]; //!< added callback labels + int call_count = 0;//!< number callbacks that are subscribed + + // helping variable for serial communication reading + char received_chars[MAX_COMMAND_LENGTH] = {0}; //!< so far received user message - waiting for newline + int rec_cnt = 0; //!< number of characters receives + + // serial printing functions + /** + * print the string message only if verbose mode on + * @param message - message to be printed + */ + void printVerbose(const char* message); + /** + * Print the string message only if verbose mode on + * - Function handling the case for strings defined by F macro + * @param message - message to be printed + */ + void printVerbose(const __FlashStringHelper *message); + /** + * print the numbers to the serial with desired decimal point number + * @param message - number to be printed + * @param newline - if needs lewline (1) otherwise (0) + */ + + void print(const float number); + void print(const int number); + void print(const char* message); + void print(const __FlashStringHelper *message); + void print(const char message); + void println(const float number); + void println(const int number); + void println(const char* message); + void println(const __FlashStringHelper *message); + void println(const char message); + + void printMachineReadable(const float number); + void printMachineReadable(const int number); + void printMachineReadable(const char* message); + void printMachineReadable(const __FlashStringHelper *message); + void printMachineReadable(const char message); + + void printlnMachineReadable(const float number); + void printlnMachineReadable(const int number); + void printlnMachineReadable(const char* message); + void printlnMachineReadable(const __FlashStringHelper *message); + void printlnMachineReadable(const char message); + + + void printError(); +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.cpp b/firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.cpp new file mode 100644 index 0000000..e969d8a --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.cpp @@ -0,0 +1,104 @@ + +#include "SimpleFOCDebug.h" + +#ifndef SIMPLEFOC_DISABLE_DEBUG + + +Print* SimpleFOCDebug::_debugPrint = NULL; + + +void SimpleFOCDebug::enable(Print* debugPrint) { + _debugPrint = debugPrint; +} + + +void SimpleFOCDebug::println(int val) { + if (_debugPrint != NULL) { + _debugPrint->println(val); + } +} + +void SimpleFOCDebug::println(float val) { + if (_debugPrint != NULL) { + _debugPrint->println(val); + } +} + + + +void SimpleFOCDebug::println(const char* str) { + if (_debugPrint != NULL) { + _debugPrint->println(str); + } +} + +void SimpleFOCDebug::println(const __FlashStringHelper* str) { + if (_debugPrint != NULL) { + _debugPrint->println(str); + } +} + +void SimpleFOCDebug::println(const char* str, float val) { + if (_debugPrint != NULL) { + _debugPrint->print(str); + _debugPrint->println(val); + } +} + +void SimpleFOCDebug::println(const __FlashStringHelper* str, float val) { + if (_debugPrint != NULL) { + _debugPrint->print(str); + _debugPrint->println(val); + } +} + +void SimpleFOCDebug::println(const char* str, int val) { + if (_debugPrint != NULL) { + _debugPrint->print(str); + _debugPrint->println(val); + } +} + +void SimpleFOCDebug::println(const __FlashStringHelper* str, int val) { + if (_debugPrint != NULL) { + _debugPrint->print(str); + _debugPrint->println(val); + } +} + + +void SimpleFOCDebug::print(const char* str) { + if (_debugPrint != NULL) { + _debugPrint->print(str); + } +} + + +void SimpleFOCDebug::print(const __FlashStringHelper* str) { + if (_debugPrint != NULL) { + _debugPrint->print(str); + } +} + + +void SimpleFOCDebug::print(int val) { + if (_debugPrint != NULL) { + _debugPrint->print(val); + } +} + + +void SimpleFOCDebug::print(float val) { + if (_debugPrint != NULL) { + _debugPrint->print(val); + } +} + + +void SimpleFOCDebug::println() { + if (_debugPrint != NULL) { + _debugPrint->println(); + } +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.h b/firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.h new file mode 100644 index 0000000..614e637 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/communication/SimpleFOCDebug.h @@ -0,0 +1,79 @@ + +#ifndef __SIMPLEFOCDEBUG_H__ +#define __SIMPLEFOCDEBUG_H__ + +#include "Arduino.h" + + +/** + * SimpleFOCDebug class + * + * This class is used to print debug messages to a chosen output. + * Currently, Print instances are supported as targets, e.g. serial port. + * + * Activate debug output globally by calling enable(), optionally passing + * in a Print instance. If none is provided "Serial" is used by default. + * + * To produce debug output, use the macro SIMPLEFOC_DEBUG: + * SIMPLEFOC_DEBUG("Debug message!"); + * SIMPLEFOC_DEBUG("a float value:", 123.456f); + * SIMPLEFOC_DEBUG("an integer value: ", 123); + * + * Keep debugging output short and simple. Some of our MCUs have limited + * RAM and limited serial output capabilities. + * + * By default, the SIMPLEFOC_DEBUG macro uses the flash string helper to + * help preserve memory on Arduino boards. + * + * You can also disable debug output completely. In this case all debug output + * and the SimpleFOCDebug class is removed from the compiled code. + * Add -DSIMPLEFOC_DISABLE_DEBUG to your compiler flags to disable debug in + * this way. + * + **/ + + +#ifndef SIMPLEFOC_DISABLE_DEBUG + +class SimpleFOCDebug { +public: + static void enable(Print* debugPrint = &Serial); + + static void println(const __FlashStringHelper* msg); + static void println(const char* msg); + static void println(const __FlashStringHelper* msg, float val); + static void println(const char* msg, float val); + static void println(const __FlashStringHelper* msg, int val); + static void println(const char* msg, int val); + static void println(); + static void println(int val); + static void println(float val); + + static void print(const char* msg); + static void print(const __FlashStringHelper* msg); + static void print(int val); + static void print(float val); + +protected: + static Print* _debugPrint; +}; + + +#define SIMPLEFOC_DEBUG(msg, ...) \ + SimpleFOCDebug::println(F(msg), ##__VA_ARGS__) + + + + + +#else //ifndef SIMPLEFOC_DISABLE_DEBUG + + + +#define SIMPLEFOC_DEBUG(msg, ...) + + + +#endif //ifndef SIMPLEFOC_DISABLE_DEBUG +#endif + diff --git a/firmware/lib/Arduino-FOC/src/communication/StepDirListener.cpp b/firmware/lib/Arduino-FOC/src/communication/StepDirListener.cpp new file mode 100644 index 0000000..ee4f69e --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/communication/StepDirListener.cpp @@ -0,0 +1,40 @@ +#include "StepDirListener.h" + +StepDirListener::StepDirListener(int _pinStep, int _pinDir, float _counter_to_value){ + pin_step = _pinStep; + pin_dir = _pinDir; + counter_to_value = _counter_to_value; +} + +void StepDirListener::init(){ + pinMode(pin_dir, INPUT); + pinMode(pin_step, INPUT_PULLUP); + count = 0; +} + +void StepDirListener::enableInterrupt(void (*doA)()){ + attachInterrupt(digitalPinToInterrupt(pin_step), doA, polarity); +} + +void StepDirListener::attach(float* variable){ + attached_variable = variable; +} + +void StepDirListener::handle(){ + // read step status + //bool step = digitalRead(pin_step); + // update counter only on rising edge + //if(step && step != step_active){ + if(digitalRead(pin_dir)) + count++; + else + count--; + //} + //step_active = step; + // if attached variable update it + if(attached_variable) *attached_variable = getValue(); +} +// calculate the position from counter +float StepDirListener::getValue(){ + return (float) count * counter_to_value; +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/communication/StepDirListener.h b/firmware/lib/Arduino-FOC/src/communication/StepDirListener.h new file mode 100644 index 0000000..f9691fd --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/communication/StepDirListener.h @@ -0,0 +1,65 @@ +#ifndef STEPDIR_H +#define STEPDIR_H + +#include "Arduino.h" +#include "../common/foc_utils.h" + + +#if !defined(TARGET_RP2040) && !defined(_SAMD21_) && !defined(_SAMD51_) && !defined(_SAME51_) && !defined(ARDUINO_UNOR4_WIFI) && !defined(ARDUINO_UNOR4_MINIMA) && !defined(NRF52_SERIES) && !defined(ARDUINO_ARCH_MEGAAVR) +#define PinStatus int +#endif + + +/** + * Step/Dir listenner class for easier interraction with this communication interface. + */ +class StepDirListener +{ + public: + + /** + * Constructor for step/direction interface + * @param step - pin + * @param direction - pin + * @param counter_to_value - step counter to value + */ + StepDirListener(int pinStep, int pinDir, float counter_to_value = 1); + /** + * Start listenning for step commands + * + * @param handleStep - on step received handler + */ + void enableInterrupt(void (*handleStep)()); + + /** + * Initialise dir and step commands + */ + void init(); + /** + * step handler + */ + void handle(); + /** + * Get so far received valued + */ + float getValue(); + /** + * Attach the value to be updated on each step receive + * - no need to call getValue function + */ + void attach(float* variable); + + // variables + int pin_step; //!< step pin + int pin_dir; //!< direction pin + long count; //!< current counter value - should be set to 0 for homing + PinStatus polarity = RISING; //!< polarity of the step pin + + private: + float* attached_variable = nullptr; //!< pointer to the attached variable + float counter_to_value; //!< step counter to value + //bool step_active = 0; //!< current step pin status (HIGH/LOW) - debouncing variable + +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/communication/commands.h b/firmware/lib/Arduino-FOC/src/communication/commands.h new file mode 100644 index 0000000..323a8e7 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/communication/commands.h @@ -0,0 +1,52 @@ +#ifndef COMMANDS_h +#define COMMANDS_h + +// see docs.simplefoc.com for in depth explanation of the commands + +// list of commands + #define CMD_C_D_PID 'D' //!< current d PID & LPF + #define CMD_C_Q_PID 'Q' //!< current d PID & LPF + #define CMD_V_PID 'V' //!< velocity PID & LPF + #define CMD_A_PID 'A' //!< angle PID & LPF + #define CMD_STATUS 'E' //!< motor status enable/disable + #define CMD_LIMITS 'L' //!< limits current/voltage/velocity + #define CMD_MOTION_TYPE 'C' //!< motion control type + #define CMD_TORQUE_TYPE 'T' //!< torque control type + #define CMD_SENSOR 'S' //!< sensor offsets + #define CMD_MONITOR 'M' //!< monitoring + #define CMD_RESIST 'R' //!< motor phase resistance + #define CMD_INDUCTANCE 'I' //!< motor phase inductance + #define CMD_KV_RATING 'K' //!< motor kv rating + #define CMD_PWMMOD 'W' //!< pwm modulation + + // commander configuration + #define CMD_SCAN '?' //!< command scaning the network - only for commander + #define CMD_VERBOSE '@' //!< command setting output mode - only for commander + #define CMD_DECIMAL '#' //!< command setting decimal places - only for commander + + // subcomands + //pid - lpf + #define SCMD_PID_P 'P' //!< PID gain P + #define SCMD_PID_I 'I' //!< PID gain I + #define SCMD_PID_D 'D' //!< PID gain D + #define SCMD_PID_RAMP 'R' //!< PID ramp + #define SCMD_PID_LIM 'L' //!< PID limit + #define SCMD_LPF_TF 'F' //!< LPF time constant + // limits + #define SCMD_LIM_CURR 'C' //!< Limit current + #define SCMD_LIM_VOLT 'U' //!< Limit voltage + #define SCMD_LIM_VEL 'V' //!< Limit velocity + //sensor + #define SCMD_SENS_MECH_OFFSET 'M' //!< Sensor offset + #define SCMD_SENS_ELEC_OFFSET 'E' //!< Sensor electrical zero offset + // monitoring + #define SCMD_DOWNSAMPLE 'D' //!< Monitoring downsample value + #define SCMD_CLEAR 'C' //!< Clear all monitored variables + #define SCMD_GET 'G' //!< Get variable only one value + #define SCMD_SET 'S' //!< Set variables to be monitored + + #define SCMD_PWMMOD_TYPE 'T' //!<< Pwm modulation type + #define SCMD_PWMMOD_CENTER 'C' //!<< Pwm modulation center flag + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.cpp b/firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.cpp new file mode 100644 index 0000000..635535f --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.cpp @@ -0,0 +1,163 @@ +#include "GenericCurrentSense.h" + +// GenericCurrentSense constructor +GenericCurrentSense::GenericCurrentSense(PhaseCurrent_s (*readCallback)(), void (*initCallback)()){ + // if function provided add it to the + if(readCallback != nullptr) this->readCallback = readCallback; + if(initCallback != nullptr) this->initCallback = initCallback; +} + +// Inline sensor init function +int GenericCurrentSense::init(){ + // configure ADC variables + if(initCallback != nullptr) initCallback(); + // calibrate zero offsets + calibrateOffsets(); + // set the initialized flag + initialized = (params!=SIMPLEFOC_CURRENT_SENSE_INIT_FAILED); + // return success + return 1; +} +// Function finding zero offsets of the ADC +void GenericCurrentSense::calibrateOffsets(){ + const int calibration_rounds = 1000; + + // find adc offset = zero current voltage + offset_ia = 0; + offset_ib = 0; + offset_ic = 0; + // read the adc voltage 1000 times ( arbitrary number ) + for (int i = 0; i < calibration_rounds; i++) { + PhaseCurrent_s current = readCallback(); + offset_ia += current.a; + offset_ib += current.b; + offset_ic += current.c; + _delay(1); + } + // calculate the mean offsets + offset_ia = offset_ia / calibration_rounds; + offset_ib = offset_ib / calibration_rounds; + offset_ic = offset_ic / calibration_rounds; +} + +// read all three phase currents (if possible 2 or 3) +PhaseCurrent_s GenericCurrentSense::getPhaseCurrents(){ + PhaseCurrent_s current = readCallback(); + current.a = (current.a - offset_ia); // amps + current.b = (current.b - offset_ib); // amps + current.c = (current.c - offset_ic); // amps + return current; +} + +// Function aligning the current sense with motor driver +// if all pins are connected well none of this is really necessary! - can be avoided +// returns flag +// 0 - fail +// 1 - success and nothing changed +// 2 - success but pins reconfigured +// 3 - success but gains inverted +// 4 - success but pins reconfigured and gains inverted +int GenericCurrentSense::driverAlign(float voltage){ + _UNUSED(voltage) ; // remove unused parameter warning + int exit_flag = 1; + if(skip_align) return exit_flag; + + if (!initialized) return 0; + + // // set phase A active and phases B and C down + // driver->setPwm(voltage, 0, 0); + // _delay(200); + // PhaseCurrent_s c = getPhaseCurrents(); + // // read the current 100 times ( arbitrary number ) + // for (int i = 0; i < 100; i++) { + // PhaseCurrent_s c1 = getPhaseCurrents(); + // c.a = c.a*0.6f + 0.4f*c1.a; + // c.b = c.b*0.6f + 0.4f*c1.b; + // c.c = c.c*0.6f + 0.4f*c1.c; + // _delay(3); + // } + // driver->setPwm(0, 0, 0); + // // align phase A + // float ab_ratio = fabs(c.a / c.b); + // float ac_ratio = c.c ? fabs(c.a / c.c) : 0; + // if( ab_ratio > 1.5f ){ // should be ~2 + // gain_a *= _sign(c.a); + // }else if( ab_ratio < 0.7f ){ // should be ~0.5 + // // switch phase A and B + // int tmp_pinA = pinA; + // pinA = pinB; + // pinB = tmp_pinA; + // gain_a *= _sign(c.b); + // exit_flag = 2; // signal that pins have been switched + // }else if(_isset(pinC) && ac_ratio < 0.7f ){ // should be ~0.5 + // // switch phase A and C + // int tmp_pinA = pinA; + // pinA = pinC; + // pinC= tmp_pinA; + // gain_a *= _sign(c.c); + // exit_flag = 2;// signal that pins have been switched + // }else{ + // // error in current sense - phase either not measured or bad connection + // return 0; + // } + + // // set phase B active and phases A and C down + // driver->setPwm(0, voltage, 0); + // _delay(200); + // c = getPhaseCurrents(); + // // read the current 50 times + // for (int i = 0; i < 100; i++) { + // PhaseCurrent_s c1 = getPhaseCurrents(); + // c.a = c.a*0.6f + 0.4f*c1.a; + // c.b = c.b*0.6f + 0.4f*c1.b; + // c.c = c.c*0.6f + 0.4f*c1.c; + // _delay(3); + // } + // driver->setPwm(0, 0, 0); + // float ba_ratio = fabs(c.b/c.a); + // float bc_ratio = c.c ? fabs(c.b / c.c) : 0; + // if( ba_ratio > 1.5f ){ // should be ~2 + // gain_b *= _sign(c.b); + // }else if( ba_ratio < 0.7f ){ // it should be ~0.5 + // // switch phase A and B + // int tmp_pinB = pinB; + // pinB = pinA; + // pinA = tmp_pinB; + // gain_b *= _sign(c.a); + // exit_flag = 2; // signal that pins have been switched + // }else if(_isset(pinC) && bc_ratio < 0.7f ){ // should be ~0.5 + // // switch phase A and C + // int tmp_pinB = pinB; + // pinB = pinC; + // pinC = tmp_pinB; + // gain_b *= _sign(c.c); + // exit_flag = 2; // signal that pins have been switched + // }else{ + // // error in current sense - phase either not measured or bad connection + // return 0; + // } + + // // if phase C measured + // if(_isset(pinC)){ + // // set phase B active and phases A and C down + // driver->setPwm(0, 0, voltage); + // _delay(200); + // c = getPhaseCurrents(); + // // read the adc voltage 500 times ( arbitrary number ) + // for (int i = 0; i < 50; i++) { + // PhaseCurrent_s c1 = getPhaseCurrents(); + // c.c = (c.c+c1.c)/50.0f; + // } + // driver->setPwm(0, 0, 0); + // gain_c *= _sign(c.c); + // } + + // if(gain_a < 0 || gain_b < 0 || gain_c < 0) exit_flag +=2; + // exit flag is either + // 0 - fail + // 1 - success and nothing changed + // 2 - success but pins reconfigured + // 3 - success but gains inverted + // 4 - success but pins reconfigured and gains inverted + return exit_flag; +} diff --git a/firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.h b/firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.h new file mode 100644 index 0000000..a63df49 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/GenericCurrentSense.h @@ -0,0 +1,40 @@ +#ifndef GENERIC_CS_LIB_H +#define GENERIC_CS_LIB_H + +#include "Arduino.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/defaults.h" +#include "../common/base_classes/CurrentSense.h" +#include "../common/lowpass_filter.h" +#include "hardware_api.h" + + +class GenericCurrentSense: public CurrentSense{ + public: + /** + GenericCurrentSense class constructor + */ + GenericCurrentSense(PhaseCurrent_s (*readCallback)() = nullptr, void (*initCallback)() = nullptr); + + // CurrentSense interface implementing functions + int init() override; + PhaseCurrent_s getPhaseCurrents() override; + int driverAlign(float align_voltage) override; + + + PhaseCurrent_s (*readCallback)() = nullptr; //!< function pointer to sensor reading + void (*initCallback)() = nullptr; //!< function pointer to sensor initialisation + + private: + /** + * Function finding zero offsets of the ADC + */ + void calibrateOffsets(); + float offset_ia; //!< zero current A voltage value (center of the adc reading) + float offset_ib; //!< zero current B voltage value (center of the adc reading) + float offset_ic; //!< zero current C voltage value (center of the adc reading) + +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.cpp b/firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.cpp new file mode 100644 index 0000000..492b3ac --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.cpp @@ -0,0 +1,253 @@ +#include "InlineCurrentSense.h" +#include "communication/SimpleFOCDebug.h" +// InlineCurrentSensor constructor +// - shunt_resistor - shunt resistor value +// - gain - current-sense op-amp gain +// - phA - A phase adc pin +// - phB - B phase adc pin +// - phC - C phase adc pin (optional) +InlineCurrentSense::InlineCurrentSense(float _shunt_resistor, float _gain, int _pinA, int _pinB, int _pinC){ + pinA = _pinA; + pinB = _pinB; + pinC = _pinC; + + shunt_resistor = _shunt_resistor; + amp_gain = _gain; + volts_to_amps_ratio = 1.0f /_shunt_resistor / _gain; // volts to amps + // gains for each phase + gain_a = volts_to_amps_ratio; + gain_b = volts_to_amps_ratio; + gain_c = volts_to_amps_ratio; +}; + + +InlineCurrentSense::InlineCurrentSense(float _mVpA, int _pinA, int _pinB, int _pinC){ + pinA = _pinA; + pinB = _pinB; + pinC = _pinC; + + volts_to_amps_ratio = 1000.0f / _mVpA; // mV to amps + // gains for each phase + gain_a = volts_to_amps_ratio; + gain_b = volts_to_amps_ratio; + gain_c = volts_to_amps_ratio; +}; + + + +// Inline sensor init function +int InlineCurrentSense::init(){ + // if no linked driver its fine in this case + // at least for init() + void* drv_params = driver ? driver->params : nullptr; + // configure ADC variables + params = _configureADCInline(drv_params,pinA,pinB,pinC); + // if init failed return fail + if (params == SIMPLEFOC_CURRENT_SENSE_INIT_FAILED) return 0; + // calibrate zero offsets + calibrateOffsets(); + // set the initialized flag + initialized = (params!=SIMPLEFOC_CURRENT_SENSE_INIT_FAILED); + // return success + return 1; +} +// Function finding zero offsets of the ADC +void InlineCurrentSense::calibrateOffsets(){ + const int calibration_rounds = 1000; + + // find adc offset = zero current voltage + offset_ia = 0; + offset_ib = 0; + offset_ic = 0; + // read the adc voltage 1000 times ( arbitrary number ) + for (int i = 0; i < calibration_rounds; i++) { + if(_isset(pinA)) offset_ia += _readADCVoltageInline(pinA, params); + if(_isset(pinB)) offset_ib += _readADCVoltageInline(pinB, params); + if(_isset(pinC)) offset_ic += _readADCVoltageInline(pinC, params); + _delay(1); + } + // calculate the mean offsets + if(_isset(pinA)) offset_ia = offset_ia / calibration_rounds; + if(_isset(pinB)) offset_ib = offset_ib / calibration_rounds; + if(_isset(pinC)) offset_ic = offset_ic / calibration_rounds; +} + +// read all three phase currents (if possible 2 or 3) +PhaseCurrent_s InlineCurrentSense::getPhaseCurrents(){ + PhaseCurrent_s current; + current.a = (!_isset(pinA)) ? 0 : (_readADCVoltageInline(pinA, params) - offset_ia)*gain_a;// amps + current.b = (!_isset(pinB)) ? 0 : (_readADCVoltageInline(pinB, params) - offset_ib)*gain_b;// amps + current.c = (!_isset(pinC)) ? 0 : (_readADCVoltageInline(pinC, params) - offset_ic)*gain_c; // amps + return current; +} + +// Function aligning the current sense with motor driver +// if all pins are connected well none of this is really necessary! - can be avoided +// returns flag +// 0 - fail +// 1 - success and nothing changed +// 2 - success but pins reconfigured +// 3 - success but gains inverted +// 4 - success but pins reconfigured and gains inverted +int InlineCurrentSense::driverAlign(float voltage){ + + int exit_flag = 1; + if(skip_align) return exit_flag; + + if (driver==nullptr) { + SIMPLEFOC_DEBUG("CUR: No driver linked!"); + return 0; + } + + if (!initialized) return 0; + + if(_isset(pinA)){ + // set phase A active and phases B and C down + driver->setPwm(voltage, 0, 0); + _delay(2000); + PhaseCurrent_s c = getPhaseCurrents(); + // read the current 100 times ( arbitrary number ) + for (int i = 0; i < 100; i++) { + PhaseCurrent_s c1 = getPhaseCurrents(); + c.a = c.a*0.6f + 0.4f*c1.a; + c.b = c.b*0.6f + 0.4f*c1.b; + c.c = c.c*0.6f + 0.4f*c1.c; + _delay(3); + } + driver->setPwm(0, 0, 0); + // align phase A + float ab_ratio = c.b ? fabs(c.a / c.b) : 0; + float ac_ratio = c.c ? fabs(c.a / c.c) : 0; + if(_isset(pinB) && ab_ratio > 1.5f ){ // should be ~2 + gain_a *= _sign(c.a); + }else if(_isset(pinC) && ac_ratio > 1.5f ){ // should be ~2 + gain_a *= _sign(c.a); + }else if(_isset(pinB) && ab_ratio < 0.7f ){ // should be ~0.5 + // switch phase A and B + int tmp_pinA = pinA; + pinA = pinB; + pinB = tmp_pinA; + float tmp_offsetA = offset_ia; + offset_ia = offset_ib; + offset_ib = tmp_offsetA; + gain_a *= _sign(c.b); + exit_flag = 2; // signal that pins have been switched + }else if(_isset(pinC) && ac_ratio < 0.7f ){ // should be ~0.5 + // switch phase A and C + int tmp_pinA = pinA; + pinA = pinC; + pinC= tmp_pinA; + float tmp_offsetA = offset_ia; + offset_ia = offset_ic; + offset_ic = tmp_offsetA; + gain_a *= _sign(c.c); + exit_flag = 2;// signal that pins have been switched + }else{ + // error in current sense - phase either not measured or bad connection + return 0; + } + } + + if(_isset(pinB)){ + // set phase B active and phases A and C down + driver->setPwm(0, voltage, 0); + _delay(200); + PhaseCurrent_s c = getPhaseCurrents(); + // read the current 50 times + for (int i = 0; i < 100; i++) { + PhaseCurrent_s c1 = getPhaseCurrents(); + c.a = c.a*0.6 + 0.4f*c1.a; + c.b = c.b*0.6 + 0.4f*c1.b; + c.c = c.c*0.6 + 0.4f*c1.c; + _delay(3); + } + driver->setPwm(0, 0, 0); + float ba_ratio = c.a ? fabs(c.b / c.a) : 0; + float bc_ratio = c.c ? fabs(c.b / c.c) : 0; + if(_isset(pinA) && ba_ratio > 1.5f ){ // should be ~2 + gain_b *= _sign(c.b); + }else if(_isset(pinC) && bc_ratio > 1.5f ){ // should be ~2 + gain_b *= _sign(c.b); + }else if(_isset(pinA) && ba_ratio < 0.7f ){ // it should be ~0.5 + // switch phase A and B + int tmp_pinB = pinB; + pinB = pinA; + pinA = tmp_pinB; + float tmp_offsetB = offset_ib; + offset_ib = offset_ia; + offset_ia = tmp_offsetB; + gain_b *= _sign(c.a); + exit_flag = 2; // signal that pins have been switched + }else if(_isset(pinC) && bc_ratio < 0.7f ){ // should be ~0.5 + // switch phase A and C + int tmp_pinB = pinB; + pinB = pinC; + pinC = tmp_pinB; + float tmp_offsetB = offset_ib; + offset_ib = offset_ic; + offset_ic = tmp_offsetB; + gain_b *= _sign(c.c); + exit_flag = 2; // signal that pins have been switched + }else{ + // error in current sense - phase either not measured or bad connection + return 0; + } + } + + // if phase C measured + if(_isset(pinC)){ + // set phase C active and phases A and B down + driver->setPwm(0, 0, voltage); + _delay(200); + PhaseCurrent_s c = getPhaseCurrents(); + // read the adc voltage 500 times ( arbitrary number ) + for (int i = 0; i < 100; i++) { + PhaseCurrent_s c1 = getPhaseCurrents(); + c.a = c.a*0.6 + 0.4f*c1.a; + c.b = c.b*0.6 + 0.4f*c1.b; + c.c = c.c*0.6 + 0.4f*c1.c; + _delay(3); + } + driver->setPwm(0, 0, 0); + float ca_ratio = c.a ? fabs(c.c / c.a) : 0; + float cb_ratio = c.b ? fabs(c.c / c.b) : 0; + if(_isset(pinA) && ca_ratio > 1.5f ){ // should be ~2 + gain_c *= _sign(c.c); + }else if(_isset(pinB) && cb_ratio > 1.5f ){ // should be ~2 + gain_c *= _sign(c.c); + }else if(_isset(pinA) && ca_ratio < 0.7f ){ // it should be ~0.5 + // switch phase A and C + int tmp_pinC = pinC; + pinC = pinA; + pinA = tmp_pinC; + float tmp_offsetC = offset_ic; + offset_ic = offset_ia; + offset_ia = tmp_offsetC; + gain_c *= _sign(c.a); + exit_flag = 2; // signal that pins have been switched + }else if(_isset(pinB) && cb_ratio < 0.7f ){ // should be ~0.5 + // switch phase B and C + int tmp_pinC = pinC; + pinC = pinB; + pinB = tmp_pinC; + float tmp_offsetC = offset_ic; + offset_ic = offset_ib; + offset_ib = tmp_offsetC; + gain_c *= _sign(c.b); + exit_flag = 2; // signal that pins have been switched + }else{ + // error in current sense - phase either not measured or bad connection + return 0; + } + } + + if(gain_a < 0 || gain_b < 0 || gain_c < 0) exit_flag +=2; + // exit flag is either + // 0 - fail + // 1 - success and nothing changed + // 2 - success but pins reconfigured + // 3 - success but gains inverted + // 4 - success but pins reconfigured and gains inverted + + return exit_flag; +} diff --git a/firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.h b/firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.h new file mode 100644 index 0000000..5fdca7d --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/InlineCurrentSense.h @@ -0,0 +1,73 @@ +#ifndef INLINE_CS_LIB_H +#define INLINE_CS_LIB_H + +#include "Arduino.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/defaults.h" +#include "../common/base_classes/CurrentSense.h" +#include "../common/lowpass_filter.h" +#include "hardware_api.h" + + +class InlineCurrentSense: public CurrentSense{ + public: + /** + InlineCurrentSense class constructor + @param shunt_resistor shunt resistor value + @param gain current-sense op-amp gain + @param phA A phase adc pin + @param phB B phase adc pin + @param phC C phase adc pin (optional) + */ + InlineCurrentSense(float shunt_resistor, float gain, int pinA, int pinB, int pinC = NOT_SET); + /** + InlineCurrentSense class constructor + @param mVpA mV per Amp ratio + @param phA A phase adc pin + @param phB B phase adc pin + @param phC C phase adc pin (optional) + */ + InlineCurrentSense(float mVpA, int pinA, int pinB, int pinC = NOT_SET); + + // CurrentSense interface implementing functions + int init() override; + PhaseCurrent_s getPhaseCurrents() override; + int driverAlign(float align_voltage) override; + + // ADC measuremnet gain for each phase + // support for different gains for different phases of more commonly - inverted phase currents + // this should be automated later + float gain_a; //!< phase A gain + float gain_b; //!< phase B gain + float gain_c; //!< phase C gain + + // // per phase low pass fileters + // LowPassFilter lpf_a{DEF_LPF_PER_PHASE_CURRENT_SENSE_Tf}; //!< current A low pass filter + // LowPassFilter lpf_b{DEF_LPF_PER_PHASE_CURRENT_SENSE_Tf}; //!< current B low pass filter + // LowPassFilter lpf_c{DEF_LPF_PER_PHASE_CURRENT_SENSE_Tf}; //!< current C low pass filter + + float offset_ia; //!< zero current A voltage value (center of the adc reading) + float offset_ib; //!< zero current B voltage value (center of the adc reading) + float offset_ic; //!< zero current C voltage value (center of the adc reading) + + private: + + // hardware variables + int pinA; //!< pin A analog pin for current measurement + int pinB; //!< pin B analog pin for current measurement + int pinC; //!< pin C analog pin for current measurement + + // gain variables + float shunt_resistor; //!< Shunt resistor value + float amp_gain; //!< amp gain value + float volts_to_amps_ratio; //!< Volts to amps ratio + + /** + * Function finding zero offsets of the ADC + */ + void calibrateOffsets(); + +}; + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.cpp b/firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.cpp new file mode 100644 index 0000000..a706bee --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.cpp @@ -0,0 +1,254 @@ +#include "LowsideCurrentSense.h" +#include "communication/SimpleFOCDebug.h" +// LowsideCurrentSensor constructor +// - shunt_resistor - shunt resistor value +// - gain - current-sense op-amp gain +// - phA - A phase adc pin +// - phB - B phase adc pin +// - phC - C phase adc pin (optional) +LowsideCurrentSense::LowsideCurrentSense(float _shunt_resistor, float _gain, int _pinA, int _pinB, int _pinC){ + pinA = _pinA; + pinB = _pinB; + pinC = _pinC; + + shunt_resistor = _shunt_resistor; + amp_gain = _gain; + volts_to_amps_ratio = 1.0f /_shunt_resistor / _gain; // volts to amps + // gains for each phase + gain_a = volts_to_amps_ratio; + gain_b = volts_to_amps_ratio; + gain_c = volts_to_amps_ratio; +} + + +LowsideCurrentSense::LowsideCurrentSense(float _mVpA, int _pinA, int _pinB, int _pinC){ + pinA = _pinA; + pinB = _pinB; + pinC = _pinC; + + volts_to_amps_ratio = 1000.0f / _mVpA; // mV to amps + // gains for each phase + gain_a = volts_to_amps_ratio; + gain_b = volts_to_amps_ratio; + gain_c = volts_to_amps_ratio; +} + + +// Lowside sensor init function +int LowsideCurrentSense::init(){ + + if (driver==nullptr) { + SIMPLEFOC_DEBUG("CUR: Driver not linked!"); + return 0; + } + + // configure ADC variables + params = _configureADCLowSide(driver->params,pinA,pinB,pinC); + // if init failed return fail + if (params == SIMPLEFOC_CURRENT_SENSE_INIT_FAILED) return 0; + // sync the driver + _driverSyncLowSide(driver->params, params); + // calibrate zero offsets + calibrateOffsets(); + // set the initialized flag + initialized = (params!=SIMPLEFOC_CURRENT_SENSE_INIT_FAILED); + // return success + return 1; +} +// Function finding zero offsets of the ADC +void LowsideCurrentSense::calibrateOffsets(){ + const int calibration_rounds = 2000; + + // find adc offset = zero current voltage + offset_ia = 0; + offset_ib = 0; + offset_ic = 0; + // read the adc voltage 1000 times ( arbitrary number ) + for (int i = 0; i < calibration_rounds; i++) { + _startADC3PinConversionLowSide(); + if(_isset(pinA)) offset_ia += (_readADCVoltageLowSide(pinA, params)); + if(_isset(pinB)) offset_ib += (_readADCVoltageLowSide(pinB, params)); + if(_isset(pinC)) offset_ic += (_readADCVoltageLowSide(pinC, params)); + _delay(1); + } + // calculate the mean offsets + if(_isset(pinA)) offset_ia = offset_ia / calibration_rounds; + if(_isset(pinB)) offset_ib = offset_ib / calibration_rounds; + if(_isset(pinC)) offset_ic = offset_ic / calibration_rounds; +} + +// read all three phase currents (if possible 2 or 3) +PhaseCurrent_s LowsideCurrentSense::getPhaseCurrents(){ + PhaseCurrent_s current; + _startADC3PinConversionLowSide(); + current.a = (!_isset(pinA)) ? 0 : (_readADCVoltageLowSide(pinA, params) - offset_ia)*gain_a;// amps + current.b = (!_isset(pinB)) ? 0 : (_readADCVoltageLowSide(pinB, params) - offset_ib)*gain_b;// amps + current.c = (!_isset(pinC)) ? 0 : (_readADCVoltageLowSide(pinC, params) - offset_ic)*gain_c; // amps + return current; +} + +// Function aligning the current sense with motor driver +// if all pins are connected well none of this is really necessary! - can be avoided +// returns flag +// 0 - fail +// 1 - success and nothing changed +// 2 - success but pins reconfigured +// 3 - success but gains inverted +// 4 - success but pins reconfigured and gains inverted +int LowsideCurrentSense::driverAlign(float voltage){ + + int exit_flag = 1; + if(skip_align) return exit_flag; + + if (!initialized) return 0; + + if(_isset(pinA)){ + // set phase A active and phases B and C down + driver->setPwm(voltage, 0, 0); + _delay(2000); + PhaseCurrent_s c = getPhaseCurrents(); + // read the current 100 times ( arbitrary number ) + for (int i = 0; i < 100; i++) { + PhaseCurrent_s c1 = getPhaseCurrents(); + c.a = c.a*0.6f + 0.4f*c1.a; + c.b = c.b*0.6f + 0.4f*c1.b; + c.c = c.c*0.6f + 0.4f*c1.c; + _delay(3); + } + driver->setPwm(0, 0, 0); + // align phase A + float ab_ratio = c.b ? fabs(c.a / c.b) : 0; + float ac_ratio = c.c ? fabs(c.a / c.c) : 0; + if(_isset(pinB) && ab_ratio > 1.5f ){ // should be ~2 + gain_a *= _sign(c.a); + }else if(_isset(pinC) && ac_ratio > 1.5f ){ // should be ~2 + gain_a *= _sign(c.a); + }else if(_isset(pinB) && ab_ratio < 0.7f ){ // should be ~0.5 + // switch phase A and B + int tmp_pinA = pinA; + pinA = pinB; + pinB = tmp_pinA; + float tmp_offsetA = offset_ia; + offset_ia = offset_ib; + offset_ib = tmp_offsetA; + gain_a *= _sign(c.b); + exit_flag = 2; // signal that pins have been switched + }else if(_isset(pinC) && ac_ratio < 0.7f ){ // should be ~0.5 + // switch phase A and C + int tmp_pinA = pinA; + pinA = pinC; + pinC= tmp_pinA; + float tmp_offsetA = offset_ia; + offset_ia = offset_ic; + offset_ic = tmp_offsetA; + gain_a *= _sign(c.c); + exit_flag = 2;// signal that pins have been switched + }else{ + // error in current sense - phase either not measured or bad connection + return 0; + } + } + + if(_isset(pinB)){ + // set phase B active and phases A and C down + driver->setPwm(0, voltage, 0); + _delay(200); + PhaseCurrent_s c = getPhaseCurrents(); + // read the current 50 times + for (int i = 0; i < 100; i++) { + PhaseCurrent_s c1 = getPhaseCurrents(); + c.a = c.a*0.6 + 0.4f*c1.a; + c.b = c.b*0.6 + 0.4f*c1.b; + c.c = c.c*0.6 + 0.4f*c1.c; + _delay(3); + } + driver->setPwm(0, 0, 0); + float ba_ratio = c.a ? fabs(c.b / c.a) : 0; + float bc_ratio = c.c ? fabs(c.b / c.c) : 0; + if(_isset(pinA) && ba_ratio > 1.5f ){ // should be ~2 + gain_b *= _sign(c.b); + }else if(_isset(pinC) && bc_ratio > 1.5f ){ // should be ~2 + gain_b *= _sign(c.b); + }else if(_isset(pinA) && ba_ratio < 0.7f ){ // it should be ~0.5 + // switch phase A and B + int tmp_pinB = pinB; + pinB = pinA; + pinA = tmp_pinB; + float tmp_offsetB = offset_ib; + offset_ib = offset_ia; + offset_ia = tmp_offsetB; + gain_b *= _sign(c.a); + exit_flag = 2; // signal that pins have been switched + }else if(_isset(pinC) && bc_ratio < 0.7f ){ // should be ~0.5 + // switch phase A and C + int tmp_pinB = pinB; + pinB = pinC; + pinC = tmp_pinB; + float tmp_offsetB = offset_ib; + offset_ib = offset_ic; + offset_ic = tmp_offsetB; + gain_b *= _sign(c.c); + exit_flag = 2; // signal that pins have been switched + }else{ + // error in current sense - phase either not measured or bad connection + return 0; + } + } + + // if phase C measured + if(_isset(pinC)){ + // set phase C active and phases A and B down + driver->setPwm(0, 0, voltage); + _delay(200); + PhaseCurrent_s c = getPhaseCurrents(); + // read the adc voltage 500 times ( arbitrary number ) + for (int i = 0; i < 100; i++) { + PhaseCurrent_s c1 = getPhaseCurrents(); + c.a = c.a*0.6 + 0.4f*c1.a; + c.b = c.b*0.6 + 0.4f*c1.b; + c.c = c.c*0.6 + 0.4f*c1.c; + _delay(3); + } + driver->setPwm(0, 0, 0); + float ca_ratio = c.a ? fabs(c.c / c.a) : 0; + float cb_ratio = c.b ? fabs(c.c / c.b) : 0; + if(_isset(pinA) && ca_ratio > 1.5f ){ // should be ~2 + gain_c *= _sign(c.c); + }else if(_isset(pinB) && cb_ratio > 1.5f ){ // should be ~2 + gain_c *= _sign(c.c); + }else if(_isset(pinA) && ca_ratio < 0.7f ){ // it should be ~0.5 + // switch phase A and C + int tmp_pinC = pinC; + pinC = pinA; + pinA = tmp_pinC; + float tmp_offsetC = offset_ic; + offset_ic = offset_ia; + offset_ia = tmp_offsetC; + gain_c *= _sign(c.a); + exit_flag = 2; // signal that pins have been switched + }else if(_isset(pinB) && cb_ratio < 0.7f ){ // should be ~0.5 + // switch phase B and C + int tmp_pinC = pinC; + pinC = pinB; + pinB = tmp_pinC; + float tmp_offsetC = offset_ic; + offset_ic = offset_ib; + offset_ib = tmp_offsetC; + gain_c *= _sign(c.b); + exit_flag = 2; // signal that pins have been switched + }else{ + // error in current sense - phase either not measured or bad connection + return 0; + } + } + + if(gain_a < 0 || gain_b < 0 || gain_c < 0) exit_flag +=2; + // exit flag is either + // 0 - fail + // 1 - success and nothing changed + // 2 - success but pins reconfigured + // 3 - success but gains inverted + // 4 - success but pins reconfigured and gains inverted + + return exit_flag; +} diff --git a/firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.h b/firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.h new file mode 100644 index 0000000..1652b33 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/LowsideCurrentSense.h @@ -0,0 +1,73 @@ +#ifndef LOWSIDE_CS_LIB_H +#define LOWSIDE_CS_LIB_H + +#include "Arduino.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/defaults.h" +#include "../common/base_classes/CurrentSense.h" +#include "../common/base_classes/FOCMotor.h" +#include "../common/lowpass_filter.h" +#include "hardware_api.h" + + +class LowsideCurrentSense: public CurrentSense{ + public: + /** + LowsideCurrentSense class constructor + @param shunt_resistor shunt resistor value + @param gain current-sense op-amp gain + @param phA A phase adc pin + @param phB B phase adc pin + @param phC C phase adc pin (optional) + */ + LowsideCurrentSense(float shunt_resistor, float gain, int pinA, int pinB, int pinC = _NC); + /** + LowsideCurrentSense class constructor + @param mVpA mV per Amp ratio + @param phA A phase adc pin + @param phB B phase adc pin + @param phC C phase adc pin (optional) + */ + LowsideCurrentSense(float mVpA, int pinA, int pinB, int pinC = _NC); + + // CurrentSense interface implementing functions + int init() override; + PhaseCurrent_s getPhaseCurrents() override; + int driverAlign(float align_voltage) override; + + // ADC measuremnet gain for each phase + // support for different gains for different phases of more commonly - inverted phase currents + // this should be automated later + float gain_a; //!< phase A gain + float gain_b; //!< phase B gain + float gain_c; //!< phase C gain + + // // per phase low pass fileters + // LowPassFilter lpf_a{DEF_LPF_PER_PHASE_CURRENT_SENSE_Tf}; //!< current A low pass filter + // LowPassFilter lpf_b{DEF_LPF_PER_PHASE_CURRENT_SENSE_Tf}; //!< current B low pass filter + // LowPassFilter lpf_c{DEF_LPF_PER_PHASE_CURRENT_SENSE_Tf}; //!< current C low pass filter + + float offset_ia; //!< zero current A voltage value (center of the adc reading) + float offset_ib; //!< zero current B voltage value (center of the adc reading) + float offset_ic; //!< zero current C voltage value (center of the adc reading) + private: + + // hardware variables + int pinA; //!< pin A analog pin for current measurement + int pinB; //!< pin B analog pin for current measurement + int pinC; //!< pin C analog pin for current measurement + + // gain variables + float shunt_resistor; //!< Shunt resistor value + float amp_gain; //!< amp gain value + float volts_to_amps_ratio; //!< Volts to amps ratio + + /** + * Function finding zero offsets of the ADC + */ + void calibrateOffsets(); + +}; + +#endif diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_api.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_api.h new file mode 100644 index 0000000..b9e3be0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_api.h @@ -0,0 +1,65 @@ +#ifndef HARDWARE_UTILS_CURRENT_H +#define HARDWARE_UTILS_CURRENT_H + +#include "../common/foc_utils.h" +#include "../common/time_utils.h" + +// flag returned if current sense init fails +#define SIMPLEFOC_CURRENT_SENSE_INIT_FAILED ((void*)-1) + +// generic implementation of the hardware specific structure +// containing all the necessary current sense parameters +// will be returned as a void pointer from the _configureADCx functions +// will be provided to the _readADCVoltageX() as a void pointer +typedef struct GenericCurrentSenseParams { + int pins[3]; + float adc_voltage_conv; +} GenericCurrentSenseParams; + + +/** + * function reading an ADC value and returning the read voltage + * + * @param pinA - the arduino pin to be read (it has to be ADC pin) + * @param cs_params -current sense parameter structure - hardware specific + */ +float _readADCVoltageInline(const int pinA, const void* cs_params); + +/** + * function configuring an ADC for inline sensing. + * + * @param driver_params - driver parameter structure - hardware specific + * @param pinA - adc pin A + * @param pinB - adc pin B + * @param pinC - adc pin C + */ +void* _configureADCInline(const void *driver_params, const int pinA,const int pinB,const int pinC = NOT_SET); + +/** + * function configuring an ADC for lowside sensing. + * + * @param driver_params - driver parameter structure - hardware specific + * @param pinA - adc pin A + * @param pinB - adc pin B + * @param pinC - adc pin C + */ +void* _configureADCLowSide(const void *driver_params, const int pinA,const int pinB,const int pinC = NOT_SET); + +void _startADC3PinConversionLowSide(); + +/** + * function reading an ADC value and returning the read voltage + * + * @param pinA - the arduino pin to be read (it has to be ADC pin) + * @param cs_params -current sense parameter structure - hardware specific + */ +float _readADCVoltageLowSide(const int pinA, const void* cs_params); + +/** + * function syncing the Driver with the ADC for the LowSide Sensing + * @param driver_params - driver parameter structure - hardware specific + * @param cs_params - current sense parameter structure - hardware specific + */ +void _driverSyncLowSide(void* driver_params, void* cs_params); + +#endif diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/atmega_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/atmega_mcu.cpp new file mode 100644 index 0000000..50ae596 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/atmega_mcu.cpp @@ -0,0 +1,40 @@ +#include "../hardware_api.h" + +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328PB__) + +#define _ADC_VOLTAGE 5.0f +#define _ADC_RESOLUTION 1024.0f + +#ifndef cbi + #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) +#endif +#ifndef sbi + #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) +#endif + +// function reading an ADC value and returning the read voltage +void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + + GenericCurrentSenseParams* params = new GenericCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION) + }; + + // set hight frequency adc - ADPS2,ADPS1,ADPS0 | 001 (16mhz/2) | 010 ( 16mhz/4 ) | 011 (16mhz/8) | 100(16mhz/16) | 101 (16mhz/32) | 110 (16mhz/64) | 111 (16mhz/128 default) + // set divisor to 8 - adc frequency 16mhz/8 = 2 mhz + // arduino takes 25 conversions per sample so - 2mhz/25 = 80k samples per second - 12.5us per sample + cbi(ADCSRA, ADPS2); + sbi(ADCSRA, ADPS1); + sbi(ADCSRA, ADPS0); + + return params; +} + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/due_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/due_mcu.cpp new file mode 100644 index 0000000..ce58cd9 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/due_mcu.cpp @@ -0,0 +1,27 @@ +#include "../hardware_api.h" + +#if defined(__arm__) && defined(__SAM3X8E__) + +#define _ADC_VOLTAGE 3.3f +#define _ADC_RESOLUTION 1024.0f + + +// function reading an ADC value and returning the read voltage +void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + GenericCurrentSenseParams* params = new GenericCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION) + }; + + return params; +} + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.cpp new file mode 100644 index 0000000..807c387 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.cpp @@ -0,0 +1,259 @@ +#include "esp32_adc_driver.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && defined(SOC_MCPWM_SUPPORTED) && !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32S3) + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "rom/ets_sys.h" +#include "esp_attr.h" +#include "esp_intr.h" +#include "soc/rtc_io_reg.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/sens_reg.h" + +static uint8_t __analogAttenuation = 3;//11db +static uint8_t __analogWidth = 3;//12 bits +static uint8_t __analogCycles = 8; +static uint8_t __analogSamples = 0;//1 sample +static uint8_t __analogClockDiv = 1; + +// Width of returned answer () +static uint8_t __analogReturnedWidth = 12; + +void __analogSetWidth(uint8_t bits){ + if(bits < 9){ + bits = 9; + } else if(bits > 12){ + bits = 12; + } + __analogReturnedWidth = bits; + __analogWidth = bits - 9; + SET_PERI_REG_BITS(SENS_SAR_START_FORCE_REG, SENS_SAR1_BIT_WIDTH, __analogWidth, SENS_SAR1_BIT_WIDTH_S); + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_SAMPLE_BIT, __analogWidth, SENS_SAR1_SAMPLE_BIT_S); + + SET_PERI_REG_BITS(SENS_SAR_START_FORCE_REG, SENS_SAR2_BIT_WIDTH, __analogWidth, SENS_SAR2_BIT_WIDTH_S); + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_SAMPLE_BIT, __analogWidth, SENS_SAR2_SAMPLE_BIT_S); +} + +void __analogSetCycles(uint8_t cycles){ + __analogCycles = cycles; + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_SAMPLE_CYCLE, __analogCycles, SENS_SAR1_SAMPLE_CYCLE_S); + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_SAMPLE_CYCLE, __analogCycles, SENS_SAR2_SAMPLE_CYCLE_S); +} + +void __analogSetSamples(uint8_t samples){ + if(!samples){ + return; + } + __analogSamples = samples - 1; + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_SAMPLE_NUM, __analogSamples, SENS_SAR1_SAMPLE_NUM_S); + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_SAMPLE_NUM, __analogSamples, SENS_SAR2_SAMPLE_NUM_S); +} + +void __analogSetClockDiv(uint8_t clockDiv){ + if(!clockDiv){ + return; + } + __analogClockDiv = clockDiv; + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_CLK_DIV, __analogClockDiv, SENS_SAR1_CLK_DIV_S); + SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_CLK_DIV, __analogClockDiv, SENS_SAR2_CLK_DIV_S); +} + +void __analogSetAttenuation(uint8_t attenuation) +{ + __analogAttenuation = attenuation & 3; + uint32_t att_data = 0; + int i = 10; + while(i--){ + att_data |= __analogAttenuation << (i * 2); + } + WRITE_PERI_REG(SENS_SAR_ATTEN1_REG, att_data & 0xFFFF);//ADC1 has 8 channels + WRITE_PERI_REG(SENS_SAR_ATTEN2_REG, att_data); +} + +void IRAM_ATTR __analogInit(){ + static bool initialized = false; + if(initialized){ + return; + } + + __analogSetAttenuation(__analogAttenuation); + __analogSetCycles(__analogCycles); + __analogSetSamples(__analogSamples + 1);//in samples + __analogSetClockDiv(__analogClockDiv); + __analogSetWidth(__analogWidth + 9);//in bits + + SET_PERI_REG_MASK(SENS_SAR_READ_CTRL_REG, SENS_SAR1_DATA_INV); + SET_PERI_REG_MASK(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_DATA_INV); + + SET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_FORCE_M); //SAR ADC1 controller (in RTC) is started by SW + SET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_SAR1_EN_PAD_FORCE_M); //SAR ADC1 pad enable bitmap is controlled by SW + SET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_FORCE_M); //SAR ADC2 controller (in RTC) is started by SW + SET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_SAR2_EN_PAD_FORCE_M); //SAR ADC2 pad enable bitmap is controlled by SW + + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_SAR_M); //force XPD_SAR=0, use XPD_FSM + SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_AMP, 0x2, SENS_FORCE_XPD_AMP_S); //force XPD_AMP=0 + + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_CTRL_REG, 0xfff << SENS_AMP_RST_FB_FSM_S); //clear FSM + SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT1_REG, SENS_SAR_AMP_WAIT1, 0x1, SENS_SAR_AMP_WAIT1_S); + SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT1_REG, SENS_SAR_AMP_WAIT2, 0x1, SENS_SAR_AMP_WAIT2_S); + SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT2_REG, SENS_SAR_AMP_WAIT3, 0x1, SENS_SAR_AMP_WAIT3_S); + while (GET_PERI_REG_BITS2(SENS_SAR_SLAVE_ADDR1_REG, 0x7, SENS_MEAS_STATUS_S) != 0); //wait det_fsm== + + initialized = true; +} + +void __analogSetPinAttenuation(uint8_t pin, uint8_t attenuation) +{ + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0 || attenuation > 3){ + return ; + } + __analogInit(); + if(channel > 7){ + SET_PERI_REG_BITS(SENS_SAR_ATTEN2_REG, 3, attenuation, ((channel - 10) * 2)); + } else { + SET_PERI_REG_BITS(SENS_SAR_ATTEN1_REG, 3, attenuation, (channel * 2)); + } +} + +bool IRAM_ATTR __adcAttachPin(uint8_t pin){ + + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + int8_t pad = digitalPinToTouchChannel(pin); + if(pad >= 0){ + uint32_t touch = READ_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG); + if(touch & (1 << pad)){ + touch &= ~((1 << (pad + SENS_TOUCH_PAD_OUTEN2_S)) + | (1 << (pad + SENS_TOUCH_PAD_OUTEN1_S)) + | (1 << (pad + SENS_TOUCH_PAD_WORKEN_S))); + WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG, touch); + } + } else if(pin == 25){ + CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE); //stop dac1 + } else if(pin == 26){ + CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_XPD_DAC | RTC_IO_PDAC2_DAC_XPD_FORCE); //stop dac2 + } + + pinMode(pin, ANALOG); + + __analogInit(); + return true; +} + +bool IRAM_ATTR __adcStart(uint8_t pin){ + + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + if(channel > 9){ + channel -= 10; + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS_START2_REG, SENS_SAR2_EN_PAD, (1 << channel), SENS_SAR2_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_SAR_M); + } else { + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS_START1_REG, SENS_SAR1_EN_PAD, (1 << channel), SENS_SAR1_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_SAR_M); + } + return true; +} + +bool IRAM_ATTR __adcBusy(uint8_t pin){ + + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + if(channel > 7){ + return (GET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DONE_SAR) == 0); + } + return (GET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DONE_SAR) == 0); +} + +uint16_t IRAM_ATTR __adcEnd(uint8_t pin) +{ + + uint16_t value = 0; + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return 0;//not adc pin + } + if(channel > 7){ + while (GET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DATA_SAR, SENS_MEAS2_DATA_SAR_S); + } else { + while (GET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DATA_SAR, SENS_MEAS1_DATA_SAR_S); + } + + // Shift result if necessary + uint8_t from = __analogWidth + 9; + if (from == __analogReturnedWidth) { + return value; + } + if (from > __analogReturnedWidth) { + return value >> (from - __analogReturnedWidth); + } + return value << (__analogReturnedWidth - from); +} + +void __analogReadResolution(uint8_t bits) +{ + if(!bits || bits > 16){ + return; + } + __analogSetWidth(bits); // hadware from 9 to 12 + __analogReturnedWidth = bits; // software from 1 to 16 +} + +uint16_t IRAM_ATTR adcRead(uint8_t pin) +{ + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + __analogInit(); + + if(channel > 9){ + channel -= 10; + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS_START2_REG, SENS_SAR2_EN_PAD, (1 << channel), SENS_SAR2_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_SAR_M); + } else { + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS_START1_REG, SENS_SAR1_EN_PAD, (1 << channel), SENS_SAR1_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_SAR_M); + } + + uint16_t value = 0; + + if(channel > 7){ + while (GET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DATA_SAR, SENS_MEAS2_DATA_SAR_S); + } else { + while (GET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DATA_SAR, SENS_MEAS1_DATA_SAR_S); + } + + // Shift result if necessary + uint8_t from = __analogWidth + 9; + if (from == __analogReturnedWidth) { + return value; + } + if (from > __analogReturnedWidth) { + return value >> (from - __analogReturnedWidth); + } + return value << (__analogReturnedWidth - from); +} + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.h new file mode 100644 index 0000000..869c4dd --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_adc_driver.h @@ -0,0 +1,88 @@ + + +#ifndef SIMPLEFOC_ESP32_HAL_ADC_DRIVER_H_ +#define SIMPLEFOC_ESP32_HAL_ADC_DRIVER_H_ + +#include "Arduino.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && defined(SOC_MCPWM_SUPPORTED) +/* + * Get ADC value for pin + * */ +uint16_t adcRead(uint8_t pin); + +/* + * Set the resolution of analogRead return values. Default is 12 bits (range from 0 to 4096). + * If between 9 and 12, it will equal the set hardware resolution, else value will be shifted. + * Range is 1 - 16 + * + * Note: compatibility with Arduino SAM + */ +void __analogReadResolution(uint8_t bits); + +/* + * Sets the sample bits and read resolution + * Default is 12bit (0 - 4095) + * Range is 9 - 12 + * */ +void __analogSetWidth(uint8_t bits); + +/* + * Set number of cycles per sample + * Default is 8 and seems to do well + * Range is 1 - 255 + * */ +void __analogSetCycles(uint8_t cycles); + +/* + * Set number of samples in the range. + * Default is 1 + * Range is 1 - 255 + * This setting splits the range into + * "samples" pieces, which could look + * like the sensitivity has been multiplied + * that many times + * */ +void __analogSetSamples(uint8_t samples); + +/* + * Set the divider for the ADC clock. + * Default is 1 + * Range is 1 - 255 + * */ +void __analogSetClockDiv(uint8_t clockDiv); + +/* + * Set the attenuation for all channels + * Default is 11db + * */ +void __analogSetAttenuation(uint8_t attenuation); + +/* + * Set the attenuation for particular pin + * Default is 11db + * */ +void __analogSetPinAttenuation(uint8_t pin, uint8_t attenuation); + +/* + * Attach pin to ADC (will also clear any other analog mode that could be on) + * */ +bool __adcAttachPin(uint8_t pin); + +/* + * Start ADC conversion on attached pin's bus + * */ +bool __adcStart(uint8_t pin); + +/* + * Check if conversion on the pin's ADC bus is currently running + * */ +bool __adcBusy(uint8_t pin); + +/* + * Get the result of the conversion (will wait if it have not finished) + * */ +uint16_t __adcEnd(uint8_t pin); + +#endif /* SIMPLEFOC_ESP32_HAL_ADC_DRIVER_H_ */ +#endif /* ESP32 */ \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_ledc_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_ledc_mcu.cpp new file mode 100644 index 0000000..f2d65f8 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_ledc_mcu.cpp @@ -0,0 +1,27 @@ +#include "../../hardware_api.h" +#include "../../../drivers/hardware_api.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && !defined(SOC_MCPWM_SUPPORTED) + +#include "esp32_adc_driver.h" + +#define _ADC_VOLTAGE 3.3f +#define _ADC_RESOLUTION 4095.0f + +// function reading an ADC value and returning the read voltage +void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + pinMode(pinA, INPUT); + pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + GenericCurrentSenseParams* params = new GenericCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION) + }; + + return params; +} + +#endif diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_mcu.cpp new file mode 100644 index 0000000..3df9dff --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32_mcu.cpp @@ -0,0 +1,162 @@ +#include "../../hardware_api.h" +#include "../../../drivers/hardware_api.h" +#include "../../../drivers/hardware_specific/esp32/esp32_driver_mcpwm.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && defined(SOC_MCPWM_SUPPORTED) && !defined(SIMPLEFOC_ESP32_USELEDC) + +#include "esp32_adc_driver.h" + +#include "driver/mcpwm.h" +#include "soc/mcpwm_reg.h" +#include "soc/mcpwm_struct.h" + +#include +#include + +#define _ADC_VOLTAGE 3.3f +#define _ADC_RESOLUTION 4095.0f + + +typedef struct ESP32MCPWMCurrentSenseParams { + int pins[3]; + float adc_voltage_conv; + mcpwm_unit_t mcpwm_unit; + int buffer_index; +} ESP32MCPWMCurrentSenseParams; + + +/** + * Inline adc reading implementation +*/ +// function reading an ADC value and returning the read voltage +float _readADCVoltageInline(const int pinA, const void* cs_params){ + uint32_t raw_adc = adcRead(pinA); + return raw_adc * ((ESP32MCPWMCurrentSenseParams*)cs_params)->adc_voltage_conv; +} + +// function reading an ADC value and returning the read voltage +void* _configureADCInline(const void* driver_params, const int pinA, const int pinB, const int pinC){ + _UNUSED(driver_params); + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + ESP32MCPWMCurrentSenseParams* params = new ESP32MCPWMCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION) + }; + + return params; +} + + + +/** + * Low side adc reading implementation +*/ + +static void IRAM_ATTR mcpwm0_isr_handler(void*); +static void IRAM_ATTR mcpwm1_isr_handler(void*); +byte currentState = 1; +// two mcpwm units +// - max 2 motors per mcpwm unit (6 adc channels) +int adc_pins[2][6]={0}; +int adc_pin_count[2]={0}; +uint32_t adc_buffer[2][6]={0}; +int adc_read_index[2]={0}; + +// function reading an ADC value and returning the read voltage +float _readADCVoltageLowSide(const int pin, const void* cs_params){ + mcpwm_unit_t unit = ((ESP32MCPWMCurrentSenseParams*)cs_params)->mcpwm_unit; + int buffer_index = ((ESP32MCPWMCurrentSenseParams*)cs_params)->buffer_index; + float adc_voltage_conv = ((ESP32MCPWMCurrentSenseParams*)cs_params)->adc_voltage_conv; + + for(int i=0; i < adc_pin_count[unit]; i++){ + if( pin == ((ESP32MCPWMCurrentSenseParams*)cs_params)->pins[i]) // found in the buffer + return adc_buffer[unit][buffer_index + i] * adc_voltage_conv; + } + // not found + return 0; +} + +// function configuring low-side current sensing +void* _configureADCLowSide(const void* driver_params, const int pinA,const int pinB,const int pinC){ + + mcpwm_unit_t unit = ((ESP32MCPWMDriverParams*)driver_params)->mcpwm_unit; + int index_start = adc_pin_count[unit]; + if( _isset(pinA) ) adc_pins[unit][adc_pin_count[unit]++] = pinA; + if( _isset(pinB) ) adc_pins[unit][adc_pin_count[unit]++] = pinB; + if( _isset(pinC) ) adc_pins[unit][adc_pin_count[unit]++] = pinC; + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + ESP32MCPWMCurrentSenseParams* params = new ESP32MCPWMCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION), + .mcpwm_unit = unit, + .buffer_index = index_start + }; + + return params; +} + + +void _driverSyncLowSide(void* driver_params, void* cs_params){ + + mcpwm_dev_t* mcpwm_dev = ((ESP32MCPWMDriverParams*)driver_params)->mcpwm_dev; + mcpwm_unit_t mcpwm_unit = ((ESP32MCPWMDriverParams*)driver_params)->mcpwm_unit; + + // low-side register enable interrupt + mcpwm_dev->int_ena.timer0_tep_int_ena = true;//A PWM timer 0 TEP event will trigger this interrupt + // high side registers enable interrupt + //mcpwm_dev->int_ena.timer0_tep_int_ena = true;//A PWM timer 0 TEZ event will trigger this interrupt + + // register interrupts (mcpwm number, interrupt handler, handler argument = NULL, interrupt signal/flag, return handler = NULL) + if(mcpwm_unit == MCPWM_UNIT_0) + mcpwm_isr_register(mcpwm_unit, mcpwm0_isr_handler, NULL, ESP_INTR_FLAG_IRAM, NULL); //Set ISR Handler + else + mcpwm_isr_register(mcpwm_unit, mcpwm1_isr_handler, NULL, ESP_INTR_FLAG_IRAM, NULL); //Set ISR Handler +} + +// Read currents when interrupt is triggered +static void IRAM_ATTR mcpwm0_isr_handler(void*){ + // // high side + // uint32_t mcpwm_intr_status = MCPWM0.int_st.timer0_tez_int_st; + + // low side + uint32_t mcpwm_intr_status = MCPWM0.int_st.timer0_tep_int_st; + if(mcpwm_intr_status){ + adc_buffer[0][adc_read_index[0]] = adcRead(adc_pins[0][adc_read_index[0]]); + adc_read_index[0]++; + if(adc_read_index[0] == adc_pin_count[0]) adc_read_index[0] = 0; + } + // low side + MCPWM0.int_clr.timer0_tep_int_clr = mcpwm_intr_status; + // high side + // MCPWM0.int_clr.timer0_tez_int_clr = mcpwm_intr_status_0; +} + + +// Read currents when interrupt is triggered +static void IRAM_ATTR mcpwm1_isr_handler(void*){ + // // high side + // uint32_t mcpwm_intr_status = MCPWM1.int_st.timer0_tez_int_st; + + // low side + uint32_t mcpwm_intr_status = MCPWM1.int_st.timer0_tep_int_st; + if(mcpwm_intr_status){ + adc_buffer[1][adc_read_index[1]] = adcRead(adc_pins[1][adc_read_index[1]]); + adc_read_index[1]++; + if(adc_read_index[1] == adc_pin_count[1]) adc_read_index[1] = 0; + } + // low side + MCPWM1.int_clr.timer0_tep_int_clr = mcpwm_intr_status; + // high side + // MCPWM1.int_clr.timer0_tez_int_clr = mcpwm_intr_status_0; +} + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32s_adc_driver.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32s_adc_driver.cpp new file mode 100644 index 0000000..a2f58ac --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/esp32/esp32s_adc_driver.cpp @@ -0,0 +1,258 @@ +#include "esp32_adc_driver.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && defined(SOC_MCPWM_SUPPORTED) && (defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3)) + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "rom/ets_sys.h" +#include "esp_attr.h" +//#include "esp_intr.h" // deprecated +#include "esp_intr_alloc.h" +#include "soc/rtc_io_reg.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/sens_reg.h" + +static uint8_t __analogAttenuation = 3;//11db +static uint8_t __analogWidth = 3;//12 bits +static uint8_t __analogCycles = 8; +static uint8_t __analogSamples = 0;//1 sample +static uint8_t __analogClockDiv = 1; + +// Width of returned answer () +static uint8_t __analogReturnedWidth = 12; + +void __analogSetWidth(uint8_t bits){ + if(bits < 9){ + bits = 9; + } else if(bits > 12){ + bits = 12; + } + __analogReturnedWidth = bits; + __analogWidth = bits - 9; + // SET_PERI_REG_BITS(SENS_SAR_START_FORCE_REG, SENS_SAR1_BIT_WIDTH, __analogWidth, SENS_SAR1_BIT_WIDTH_S); + // SET_PERI_REG_BITS(SENS_SAR_READER1_CTRL_REG, SENS_SAR1_SAMPLE_BIT, __analogWidth, SENS_SAR1_SAMPLE_BIT_S); + + // SET_PERI_REG_BITS(SENS_SAR_START_FORCE_REG, SENS_SAR2_BIT_WIDTH, __analogWidth, SENS_SAR2_BIT_WIDTH_S); + // SET_PERI_REG_BITS(SENS_SAR_READER2_CTRL_REG, SENS_SAR2_SAMPLE_BIT, __analogWidth, SENS_SAR2_SAMPLE_BIT_S); +} + +void __analogSetCycles(uint8_t cycles){ + __analogCycles = cycles; + // SET_PERI_REG_BITS(SENS_SAR_READER1_CTRL_REG, SENS_SAR1_SAMPLE_CYCLE, __analogCycles, SENS_SAR1_SAMPLE_CYCLE_S); + // SET_PERI_REG_BITS(SENS_SAR_READER2_CTRL_REG, SENS_SAR2_SAMPLE_CYCLE, __analogCycles, SENS_SAR2_SAMPLE_CYCLE_S); +} + +void __analogSetSamples(uint8_t samples){ + if(!samples){ + return; + } + __analogSamples = samples - 1; + SET_PERI_REG_BITS(SENS_SAR_READER1_CTRL_REG, SENS_SAR1_SAMPLE_NUM, __analogSamples, SENS_SAR1_SAMPLE_NUM_S); + SET_PERI_REG_BITS(SENS_SAR_READER2_CTRL_REG, SENS_SAR2_SAMPLE_NUM, __analogSamples, SENS_SAR2_SAMPLE_NUM_S); +} + +void __analogSetClockDiv(uint8_t clockDiv){ + if(!clockDiv){ + return; + } + __analogClockDiv = clockDiv; + SET_PERI_REG_BITS(SENS_SAR_READER1_CTRL_REG, SENS_SAR1_CLK_DIV, __analogClockDiv, SENS_SAR1_CLK_DIV_S); + SET_PERI_REG_BITS(SENS_SAR_READER2_CTRL_REG, SENS_SAR2_CLK_DIV, __analogClockDiv, SENS_SAR2_CLK_DIV_S); +} + +void __analogSetAttenuation(uint8_t attenuation) +{ + __analogAttenuation = attenuation & 3; + uint32_t att_data = 0; + int i = 10; + while(i--){ + att_data |= __analogAttenuation << (i * 2); + } + WRITE_PERI_REG(SENS_SAR_ATTEN1_REG, att_data & 0xFFFF);//ADC1 has 8 channels + WRITE_PERI_REG(SENS_SAR_ATTEN2_REG, att_data); +} + +void IRAM_ATTR __analogInit(){ + static bool initialized = false; + if(initialized){ + return; + } + + __analogSetAttenuation(__analogAttenuation); + __analogSetCycles(__analogCycles); + __analogSetSamples(__analogSamples + 1);//in samples + __analogSetClockDiv(__analogClockDiv); + __analogSetWidth(__analogWidth + 9);//in bits + + SET_PERI_REG_MASK(SENS_SAR_READER1_CTRL_REG, SENS_SAR1_DATA_INV); + SET_PERI_REG_MASK(SENS_SAR_READER2_CTRL_REG, SENS_SAR2_DATA_INV); + + SET_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_START_FORCE_M); //SAR ADC1 controller (in RTC) is started by SW + SET_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_SAR1_EN_PAD_FORCE_M); //SAR ADC1 pad enable bitmap is controlled by SW + SET_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_START_FORCE_M); //SAR ADC2 controller (in RTC) is started by SW + SET_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_SAR2_EN_PAD_FORCE_M); //SAR ADC2 pad enable bitmap is controlled by SW + + CLEAR_PERI_REG_MASK(SENS_SAR_POWER_XPD_SAR_REG, SENS_FORCE_XPD_SAR_M); //force XPD_SAR=0, use XPD_FSM + SET_PERI_REG_BITS(SENS_SAR_POWER_XPD_SAR_REG, SENS_FORCE_XPD_AMP, 0x2, SENS_FORCE_XPD_AMP_S); //force XPD_AMP=0 + + CLEAR_PERI_REG_MASK(SENS_SAR_AMP_CTRL3_REG, 0xfff << SENS_AMP_RST_FB_FSM_S); //clear FSM + SET_PERI_REG_BITS(SENS_SAR_AMP_CTRL1_REG, SENS_SAR_AMP_WAIT1, 0x1, SENS_SAR_AMP_WAIT1_S); + SET_PERI_REG_BITS(SENS_SAR_AMP_CTRL1_REG, SENS_SAR_AMP_WAIT2, 0x1, SENS_SAR_AMP_WAIT2_S); + SET_PERI_REG_BITS(SENS_SAR_POWER_XPD_SAR_REG, SENS_SAR_AMP_WAIT3, 0x1, SENS_SAR_AMP_WAIT3_S); + while (GET_PERI_REG_BITS2(SENS_SAR_SLAVE_ADDR1_REG, 0x7, SENS_SARADC_MEAS_STATUS_S) != 0); //wait det_fsm== + + initialized = true; +} + +void __analogSetPinAttenuation(uint8_t pin, uint8_t attenuation) +{ + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0 || attenuation > 3){ + return ; + } + __analogInit(); + if(channel > 7){ + SET_PERI_REG_BITS(SENS_SAR_ATTEN2_REG, 3, attenuation, ((channel - 10) * 2)); + } else { + SET_PERI_REG_BITS(SENS_SAR_ATTEN1_REG, 3, attenuation, (channel * 2)); + } +} + +bool IRAM_ATTR __adcAttachPin(uint8_t pin){ + + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + int8_t pad = digitalPinToTouchChannel(pin); + if(pad >= 0){ + uint32_t touch = READ_PERI_REG(SENS_SAR_TOUCH_CONF_REG); + if(touch & (1 << pad)){ + touch &= ~((1 << (pad + SENS_TOUCH_OUTEN_S))); + WRITE_PERI_REG(SENS_SAR_TOUCH_CONF_REG, touch); + } + } else if(pin == 25){ + CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE); //stop dac1 + } else if(pin == 26){ + CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_XPD_DAC | RTC_IO_PDAC2_DAC_XPD_FORCE); //stop dac2 + } + + pinMode(pin, ANALOG); + + __analogInit(); + return true; +} + +bool IRAM_ATTR __adcStart(uint8_t pin){ + + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + if(channel > 9){ + channel -= 10; + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS2_CTRL2_REG, SENS_SAR2_EN_PAD, (1 << channel), SENS_SAR2_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_START_SAR_M); + } else { + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS1_CTRL2_REG, SENS_SAR1_EN_PAD, (1 << channel), SENS_SAR1_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_START_SAR_M); + } + return true; +} + +bool IRAM_ATTR __adcBusy(uint8_t pin){ + + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + if(channel > 7){ + return (GET_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_DONE_SAR) == 0); + } + return (GET_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_DONE_SAR) == 0); +} + +uint16_t IRAM_ATTR __adcEnd(uint8_t pin) +{ + + uint16_t value = 0; + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return 0;//not adc pin + } + if(channel > 7){ + while (GET_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_DATA_SAR, SENS_MEAS2_DATA_SAR_S); + } else { + while (GET_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_DATA_SAR, SENS_MEAS1_DATA_SAR_S); + } + + // Shift result if necessary + uint8_t from = __analogWidth + 9; + if (from == __analogReturnedWidth) { + return value; + } + if (from > __analogReturnedWidth) { + return value >> (from - __analogReturnedWidth); + } + return value << (__analogReturnedWidth - from); +} + +void __analogReadResolution(uint8_t bits) +{ + if(!bits || bits > 16){ + return; + } + __analogSetWidth(bits); // hadware from 9 to 12 + __analogReturnedWidth = bits; // software from 1 to 16 +} + +uint16_t IRAM_ATTR adcRead(uint8_t pin) +{ + int8_t channel = digitalPinToAnalogChannel(pin); + if(channel < 0){ + return false;//not adc pin + } + + __analogInit(); + + if(channel > 9){ + channel -= 10; + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS2_CTRL2_REG, SENS_SAR2_EN_PAD, (1 << channel), SENS_SAR2_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_START_SAR_M); + } else { + CLEAR_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_START_SAR_M); + SET_PERI_REG_BITS(SENS_SAR_MEAS1_CTRL2_REG, SENS_SAR1_EN_PAD, (1 << channel), SENS_SAR1_EN_PAD_S); + SET_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_START_SAR_M); + } + + uint16_t value = 0; + + if(channel > 7){ + while (GET_PERI_REG_MASK(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS2_CTRL2_REG, SENS_MEAS2_DATA_SAR, SENS_MEAS2_DATA_SAR_S); + } else { + while (GET_PERI_REG_MASK(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_DONE_SAR) == 0); //wait for conversion + value = GET_PERI_REG_BITS2(SENS_SAR_MEAS1_CTRL2_REG, SENS_MEAS1_DATA_SAR, SENS_MEAS1_DATA_SAR_S); + } + + // Shift result if necessary + uint8_t from = __analogWidth + 9; + if (from == __analogReturnedWidth) { + return value; + } + if (from > __analogReturnedWidth) { + return value >> (from - __analogReturnedWidth); + } + return value << (__analogReturnedWidth - from); +} + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/generic_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/generic_mcu.cpp new file mode 100644 index 0000000..dec7205 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/generic_mcu.cpp @@ -0,0 +1,41 @@ +#include "../hardware_api.h" + +// function reading an ADC value and returning the read voltage +__attribute__((weak)) float _readADCVoltageInline(const int pinA, const void* cs_params){ + uint32_t raw_adc = analogRead(pinA); + return raw_adc * ((GenericCurrentSenseParams*)cs_params)->adc_voltage_conv; +} + +// function reading an ADC value and returning the read voltage +__attribute__((weak)) void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + GenericCurrentSenseParams* params = new GenericCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (5.0f)/(1024.0f) + }; + + return params; +} + +// function reading an ADC value and returning the read voltage +__attribute__((weak)) float _readADCVoltageLowSide(const int pinA, const void* cs_params){ + return _readADCVoltageInline(pinA, cs_params); +} + +// Configure low side for generic mcu +// cannot do much but +__attribute__((weak)) void* _configureADCLowSide(const void* driver_params, const int pinA,const int pinB,const int pinC){ + return _configureADCInline(driver_params, pinA, pinB, pinC); +} + +// sync driver and the adc +__attribute__((weak)) void _driverSyncLowSide(void* driver_params, void* cs_params){ + _UNUSED(driver_params); + _UNUSED(cs_params); +} +__attribute__((weak)) void _startADC3PinConversionLowSide(){ } diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.cpp new file mode 100644 index 0000000..d84c2fd --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.cpp @@ -0,0 +1,265 @@ + +#if defined(TARGET_RP2040) + + +#include "../../hardware_api.h" +#include "./rp2040_mcu.h" +#include "../../../drivers/hardware_specific/rp2040/rp2040_mcu.h" +#include "communication/SimpleFOCDebug.h" + +#include "hardware/dma.h" +#include "hardware/irq.h" +#include "hardware/pwm.h" +#include "hardware/adc.h" + + +/* Singleton instance of the ADC engine */ +RP2040ADCEngine engine; + +alignas(32) const uint32_t trigger_value = ADC_CS_START_ONCE_BITS; // start once + +/* Hardware API implementation */ + +float _readADCVoltageInline(const int pinA, const void* cs_params) { + // not super-happy with this. Here we have to return 1 phase current at a time, when actually we want to + // return readings from the same ADC conversion run. The ADC on RP2040 is anyway in round robin mode :-( + // like this we either have to block interrupts, or of course have the chance of reading across + // new ADC conversions, which probably won't improve the accuracy. + _UNUSED(cs_params); + + if (pinA>=26 && pinA<=29 && engine.channelsEnabled[pinA-26]) { + return engine.lastResults.raw[pinA-26]*engine.adc_conv; + } + + // otherwise return NaN + return NAN; +}; + + +void* _configureADCInline(const void *driver_params, const int pinA, const int pinB, const int pinC) { + _UNUSED(driver_params); + + if( _isset(pinA) ) + engine.addPin(pinA); + if( _isset(pinB) ) + engine.addPin(pinB); + if( _isset(pinC) ) + engine.addPin(pinC); + engine.init(); // TODO this has to happen later if we want to support more than one motor... + engine.start(); + return &engine; +}; + + +// not supported at the moment +// void* _configureADCLowSide(const void *driver_params, const int pinA, const int pinB, const int pinC) { +// if( _isset(pinA) ) +// engine.addPin(pinA); +// if( _isset(pinB) ) +// engine.addPin(pinB); +// if( _isset(pinC) ) +// engine.addPin(pinC); +// engine.setPWMTrigger(((RP2040DriverParams*)driver_params)->slice[0]); +// engine.init(); +// engine.start(); +// return &engine; +// }; + + +// void _startADC3PinConversionLowSide() { +// // what is this for? +// }; + + +// float _readADCVoltageLowSide(const int pinA, const void* cs_params) { +// // not super-happy with this. Here we have to return 1 phase current at a time, when actually we want to +// // return readings from the same ADC conversion run. The ADC on RP2040 is anyway in round robin mode :-( +// // like this we have block interrupts 3x instead of just once, and of course have the chance of reading across +// // new ADC conversions, which probably won't improve the accuracy. + +// if (pinA>=26 && pinA<=29 && engine.channelsEnabled[pinA-26]) { +// return engine.lastResults[pinA-26]*engine.adc_conv; +// } + +// // otherwise return NaN +// return NAN; +// }; + + +// void _driverSyncLowSide(void* driver_params, void* cs_params) { +// // nothing to do +// }; + + + +volatile int rp2040_intcount = 0; + +void _adcConversionFinishedHandler() { + // conversion of all channels finished. copy results. + volatile uint8_t* from = engine.samples; + if (engine.channelsEnabled[0]) + engine.lastResults.raw[0] = (*from++); + if (engine.channelsEnabled[1]) + engine.lastResults.raw[1] = (*from++); + if (engine.channelsEnabled[2]) + engine.lastResults.raw[2] = (*from++); + if (engine.channelsEnabled[3]) + engine.lastResults.raw[3] = (*from++); + //dma_channel_acknowledge_irq0(engine.readDMAChannel); + dma_hw->ints0 = 1u << engine.readDMAChannel; + //dma_start_channel_mask( (1u << engine.readDMAChannel) ); + dma_channel_set_write_addr(engine.readDMAChannel, engine.samples, true); + // if (engine.triggerPWMSlice>=0) + // dma_channel_set_trans_count(engine.triggerDMAChannel, 1, true); + rp2040_intcount++; +}; + + + +/* ADC engine implementation */ + + +RP2040ADCEngine::RP2040ADCEngine() { + channelsEnabled[0] = false; + channelsEnabled[1] = false; + channelsEnabled[2] = false; + channelsEnabled[3] = false; + initialized = false; +}; + + + +void RP2040ADCEngine::addPin(int pin) { + if (pin>=26 && pin<=29) + channelsEnabled[pin-26] = true; + else + SIMPLEFOC_DEBUG("RP2040-CUR: ERR: Not an ADC pin: ", pin); +}; + + + +// void RP2040ADCEngine::setPWMTrigger(uint slice){ +// triggerPWMSlice = slice; +// }; + + + + +bool RP2040ADCEngine::init() { + if (initialized) + return true; + + adc_init(); + int enableMask = 0x00; + int channelCount = 0; + for (int i = 3; i>=0; i--) { + if (channelsEnabled[i]){ + adc_gpio_init(i+26); + enableMask |= (0x01<=500000) { + samples_per_second = 0; + adc_set_clkdiv(0); + } + else + adc_set_clkdiv(48000000/samples_per_second); + SIMPLEFOC_DEBUG("RP2040-CUR: ADC init"); + + readDMAChannel = dma_claim_unused_channel(true); + dma_channel_config cc1 = dma_channel_get_default_config(readDMAChannel); + channel_config_set_transfer_data_size(&cc1, DMA_SIZE_8); + channel_config_set_read_increment(&cc1, false); + channel_config_set_write_increment(&cc1, true); + channel_config_set_dreq(&cc1, DREQ_ADC); + channel_config_set_irq_quiet(&cc1, false); + dma_channel_configure(readDMAChannel, + &cc1, + samples, // dest + &adc_hw->fifo, // source + channelCount, // count + false // defer start + ); + dma_channel_set_irq0_enabled(readDMAChannel, true); + irq_add_shared_handler(DMA_IRQ_0, _adcConversionFinishedHandler, PICO_SHARED_IRQ_HANDLER_DEFAULT_ORDER_PRIORITY); + + SIMPLEFOC_DEBUG("RP2040-CUR: DMA init"); + + // if (triggerPWMSlice>=0) { // if we have a trigger + // triggerDMAChannel = dma_claim_unused_channel(true); + // dma_channel_config cc3 = dma_channel_get_default_config(triggerDMAChannel); + // channel_config_set_transfer_data_size(&cc3, DMA_SIZE_32); + // channel_config_set_read_increment(&cc3, false); + // channel_config_set_write_increment(&cc3, false); + // channel_config_set_irq_quiet(&cc3, true); + // channel_config_set_dreq(&cc3, DREQ_PWM_WRAP0+triggerPWMSlice); //pwm_get_dreq(triggerPWMSlice)); + // pwm_set_irq_enabled(triggerPWMSlice, true); + // dma_channel_configure(triggerDMAChannel, + // &cc3, + // hw_set_alias_untyped(&adc_hw->cs), // dest + // &trigger_value, // source + // 1, // count + // true // defer start + // ); + // SIMPLEFOC_DEBUG("RP2040-CUR: PWM trigger init slice ", triggerPWMSlice); + // } + + initialized = true; + return initialized; +}; + + + + +void RP2040ADCEngine::start() { + SIMPLEFOC_DEBUG("RP2040-CUR: ADC engine starting"); + irq_set_enabled(DMA_IRQ_0, true); + dma_start_channel_mask( (1u << readDMAChannel) ); + for (int i=0;i<4;i++) { + if (channelsEnabled[i]) { + adc_select_input(i); // set input to first enabled channel + break; + } + } + // if (triggerPWMSlice>=0) { + // dma_start_channel_mask( (1u << triggerDMAChannel) ); + // //hw_set_bits(&adc_hw->cs, trigger_value); + // } + // else + adc_run(true); + SIMPLEFOC_DEBUG("RP2040-CUR: ADC engine started"); +}; + + + + +void RP2040ADCEngine::stop() { + adc_run(false); + irq_set_enabled(DMA_IRQ_0, false); + dma_channel_abort(readDMAChannel); + // if (triggerPWMSlice>=0) + // dma_channel_abort(triggerDMAChannel); + adc_fifo_drain(); + SIMPLEFOC_DEBUG("RP2040-CUR: ADC engine stopped"); +}; + + + +ADCResults RP2040ADCEngine::getLastResults() { + ADCResults r; + r.value = lastResults.value; + return r; +}; + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.h new file mode 100644 index 0000000..ae28bb2 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/rp2040/rp2040_mcu.h @@ -0,0 +1,93 @@ + + +#pragma once + +/* + * RP2040 ADC features are very weak :-( + * - only 4 inputs + * - only 9 bit effective resolution + * - read only 1 input at a time + * - 2 microseconds conversion time! + * - no triggers from PWM / events, only DMA + * + * So to read 3 phases takes 6 microseconds. :-( + * + * The RP2040 ADC engine takes over the control of the MCU's ADC. Parallel ADC access is not permitted, as this would + * cause conflicts with the engine's DMA based access and cause crashes. + * To use the other ADC channels, use them via this engine. Use addPin() to add them to the conversion, and getLastResult() + * to retrieve their value at any time. + * + * For motor current sensing, the engine supports inline sensing only. + * + * Inline sensing is supported by offering a user-selectable fixed ADC sampling rate, which can be set between 500kHz and 1Hz. + * After starting the engine it will continuously sample and provide new values at the configured rate. + * + * The default sampling rate is 20kHz, which is suitable for 2 channels assuming you a 5kHz main loop speed (a new measurement is used per + * main loop iteration). + * + * Low-side sensing is currently not supported. + * + * The SimpleFOC PWM driver for RP2040 syncs all the slices, so the PWM trigger is applied to the first used slice. For current + * sensing to work correctly, all PWM slices have to be set to the same PWM frequency. + * In theory, two motors could be sensed using 2 shunts on each motor. + * + * Note that if using other ADC channels along with the motor current sensing, those channels will be subject to the same conversion schedule as the motor's ADC channels, i.e. convert at the same fixed rate in case + * of inline sensing. + * + * Solution to trigger ADC conversion from PWM via DMA: + * use the PWM wrap as a DREQ to a DMA channel, and have the DMA channel write to the ADC's CS register to trigger an ADC sample. + * Unfortunately, I could not get this to work, so no low side sensing for the moment. + * + * Solution for ADC conversion: + * ADC converts all channels in round-robin mode, and writes to FIFO. FIFO is emptied by a DMA which triggers after N conversions, + * where N is the number of ADC channels used. So this DMA copies all the values from one round-robin conversion. + * + * + */ + + +#define SIMPLEFOC_RP2040_ADC_RESOLUTION 256 +#ifndef SIMPLEFOC_RP2040_ADC_VDDA +#define SIMPLEFOC_RP2040_ADC_VDDA 3.3f +#endif + + +union ADCResults { + uint32_t value; + uint8_t raw[4]; + struct { + uint8_t ch0; + uint8_t ch1; + uint8_t ch2; + uint8_t ch3; + }; +}; + + +class RP2040ADCEngine { + +public: + RP2040ADCEngine(); + void addPin(int pin); + //void setPWMTrigger(uint slice); + + bool init(); + void start(); + void stop(); + + ADCResults getLastResults(); // TODO find a better API and representation for this + + int samples_per_second = 20000; // 20kHz default (assuming 2 shunts and 5kHz loop speed), set to 0 to convert in tight loop + float adc_conv = (SIMPLEFOC_RP2040_ADC_VDDA / SIMPLEFOC_RP2040_ADC_RESOLUTION); // conversion from raw ADC to float + + //int triggerPWMSlice = -1; + bool initialized; + uint readDMAChannel; + //uint copyDMAChannel; + //uint triggerDMAChannel; + + bool channelsEnabled[4]; + volatile uint8_t samples[4]; + volatile ADCResults lastResults; + //alignas(32) volatile uint8_t nextResults[4]; +}; \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.cpp new file mode 100644 index 0000000..da5ba85 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.cpp @@ -0,0 +1,318 @@ +#ifdef _SAMD21_ + +#include "samd21_mcu.h" +#include "../../hardware_api.h" + + +static bool freeRunning = false; +static int _pinA, _pinB, _pinC; +static uint16_t a = 0xFFFF, b = 0xFFFF, c = 0xFFFF; // updated by adcStopWithDMA when configured in freerunning mode +static SAMDCurrentSenseADCDMA instance; + +// function configuring low-side current sensing +void* _configureADCLowSide(const void* driver_params, const int pinA,const int pinB,const int pinC) +{ + _UNUSED(driver_params); + + _pinA = pinA; + _pinB = pinB; + _pinC = pinC; + freeRunning = true; + instance.init(pinA, pinB, pinC); + + GenericCurrentSenseParams* params = new GenericCurrentSenseParams { + .pins = { pinA, pinB, pinC } + }; + + return params; +} +void _startADC3PinConversionLowSide() +{ + instance.startADCScan(); +} +/** + * function reading an ADC value and returning the read voltage + * + * @param pinA - the arduino pin to be read (it has to be ADC pin) + */ +float _readADCVoltageLowSide(const int pinA, const void* cs_params) +{ + _UNUSED(cs_params); + + instance.readResults(a, b, c); + + if(pinA == _pinA) + return instance.toVolts(a); + if(pinA == _pinB) + return instance.toVolts(b); + if(pinA == _pinC) + return instance.toVolts(c); + + return NAN; +} + +/** + * function syncing the Driver with the ADC for the LowSide Sensing + */ +void _driverSyncLowSide(void* driver_params, void* cs_params) +{ + _UNUSED(driver_params); + _UNUSED(cs_params); + + SIMPLEFOC_SAMD_DEBUG_SERIAL.println(F("TODO! _driverSyncLowSide() is not implemented")); + instance.startADCScan(); + //TODO: hook with PWM interrupts +} + + + + + + + + + + + // Credit: significant portions of this code were pulled from Paul Gould's git https://github.com/gouldpa/FOC-Arduino-Brushless + +static void adcStopWithDMA(void); +static void adcStartWithDMA(void); + +/** + * @brief ADC sync wait + * @retval void + */ +static __inline__ void ADCsync() __attribute__((always_inline, unused)); +static void ADCsync() { + while (ADC->STATUS.bit.SYNCBUSY == 1); //Just wait till the ADC is free +} + +// ADC DMA sequential free running (6) with Interrupts ///////////////// + +SAMDCurrentSenseADCDMA * SAMDCurrentSenseADCDMA::getHardwareAPIInstance() +{ + + return &instance; +} + +SAMDCurrentSenseADCDMA::SAMDCurrentSenseADCDMA() +{ +} + +void SAMDCurrentSenseADCDMA::init(int pinA, int pinB, int pinC, int pinAREF, float voltageAREF, uint32_t adcBits, uint32_t channelDMA) +{ + this->pinA = pinA; + this->pinB = pinB; + this->pinC = pinC; + this->pinAREF = pinAREF; + this->channelDMA = channelDMA; + this->voltageAREF = voltageAREF; + this->maxCountsADC = 1 << adcBits; + countsToVolts = ( voltageAREF / maxCountsADC ); + + initPins(); + initADC(); + initDMA(); + startADCScan(); //so we have something to read next time we call readResults() +} + + +void SAMDCurrentSenseADCDMA::startADCScan(){ + adcToDMATransfer(adcBuffer + oneBeforeFirstAIN, BufferSize); + adcStartWithDMA(); +} + +bool SAMDCurrentSenseADCDMA::readResults(uint16_t & a, uint16_t & b, uint16_t & c){ + if(ADC->CTRLA.bit.ENABLE) + return false; + uint32_t ainA = g_APinDescription[pinA].ulADCChannelNumber; + uint32_t ainB = g_APinDescription[pinB].ulADCChannelNumber; + a = adcBuffer[ainA]; + b = adcBuffer[ainB]; + if(_isset(pinC)) + { + uint32_t ainC = g_APinDescription[pinC].ulADCChannelNumber; + c = adcBuffer[ainC]; + } + return true; +} + + +float SAMDCurrentSenseADCDMA::toVolts(uint16_t counts) { + return counts * countsToVolts; +} + +void SAMDCurrentSenseADCDMA::initPins(){ + + if (pinAREF>=0) + pinMode(pinAREF, INPUT); + pinMode(pinA, INPUT); + pinMode(pinB, INPUT); + + uint32_t ainA = g_APinDescription[pinA].ulADCChannelNumber; + uint32_t ainB = g_APinDescription[pinB].ulADCChannelNumber; + firstAIN = min(ainA, ainB); + lastAIN = max(ainA, ainB); + if( _isset(pinC) ) + { + uint32_t ainC = g_APinDescription[pinC].ulADCChannelNumber; + pinMode(pinC, INPUT); + firstAIN = min(firstAIN, ainC); + lastAIN = max(lastAIN, ainC); + } + + oneBeforeFirstAIN = firstAIN - 1; //hack to discard noisy first readout + BufferSize = lastAIN - oneBeforeFirstAIN + 1; + +} + +void SAMDCurrentSenseADCDMA::initADC(){ + + analogRead(pinA); // do some pin init pinPeripheral() + analogRead(pinB); // do some pin init pinPeripheral() + analogRead(pinC); // do some pin init pinPeripheral() + + ADC->CTRLA.bit.ENABLE = 0x00; // Disable ADC + ADCsync(); + //ADC->REFCTRL.bit.REFSEL = ADC_REFCTRL_REFSEL_INTVCC0_Val; // 2.2297 V Supply VDDANA + ADC->INPUTCTRL.bit.GAIN = ADC_INPUTCTRL_GAIN_1X_Val; // Gain select as 1X + // ADC->INPUTCTRL.bit.GAIN = ADC_INPUTCTRL_GAIN_DIV2_Val; // default + if (pinAREF>=0) + ADC->REFCTRL.bit.REFSEL = ADC_REFCTRL_REFSEL_AREFA; + else + ADC->REFCTRL.bit.REFSEL = ADC_REFCTRL_REFSEL_INTVCC0; + ADCsync(); // ref 31.6.16 + + /* + Bits 19:16 – INPUTSCAN[3:0]: Number of Input Channels Included in Scan + This register gives the number of input sources included in the pin scan. The number of input sources included is + INPUTSCAN + 1. The input channels included are in the range from MUXPOS + INPUTOFFSET to MUXPOS + + INPUTOFFSET + INPUTSCAN. + The range of the scan mode must not exceed the number of input channels available on the device. + Bits 4:0 – MUXPOS[4:0]: Positive Mux Input Selection + These bits define the Mux selection for the positive ADC input. Table 32-14 shows the possible input selections. If + the internal bandgap voltage or temperature sensor input channel is selected, then the Sampling Time Length bit + group in the SamplingControl register must be written. + Table 32-14. Positive Mux Input Selection + MUXPOS[4:0] Group configuration Description + 0x00 PIN0 ADC AIN0 pin + 0x01 PIN1 ADC AIN1 pin + 0x02 PIN2 ADC AIN2 pin + 0x03 PIN3 ADC AIN3 pin + 0x04 PIN4 ADC AIN4 pin + 0x05 PIN5 ADC AIN5 pin + 0x06 PIN6 ADC AIN6 pin + 0x07 PIN7 ADC AIN7 pin + 0x08 PIN8 ADC AIN8 pin + 0x09 PIN9 ADC AIN9 pin + 0x0A PIN10 ADC AIN10 pin + 0x0B PIN11 ADC AIN11 pin + 0x0C PIN12 ADC AIN12 pin + 0x0D PIN13 ADC AIN13 pin + 0x0E PIN14 ADC AIN14 pin + 0x0F PIN15 ADC AIN15 pin + 0x10 PIN16 ADC AIN16 pin + 0x11 PIN17 ADC AIN17 pin + 0x12 PIN18 ADC AIN18 pin + 0x13 PIN19 ADC AIN19 pin + 0x14-0x17 Reserved + 0x18 TEMP Temperature reference + 0x19 BANDGAP Bandgap voltage + 0x1A SCALEDCOREVCC 1/4 scaled core supply + 0x1B SCALEDIOVCC 1/4 scaled I/O supply + 0x1C DAC DAC output + 0x1D-0x1F Reserved + */ + ADC->INPUTCTRL.bit.MUXPOS = oneBeforeFirstAIN; + ADCsync(); + ADC->INPUTCTRL.bit.INPUTSCAN = lastAIN; // so the adc will scan from oneBeforeFirstAIN to lastAIN (inclusive) + ADCsync(); + ADC->INPUTCTRL.bit.INPUTOFFSET = 0; //input scan cursor + ADCsync(); + ADC->AVGCTRL.reg = 0x00 ; //no averaging + ADC->SAMPCTRL.reg = 0x05; ; //sample length in 1/2 CLK_ADC cycles, see GCLK_ADC and ADC_CTRLB_PRESCALER_DIV16 + // according to the specsheet: f_GCLK_ADC ADC input clock frequency 48 MHz, so same as fCPU + ADCsync(); + ADC->CTRLB.reg = ADC_CTRLB_PRESCALER_DIV16 | ADC_CTRLB_FREERUN | ADC_CTRLB_RESSEL_12BIT; + ADCsync(); +} + +volatile dmacdescriptor wrb[12] __attribute__ ((aligned (16))); + +void SAMDCurrentSenseADCDMA::initDMA() { + // probably on by default + PM->AHBMASK.reg |= PM_AHBMASK_DMAC ; + PM->APBBMASK.reg |= PM_APBBMASK_DMAC ; + NVIC_EnableIRQ( DMAC_IRQn ) ; + DMAC->BASEADDR.reg = (uint32_t)descriptor_section; + DMAC->WRBADDR.reg = (uint32_t)wrb; + DMAC->CTRL.reg = DMAC_CTRL_DMAENABLE | DMAC_CTRL_LVLEN(0xf); +} + + +void SAMDCurrentSenseADCDMA::adcToDMATransfer(void *rxdata, uint32_t hwords) { + + DMAC->CHID.reg = DMAC_CHID_ID(channelDMA); + DMAC->CHCTRLA.reg &= ~DMAC_CHCTRLA_ENABLE; + DMAC->CHCTRLA.reg = DMAC_CHCTRLA_SWRST; + DMAC->SWTRIGCTRL.reg &= (uint32_t)(~(1 << channelDMA)); + + DMAC->CHCTRLB.reg = DMAC_CHCTRLB_LVL(0) + | DMAC_CHCTRLB_TRIGSRC(ADC_DMAC_ID_RESRDY) + | DMAC_CHCTRLB_TRIGACT_BEAT; + DMAC->CHINTENSET.reg = DMAC_CHINTENSET_MASK ; // enable all 3 interrupts + descriptor.descaddr = 0; + descriptor.srcaddr = (uint32_t) &ADC->RESULT.reg; + descriptor.btcnt = hwords; + descriptor.dstaddr = (uint32_t)rxdata + hwords*2; // end address + descriptor.btctrl = DMAC_BTCTRL_BEATSIZE_HWORD | DMAC_BTCTRL_DSTINC | DMAC_BTCTRL_VALID; + memcpy(&descriptor_section[channelDMA],&descriptor, sizeof(dmacdescriptor)); + + // start channel + DMAC->CHID.reg = DMAC_CHID_ID(channelDMA); + DMAC->CHCTRLA.reg |= DMAC_CHCTRLA_ENABLE; +} + + +int iii = 0; + +void adcStopWithDMA(void){ + ADCsync(); + ADC->CTRLA.bit.ENABLE = 0x00; + // ADCsync(); + // if(iii++ % 1000 == 0) + // { + // SIMPLEFOC_SAMD_DEBUG_SERIAL.print(a); + // SIMPLEFOC_SAMD_DEBUG_SERIAL.print(" :: "); + // SIMPLEFOC_SAMD_DEBUG_SERIAL.print(b); + // SIMPLEFOC_SAMD_DEBUG_SERIAL.print(" :: "); + // SIMPLEFOC_SAMD_DEBUG_SERIAL.print(c); + // SIMPLEFOC_SAMD_DEBUG_SERIAL.println("yo!"); + // } + + +} + +void adcStartWithDMA(void){ + ADCsync(); + ADC->INPUTCTRL.bit.INPUTOFFSET = 0; + ADCsync(); + ADC->SWTRIG.bit.FLUSH = 1; + ADCsync(); + ADC->CTRLA.bit.ENABLE = 0x01; + ADCsync(); +} + +void DMAC_Handler() { + uint8_t active_channel; + active_channel = DMAC->INTPEND.reg & DMAC_INTPEND_ID_Msk; // get channel number + DMAC->CHID.reg = DMAC_CHID_ID(active_channel); + adcStopWithDMA(); + DMAC->CHINTFLAG.reg = DMAC_CHINTENCLR_TCMPL; // clear + DMAC->CHINTFLAG.reg = DMAC_CHINTENCLR_TERR; + DMAC->CHINTFLAG.reg = DMAC_CHINTENCLR_SUSP; + +} + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.h new file mode 100644 index 0000000..e7d7442 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd21_mcu.h @@ -0,0 +1,69 @@ +#ifdef _SAMD21_ + +#ifndef CURRENT_SENSE_SAMD21_H +#define CURRENT_SENSE_SAMD21_H + +#define SIMPLEFOC_SAMD_DEBUG +#if !defined(SIMPLEFOC_SAMD_DEBUG_SERIAL) +#define SIMPLEFOC_SAMD_DEBUG_SERIAL Serial +#endif + +#include + typedef struct { + uint16_t btctrl; + uint16_t btcnt; + uint32_t srcaddr; + uint32_t dstaddr; + uint32_t descaddr; + } dmacdescriptor ; + + +// AREF pin is 42 + +class SAMDCurrentSenseADCDMA +{ + +public: + static SAMDCurrentSenseADCDMA * getHardwareAPIInstance(); + SAMDCurrentSenseADCDMA(); + void init(int pinA, int pinB, int pinC, int pinAREF = 42, float voltageAREF = 3.3, uint32_t adcBits = 12, uint32_t channelDMA = 3); + void startADCScan(); + bool readResults(uint16_t & a, uint16_t & b, uint16_t & c); + float toVolts(uint16_t counts); +private: + + void adcToDMATransfer(void *rxdata, uint32_t hwords); + + void initPins(); + void initADC(); + void initDMA(); + + uint32_t oneBeforeFirstAIN; // hack to discard first noisy readout + uint32_t firstAIN; + uint32_t lastAIN; + uint32_t BufferSize = 0; + + uint16_t adcBuffer[20]; + + + uint32_t pinA; + uint32_t pinB; + uint32_t pinC; + uint32_t pinAREF; + uint32_t channelDMA; // DMA channel + bool freeRunning; + + float voltageAREF; + float maxCountsADC; + float countsToVolts; + + dmacdescriptor descriptor_section[12] __attribute__ ((aligned (16))); + dmacdescriptor descriptor __attribute__ ((aligned (16))); + +}; + +#endif + + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd_mcu.cpp new file mode 100644 index 0000000..2ec47c0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/samd/samd_mcu.cpp @@ -0,0 +1,23 @@ +#include "../../hardware_api.h" + +#if defined(_SAMD21_)|| defined(_SAMD51_) || defined(_SAME51_) + +#define _ADC_VOLTAGE 3.3f +#define _ADC_RESOLUTION 1024.0f + +// function reading an ADC value and returning the read voltage +void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + GenericCurrentSenseParams* params = new GenericCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION) + }; + + return params; +} +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.cpp new file mode 100644 index 0000000..892441a --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.cpp @@ -0,0 +1,364 @@ +#include "../../../hardware_api.h" +#if defined(ARDUINO_B_G431B_ESC1) + +#include "communication/SimpleFOCDebug.h" + +#include "stm32g4xx_hal.h" +#include "stm32g4xx_ll_pwr.h" +#include "stm32g4xx_hal_adc.h" +#include "b_g431_hal.h" + +// From STM32 cube IDE +/** + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2020 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ + + +/** + * @brief GPIO Initialization Function + * @param None + * @retval None + */ +void MX_GPIO_Init(void) +{ + /* GPIO Ports Clock Enable */ + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOF_CLK_ENABLE(); + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + + __HAL_RCC_ADC12_CLK_ENABLE(); +} + +/** + * Enable DMA controller clock + */ +void MX_DMA_Init(void) +{ + /* DMA controller clock enable */ + __HAL_RCC_DMAMUX1_CLK_ENABLE(); + __HAL_RCC_DMA1_CLK_ENABLE(); + __HAL_RCC_DMA2_CLK_ENABLE(); + + /* DMA interrupt init */ + /* DMA1_Channel1_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn); + /* DMA1_Channel2_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Channel2_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(DMA1_Channel2_IRQn); + + // Enable external clock for ADC + RCC_PeriphCLKInitTypeDef PeriphClkInit; + PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC12; + PeriphClkInit.Adc12ClockSelection = RCC_ADC12CLKSOURCE_PLL; + HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit); +} + + +/** + * @brief ADC1 Initialization Function + * @param None + * @retval None + */ +void MX_ADC1_Init(ADC_HandleTypeDef* hadc1) +{ + /* USER CODE BEGIN ADC1_Init 0 */ + + /* USER CODE END ADC1_Init 0 */ + + ADC_MultiModeTypeDef multimode = {0}; + ADC_ChannelConfTypeDef sConfig = {0}; + + /* USER CODE BEGIN ADC1_Init 1 */ + + /* USER CODE END ADC1_Init 1 */ + /** Common config + */ + hadc1->Instance = ADC1; + hadc1->Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV16; + hadc1->Init.Resolution = ADC_RESOLUTION_12B; + hadc1->Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc1->Init.GainCompensation = 0; + hadc1->Init.ScanConvMode = ADC_SCAN_ENABLE; + hadc1->Init.EOCSelection = ADC_EOC_SINGLE_CONV; + hadc1->Init.LowPowerAutoWait = DISABLE; + hadc1->Init.ContinuousConvMode = DISABLE; + hadc1->Init.NbrOfConversion = 2; + hadc1->Init.DiscontinuousConvMode = DISABLE; + hadc1->Init.ExternalTrigConv = ADC_EXTERNALTRIG_T3_TRGO; + hadc1->Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING; + hadc1->Init.DMAContinuousRequests = ENABLE; + hadc1->Init.Overrun = ADC_OVR_DATA_PRESERVED; + + if (HAL_ADC_Init(hadc1) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADC_Init failed!"); + } + + /** Configure the ADC multi-mode + */ + multimode.Mode = ADC_MODE_INDEPENDENT; + if (HAL_ADCEx_MultiModeConfigChannel(hadc1, &multimode) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADCEx_MultiModeConfigChannel failed!"); + } + /** Configure Regular Channel + */ + sConfig.Channel = ADC_CHANNEL_12; // ADC1_IN12 = PB1 = OP3_OUT + sConfig.Rank = ADC_REGULAR_RANK_1; + sConfig.SamplingTime = ADC_SAMPLETIME_2CYCLES_5; + sConfig.SingleDiff = ADC_SINGLE_ENDED; + sConfig.OffsetNumber = ADC_OFFSET_NONE; + sConfig.Offset = 0; + if (HAL_ADC_ConfigChannel(hadc1, &sConfig) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADC_ConfigChannel failed!"); + } + /** Configure Regular Channel + */ + sConfig.Channel = ADC_CHANNEL_3; // ADC1_IN3 = PA2 = OP1_OUT + sConfig.Rank = ADC_REGULAR_RANK_2; + if (HAL_ADC_ConfigChannel(hadc1, &sConfig) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADC_ConfigChannel failed!"); + } + + //****************************************************************** + // Temp, Poti .... + /** Configure Regular Channel (PB14, Temperature) + */ + sConfig.Channel = ADC_CHANNEL_5; + sConfig.Rank = ADC_REGULAR_RANK_4; + sConfig.SamplingTime = ADC_SAMPLETIME_47CYCLES_5; + sConfig.SingleDiff = ADC_SINGLE_ENDED; + sConfig.OffsetNumber = ADC_OFFSET_NONE; + sConfig.Offset = 0; + if (HAL_ADC_ConfigChannel(hadc1, &sConfig) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADC_ConfigChannel failed!"); + } + + /** Configure Regular Channel (PB14, Temperature) + */ + sConfig.Channel = ADC_CHANNEL_1; + sConfig.Rank = ADC_REGULAR_RANK_5; + sConfig.SamplingTime = ADC_SAMPLETIME_47CYCLES_5; + sConfig.SingleDiff = ADC_SINGLE_ENDED; + sConfig.OffsetNumber = ADC_OFFSET_NONE; + sConfig.Offset = 0; + if (HAL_ADC_ConfigChannel(hadc1, &sConfig) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADC_ConfigChannel failed!"); + } + /* USER CODE BEGIN ADC1_Init 2 */ + + /* USER CODE END ADC1_Init 2 */ + +} + +/** + * @brief ADC2 Initialization Function + * @param None + * @retval None + */ +void MX_ADC2_Init(ADC_HandleTypeDef* hadc2) +{ + /* USER CODE BEGIN ADC2_Init 0 */ + + /* USER CODE END ADC2_Init 0 */ + + ADC_ChannelConfTypeDef sConfig = {0}; + + /* USER CODE BEGIN ADC2_Init 1 */ + + /* USER CODE END ADC2_Init 1 */ + /** Common config + */ + hadc2->Instance = ADC2; + hadc2->Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV16; + hadc2->Init.Resolution = ADC_RESOLUTION_12B; + hadc2->Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc2->Init.GainCompensation = 0; + hadc2->Init.ScanConvMode = ADC_SCAN_ENABLE; + hadc2->Init.EOCSelection = ADC_EOC_SINGLE_CONV; + hadc2->Init.LowPowerAutoWait = DISABLE; + hadc2->Init.ContinuousConvMode = DISABLE; + hadc2->Init.NbrOfConversion = 1; + hadc2->Init.DiscontinuousConvMode = DISABLE; + hadc2->Init.ExternalTrigConv = ADC_EXTERNALTRIG_T1_TRGO; + hadc2->Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING; + hadc2->Init.DMAContinuousRequests = ENABLE; + hadc2->Init.Overrun = ADC_OVR_DATA_PRESERVED; + + if (HAL_ADC_Init(hadc2) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADC_Init failed!"); + } + /** Configure Regular Channel + */ + sConfig.Channel = ADC_CHANNEL_3; // ADC2_IN3 = PA6 + sConfig.Rank = ADC_REGULAR_RANK_1; + sConfig.SamplingTime = ADC_SAMPLETIME_2CYCLES_5; + sConfig.SingleDiff = ADC_SINGLE_ENDED; + sConfig.OffsetNumber = ADC_OFFSET_NONE; + sConfig.Offset = 0; + if (HAL_ADC_ConfigChannel(hadc2, &sConfig) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_ADC_ConfigChannel failed!"); + } + /* USER CODE BEGIN ADC2_Init 2 */ + + /* USER CODE END ADC2_Init 2 */ + +} + +/** +* @brief OPAMP MSP Initialization +* This function configures the hardware resources used in this example +* @param hopamp-> OPAMP handle pointer +* @retval None +*/ +void HAL_OPAMP_MspInit(OPAMP_HandleTypeDef* hopamp) +{ + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(hopamp->Instance==OPAMP1) + { + /* USER CODE BEGIN OPAMP1_MspInit 0 */ + + /* USER CODE END OPAMP1_MspInit 0 */ + + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**OPAMP1 GPIO Configuration + PA1 ------> OPAMP1_VINP + PA2 ------> OPAMP1_VOUT + PA3 ------> OPAMP1_VINM + */ + GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* USER CODE BEGIN OPAMP1_MspInit 1 */ + + /* USER CODE END OPAMP1_MspInit 1 */ + } + else if(hopamp->Instance==OPAMP2) + { + /* USER CODE BEGIN OPAMP2_MspInit 0 */ + + /* USER CODE END OPAMP2_MspInit 0 */ + + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**OPAMP2 GPIO Configuration + PA5 ------> OPAMP2_VINM + PA6 ------> OPAMP2_VOUT + PA7 ------> OPAMP2_VINP + */ + GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* USER CODE BEGIN OPAMP2_MspInit 1 */ + + /* USER CODE END OPAMP2_MspInit 1 */ + } + else if(hopamp->Instance==OPAMP3) + { + /* USER CODE BEGIN OPAMP3_MspInit 0 */ + + /* USER CODE END OPAMP3_MspInit 0 */ + + __HAL_RCC_GPIOB_CLK_ENABLE(); + /**OPAMP3 GPIO Configuration + PB0 ------> OPAMP3_VINP + PB1 ------> OPAMP3_VOUT + PB2 ------> OPAMP3_VINM + */ + GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* USER CODE BEGIN OPAMP3_MspInit 1 */ + + /* USER CODE END OPAMP3_MspInit 1 */ + } + +} + +/** +* @brief OPAMP MSP De-Initialization +* This function freeze the hardware resources used in this example +* @param hopamp-> OPAMP handle pointer +* @retval None +*/ +void HAL_OPAMP_MspDeInit(OPAMP_HandleTypeDef* hopamp) +{ + if(hopamp->Instance==OPAMP1) + { + /* USER CODE BEGIN OPAMP1_MspDeInit 0 */ + + /* USER CODE END OPAMP1_MspDeInit 0 */ + + /**OPAMP1 GPIO Configuration + PA1 ------> OPAMP1_VINP + PA2 ------> OPAMP1_VOUT + PA3 ------> OPAMP1_VINM + */ + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3); + + /* USER CODE BEGIN OPAMP1_MspDeInit 1 */ + + /* USER CODE END OPAMP1_MspDeInit 1 */ + } + else if(hopamp->Instance==OPAMP2) + { + /* USER CODE BEGIN OPAMP2_MspDeInit 0 */ + + /* USER CODE END OPAMP2_MspDeInit 0 */ + + /**OPAMP2 GPIO Configuration + PA5 ------> OPAMP2_VINM + PA6 ------> OPAMP2_VOUT + PA7 ------> OPAMP2_VINP + */ + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7); + + /* USER CODE BEGIN OPAMP2_MspDeInit 1 */ + + /* USER CODE END OPAMP2_MspDeInit 1 */ + } + else if(hopamp->Instance==OPAMP3) + { + /* USER CODE BEGIN OPAMP3_MspDeInit 0 */ + + /* USER CODE END OPAMP3_MspDeInit 0 */ + + /**OPAMP3 GPIO Configuration + PB0 ------> OPAMP3_VINP + PB1 ------> OPAMP3_VOUT + PB2 ------> OPAMP3_VINM + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2); + + /* USER CODE BEGIN OPAMP3_MspDeInit 1 */ + + /* USER CODE END OPAMP3_MspDeInit 1 */ + } + +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.h new file mode 100644 index 0000000..2d6a1f0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_hal.h @@ -0,0 +1,18 @@ +#ifndef B_G431_ESC1_HAL +#define B_G431_ESC1_HAL + +#if defined(ARDUINO_B_G431B_ESC1) + +#include +#include + +void MX_GPIO_Init(void); +void MX_DMA_Init(void); +void MX_ADC1_Init(ADC_HandleTypeDef* hadc1); +void MX_ADC2_Init(ADC_HandleTypeDef* hadc2); +void MX_OPAMP1_Init(OPAMP_HandleTypeDef* hopamp); +void MX_OPAMP2_Init(OPAMP_HandleTypeDef* hopamp); +void MX_OPAMP3_Init(OPAMP_HandleTypeDef* hopamp); +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_mcu.cpp new file mode 100644 index 0000000..35db4c4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/b_g431/b_g431_mcu.cpp @@ -0,0 +1,164 @@ +#include "../../../hardware_api.h" + +#if defined(ARDUINO_B_G431B_ESC1) + +#include "b_g431_hal.h" +#include "Arduino.h" +#include "../stm32_mcu.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "communication/SimpleFOCDebug.h" + +#define _ADC_VOLTAGE 3.3f +#define _ADC_RESOLUTION 4096.0f +#define ADC_BUF_LEN_1 5 +#define ADC_BUF_LEN_2 1 + +static ADC_HandleTypeDef hadc1; +static ADC_HandleTypeDef hadc2; +static OPAMP_HandleTypeDef hopamp1; +static OPAMP_HandleTypeDef hopamp2; +static OPAMP_HandleTypeDef hopamp3; + +static DMA_HandleTypeDef hdma_adc1; +static DMA_HandleTypeDef hdma_adc2; + +volatile uint16_t adcBuffer1[ADC_BUF_LEN_1] = {0}; // Buffer for store the results of the ADC conversion +volatile uint16_t adcBuffer2[ADC_BUF_LEN_2] = {0}; // Buffer for store the results of the ADC conversion + +// function reading an ADC value and returning the read voltage +// As DMA is being used just return the DMA result +float _readADCVoltageInline(const int pin, const void* cs_params){ + uint32_t raw_adc = 0; + if(pin == PA2) // = ADC1_IN3 = phase U (OP1_OUT) on B-G431B-ESC1 + raw_adc = adcBuffer1[1]; + else if(pin == PA6) // = ADC2_IN3 = phase V (OP2_OUT) on B-G431B-ESC1 + raw_adc = adcBuffer2[0]; + else if(pin == PB1) // = ADC1_IN12 = phase W (OP3_OUT) on B-G431B-ESC1 + raw_adc = adcBuffer1[0]; + else if (pin == A_TEMPERATURE) + raw_adc = adcBuffer1[3]; + + return raw_adc * ((Stm32CurrentSenseParams*)cs_params)->adc_voltage_conv; +} + +void _configureOPAMP(OPAMP_HandleTypeDef *hopamp, OPAMP_TypeDef *OPAMPx_Def){ + // could this be replaced with LL_OPAMP calls?? + hopamp->Instance = OPAMPx_Def; + hopamp->Init.PowerMode = OPAMP_POWERMODE_HIGHSPEED; + hopamp->Init.Mode = OPAMP_PGA_MODE; + hopamp->Init.NonInvertingInput = OPAMP_NONINVERTINGINPUT_IO0; + hopamp->Init.InternalOutput = DISABLE; + hopamp->Init.TimerControlledMuxmode = OPAMP_TIMERCONTROLLEDMUXMODE_DISABLE; + hopamp->Init.PgaConnect = OPAMP_PGA_CONNECT_INVERTINGINPUT_IO0_BIAS; + hopamp->Init.PgaGain = OPAMP_PGA_GAIN_16_OR_MINUS_15; + hopamp->Init.UserTrimming = OPAMP_TRIMMING_FACTORY; + if (HAL_OPAMP_Init(hopamp) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_OPAMP_Init failed!"); + } +} +void _configureOPAMPs(OPAMP_HandleTypeDef *OPAMPA, OPAMP_HandleTypeDef *OPAMPB, OPAMP_HandleTypeDef *OPAMPC){ + // Configure the opamps + _configureOPAMP(OPAMPA, OPAMP1); + _configureOPAMP(OPAMPB, OPAMP2); + _configureOPAMP(OPAMPC, OPAMP3); +} + +void MX_DMA1_Init(ADC_HandleTypeDef *hadc, DMA_HandleTypeDef *hdma_adc, DMA_Channel_TypeDef* channel, uint32_t request) { + hdma_adc->Instance = channel; + hdma_adc->Init.Request = request; + hdma_adc->Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_adc->Init.PeriphInc = DMA_PINC_DISABLE; + hdma_adc->Init.MemInc = DMA_MINC_ENABLE; + hdma_adc->Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; + hdma_adc->Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD; + hdma_adc->Init.Mode = DMA_CIRCULAR; + hdma_adc->Init.Priority = DMA_PRIORITY_LOW; + HAL_DMA_DeInit(hdma_adc); + if (HAL_DMA_Init(hdma_adc) != HAL_OK) + { + SIMPLEFOC_DEBUG("HAL_DMA_Init failed!"); + } + __HAL_LINKDMA(hadc, DMA_Handle, *hdma_adc); +} + +void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + _UNUSED(pinA); + _UNUSED(pinB); + _UNUSED(pinC); + + SIMPLEFOC_DEBUG("B-G431B does not implement inline current sense. Use low-side current sense instead."); + return SIMPLEFOC_CURRENT_SENSE_INIT_FAILED; +} + + +void* _configureADCLowSide(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + HAL_Init(); + MX_GPIO_Init(); + MX_DMA_Init(); + _configureOPAMPs(&hopamp1, &hopamp3, &hopamp2); + MX_ADC1_Init(&hadc1); + MX_ADC2_Init(&hadc2); + + MX_DMA1_Init(&hadc1, &hdma_adc1, DMA1_Channel1, DMA_REQUEST_ADC1); + MX_DMA1_Init(&hadc2, &hdma_adc2, DMA1_Channel2, DMA_REQUEST_ADC2); + + if (HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adcBuffer1, ADC_BUF_LEN_1) != HAL_OK) + { + SIMPLEFOC_DEBUG("DMA read init failed"); + } + if (HAL_ADC_Start_DMA(&hadc2, (uint32_t*)adcBuffer2, ADC_BUF_LEN_2) != HAL_OK) + { + SIMPLEFOC_DEBUG("DMA read init failed"); + } + + HAL_OPAMP_Start(&hopamp1); + HAL_OPAMP_Start(&hopamp2); + HAL_OPAMP_Start(&hopamp3); + + Stm32CurrentSenseParams* params = new Stm32CurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE) / (_ADC_RESOLUTION), + .timer_handle = (HardwareTimer *)(HardwareTimer_Handle[get_timer_index(TIM1)]->__this) + }; + + return params; +} + +extern "C" { +void DMA1_Channel1_IRQHandler(void) { + HAL_DMA_IRQHandler(&hdma_adc1); +} + +void DMA1_Channel2_IRQHandler(void) { + HAL_DMA_IRQHandler(&hdma_adc2); +} +} + +void _driverSyncLowSide(void* _driver_params, void* _cs_params){ + STM32DriverParams* driver_params = (STM32DriverParams*)_driver_params; + Stm32CurrentSenseParams* cs_params = (Stm32CurrentSenseParams*)_cs_params; + + // stop all the timers for the driver + _stopTimers(driver_params->timers, 6); + + // if timer has repetition counter - it will downsample using it + // and it does not need the software downsample + if( IS_TIM_REPETITION_COUNTER_INSTANCE(cs_params->timer_handle->getHandle()->Instance) ){ + // adjust the initial timer state such that the trigger for DMA transfer aligns with the pwm peaks instead of throughs. + // only necessary for the timers that have repetition counters + cs_params->timer_handle->getHandle()->Instance->CR1 |= TIM_CR1_DIR; + cs_params->timer_handle->getHandle()->Instance->CNT = cs_params->timer_handle->getHandle()->Instance->ARR; + } + // set the trigger output event + LL_TIM_SetTriggerOutput(cs_params->timer_handle->getHandle()->Instance, LL_TIM_TRGO_UPDATE); + + // restart all the timers of the driver + _startTimers(driver_params->timers, 6); + +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.cpp new file mode 100644 index 0000000..b3e76b1 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.cpp @@ -0,0 +1,33 @@ + +#include "../../hardware_api.h" + +#if defined(_STM32_DEF_) and !defined(ARDUINO_B_G431B_ESC1) and !defined(SIMPLEFOC_STM32_CUSTOMCURRENTSENSE) + +#include "stm32_mcu.h" + +#define _ADC_VOLTAGE 3.3f +#define _ADC_RESOLUTION 1024.0f + +// function reading an ADC value and returning the read voltage +__attribute__((weak)) void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + Stm32CurrentSenseParams* params = new Stm32CurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION) + }; + + return params; +} + +// function reading an ADC value and returning the read voltage +__attribute__((weak)) float _readADCVoltageInline(const int pinA, const void* cs_params){ + uint32_t raw_adc = analogRead(pinA); + return raw_adc * ((Stm32CurrentSenseParams*)cs_params)->adc_voltage_conv; +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.h new file mode 100644 index 0000000..6e23817 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32_mcu.h @@ -0,0 +1,21 @@ + +#ifndef STM32_CURRENTSENSE_MCU_DEF +#define STM32_CURRENTSENSE_MCU_DEF +#include "../../hardware_api.h" +#include "../../../common/foc_utils.h" + +#if defined(_STM32_DEF_) + +// generic implementation of the hardware specific structure +// containing all the necessary current sense parameters +// will be returned as a void pointer from the _configureADCx functions +// will be provided to the _readADCVoltageX() as a void pointer +typedef struct Stm32CurrentSenseParams { + int pins[3] = {(int)NOT_SET}; + float adc_voltage_conv; + ADC_HandleTypeDef* adc_handle = NP; + HardwareTimer* timer_handle = NP; +} Stm32CurrentSenseParams; + +#endif +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.cpp new file mode 100644 index 0000000..27e1195 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.cpp @@ -0,0 +1,162 @@ +#include "stm32f1_hal.h" + +#if defined(STM32F1xx) + +#include "../../../../communication/SimpleFOCDebug.h" +#define _TRGO_NOT_AVAILABLE 12345 + +// timer to injected TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/e156c32db24d69cb4818208ccc28894e2f427cfa/system/Drivers/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc_ex.h#L215 +uint32_t _timerToInjectedTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM1) + return ADC_EXTERNALTRIGINJECCONV_T1_TRGO; +#ifdef TIM2 // if defined timer 2 + else if(timer->getHandle()->Instance == TIM2) + return ADC_EXTERNALTRIGINJECCONV_T2_TRGO; +#endif +#ifdef TIM4 // if defined timer 4 + else if(timer->getHandle()->Instance == TIM4) + return ADC_EXTERNALTRIGINJECCONV_T4_TRGO; +#endif +#ifdef TIM5 // if defined timer 5 + else if(timer->getHandle()->Instance == TIM5) + return ADC_EXTERNALTRIGINJECCONV_T5_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + +// timer to regular TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/e156c32db24d69cb4818208ccc28894e2f427cfa/system/Drivers/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc_ex.h#L215 +uint32_t _timerToRegularTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM3) + return ADC_EXTERNALTRIGCONV_T3_TRGO; +#ifdef TIM8 // if defined timer 8 + else if(timer->getHandle()->Instance == TIM8) + return ADC_EXTERNALTRIGCONV_T8_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + +ADC_HandleTypeDef hadc; + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params) +{ + ADC_InjectionConfTypeDef sConfigInjected; + + /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) + */ + hadc.Instance = (ADC_TypeDef *)pinmap_peripheral(analogInputToPinName(cs_params->pins[0]), PinMap_ADC); + if(hadc.Instance == ADC1) __HAL_RCC_ADC1_CLK_ENABLE(); +#ifdef ADC2 // if defined ADC2 + else if(hadc.Instance == ADC2) __HAL_RCC_ADC2_CLK_ENABLE(); +#endif +#ifdef ADC3 // if defined ADC3 + else if(hadc.Instance == ADC3) __HAL_RCC_ADC3_CLK_ENABLE(); +#endif + else{ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: Pin does not belong to any ADC!"); +#endif + return -1; // error not a valid ADC instance + } + + hadc.Init.ScanConvMode = ADC_SCAN_ENABLE; + hadc.Init.ContinuousConvMode = ENABLE; + hadc.Init.DiscontinuousConvMode = DISABLE; + hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START; + hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc.Init.NbrOfConversion = 0; + HAL_ADC_Init(&hadc); + /**Configure for the selected ADC regular channel to be converted. + */ + + /**Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time + */ + sConfigInjected.InjectedNbrOfConversion = _isset(cs_params->pins[2]) ? 3 : 2; + sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5; + sConfigInjected.AutoInjectedConv = DISABLE; + sConfigInjected.InjectedDiscontinuousConvMode = DISABLE; + sConfigInjected.InjectedOffset = 0; + + // automating TRGO flag finding - hardware specific + uint8_t tim_num = 0; + while(driver_params->timers[tim_num] != NP && tim_num < 6){ + uint32_t trigger_flag = _timerToInjectedTRGO(driver_params->timers[tim_num++]); + if(trigger_flag == _TRGO_NOT_AVAILABLE) continue; // timer does not have valid trgo for injected channels + + // if the code comes here, it has found the timer available + // timer does have trgo flag for injected channels + sConfigInjected.ExternalTrigInjecConv = trigger_flag; + + // this will be the timer with which the ADC will sync + cs_params->timer_handle = driver_params->timers[tim_num-1]; + // done + break; + } + if( cs_params->timer_handle == NP ){ + // not possible to use these timers for low-side current sense + #ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot sync any timer to injected channels!"); + #endif + return -1; + } + // display which timer is being used + #ifdef SIMPLEFOC_STM32_DEBUG + // it would be better to use the getTimerNumber from driver + SIMPLEFOC_DEBUG("STM32-CS: injected trigger for timer index: ", get_timer_index(cs_params->timer_handle->getHandle()->Instance) + 1); + #endif + + // first channel + sConfigInjected.InjectedRank = ADC_REGULAR_RANK_1; + sConfigInjected.InjectedChannel = STM_PIN_CHANNEL(pinmap_function(analogInputToPinName(cs_params->pins[0]), PinMap_ADC)); + HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected); + // second channel + sConfigInjected.InjectedRank = ADC_REGULAR_RANK_2; + sConfigInjected.InjectedChannel = STM_PIN_CHANNEL(pinmap_function(analogInputToPinName(cs_params->pins[1]), PinMap_ADC)); + HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected); + + // third channel - if exists + if(_isset(cs_params->pins[2])){ + sConfigInjected.InjectedRank = ADC_REGULAR_RANK_3; + sConfigInjected.InjectedChannel = STM_PIN_CHANNEL(pinmap_function(analogInputToPinName(cs_params->pins[2]), PinMap_ADC)); + HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected); + } + + // enable interrupt + HAL_NVIC_SetPriority(ADC1_2_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC1_2_IRQn); + + cs_params->adc_handle = &hadc; + + return 0; +} + +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC) +{ + uint8_t cnt = 0; + if(_isset(pinA)){ + pinmap_pinout(analogInputToPinName(pinA), PinMap_ADC); + cs_params->pins[cnt++] = pinA; + } + if(_isset(pinB)){ + pinmap_pinout(analogInputToPinName(pinB), PinMap_ADC); + cs_params->pins[cnt++] = pinB; + } + if(_isset(pinC)){ + pinmap_pinout(analogInputToPinName(pinC), PinMap_ADC); + cs_params->pins[cnt] = pinC; + } + +} + +extern "C" { + void ADC1_2_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } + +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.h new file mode 100644 index 0000000..b0f4f83 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_hal.h @@ -0,0 +1,17 @@ +#ifndef STM32F1_LOWSIDE_HAL +#define STM32F1_LOWSIDE_HAL + +#include "Arduino.h" + +#if defined(STM32F1xx) +#include "stm32f1xx_hal.h" +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../stm32_mcu.h" + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params); +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC); + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_mcu.cpp new file mode 100644 index 0000000..8daa7ee --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f1/stm32f1_mcu.cpp @@ -0,0 +1,104 @@ +#include "../../../hardware_api.h" + +#if defined(STM32F1xx) +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_api.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../../../hardware_api.h" +#include "../stm32_mcu.h" +#include "stm32f1_hal.h" +#include "Arduino.h" + +#define _ADC_VOLTAGE_F1 3.3f +#define _ADC_RESOLUTION_F1 4096.0f + +// array of values of 4 injected channels per adc instance (3) +uint32_t adc_val[3][4]={0}; +// does adc interrupt need a downsample - per adc (3) +bool needs_downsample[3] = {1}; +// downsampling variable - per adc (3) +uint8_t tim_downsample[3] = {0}; + +int _adcToIndex(ADC_HandleTypeDef *AdcHandle){ + if(AdcHandle->Instance == ADC1) return 0; +#ifdef ADC2 // if ADC2 exists + else if(AdcHandle->Instance == ADC2) return 1; +#endif +#ifdef ADC3 // if ADC3 exists + else if(AdcHandle->Instance == ADC3) return 2; +#endif + return 0; +} + +void* _configureADCLowSide(const void* driver_params, const int pinA, const int pinB, const int pinC){ + + Stm32CurrentSenseParams* cs_params= new Stm32CurrentSenseParams { + .pins={(int)NOT_SET,(int)NOT_SET,(int)NOT_SET}, + .adc_voltage_conv = (_ADC_VOLTAGE_F1) / (_ADC_RESOLUTION_F1) + }; + _adc_gpio_init(cs_params, pinA,pinB,pinC); + if(_adc_init(cs_params, (STM32DriverParams*)driver_params) != 0) return SIMPLEFOC_CURRENT_SENSE_INIT_FAILED; + return cs_params; +} + + +void _driverSyncLowSide(void* _driver_params, void* _cs_params){ + STM32DriverParams* driver_params = (STM32DriverParams*)_driver_params; + Stm32CurrentSenseParams* cs_params = (Stm32CurrentSenseParams*)_cs_params; + + // if compatible timer has not been found + if (cs_params->timer_handle == NULL) return; + + // stop all the timers for the driver + _stopTimers(driver_params->timers, 6); + + // if timer has repetition counter - it will downsample using it + // and it does not need the software downsample + if( IS_TIM_REPETITION_COUNTER_INSTANCE(cs_params->timer_handle->getHandle()->Instance) ){ + // adjust the initial timer state such that the trigger + // - for DMA transfer aligns with the pwm peaks instead of throughs. + // - for interrupt based ADC transfer + // - only necessary for the timers that have repetition counters + cs_params->timer_handle->getHandle()->Instance->CR1 |= TIM_CR1_DIR; + cs_params->timer_handle->getHandle()->Instance->CNT = cs_params->timer_handle->getHandle()->Instance->ARR; + // remember that this timer has repetition counter - no need to downasmple + needs_downsample[_adcToIndex(cs_params->adc_handle)] = 0; + } + // set the trigger output event + LL_TIM_SetTriggerOutput(cs_params->timer_handle->getHandle()->Instance, LL_TIM_TRGO_UPDATE); + // start the adc + HAL_ADCEx_InjectedStart_IT(cs_params->adc_handle); + + // restart all the timers of the driver + _startTimers(driver_params->timers, 6); +} + + +// function reading an ADC value and returning the read voltage +float _readADCVoltageLowSide(const int pin, const void* cs_params){ + for(int i=0; i < 3; i++){ + if( pin == ((Stm32CurrentSenseParams*)cs_params)->pins[i]) // found in the buffer + return adc_val[_adcToIndex(((Stm32CurrentSenseParams*)cs_params)->adc_handle)][i] * ((Stm32CurrentSenseParams*)cs_params)->adc_voltage_conv; + } + return 0; +} + + +extern "C" { + void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *AdcHandle){ + // calculate the instance + int adc_index = _adcToIndex(AdcHandle); + + // if the timer han't repetition counter - downsample two times + if( needs_downsample[adc_index] && tim_downsample[adc_index]++ > 0) { + tim_downsample[adc_index] = 0; + return; + } + + adc_val[adc_index][0]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_1); + adc_val[adc_index][1]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_2); + adc_val[adc_index][2]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_3); + } +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.cpp new file mode 100644 index 0000000..68a9d09 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.cpp @@ -0,0 +1,170 @@ +#include "stm32f4_hal.h" + +#if defined(STM32F4xx) + +//#define SIMPLEFOC_STM32_DEBUG + +#include "../../../../communication/SimpleFOCDebug.h" +#define _TRGO_NOT_AVAILABLE 12345 + +ADC_HandleTypeDef hadc; + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params) +{ + ADC_InjectionConfTypeDef sConfigInjected; + + // check if all pins belong to the same ADC + ADC_TypeDef* adc_pin1 = (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[0]), PinMap_ADC); + ADC_TypeDef* adc_pin2 = (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[1]), PinMap_ADC); + ADC_TypeDef* adc_pin3 = _isset(cs_params->pins[2]) ? (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[2]), PinMap_ADC) : nullptr; + if ( (adc_pin1 != adc_pin2) || ( (adc_pin3) && (adc_pin1 != adc_pin3) )){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: Analog pins dont belong to the same ADC!"); +#endif + return -1; + } + + + /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) + */ + hadc.Instance = (ADC_TypeDef *)pinmap_peripheral(analogInputToPinName(cs_params->pins[0]), PinMap_ADC); + + if(hadc.Instance == ADC1) __HAL_RCC_ADC1_CLK_ENABLE(); +#ifdef ADC2 // if defined ADC2 + else if(hadc.Instance == ADC2) __HAL_RCC_ADC2_CLK_ENABLE(); +#endif +#ifdef ADC3 // if defined ADC3 + else if(hadc.Instance == ADC3) __HAL_RCC_ADC3_CLK_ENABLE(); +#endif + else{ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: Pin does not belong to any ADC!"); +#endif + return -1; // error not a valid ADC instance + } + +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: Using ADC: ", _adcToIndex(&hadc)+1); +#endif + + hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; + hadc.Init.Resolution = ADC_RESOLUTION_12B; + hadc.Init.ScanConvMode = ENABLE; + hadc.Init.ContinuousConvMode = ENABLE; + hadc.Init.DiscontinuousConvMode = DISABLE; + hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START; // for now + hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc.Init.NbrOfConversion = 1; + hadc.Init.DMAContinuousRequests = DISABLE; + hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + if ( HAL_ADC_Init(&hadc) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init ADC!"); +#endif + return -1; + } + + /**Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time + */ + sConfigInjected.InjectedNbrOfConversion = _isset(cs_params->pins[2]) ? 3 : 2; + sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_3CYCLES; + sConfigInjected.ExternalTrigInjecConvEdge = ADC_EXTERNALTRIGINJECCONVEDGE_RISING; + sConfigInjected.AutoInjectedConv = DISABLE; + sConfigInjected.InjectedDiscontinuousConvMode = DISABLE; + sConfigInjected.InjectedOffset = 0; + + // automating TRGO flag finding - hardware specific + uint8_t tim_num = 0; + while(driver_params->timers[tim_num] != NP && tim_num < 6){ + uint32_t trigger_flag = _timerToInjectedTRGO(driver_params->timers[tim_num++]); + if(trigger_flag == _TRGO_NOT_AVAILABLE) continue; // timer does not have valid trgo for injected channels + + // if the code comes here, it has found the timer available + // timer does have trgo flag for injected channels + sConfigInjected.ExternalTrigInjecConv = trigger_flag; + + // this will be the timer with which the ADC will sync + cs_params->timer_handle = driver_params->timers[tim_num-1]; + // done + break; + } + if( cs_params->timer_handle == NP ){ + // not possible to use these timers for low-side current sense + #ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot sync any timer to injected channels!"); + #endif + return -1; + } + // display which timer is being used + #ifdef SIMPLEFOC_STM32_DEBUG + // it would be better to use the getTimerNumber from driver + SIMPLEFOC_DEBUG("STM32-CS: injected trigger for timer index: ", get_timer_index(cs_params->timer_handle->getHandle()->Instance) + 1); + #endif + + + // first channel + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_1; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[0])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[0])) ); +#endif + return -1; + } + + // second channel + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_2; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[1])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[1]))) ; +#endif + return -1; + } + + // third channel - if exists + if(_isset(cs_params->pins[2])){ + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_3; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[2])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[2]))) ; +#endif + return -1; + } + } + + // enable interrupt + HAL_NVIC_SetPriority(ADC_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC_IRQn); + + cs_params->adc_handle = &hadc; + return 0; +} + +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC) +{ + uint8_t cnt = 0; + if(_isset(pinA)){ + pinmap_pinout(analogInputToPinName(pinA), PinMap_ADC); + cs_params->pins[cnt++] = pinA; + } + if(_isset(pinB)){ + pinmap_pinout(analogInputToPinName(pinB), PinMap_ADC); + cs_params->pins[cnt++] = pinB; + } + if(_isset(pinC)){ + pinmap_pinout(analogInputToPinName(pinC), PinMap_ADC); + cs_params->pins[cnt] = pinC; + } +} + +extern "C" { + void ADC_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.h new file mode 100644 index 0000000..71071a5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_hal.h @@ -0,0 +1,18 @@ +#ifndef STM32F4_LOWSIDE_HAL +#define STM32F4_LOWSIDE_HAL + +#include "Arduino.h" + +#if defined(STM32F4xx) +#include "stm32f4xx_hal.h" +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../stm32_mcu.h" +#include "stm32f4_utils.h" + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params); +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC); + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_mcu.cpp new file mode 100644 index 0000000..6034478 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_mcu.cpp @@ -0,0 +1,96 @@ +#include "../../../hardware_api.h" + +#if defined(STM32F4xx) +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_api.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../../../hardware_api.h" +#include "../stm32_mcu.h" +#include "stm32f4_hal.h" +#include "stm32f4_utils.h" +#include "Arduino.h" + + +#define _ADC_VOLTAGE_F4 3.3f +#define _ADC_RESOLUTION_F4 4096.0f + + +// array of values of 4 injected channels per adc instance (3) +uint32_t adc_val[3][4]={0}; +// does adc interrupt need a downsample - per adc (3) +bool needs_downsample[3] = {1}; +// downsampling variable - per adc (3) +uint8_t tim_downsample[3] = {0}; + +void* _configureADCLowSide(const void* driver_params, const int pinA, const int pinB, const int pinC){ + + Stm32CurrentSenseParams* cs_params= new Stm32CurrentSenseParams { + .pins={(int)NOT_SET,(int)NOT_SET,(int)NOT_SET}, + .adc_voltage_conv = (_ADC_VOLTAGE_F4) / (_ADC_RESOLUTION_F4) + }; + _adc_gpio_init(cs_params, pinA,pinB,pinC); + if(_adc_init(cs_params, (STM32DriverParams*)driver_params) != 0) return SIMPLEFOC_CURRENT_SENSE_INIT_FAILED; + return cs_params; +} + + +void _driverSyncLowSide(void* _driver_params, void* _cs_params){ + STM32DriverParams* driver_params = (STM32DriverParams*)_driver_params; + Stm32CurrentSenseParams* cs_params = (Stm32CurrentSenseParams*)_cs_params; + + // if compatible timer has not been found + if (cs_params->timer_handle == NULL) return; + + // stop all the timers for the driver + _stopTimers(driver_params->timers, 6); + + // if timer has repetition counter - it will downsample using it + // and it does not need the software downsample + if( IS_TIM_REPETITION_COUNTER_INSTANCE(cs_params->timer_handle->getHandle()->Instance) ){ + // adjust the initial timer state such that the trigger + // - for DMA transfer aligns with the pwm peaks instead of throughs. + // - for interrupt based ADC transfer + // - only necessary for the timers that have repetition counters + cs_params->timer_handle->getHandle()->Instance->CR1 |= TIM_CR1_DIR; + cs_params->timer_handle->getHandle()->Instance->CNT = cs_params->timer_handle->getHandle()->Instance->ARR; + // remember that this timer has repetition counter - no need to downasmple + needs_downsample[_adcToIndex(cs_params->adc_handle)] = 0; + } + // set the trigger output event + LL_TIM_SetTriggerOutput(cs_params->timer_handle->getHandle()->Instance, LL_TIM_TRGO_UPDATE); + // start the adc + HAL_ADCEx_InjectedStart_IT(cs_params->adc_handle); + + // restart all the timers of the driver + _startTimers(driver_params->timers, 6); +} + + +// function reading an ADC value and returning the read voltage +float _readADCVoltageLowSide(const int pin, const void* cs_params){ + for(int i=0; i < 3; i++){ + if( pin == ((Stm32CurrentSenseParams*)cs_params)->pins[i]) // found in the buffer + return adc_val[_adcToIndex(((Stm32CurrentSenseParams*)cs_params)->adc_handle)][i] * ((Stm32CurrentSenseParams*)cs_params)->adc_voltage_conv; + } + return 0; +} + + +extern "C" { + void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *AdcHandle){ + // calculate the instance + int adc_index = _adcToIndex(AdcHandle); + + // if the timer han't repetition counter - downsample two times + if( needs_downsample[adc_index] && tim_downsample[adc_index]++ > 0) { + tim_downsample[adc_index] = 0; + return; + } + + adc_val[adc_index][0]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_1); + adc_val[adc_index][1]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_2); + adc_val[adc_index][2]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_3); + } +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.cpp new file mode 100644 index 0000000..20793d8 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.cpp @@ -0,0 +1,193 @@ +#include "stm32f4_utils.h" + +#if defined(STM32F4xx) + +/* Exported Functions */ +/** + * @brief Return ADC HAL channel linked to a PinName + * @param pin: PinName + * @retval Valid HAL channel + */ +uint32_t _getADCChannel(PinName pin) +{ + uint32_t function = pinmap_function(pin, PinMap_ADC); + uint32_t channel = 0; + switch (STM_PIN_CHANNEL(function)) { +#ifdef ADC_CHANNEL_0 + case 0: + channel = ADC_CHANNEL_0; + break; +#endif + case 1: + channel = ADC_CHANNEL_1; + break; + case 2: + channel = ADC_CHANNEL_2; + break; + case 3: + channel = ADC_CHANNEL_3; + break; + case 4: + channel = ADC_CHANNEL_4; + break; + case 5: + channel = ADC_CHANNEL_5; + break; + case 6: + channel = ADC_CHANNEL_6; + break; + case 7: + channel = ADC_CHANNEL_7; + break; + case 8: + channel = ADC_CHANNEL_8; + break; + case 9: + channel = ADC_CHANNEL_9; + break; + case 10: + channel = ADC_CHANNEL_10; + break; + case 11: + channel = ADC_CHANNEL_11; + break; + case 12: + channel = ADC_CHANNEL_12; + break; + case 13: + channel = ADC_CHANNEL_13; + break; + case 14: + channel = ADC_CHANNEL_14; + break; + case 15: + channel = ADC_CHANNEL_15; + break; +#ifdef ADC_CHANNEL_16 + case 16: + channel = ADC_CHANNEL_16; + break; +#endif + case 17: + channel = ADC_CHANNEL_17; + break; +#ifdef ADC_CHANNEL_18 + case 18: + channel = ADC_CHANNEL_18; + break; +#endif +#ifdef ADC_CHANNEL_19 + case 19: + channel = ADC_CHANNEL_19; + break; +#endif +#ifdef ADC_CHANNEL_20 + case 20: + channel = ADC_CHANNEL_20; + break; + case 21: + channel = ADC_CHANNEL_21; + break; + case 22: + channel = ADC_CHANNEL_22; + break; + case 23: + channel = ADC_CHANNEL_23; + break; +#ifdef ADC_CHANNEL_24 + case 24: + channel = ADC_CHANNEL_24; + break; + case 25: + channel = ADC_CHANNEL_25; + break; + case 26: + channel = ADC_CHANNEL_26; + break; +#ifdef ADC_CHANNEL_27 + case 27: + channel = ADC_CHANNEL_27; + break; + case 28: + channel = ADC_CHANNEL_28; + break; + case 29: + channel = ADC_CHANNEL_29; + break; + case 30: + channel = ADC_CHANNEL_30; + break; + case 31: + channel = ADC_CHANNEL_31; + break; +#endif +#endif +#endif + default: + _Error_Handler("ADC: Unknown adc channel", (int)(STM_PIN_CHANNEL(function))); + break; + } + return channel; +} + + +// timer to injected TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/e156c32db24d69cb4818208ccc28894e2f427cfa/system/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_adc_ex.h#L179 +uint32_t _timerToInjectedTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM1) + return ADC_EXTERNALTRIGINJECCONV_T1_TRGO; +#ifdef TIM2 // if defined timer 2 + else if(timer->getHandle()->Instance == TIM2) + return ADC_EXTERNALTRIGINJECCONV_T2_TRGO; +#endif +#ifdef TIM4 // if defined timer 4 + else if(timer->getHandle()->Instance == TIM4) + return ADC_EXTERNALTRIGINJECCONV_T4_TRGO; +#endif +#ifdef TIM5 // if defined timer 5 + else if(timer->getHandle()->Instance == TIM5) + return ADC_EXTERNALTRIGINJECCONV_T5_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + +// timer to regular TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/e156c32db24d69cb4818208ccc28894e2f427cfa/system/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_adc.h#L331 +uint32_t _timerToRegularTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM2) + return ADC_EXTERNALTRIGCONV_T2_TRGO; +#ifdef TIM3 // if defined timer 3 + else if(timer->getHandle()->Instance == TIM3) + return ADC_EXTERNALTRIGCONV_T3_TRGO; +#endif +#ifdef TIM8 // if defined timer 8 + else if(timer->getHandle()->Instance == TIM8) + return ADC_EXTERNALTRIGCONV_T8_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + + +int _adcToIndex(ADC_TypeDef *AdcHandle){ + if(AdcHandle == ADC1) return 0; +#ifdef ADC2 // if ADC2 exists + else if(AdcHandle == ADC2) return 1; +#endif +#ifdef ADC3 // if ADC3 exists + else if(AdcHandle == ADC3) return 2; +#endif +#ifdef ADC4 // if ADC4 exists + else if(AdcHandle == ADC4) return 3; +#endif +#ifdef ADC5 // if ADC5 exists + else if(AdcHandle == ADC5) return 4; +#endif + return 0; +} +int _adcToIndex(ADC_HandleTypeDef *AdcHandle){ + return _adcToIndex(AdcHandle->Instance); +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.h new file mode 100644 index 0000000..b4549ba --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32f4/stm32f4_utils.h @@ -0,0 +1,34 @@ + +#ifndef STM32F4_UTILS_HAL +#define STM32F4_UTILS_HAL + +#include "Arduino.h" + +#if defined(STM32F4xx) + +#define _TRGO_NOT_AVAILABLE 12345 + + +/* Exported Functions */ +/** + * @brief Return ADC HAL channel linked to a PinName + * @param pin: PinName + * @retval Valid HAL channel + */ +uint32_t _getADCChannel(PinName pin); + +// timer to injected TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/e156c32db24d69cb4818208ccc28894e2f427cfa/system/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_adc_ex.h#L179 +uint32_t _timerToInjectedTRGO(HardwareTimer* timer); + +// timer to regular TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/e156c32db24d69cb4818208ccc28894e2f427cfa/system/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_adc.h#L331 +uint32_t _timerToRegularTRGO(HardwareTimer* timer); + +// function returning index of the ADC instance +int _adcToIndex(ADC_HandleTypeDef *AdcHandle); +int _adcToIndex(ADC_TypeDef *AdcHandle); + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.cpp new file mode 100644 index 0000000..656aed2 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.cpp @@ -0,0 +1,267 @@ +#include "stm32g4_hal.h" + +#if defined(STM32G4xx) && !defined(ARDUINO_B_G431B_ESC1) and !defined(SIMPLEFOC_STM32_CUSTOMCURRENTSENSE) + +#include "../../../../communication/SimpleFOCDebug.h" + +#define SIMPLEFOC_STM32_DEBUG + +ADC_HandleTypeDef hadc; + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params) +{ + ADC_InjectionConfTypeDef sConfigInjected; + + // check if all pins belong to the same ADC + ADC_TypeDef* adc_pin1 = (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[0]), PinMap_ADC); + ADC_TypeDef* adc_pin2 = (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[1]), PinMap_ADC); + ADC_TypeDef* adc_pin3 = _isset(cs_params->pins[2]) ? (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[2]), PinMap_ADC) : nullptr; + if ( (adc_pin1 != adc_pin2) || ( (adc_pin3) && (adc_pin1 != adc_pin3) )){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: Analog pins dont belong to the same ADC!"); +#endif + return -1; + } + + + /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) + */ + hadc.Instance = (ADC_TypeDef *)pinmap_peripheral(analogInputToPinName(cs_params->pins[0]), PinMap_ADC); + + if(hadc.Instance == ADC1) { +#ifdef __HAL_RCC_ADC1_CLK_ENABLE + __HAL_RCC_ADC1_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC12_CLK_ENABLE + __HAL_RCC_ADC12_CLK_ENABLE(); +#endif + } +#ifdef ADC2 + else if (hadc.Instance == ADC2) { +#ifdef __HAL_RCC_ADC2_CLK_ENABLE + __HAL_RCC_ADC2_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC12_CLK_ENABLE + __HAL_RCC_ADC12_CLK_ENABLE(); +#endif + } +#endif +#ifdef ADC3 + else if (hadc.Instance == ADC3) { +#ifdef __HAL_RCC_ADC3_CLK_ENABLE + __HAL_RCC_ADC3_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC34_CLK_ENABLE + __HAL_RCC_ADC34_CLK_ENABLE(); +#endif +#if defined(ADC345_COMMON) + __HAL_RCC_ADC345_CLK_ENABLE(); +#endif + } +#endif +#ifdef ADC4 + else if (hadc.Instance == ADC4) { +#ifdef __HAL_RCC_ADC4_CLK_ENABLE + __HAL_RCC_ADC4_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC34_CLK_ENABLE + __HAL_RCC_ADC34_CLK_ENABLE(); +#endif +#if defined(ADC345_COMMON) + __HAL_RCC_ADC345_CLK_ENABLE(); +#endif + } +#endif +#ifdef ADC5 + else if (hadc.Instance == ADC5) { +#if defined(ADC345_COMMON) + __HAL_RCC_ADC345_CLK_ENABLE(); +#endif + } +#endif + else{ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: Pin does not belong to any ADC!"); +#endif + return -1; // error not a valid ADC instance + } + +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: Using ADC: ", _adcToIndex(&hadc)+1); +#endif + + hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; + hadc.Init.Resolution = ADC_RESOLUTION_12B; + hadc.Init.ScanConvMode = ADC_SCAN_ENABLE; + hadc.Init.ContinuousConvMode = DISABLE; + hadc.Init.LowPowerAutoWait = DISABLE; + hadc.Init.GainCompensation = 0; + hadc.Init.DiscontinuousConvMode = DISABLE; + hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START; // for now + hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc.Init.NbrOfConversion = 2; + hadc.Init.DMAContinuousRequests = DISABLE; + hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + hadc.Init.Overrun = ADC_OVR_DATA_PRESERVED; + if ( HAL_ADC_Init(&hadc) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init ADC!"); +#endif + return -1; + } + + /**Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time + */ + sConfigInjected.InjectedNbrOfConversion = _isset(cs_params->pins[2]) ? 3 : 2; + sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_2CYCLES_5; + sConfigInjected.ExternalTrigInjecConvEdge = ADC_EXTERNALTRIGINJECCONV_EDGE_RISING; + sConfigInjected.AutoInjectedConv = DISABLE; + sConfigInjected.InjectedSingleDiff = ADC_SINGLE_ENDED; + sConfigInjected.InjectedDiscontinuousConvMode = DISABLE; + sConfigInjected.InjectedOffsetNumber = ADC_OFFSET_NONE; + sConfigInjected.InjectedOffset = 0; + sConfigInjected.InjecOversamplingMode = DISABLE; + sConfigInjected.QueueInjectedContext = DISABLE; + + // automating TRGO flag finding - hardware specific + uint8_t tim_num = 0; + while(driver_params->timers[tim_num] != NP && tim_num < 6){ + uint32_t trigger_flag = _timerToInjectedTRGO(driver_params->timers[tim_num++]); + if(trigger_flag == _TRGO_NOT_AVAILABLE) continue; // timer does not have valid trgo for injected channels + + // if the code comes here, it has found the timer available + // timer does have trgo flag for injected channels + sConfigInjected.ExternalTrigInjecConv = trigger_flag; + + // this will be the timer with which the ADC will sync + cs_params->timer_handle = driver_params->timers[tim_num-1]; + // done + break; + } + if( cs_params->timer_handle == NP ){ + // not possible to use these timers for low-side current sense +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot sync any timer to injected channels!"); +#endif + return -1; + } + + + // first channel + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_1; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[0])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[0])) ); +#endif + return -1; + } + + // second channel + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_2; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[1])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[1]))) ; +#endif + return -1; + } + + // third channel - if exists + if(_isset(cs_params->pins[2])){ + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_3; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[2])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[2]))) ; +#endif + return -1; + } + } + + + + if(hadc.Instance == ADC1) { + // enable interrupt + HAL_NVIC_SetPriority(ADC1_2_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC1_2_IRQn); + } +#ifdef ADC2 + else if (hadc.Instance == ADC2) { + // enable interrupt + HAL_NVIC_SetPriority(ADC1_2_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC1_2_IRQn); + } +#endif +#ifdef ADC3 + else if (hadc.Instance == ADC3) { + // enable interrupt + HAL_NVIC_SetPriority(ADC3_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC3_IRQn); + } +#endif +#ifdef ADC4 + else if (hadc.Instance == ADC4) { + // enable interrupt + HAL_NVIC_SetPriority(ADC4_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC4_IRQn); + } +#endif +#ifdef ADC5 + else if (hadc.Instance == ADC5) { + // enable interrupt + HAL_NVIC_SetPriority(ADC5_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC5_IRQn); + } +#endif + + cs_params->adc_handle = &hadc; + return 0; +} + +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC) +{ + uint8_t cnt = 0; + if(_isset(pinA)){ + pinmap_pinout(analogInputToPinName(pinA), PinMap_ADC); + cs_params->pins[cnt++] = pinA; + } + if(_isset(pinB)){ + pinmap_pinout(analogInputToPinName(pinB), PinMap_ADC); + cs_params->pins[cnt++] = pinB; + } + if(_isset(pinC)){ + pinmap_pinout(analogInputToPinName(pinC), PinMap_ADC); + cs_params->pins[cnt] = pinC; + } +} + +extern "C" { + void ADC1_2_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#ifdef ADC3 + void ADC3_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#endif + +#ifdef ADC4 + void ADC4_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#endif + +#ifdef ADC5 + void ADC5_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#endif +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.h new file mode 100644 index 0000000..2298b17 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_hal.h @@ -0,0 +1,19 @@ +#ifndef STM32G4_LOWSIDE_HAL +#define STM32G4_LOWSIDE_HAL + +#include "Arduino.h" + +#if defined(STM32G4xx) && !defined(ARDUINO_B_G431B_ESC1) + +#include "stm32g4xx_hal.h" +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../stm32_mcu.h" +#include "stm32g4_utils.h" + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params); +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC); + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_mcu.cpp new file mode 100644 index 0000000..38fe3a0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_mcu.cpp @@ -0,0 +1,98 @@ +#include "../../../hardware_api.h" + +#if defined(STM32G4xx) && !defined(ARDUINO_B_G431B_ESC1) and !defined(SIMPLEFOC_STM32_CUSTOMCURRENTSENSE) + +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_api.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../../../hardware_api.h" +#include "../stm32_mcu.h" +#include "stm32g4_hal.h" +#include "stm32g4_utils.h" +#include "Arduino.h" + + +#define _ADC_VOLTAGE_G4 3.3f +#define _ADC_RESOLUTION_G4 4096.0f + + +// array of values of 4 injected channels per adc instance (5) +uint32_t adc_val[5][4]={0}; +// does adc interrupt need a downsample - per adc (5) +bool needs_downsample[5] = {1}; +// downsampling variable - per adc (5) +uint8_t tim_downsample[5] = {0}; + + +void* _configureADCLowSide(const void* driver_params, const int pinA, const int pinB, const int pinC){ + + Stm32CurrentSenseParams* cs_params= new Stm32CurrentSenseParams { + .pins={(int)NOT_SET, (int)NOT_SET, (int)NOT_SET}, + .adc_voltage_conv = (_ADC_VOLTAGE_G4) / (_ADC_RESOLUTION_G4) + }; + _adc_gpio_init(cs_params, pinA,pinB,pinC); + if(_adc_init(cs_params, (STM32DriverParams*)driver_params) != 0) return SIMPLEFOC_CURRENT_SENSE_INIT_FAILED; + return cs_params; +} + + +void _driverSyncLowSide(void* _driver_params, void* _cs_params){ + STM32DriverParams* driver_params = (STM32DriverParams*)_driver_params; + Stm32CurrentSenseParams* cs_params = (Stm32CurrentSenseParams*)_cs_params; + + // if compatible timer has not been found + if (cs_params->timer_handle == NULL) return; + + // stop all the timers for the driver + _stopTimers(driver_params->timers, 6); + + // if timer has repetition counter - it will downsample using it + // and it does not need the software downsample + if( IS_TIM_REPETITION_COUNTER_INSTANCE(cs_params->timer_handle->getHandle()->Instance) ){ + // adjust the initial timer state such that the trigger + // - for DMA transfer aligns with the pwm peaks instead of throughs. + // - for interrupt based ADC transfer + // - only necessary for the timers that have repetition counters + cs_params->timer_handle->getHandle()->Instance->CR1 |= TIM_CR1_DIR; + cs_params->timer_handle->getHandle()->Instance->CNT = cs_params->timer_handle->getHandle()->Instance->ARR; + // remember that this timer has repetition counter - no need to downasmple + needs_downsample[_adcToIndex(cs_params->adc_handle)] = 0; + } + + // set the trigger output event + LL_TIM_SetTriggerOutput(cs_params->timer_handle->getHandle()->Instance, LL_TIM_TRGO_UPDATE); + // start the adc + HAL_ADCEx_InjectedStart_IT(cs_params->adc_handle); + // restart all the timers of the driver + _startTimers(driver_params->timers, 6); +} + + +// function reading an ADC value and returning the read voltage +float _readADCVoltageLowSide(const int pin, const void* cs_params){ + for(int i=0; i < 3; i++){ + if( pin == ((Stm32CurrentSenseParams*)cs_params)->pins[i]) // found in the buffer + return adc_val[_adcToIndex(((Stm32CurrentSenseParams*)cs_params)->adc_handle)][i] * ((Stm32CurrentSenseParams*)cs_params)->adc_voltage_conv; + } + return 0; +} + + +extern "C" { + void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *AdcHandle){ + // calculate the instance + int adc_index = _adcToIndex(AdcHandle); + + // if the timer han't repetition counter - downsample two times + if( needs_downsample[adc_index] && tim_downsample[adc_index]++ > 0) { + tim_downsample[adc_index] = 0; + return; + } + + adc_val[adc_index][0]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_1); + adc_val[adc_index][1]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_2); + adc_val[adc_index][2]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_3); + } +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.cpp new file mode 100644 index 0000000..49e53f0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.cpp @@ -0,0 +1,237 @@ +#include "stm32g4_utils.h" + +#if defined(STM32G4xx) && !defined(ARDUINO_B_G431B_ESC1) and !defined(SIMPLEFOC_STM32_CUSTOMCURRENTSENSE) + +/* Exported Functions */ +/** + * @brief Return ADC HAL channel linked to a PinName + * @param pin: PinName + * @retval Valid HAL channel + */ +uint32_t _getADCChannel(PinName pin) +{ + uint32_t function = pinmap_function(pin, PinMap_ADC); + uint32_t channel = 0; + switch (STM_PIN_CHANNEL(function)) { +#ifdef ADC_CHANNEL_0 + case 0: + channel = ADC_CHANNEL_0; + break; +#endif + case 1: + channel = ADC_CHANNEL_1; + break; + case 2: + channel = ADC_CHANNEL_2; + break; + case 3: + channel = ADC_CHANNEL_3; + break; + case 4: + channel = ADC_CHANNEL_4; + break; + case 5: + channel = ADC_CHANNEL_5; + break; + case 6: + channel = ADC_CHANNEL_6; + break; + case 7: + channel = ADC_CHANNEL_7; + break; + case 8: + channel = ADC_CHANNEL_8; + break; + case 9: + channel = ADC_CHANNEL_9; + break; + case 10: + channel = ADC_CHANNEL_10; + break; + case 11: + channel = ADC_CHANNEL_11; + break; + case 12: + channel = ADC_CHANNEL_12; + break; + case 13: + channel = ADC_CHANNEL_13; + break; + case 14: + channel = ADC_CHANNEL_14; + break; + case 15: + channel = ADC_CHANNEL_15; + break; +#ifdef ADC_CHANNEL_16 + case 16: + channel = ADC_CHANNEL_16; + break; +#endif + case 17: + channel = ADC_CHANNEL_17; + break; +#ifdef ADC_CHANNEL_18 + case 18: + channel = ADC_CHANNEL_18; + break; +#endif +#ifdef ADC_CHANNEL_19 + case 19: + channel = ADC_CHANNEL_19; + break; +#endif +#ifdef ADC_CHANNEL_20 + case 20: + channel = ADC_CHANNEL_20; + break; + case 21: + channel = ADC_CHANNEL_21; + break; + case 22: + channel = ADC_CHANNEL_22; + break; + case 23: + channel = ADC_CHANNEL_23; + break; +#ifdef ADC_CHANNEL_24 + case 24: + channel = ADC_CHANNEL_24; + break; + case 25: + channel = ADC_CHANNEL_25; + break; + case 26: + channel = ADC_CHANNEL_26; + break; +#ifdef ADC_CHANNEL_27 + case 27: + channel = ADC_CHANNEL_27; + break; + case 28: + channel = ADC_CHANNEL_28; + break; + case 29: + channel = ADC_CHANNEL_29; + break; + case 30: + channel = ADC_CHANNEL_30; + break; + case 31: + channel = ADC_CHANNEL_31; + break; +#endif +#endif +#endif + default: + _Error_Handler("ADC: Unknown adc channel", (int)(STM_PIN_CHANNEL(function))); + break; + } + return channel; +} + + +// timer to injected TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/6588dee03382e73ed42c4a5e473900ab3b79d6e4/system/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_adc_ex.h#L217 +uint32_t _timerToInjectedTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM1) + return ADC_EXTERNALTRIGINJEC_T1_TRGO; +#ifdef TIM2 // if defined timer 2 + else if(timer->getHandle()->Instance == TIM2) + return ADC_EXTERNALTRIGINJEC_T2_TRGO; +#endif +#ifdef TIM3 // if defined timer 3 + else if(timer->getHandle()->Instance == TIM3) + return ADC_EXTERNALTRIGINJEC_T3_TRGO; +#endif +#ifdef TIM4 // if defined timer 4 + else if(timer->getHandle()->Instance == TIM4) + return ADC_EXTERNALTRIGINJEC_T4_TRGO; +#endif +#ifdef TIM6 // if defined timer 6 + else if(timer->getHandle()->Instance == TIM6) + return ADC_EXTERNALTRIGINJEC_T6_TRGO; +#endif +#ifdef TIM7 // if defined timer 7 + else if(timer->getHandle()->Instance == TIM7) + return ADC_EXTERNALTRIGINJEC_T7_TRGO; +#endif +#ifdef TIM8 // if defined timer 8 + else if(timer->getHandle()->Instance == TIM8) + return ADC_EXTERNALTRIGINJEC_T8_TRGO; +#endif +#ifdef TIM15 // if defined timer 15 + else if(timer->getHandle()->Instance == TIM15) + return ADC_EXTERNALTRIGINJEC_T15_TRGO; +#endif +#ifdef TIM20 // if defined timer 15 + else if(timer->getHandle()->Instance == TIM20) + return ADC_EXTERNALTRIGINJEC_T20_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + +// timer to regular TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/6588dee03382e73ed42c4a5e473900ab3b79d6e4/system/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_adc.h#L519 +uint32_t _timerToRegularTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM1) + return ADC_EXTERNALTRIG_T1_TRGO; +#ifdef TIM2 // if defined timer 2 + else if(timer->getHandle()->Instance == TIM2) + return ADC_EXTERNALTRIG_T2_TRGO; +#endif +#ifdef TIM3 // if defined timer 3 + else if(timer->getHandle()->Instance == TIM3) + return ADC_EXTERNALTRIG_T3_TRGO; +#endif +#ifdef TIM4 // if defined timer 4 + else if(timer->getHandle()->Instance == TIM4) + return ADC_EXTERNALTRIG_T4_TRGO; +#endif +#ifdef TIM6 // if defined timer 6 + else if(timer->getHandle()->Instance == TIM6) + return ADC_EXTERNALTRIG_T6_TRGO; +#endif +#ifdef TIM7 // if defined timer 7 + else if(timer->getHandle()->Instance == TIM7) + return ADC_EXTERNALTRIG_T7_TRGO; +#endif +#ifdef TIM8 // if defined timer 8 + else if(timer->getHandle()->Instance == TIM8) + return ADC_EXTERNALTRIG_T7_TRGO; +#endif +#ifdef TIM15 // if defined timer 15 + else if(timer->getHandle()->Instance == TIM15) + return ADC_EXTERNALTRIG_T15_TRGO; +#endif +#ifdef TIM20 // if defined timer 15 + else if(timer->getHandle()->Instance == TIM20) + return ADC_EXTERNALTRIG_T20_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + + +int _adcToIndex(ADC_TypeDef *AdcHandle){ + if(AdcHandle == ADC1) return 0; +#ifdef ADC2 // if ADC2 exists + else if(AdcHandle == ADC2) return 1; +#endif +#ifdef ADC3 // if ADC3 exists + else if(AdcHandle == ADC3) return 2; +#endif +#ifdef ADC4 // if ADC4 exists + else if(AdcHandle == ADC4) return 3; +#endif +#ifdef ADC5 // if ADC5 exists + else if(AdcHandle == ADC5) return 4; +#endif + return 0; +} +int _adcToIndex(ADC_HandleTypeDef *AdcHandle){ + return _adcToIndex(AdcHandle->Instance); +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.h new file mode 100644 index 0000000..85552d7 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32g4/stm32g4_utils.h @@ -0,0 +1,34 @@ + +#ifndef STM32G4_UTILS_HAL +#define STM32G4_UTILS_HAL + +#include "Arduino.h" + +#if defined(STM32G4xx) && !defined(ARDUINO_B_G431B_ESC1) and !defined(SIMPLEFOC_STM32_CUSTOMCURRENTSENSE) + +#define _TRGO_NOT_AVAILABLE 12345 + + +/* Exported Functions */ +/** + * @brief Return ADC HAL channel linked to a PinName + * @param pin: PinName + * @retval Valid HAL channel + */ +uint32_t _getADCChannel(PinName pin); + +// timer to injected TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/6588dee03382e73ed42c4a5e473900ab3b79d6e4/system/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_adc_ex.h#L217 +uint32_t _timerToInjectedTRGO(HardwareTimer* timer); + +// timer to regular TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/6588dee03382e73ed42c4a5e473900ab3b79d6e4/system/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_adc.h#L519 +uint32_t _timerToRegularTRGO(HardwareTimer* timer); + +// function returning index of the ADC instance +int _adcToIndex(ADC_HandleTypeDef *AdcHandle); +int _adcToIndex(ADC_TypeDef *AdcHandle); + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.cpp new file mode 100644 index 0000000..bfec217 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.cpp @@ -0,0 +1,266 @@ +#include "stm32l4_hal.h" + +#if defined(STM32L4xx) + +#include "../../../../communication/SimpleFOCDebug.h" + +#define SIMPLEFOC_STM32_DEBUG + +ADC_HandleTypeDef hadc; + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params) +{ + ADC_InjectionConfTypeDef sConfigInjected; + + // check if all pins belong to the same ADC + ADC_TypeDef* adc_pin1 = (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[0]), PinMap_ADC); + ADC_TypeDef* adc_pin2 = (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[1]), PinMap_ADC); + ADC_TypeDef* adc_pin3 = _isset(cs_params->pins[2]) ? (ADC_TypeDef*)pinmap_peripheral(analogInputToPinName(cs_params->pins[2]), PinMap_ADC) : nullptr; + if ( (adc_pin1 != adc_pin2) || ( (adc_pin3) && (adc_pin1 != adc_pin3) )){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: Analog pins dont belong to the same ADC!"); +#endif + return -1; + } + + + /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) + */ + hadc.Instance = (ADC_TypeDef *)pinmap_peripheral(analogInputToPinName(cs_params->pins[0]), PinMap_ADC); + + if(hadc.Instance == ADC1) { +#ifdef __HAL_RCC_ADC1_CLK_ENABLE + __HAL_RCC_ADC1_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC12_CLK_ENABLE + __HAL_RCC_ADC12_CLK_ENABLE(); +#endif + } +#ifdef ADC2 + else if (hadc.Instance == ADC2) { +#ifdef __HAL_RCC_ADC2_CLK_ENABLE + __HAL_RCC_ADC2_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC12_CLK_ENABLE + __HAL_RCC_ADC12_CLK_ENABLE(); +#endif + } +#endif +#ifdef ADC3 + else if (hadc.Instance == ADC3) { +#ifdef __HAL_RCC_ADC3_CLK_ENABLE + __HAL_RCC_ADC3_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC34_CLK_ENABLE + __HAL_RCC_ADC34_CLK_ENABLE(); +#endif +#if defined(ADC345_COMMON) + __HAL_RCC_ADC345_CLK_ENABLE(); +#endif + } +#endif +#ifdef ADC4 + else if (hadc.Instance == ADC4) { +#ifdef __HAL_RCC_ADC4_CLK_ENABLE + __HAL_RCC_ADC4_CLK_ENABLE(); +#endif +#ifdef __HAL_RCC_ADC34_CLK_ENABLE + __HAL_RCC_ADC34_CLK_ENABLE(); +#endif +#if defined(ADC345_COMMON) + __HAL_RCC_ADC345_CLK_ENABLE(); +#endif + } +#endif +#ifdef ADC5 + else if (hadc.Instance == ADC5) { +#if defined(ADC345_COMMON) + __HAL_RCC_ADC345_CLK_ENABLE(); +#endif + } +#endif + else{ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: Pin does not belong to any ADC!"); +#endif + return -1; // error not a valid ADC instance + } + +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: Using ADC: ", _adcToIndex(&hadc)+1); +#endif + + hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; + hadc.Init.Resolution = ADC_RESOLUTION_12B; + hadc.Init.ScanConvMode = ADC_SCAN_ENABLE; + hadc.Init.ContinuousConvMode = DISABLE; + hadc.Init.LowPowerAutoWait = DISABLE; + hadc.Init.DiscontinuousConvMode = DISABLE; + hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START; // for now + hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc.Init.NbrOfConversion = 2; + hadc.Init.DMAContinuousRequests = DISABLE; + hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + hadc.Init.Overrun = ADC_OVR_DATA_PRESERVED; + if ( HAL_ADC_Init(&hadc) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init ADC!"); +#endif + return -1; + } + + /**Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time + */ + sConfigInjected.InjectedNbrOfConversion = _isset(cs_params->pins[2]) ? 3 : 2; + sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_2CYCLES_5; + sConfigInjected.ExternalTrigInjecConvEdge = ADC_EXTERNALTRIGINJECCONV_EDGE_RISING; + sConfigInjected.AutoInjectedConv = DISABLE; + sConfigInjected.InjectedSingleDiff = ADC_SINGLE_ENDED; + sConfigInjected.InjectedDiscontinuousConvMode = DISABLE; + sConfigInjected.InjectedOffsetNumber = ADC_OFFSET_NONE; + sConfigInjected.InjectedOffset = 0; + sConfigInjected.InjecOversamplingMode = DISABLE; + sConfigInjected.QueueInjectedContext = DISABLE; + + // automating TRGO flag finding - hardware specific + uint8_t tim_num = 0; + while(driver_params->timers[tim_num] != NP && tim_num < 6){ + uint32_t trigger_flag = _timerToInjectedTRGO(driver_params->timers[tim_num++]); + if(trigger_flag == _TRGO_NOT_AVAILABLE) continue; // timer does not have valid trgo for injected channels + + // if the code comes here, it has found the timer available + // timer does have trgo flag for injected channels + sConfigInjected.ExternalTrigInjecConv = trigger_flag; + + // this will be the timer with which the ADC will sync + cs_params->timer_handle = driver_params->timers[tim_num-1]; + // done + break; + } + if( cs_params->timer_handle == NP ){ + // not possible to use these timers for low-side current sense +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot sync any timer to injected channels!"); +#endif + return -1; + } + + + // first channel + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_1; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[0])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[0])) ); +#endif + return -1; + } + + // second channel + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_2; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[1])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[1]))) ; +#endif + return -1; + } + + // third channel - if exists + if(_isset(cs_params->pins[2])){ + sConfigInjected.InjectedRank = ADC_INJECTED_RANK_3; + sConfigInjected.InjectedChannel = _getADCChannel(analogInputToPinName(cs_params->pins[2])); + if (HAL_ADCEx_InjectedConfigChannel(&hadc, &sConfigInjected) != HAL_OK){ +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-CS: ERR: cannot init injected channel: ", (int)_getADCChannel(analogInputToPinName(cs_params->pins[2]))) ; +#endif + return -1; + } + } + + + + if(hadc.Instance == ADC1) { + // enable interrupt + HAL_NVIC_SetPriority(ADC1_2_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC1_2_IRQn); + } +#ifdef ADC2 + else if (hadc.Instance == ADC2) { + // enable interrupt + HAL_NVIC_SetPriority(ADC1_2_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC1_2_IRQn); + } +#endif +#ifdef ADC3 + else if (hadc.Instance == ADC3) { + // enable interrupt + HAL_NVIC_SetPriority(ADC3_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC3_IRQn); + } +#endif +#ifdef ADC4 + else if (hadc.Instance == ADC4) { + // enable interrupt + HAL_NVIC_SetPriority(ADC4_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC4_IRQn); + } +#endif +#ifdef ADC5 + else if (hadc.Instance == ADC5) { + // enable interrupt + HAL_NVIC_SetPriority(ADC5_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ADC5_IRQn); + } +#endif + + cs_params->adc_handle = &hadc; + return 0; +} + +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC) +{ + uint8_t cnt = 0; + if(_isset(pinA)){ + pinmap_pinout(analogInputToPinName(pinA), PinMap_ADC); + cs_params->pins[cnt++] = pinA; + } + if(_isset(pinB)){ + pinmap_pinout(analogInputToPinName(pinB), PinMap_ADC); + cs_params->pins[cnt++] = pinB; + } + if(_isset(pinC)){ + pinmap_pinout(analogInputToPinName(pinC), PinMap_ADC); + cs_params->pins[cnt] = pinC; + } +} + +extern "C" { + void ADC1_2_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#ifdef ADC3 + void ADC3_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#endif + +#ifdef ADC4 + void ADC4_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#endif + +#ifdef ADC5 + void ADC5_IRQHandler(void) + { + HAL_ADC_IRQHandler(&hadc); + } +#endif +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.h new file mode 100644 index 0000000..0317b74 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_hal.h @@ -0,0 +1,19 @@ +#ifndef STM32L4_LOWSIDE_HAL +#define STM32L4_LOWSIDE_HAL + +#include "Arduino.h" + +#if defined(STM32L4xx) + +#include "stm32l4xx_hal.h" +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../stm32_mcu.h" +#include "stm32l4_utils.h" + +int _adc_init(Stm32CurrentSenseParams* cs_params, const STM32DriverParams* driver_params); +void _adc_gpio_init(Stm32CurrentSenseParams* cs_params, const int pinA, const int pinB, const int pinC); + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_mcu.cpp new file mode 100644 index 0000000..edac641 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_mcu.cpp @@ -0,0 +1,98 @@ +#include "../../../hardware_api.h" + +#if defined(STM32L4xx) + +#include "../../../../common/foc_utils.h" +#include "../../../../drivers/hardware_api.h" +#include "../../../../drivers/hardware_specific/stm32/stm32_mcu.h" +#include "../../../hardware_api.h" +#include "../stm32_mcu.h" +#include "stm32l4_hal.h" +#include "stm32l4_utils.h" +#include "Arduino.h" + + +#define _ADC_VOLTAGE_L4 3.3f +#define _ADC_RESOLUTION_L4 4096.0f + + +// array of values of 4 injected channels per adc instance (5) +uint32_t adc_val[5][4]={0}; +// does adc interrupt need a downsample - per adc (5) +bool needs_downsample[5] = {1}; +// downsampling variable - per adc (5) +uint8_t tim_downsample[5] = {0}; + + +void* _configureADCLowSide(const void* driver_params, const int pinA, const int pinB, const int pinC){ + + Stm32CurrentSenseParams* cs_params= new Stm32CurrentSenseParams { + .pins={(int)NOT_SET, (int)NOT_SET, (int)NOT_SET}, + .adc_voltage_conv = (_ADC_VOLTAGE_L4) / (_ADC_RESOLUTION_L4) + }; + _adc_gpio_init(cs_params, pinA,pinB,pinC); + if(_adc_init(cs_params, (STM32DriverParams*)driver_params) != 0) return SIMPLEFOC_CURRENT_SENSE_INIT_FAILED; + return cs_params; +} + + +void _driverSyncLowSide(void* _driver_params, void* _cs_params){ + STM32DriverParams* driver_params = (STM32DriverParams*)_driver_params; + Stm32CurrentSenseParams* cs_params = (Stm32CurrentSenseParams*)_cs_params; + + // if compatible timer has not been found + if (cs_params->timer_handle == NULL) return; + + // stop all the timers for the driver + _stopTimers(driver_params->timers, 6); + + // if timer has repetition counter - it will downsample using it + // and it does not need the software downsample + if( IS_TIM_REPETITION_COUNTER_INSTANCE(cs_params->timer_handle->getHandle()->Instance) ){ + // adjust the initial timer state such that the trigger + // - for DMA transfer aligns with the pwm peaks instead of throughs. + // - for interrupt based ADC transfer + // - only necessary for the timers that have repetition counters + cs_params->timer_handle->getHandle()->Instance->CR1 |= TIM_CR1_DIR; + cs_params->timer_handle->getHandle()->Instance->CNT = cs_params->timer_handle->getHandle()->Instance->ARR; + // remember that this timer has repetition counter - no need to downasmple + needs_downsample[_adcToIndex(cs_params->adc_handle)] = 0; + } + + // set the trigger output event + LL_TIM_SetTriggerOutput(cs_params->timer_handle->getHandle()->Instance, LL_TIM_TRGO_UPDATE); + // start the adc + HAL_ADCEx_InjectedStart_IT(cs_params->adc_handle); + // restart all the timers of the driver + _startTimers(driver_params->timers, 6); +} + + +// function reading an ADC value and returning the read voltage +float _readADCVoltageLowSide(const int pin, const void* cs_params){ + for(int i=0; i < 3; i++){ + if( pin == ((Stm32CurrentSenseParams*)cs_params)->pins[i]) // found in the buffer + return adc_val[_adcToIndex(((Stm32CurrentSenseParams*)cs_params)->adc_handle)][i] * ((Stm32CurrentSenseParams*)cs_params)->adc_voltage_conv; + } + return 0; +} + + +extern "C" { + void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *AdcHandle){ + // calculate the instance + int adc_index = _adcToIndex(AdcHandle); + + // if the timer han't repetition counter - downsample two times + if( needs_downsample[adc_index] && tim_downsample[adc_index]++ > 0) { + tim_downsample[adc_index] = 0; + return; + } + + adc_val[adc_index][0]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_1); + adc_val[adc_index][1]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_2); + adc_val[adc_index][2]=HAL_ADCEx_InjectedGetValue(AdcHandle, ADC_INJECTED_RANK_3); + } +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.cpp new file mode 100644 index 0000000..376d9d6 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.cpp @@ -0,0 +1,221 @@ +#include "stm32l4_utils.h" + +#if defined(STM32L4xx) + +/* Exported Functions */ +/** + * @brief Return ADC HAL channel linked to a PinName + * @param pin: PinName + * @retval Valid HAL channel + */ +uint32_t _getADCChannel(PinName pin) +{ + uint32_t function = pinmap_function(pin, PinMap_ADC); + uint32_t channel = 0; + switch (STM_PIN_CHANNEL(function)) { +#ifdef ADC_CHANNEL_0 + case 0: + channel = ADC_CHANNEL_0; + break; +#endif + case 1: + channel = ADC_CHANNEL_1; + break; + case 2: + channel = ADC_CHANNEL_2; + break; + case 3: + channel = ADC_CHANNEL_3; + break; + case 4: + channel = ADC_CHANNEL_4; + break; + case 5: + channel = ADC_CHANNEL_5; + break; + case 6: + channel = ADC_CHANNEL_6; + break; + case 7: + channel = ADC_CHANNEL_7; + break; + case 8: + channel = ADC_CHANNEL_8; + break; + case 9: + channel = ADC_CHANNEL_9; + break; + case 10: + channel = ADC_CHANNEL_10; + break; + case 11: + channel = ADC_CHANNEL_11; + break; + case 12: + channel = ADC_CHANNEL_12; + break; + case 13: + channel = ADC_CHANNEL_13; + break; + case 14: + channel = ADC_CHANNEL_14; + break; + case 15: + channel = ADC_CHANNEL_15; + break; +#ifdef ADC_CHANNEL_16 + case 16: + channel = ADC_CHANNEL_16; + break; +#endif + case 17: + channel = ADC_CHANNEL_17; + break; +#ifdef ADC_CHANNEL_18 + case 18: + channel = ADC_CHANNEL_18; + break; +#endif +#ifdef ADC_CHANNEL_19 + case 19: + channel = ADC_CHANNEL_19; + break; +#endif +#ifdef ADC_CHANNEL_20 + case 20: + channel = ADC_CHANNEL_20; + break; + case 21: + channel = ADC_CHANNEL_21; + break; + case 22: + channel = ADC_CHANNEL_22; + break; + case 23: + channel = ADC_CHANNEL_23; + break; +#ifdef ADC_CHANNEL_24 + case 24: + channel = ADC_CHANNEL_24; + break; + case 25: + channel = ADC_CHANNEL_25; + break; + case 26: + channel = ADC_CHANNEL_26; + break; +#ifdef ADC_CHANNEL_27 + case 27: + channel = ADC_CHANNEL_27; + break; + case 28: + channel = ADC_CHANNEL_28; + break; + case 29: + channel = ADC_CHANNEL_29; + break; + case 30: + channel = ADC_CHANNEL_30; + break; + case 31: + channel = ADC_CHANNEL_31; + break; +#endif +#endif +#endif + default: + _Error_Handler("ADC: Unknown adc channel", (int)(STM_PIN_CHANNEL(function))); + break; + } + return channel; +} + + +// timer to injected TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/e156c32db24d69cb4818208ccc28894e2f427cfa/system/Drivers/STM32L4xx_HAL_Driver/Inc/stm32l4xx_hal_adc_ex.h#L210 +uint32_t _timerToInjectedTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM1) + return ADC_EXTERNALTRIGINJEC_T1_TRGO; +#ifdef TIM2 // if defined timer 2 + else if(timer->getHandle()->Instance == TIM2) + return ADC_EXTERNALTRIGINJEC_T2_TRGO; +#endif +#ifdef TIM3 // if defined timer 3 + else if(timer->getHandle()->Instance == TIM3) + return ADC_EXTERNALTRIGINJEC_T3_TRGO; +#endif +#ifdef TIM4 // if defined timer 4 + else if(timer->getHandle()->Instance == TIM4) + return ADC_EXTERNALTRIGINJEC_T4_TRGO; +#endif +#ifdef TIM6 // if defined timer 6 + else if(timer->getHandle()->Instance == TIM6) + return ADC_EXTERNALTRIGINJEC_T6_TRGO; +#endif +#ifdef TIM8 // if defined timer 8 + else if(timer->getHandle()->Instance == TIM8) + return ADC_EXTERNALTRIGINJEC_T8_TRGO; +#endif +#ifdef TIM15 // if defined timer 15 + else if(timer->getHandle()->Instance == TIM15) + return ADC_EXTERNALTRIGINJEC_T15_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + +// timer to regular TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/6588dee03382e73ed42c4a5e473900ab3b79d6e4/system/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_adc.h#L519 +uint32_t _timerToRegularTRGO(HardwareTimer* timer){ + if(timer->getHandle()->Instance == TIM1) + return ADC_EXTERNALTRIG_T1_TRGO; +#ifdef TIM2 // if defined timer 2 + else if(timer->getHandle()->Instance == TIM2) + return ADC_EXTERNALTRIG_T2_TRGO; +#endif +#ifdef TIM3 // if defined timer 3 + else if(timer->getHandle()->Instance == TIM3) + return ADC_EXTERNALTRIG_T3_TRGO; +#endif +#ifdef TIM4 // if defined timer 4 + else if(timer->getHandle()->Instance == TIM4) + return ADC_EXTERNALTRIG_T4_TRGO; +#endif +#ifdef TIM6 // if defined timer 6 + else if(timer->getHandle()->Instance == TIM6) + return ADC_EXTERNALTRIG_T6_TRGO; +#endif +#ifdef TIM8 // if defined timer 8 + else if(timer->getHandle()->Instance == TIM8) + return ADC_EXTERNALTRIG_T8_TRGO; +#endif +#ifdef TIM15 // if defined timer 15 + else if(timer->getHandle()->Instance == TIM15) + return ADC_EXTERNALTRIG_T15_TRGO; +#endif + else + return _TRGO_NOT_AVAILABLE; +} + + +int _adcToIndex(ADC_TypeDef *AdcHandle){ + if(AdcHandle == ADC1) return 0; +#ifdef ADC2 // if ADC2 exists + else if(AdcHandle == ADC2) return 1; +#endif +#ifdef ADC3 // if ADC3 exists + else if(AdcHandle == ADC3) return 2; +#endif +#ifdef ADC4 // if ADC4 exists + else if(AdcHandle == ADC4) return 3; +#endif +#ifdef ADC5 // if ADC5 exists + else if(AdcHandle == ADC5) return 4; +#endif + return 0; +} +int _adcToIndex(ADC_HandleTypeDef *AdcHandle){ + return _adcToIndex(AdcHandle->Instance); +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.h b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.h new file mode 100644 index 0000000..ceef9be --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/stm32/stm32l4/stm32l4_utils.h @@ -0,0 +1,34 @@ + +#ifndef STM32L4_UTILS_HAL +#define STM32L4_UTILS_HAL + +#include "Arduino.h" + +#if defined(STM32L4xx) + +#define _TRGO_NOT_AVAILABLE 12345 + + +/* Exported Functions */ +/** + * @brief Return ADC HAL channel linked to a PinName + * @param pin: PinName + * @retval Valid HAL channel + */ +uint32_t _getADCChannel(PinName pin); + +// timer to injected TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/6588dee03382e73ed42c4a5e473900ab3b79d6e4/system/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_adc_ex.h#L217 +uint32_t _timerToInjectedTRGO(HardwareTimer* timer); + +// timer to regular TRGO +// https://github.com/stm32duino/Arduino_Core_STM32/blob/6588dee03382e73ed42c4a5e473900ab3b79d6e4/system/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_adc.h#L519 +uint32_t _timerToRegularTRGO(HardwareTimer* timer); + +// function returning index of the ADC instance +int _adcToIndex(ADC_HandleTypeDef *AdcHandle); +int _adcToIndex(ADC_TypeDef *AdcHandle); + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/teensy_mcu.cpp b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/teensy_mcu.cpp new file mode 100644 index 0000000..7ab370a --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/current_sense/hardware_specific/teensy_mcu.cpp @@ -0,0 +1,24 @@ +#include "../hardware_api.h" + +#if defined(__arm__) && defined(CORE_TEENSY) + +#define _ADC_VOLTAGE 3.3f +#define _ADC_RESOLUTION 1024.0f + +// function reading an ADC value and returning the read voltage +void* _configureADCInline(const void* driver_params, const int pinA,const int pinB,const int pinC){ + _UNUSED(driver_params); + + if( _isset(pinA) ) pinMode(pinA, INPUT); + if( _isset(pinB) ) pinMode(pinB, INPUT); + if( _isset(pinC) ) pinMode(pinC, INPUT); + + GenericCurrentSenseParams* params = new GenericCurrentSenseParams { + .pins = { pinA, pinB, pinC }, + .adc_voltage_conv = (_ADC_VOLTAGE)/(_ADC_RESOLUTION) + }; + + return params; +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.cpp b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.cpp new file mode 100644 index 0000000..637c8db --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.cpp @@ -0,0 +1,92 @@ +#include "BLDCDriver3PWM.h" + +BLDCDriver3PWM::BLDCDriver3PWM(int phA, int phB, int phC, int en1, int en2, int en3){ + // Pin initialization + pwmA = phA; + pwmB = phB; + pwmC = phC; + + // enable_pin pin + enableA_pin = en1; + enableB_pin = en2; + enableC_pin = en3; + + // default power-supply value + voltage_power_supply = DEF_POWER_SUPPLY; + voltage_limit = NOT_SET; + pwm_frequency = NOT_SET; + +} + +// enable motor driver +void BLDCDriver3PWM::enable(){ + // enable_pin the driver - if enable_pin pin available + if ( _isset(enableA_pin) ) digitalWrite(enableA_pin, enable_active_high); + if ( _isset(enableB_pin) ) digitalWrite(enableB_pin, enable_active_high); + if ( _isset(enableC_pin) ) digitalWrite(enableC_pin, enable_active_high); + // set zero to PWM + setPwm(0,0,0); +} + +// disable motor driver +void BLDCDriver3PWM::disable() +{ + // set zero to PWM + setPwm(0, 0, 0); + // disable the driver - if enable_pin pin available + if ( _isset(enableA_pin) ) digitalWrite(enableA_pin, !enable_active_high); + if ( _isset(enableB_pin) ) digitalWrite(enableB_pin, !enable_active_high); + if ( _isset(enableC_pin) ) digitalWrite(enableC_pin, !enable_active_high); + +} + +// init hardware pins +int BLDCDriver3PWM::init() { + // PWM pins + pinMode(pwmA, OUTPUT); + pinMode(pwmB, OUTPUT); + pinMode(pwmC, OUTPUT); + if( _isset(enableA_pin)) pinMode(enableA_pin, OUTPUT); + if( _isset(enableB_pin)) pinMode(enableB_pin, OUTPUT); + if( _isset(enableC_pin)) pinMode(enableC_pin, OUTPUT); + + + // sanity check for the voltage limit configuration + if(!_isset(voltage_limit) || voltage_limit > voltage_power_supply) voltage_limit = voltage_power_supply; + + // Set the pwm frequency to the pins + // hardware specific function - depending on driver and mcu + params = _configure3PWM(pwm_frequency, pwmA, pwmB, pwmC); + initialized = (params!=SIMPLEFOC_DRIVER_INIT_FAILED); + return params!=SIMPLEFOC_DRIVER_INIT_FAILED; +} + + + +// Set voltage to the pwm pin +void BLDCDriver3PWM::setPhaseState(PhaseState sa, PhaseState sb, PhaseState sc) { + // disable if needed + if( _isset(enableA_pin) && _isset(enableB_pin) && _isset(enableC_pin) ){ + digitalWrite(enableA_pin, sa == PhaseState::PHASE_ON ? enable_active_high:!enable_active_high); + digitalWrite(enableB_pin, sb == PhaseState::PHASE_ON ? enable_active_high:!enable_active_high); + digitalWrite(enableC_pin, sc == PhaseState::PHASE_ON ? enable_active_high:!enable_active_high); + } +} + +// Set voltage to the pwm pin +void BLDCDriver3PWM::setPwm(float Ua, float Ub, float Uc) { + + // limit the voltage in driver + Ua = _constrain(Ua, 0.0f, voltage_limit); + Ub = _constrain(Ub, 0.0f, voltage_limit); + Uc = _constrain(Uc, 0.0f, voltage_limit); + // calculate duty cycle + // limited in [0,1] + dc_a = _constrain(Ua / voltage_power_supply, 0.0f , 1.0f ); + dc_b = _constrain(Ub / voltage_power_supply, 0.0f , 1.0f ); + dc_c = _constrain(Uc / voltage_power_supply, 0.0f , 1.0f ); + + // hardware specific writing + // hardware specific function - depending on driver and mcu + _writeDutyCycle3PWM(dc_a, dc_b, dc_c, params); +} diff --git a/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.h b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.h new file mode 100644 index 0000000..1942f60 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver3PWM.h @@ -0,0 +1,64 @@ +#ifndef BLDCDriver3PWM_h +#define BLDCDriver3PWM_h + +#include "../common/base_classes/BLDCDriver.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/defaults.h" +#include "hardware_api.h" + +/** + 3 pwm bldc driver class +*/ +class BLDCDriver3PWM: public BLDCDriver +{ + public: + /** + BLDCDriver class constructor + @param phA A phase pwm pin + @param phB B phase pwm pin + @param phC C phase pwm pin + @param en1 enable pin (optional input) + @param en2 enable pin (optional input) + @param en3 enable pin (optional input) + */ + BLDCDriver3PWM(int phA,int phB,int phC, int en1 = NOT_SET, int en2 = NOT_SET, int en3 = NOT_SET); + + /** Motor hardware init function */ + int init() override; + /** Motor disable function */ + void disable() override; + /** Motor enable function */ + void enable() override; + + // hardware variables + int pwmA; //!< phase A pwm pin number + int pwmB; //!< phase B pwm pin number + int pwmC; //!< phase C pwm pin number + int enableA_pin; //!< enable pin number + int enableB_pin; //!< enable pin number + int enableC_pin; //!< enable pin number + bool enable_active_high = true; + + /** + * Set phase voltages to the harware + * + * @param Ua - phase A voltage + * @param Ub - phase B voltage + * @param Uc - phase C voltage + */ + void setPwm(float Ua, float Ub, float Uc) override; + + /** + * Set phase voltages to the harware + * + * @param sc - phase A state : active / disabled ( high impedance ) + * @param sb - phase B state : active / disabled ( high impedance ) + * @param sa - phase C state : active / disabled ( high impedance ) + */ + virtual void setPhaseState(PhaseState sa, PhaseState sb, PhaseState sc) override; + private: +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.cpp b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.cpp new file mode 100644 index 0000000..4981858 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.cpp @@ -0,0 +1,103 @@ +#include "BLDCDriver6PWM.h" + +BLDCDriver6PWM::BLDCDriver6PWM(int phA_h,int phA_l,int phB_h,int phB_l,int phC_h,int phC_l, int en){ + // Pin initialization + pwmA_h = phA_h; + pwmB_h = phB_h; + pwmC_h = phC_h; + pwmA_l = phA_l; + pwmB_l = phB_l; + pwmC_l = phC_l; + + // enable_pin pin + enable_pin = en; + + // default power-supply value + voltage_power_supply = DEF_POWER_SUPPLY; + voltage_limit = NOT_SET; + pwm_frequency = NOT_SET; + + // dead zone initial - 2% + dead_zone = 0.02f; + +} + +// enable motor driver +void BLDCDriver6PWM::enable(){ + // enable_pin the driver - if enable_pin pin available + if ( _isset(enable_pin) ) digitalWrite(enable_pin, enable_active_high); + // set phase state enabled + setPhaseState(PhaseState::PHASE_ON, PhaseState::PHASE_ON, PhaseState::PHASE_ON); + // set zero to PWM + setPwm(0, 0, 0); +} + +// disable motor driver +void BLDCDriver6PWM::disable() +{ + // set phase state to disabled + setPhaseState(PhaseState::PHASE_OFF, PhaseState::PHASE_OFF, PhaseState::PHASE_OFF); + // set zero to PWM + setPwm(0, 0, 0); + // disable the driver - if enable_pin pin available + if ( _isset(enable_pin) ) digitalWrite(enable_pin, !enable_active_high); + +} + +// init hardware pins +int BLDCDriver6PWM::init() { + + // PWM pins + pinMode(pwmA_h, OUTPUT); + pinMode(pwmB_h, OUTPUT); + pinMode(pwmC_h, OUTPUT); + pinMode(pwmA_l, OUTPUT); + pinMode(pwmB_l, OUTPUT); + pinMode(pwmC_l, OUTPUT); + if(_isset(enable_pin)) pinMode(enable_pin, OUTPUT); + + + // sanity check for the voltage limit configuration + if( !_isset(voltage_limit) || voltage_limit > voltage_power_supply) voltage_limit = voltage_power_supply; + + // set phase state to disabled + phase_state[0] = PhaseState::PHASE_OFF; + phase_state[1] = PhaseState::PHASE_OFF; + phase_state[2] = PhaseState::PHASE_OFF; + + // set zero to PWM + dc_a = dc_b = dc_c = 0; + + // configure 6pwm + // hardware specific function - depending on driver and mcu + params = _configure6PWM(pwm_frequency, dead_zone, pwmA_h,pwmA_l, pwmB_h,pwmB_l, pwmC_h,pwmC_l); + initialized = (params!=SIMPLEFOC_DRIVER_INIT_FAILED); + return params!=SIMPLEFOC_DRIVER_INIT_FAILED; +} + + +// Set voltage to the pwm pin +void BLDCDriver6PWM::setPwm(float Ua, float Ub, float Uc) { + // limit the voltage in driver + Ua = _constrain(Ua, 0, voltage_limit); + Ub = _constrain(Ub, 0, voltage_limit); + Uc = _constrain(Uc, 0, voltage_limit); + // calculate duty cycle + // limited in [0,1] + dc_a = _constrain(Ua / voltage_power_supply, 0.0f , 1.0f ); + dc_b = _constrain(Ub / voltage_power_supply, 0.0f , 1.0f ); + dc_c = _constrain(Uc / voltage_power_supply, 0.0f , 1.0f ); + // hardware specific writing + // hardware specific function - depending on driver and mcu + _writeDutyCycle6PWM(dc_a, dc_b, dc_c, phase_state, params); +} + + +// Set the phase state +// actually changing the state is only done on the next call to setPwm, and depends +// on the hardware capabilities of the driver and MCU. +void BLDCDriver6PWM::setPhaseState(PhaseState sa, PhaseState sb, PhaseState sc) { + phase_state[0] = sa; + phase_state[1] = sb; + phase_state[2] = sc; +} diff --git a/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.h b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.h new file mode 100644 index 0000000..e8643cc --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/BLDCDriver6PWM.h @@ -0,0 +1,70 @@ +#ifndef BLDCDriver6PWM_h +#define BLDCDriver6PWM_h + +#include "../common/base_classes/BLDCDriver.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/defaults.h" +#include "hardware_api.h" + +/** + 6 pwm bldc driver class +*/ +class BLDCDriver6PWM: public BLDCDriver +{ + public: + /** + BLDCDriver class constructor + @param phA_h A phase pwm pin + @param phA_l A phase pwm pin + @param phB_h B phase pwm pin + @param phB_l A phase pwm pin + @param phC_h C phase pwm pin + @param phC_l A phase pwm pin + @param en enable pin (optional input) + */ + BLDCDriver6PWM(int phA_h,int phA_l,int phB_h,int phB_l,int phC_h,int phC_l, int en = NOT_SET); + + /** Motor hardware init function */ + int init() override; + /** Motor disable function */ + void disable() override; + /** Motor enable function */ + void enable() override; + + // hardware variables + int pwmA_h,pwmA_l; //!< phase A pwm pin number + int pwmB_h,pwmB_l; //!< phase B pwm pin number + int pwmC_h,pwmC_l; //!< phase C pwm pin number + int enable_pin; //!< enable pin number + bool enable_active_high = true; + + float dead_zone; //!< a percentage of dead-time(zone) (both high and low side in low) for each pwm cycle [0,1] + + PhaseState phase_state[3]; //!< phase state (active / disabled) + + + /** + * Set phase voltages to the harware + * + * @param Ua - phase A voltage + * @param Ub - phase B voltage + * @param Uc - phase C voltage + */ + void setPwm(float Ua, float Ub, float Uc) override; + + /** + * Set phase voltages to the harware + * + * @param sc - phase A state : active / disabled ( high impedance ) + * @param sb - phase B state : active / disabled ( high impedance ) + * @param sa - phase C state : active / disabled ( high impedance ) + */ + virtual void setPhaseState(PhaseState sa, PhaseState sb, PhaseState sc) override; + + private: + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.cpp b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.cpp new file mode 100644 index 0000000..dbbf5b8 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.cpp @@ -0,0 +1,107 @@ +#include "StepperDriver2PWM.h" + +StepperDriver2PWM::StepperDriver2PWM(int _pwm1, int* _in1, int _pwm2, int* _in2, int en1, int en2){ + // Pin initialization + pwm1 = _pwm1; // phase 1 pwm pin number + dir1a = _in1[0]; // phase 1 INA pin number + dir1b = _in1[1]; // phase 1 INB pin number + pwm2 = _pwm2; // phase 2 pwm pin number + dir2a = _in2[0]; // phase 2 INA pin number + dir2b = _in2[1]; // phase 2 INB pin number + + // enable_pin pin + enable_pin1 = en1; + enable_pin2 = en2; + + // default power-supply value + voltage_power_supply = DEF_POWER_SUPPLY; + voltage_limit = NOT_SET; + pwm_frequency = NOT_SET; + +} + +StepperDriver2PWM::StepperDriver2PWM(int _pwm1, int _dir1, int _pwm2, int _dir2, int en1, int en2){ + // Pin initialization + pwm1 = _pwm1; // phase 1 pwm pin number + dir1a = _dir1; // phase 1 direction pin + pwm2 = _pwm2; // phase 2 pwm pin number + dir2a = _dir2; // phase 2 direction pin + // these pins are not used + dir1b = NOT_SET; + dir2b = NOT_SET; + + // enable_pin pin + enable_pin1 = en1; + enable_pin2 = en2; + + // default power-supply value + voltage_power_supply = DEF_POWER_SUPPLY; + voltage_limit = NOT_SET; + pwm_frequency = NOT_SET; + +} + +// enable motor driver +void StepperDriver2PWM::enable(){ + // enable_pin the driver - if enable_pin pin available + if ( _isset(enable_pin1) ) digitalWrite(enable_pin1, HIGH); + if ( _isset(enable_pin2) ) digitalWrite(enable_pin2, HIGH); + // set zero to PWM + setPwm(0,0); +} + +// disable motor driver +void StepperDriver2PWM::disable() +{ + // set zero to PWM + setPwm(0, 0); + // disable the driver - if enable_pin pin available + if ( _isset(enable_pin1) ) digitalWrite(enable_pin1, LOW); + if ( _isset(enable_pin2) ) digitalWrite(enable_pin2, LOW); + +} + +// init hardware pins +int StepperDriver2PWM::init() { + // PWM pins + pinMode(pwm1, OUTPUT); + pinMode(pwm2, OUTPUT); + pinMode(dir1a, OUTPUT); + pinMode(dir2a, OUTPUT); + if( _isset(dir1b) ) pinMode(dir1b, OUTPUT); + if( _isset(dir2b) ) pinMode(dir2b, OUTPUT); + + if( _isset(enable_pin1) ) pinMode(enable_pin1, OUTPUT); + if( _isset(enable_pin2) ) pinMode(enable_pin2, OUTPUT); + + // sanity check for the voltage limit configuration + if( !_isset(voltage_limit) || voltage_limit > voltage_power_supply) voltage_limit = voltage_power_supply; + + // Set the pwm frequency to the pins + // hardware specific function - depending on driver and mcu + params = _configure2PWM(pwm_frequency, pwm1, pwm2); + initialized = (params!=SIMPLEFOC_DRIVER_INIT_FAILED); + return params!=SIMPLEFOC_DRIVER_INIT_FAILED; +} + + +// Set voltage to the pwm pin +void StepperDriver2PWM::setPwm(float Ua, float Ub) { + float duty_cycle1(0.0f),duty_cycle2(0.0f); + // limit the voltage in driver + Ua = _constrain(Ua, -voltage_limit, voltage_limit); + Ub = _constrain(Ub, -voltage_limit, voltage_limit); + // hardware specific writing + duty_cycle1 = _constrain(abs(Ua)/voltage_power_supply,0.0f,1.0f); + duty_cycle2 = _constrain(abs(Ub)/voltage_power_supply,0.0f,1.0f); + + // phase 1 direction + digitalWrite(dir1a, Ua >= 0 ? LOW : HIGH); + if( _isset(dir1b) ) digitalWrite(dir1b, Ua >= 0 ? HIGH : LOW ); + // phase 2 direction + digitalWrite(dir2a, Ub >= 0 ? LOW : HIGH); + if( _isset(dir2b) ) digitalWrite(dir2b, Ub >= 0 ? HIGH : LOW ); + + // write to hardware + _writeDutyCycle2PWM(duty_cycle1, duty_cycle2, params); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.h b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.h new file mode 100644 index 0000000..b349af0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver2PWM.h @@ -0,0 +1,68 @@ +#ifndef STEPPER_DRIVER_2PWM_h +#define STEPPER_DRIVER_2PWM_h + +#include "../common/base_classes/StepperDriver.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/defaults.h" +#include "hardware_api.h" + +/** + 2 pwm stepper driver class +*/ +class StepperDriver2PWM: public StepperDriver +{ + public: + /** + StepperMotor class constructor + @param pwm1 PWM1 phase pwm pin + @param in1 IN1A phase dir pin + @param pwm2 PWM2 phase pwm pin + @param in2 IN2A phase dir + @param en1 enable pin phase 1 (optional input) + @param en2 enable pin phase 2 (optional input) + */ + StepperDriver2PWM(int pwm1, int* in1, int pwm2, int* in2, int en1 = NOT_SET, int en2 = NOT_SET); + + /** + StepperMotor class constructor + @param pwm1 PWM1 phase pwm pin + @param dir1 DIR1 phase dir pin + @param pwm2 PWM2 phase pwm pin + @param dir2 DIR2 phase dir pin + @param en1 enable pin phase 1 (optional input) + @param en2 enable pin phase 2 (optional input) + */ + StepperDriver2PWM(int pwm1, int dir1, int pwm2, int dir2, int en1 = NOT_SET, int en2 = NOT_SET); + + /** Motor hardware init function */ + int init() override; + /** Motor disable function */ + void disable() override; + /** Motor enable function */ + void enable() override; + + // hardware variables + int pwm1; //!< phase 1 pwm pin number + int dir1a; //!< phase 1 INA pin number + int dir1b; //!< phase 1 INB pin number + int pwm2; //!< phase 2 pwm pin number + int dir2a; //!< phase 2 INA pin number + int dir2b; //!< phase 2 INB pin number + int enable_pin1; //!< enable pin number phase 1 + int enable_pin2; //!< enable pin number phase 2 + + /** + * Set phase voltages to the harware + * + * @param Ua phase A voltage + * @param Ub phase B voltage + */ + void setPwm(float Ua, float Ub) override; + + private: + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.cpp b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.cpp new file mode 100644 index 0000000..836f547 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.cpp @@ -0,0 +1,81 @@ +#include "StepperDriver4PWM.h" + +StepperDriver4PWM::StepperDriver4PWM(int ph1A,int ph1B,int ph2A,int ph2B,int en1, int en2){ + // Pin initialization + pwm1A = ph1A; + pwm1B = ph1B; + pwm2A = ph2A; + pwm2B = ph2B; + + // enable_pin pin + enable_pin1 = en1; + enable_pin2 = en2; + + // default power-supply value + voltage_power_supply = DEF_POWER_SUPPLY; + voltage_limit = NOT_SET; + pwm_frequency = NOT_SET; + +} + +// enable motor driver +void StepperDriver4PWM::enable(){ + // enable_pin the driver - if enable_pin pin available + if ( _isset(enable_pin1) ) digitalWrite(enable_pin1, HIGH); + if ( _isset(enable_pin2) ) digitalWrite(enable_pin2, HIGH); + // set zero to PWM + setPwm(0,0); +} + +// disable motor driver +void StepperDriver4PWM::disable() +{ + // set zero to PWM + setPwm(0, 0); + // disable the driver - if enable_pin pin available + if ( _isset(enable_pin1) ) digitalWrite(enable_pin1, LOW); + if ( _isset(enable_pin2) ) digitalWrite(enable_pin2, LOW); + +} + +// init hardware pins +int StepperDriver4PWM::init() { + + // PWM pins + pinMode(pwm1A, OUTPUT); + pinMode(pwm1B, OUTPUT); + pinMode(pwm2A, OUTPUT); + pinMode(pwm2B, OUTPUT); + if( _isset(enable_pin1) ) pinMode(enable_pin1, OUTPUT); + if( _isset(enable_pin2) ) pinMode(enable_pin2, OUTPUT); + + // sanity check for the voltage limit configuration + if( !_isset(voltage_limit) || voltage_limit > voltage_power_supply) voltage_limit = voltage_power_supply; + + // Set the pwm frequency to the pins + // hardware specific function - depending on driver and mcu + params = _configure4PWM(pwm_frequency, pwm1A, pwm1B, pwm2A, pwm2B); + initialized = (params!=SIMPLEFOC_DRIVER_INIT_FAILED); + return params!=SIMPLEFOC_DRIVER_INIT_FAILED; +} + + +// Set voltage to the pwm pin +void StepperDriver4PWM::setPwm(float Ualpha, float Ubeta) { + float duty_cycle1A(0.0f),duty_cycle1B(0.0f),duty_cycle2A(0.0f),duty_cycle2B(0.0f); + // limit the voltage in driver + Ualpha = _constrain(Ualpha, -voltage_limit, voltage_limit); + Ubeta = _constrain(Ubeta, -voltage_limit, voltage_limit); + // hardware specific writing + if( Ualpha > 0 ) + duty_cycle1B = _constrain(abs(Ualpha)/voltage_power_supply,0.0f,1.0f); + else + duty_cycle1A = _constrain(abs(Ualpha)/voltage_power_supply,0.0f,1.0f); + + if( Ubeta > 0 ) + duty_cycle2B = _constrain(abs(Ubeta)/voltage_power_supply,0.0f,1.0f); + else + duty_cycle2A = _constrain(abs(Ubeta)/voltage_power_supply,0.0f,1.0f); + // write to hardware + _writeDutyCycle4PWM(duty_cycle1A, duty_cycle1B, duty_cycle2A, duty_cycle2B, params); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.h b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.h new file mode 100644 index 0000000..e4b2ee4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/StepperDriver4PWM.h @@ -0,0 +1,55 @@ +#ifndef STEPPER_DRIVER_4PWM_h +#define STEPPER_DRIVER_4PWM_h + +#include "../common/base_classes/StepperDriver.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/defaults.h" +#include "hardware_api.h" + +/** + 4 pwm stepper driver class +*/ +class StepperDriver4PWM: public StepperDriver +{ + public: + /** + StepperMotor class constructor + @param ph1A 1A phase pwm pin + @param ph1B 1B phase pwm pin + @param ph2A 2A phase pwm pin + @param ph2B 2B phase pwm pin + @param en1 enable pin phase 1 (optional input) + @param en2 enable pin phase 2 (optional input) + */ + StepperDriver4PWM(int ph1A,int ph1B,int ph2A,int ph2B, int en1 = NOT_SET, int en2 = NOT_SET); + + /** Motor hardware init function */ + int init() override; + /** Motor disable function */ + void disable() override; + /** Motor enable function */ + void enable() override; + + // hardware variables + int pwm1A; //!< phase 1A pwm pin number + int pwm1B; //!< phase 1B pwm pin number + int pwm2A; //!< phase 2A pwm pin number + int pwm2B; //!< phase 2B pwm pin number + int enable_pin1; //!< enable pin number phase 1 + int enable_pin2; //!< enable pin number phase 2 + + /** + * Set phase voltages to the harware + * + * @param Ua phase A voltage + * @param Ub phase B voltage + */ + void setPwm(float Ua, float Ub) override; + + private: + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_api.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_api.h new file mode 100644 index 0000000..8b47745 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_api.h @@ -0,0 +1,180 @@ +#ifndef HARDWARE_UTILS_DRIVER_H +#define HARDWARE_UTILS_DRIVER_H + +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../communication/SimpleFOCDebug.h" +#include "../common/base_classes/BLDCDriver.h" + + +// these defines determine the polarity of the PWM output. Normally, the polarity is active-high, +// i.e. a high-level PWM output is expected to switch on the MOSFET. But should your driver design +// require inverted polarity, you can change the defines below, or set them via your build environment +// or board definition files. + +// used for 1-PWM, 2-PWM, 3-PWM, and 4-PWM modes +#ifndef SIMPLEFOC_PWM_ACTIVE_HIGH +#define SIMPLEFOC_PWM_ACTIVE_HIGH true +#endif +// used for 6-PWM mode, high-side +#ifndef SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH +#define SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH true +#endif +// used for 6-PWM mode, low-side +#ifndef SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH +#define SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH true +#endif + + + + +// flag returned if driver init fails +#define SIMPLEFOC_DRIVER_INIT_FAILED ((void*)-1) + +// generic implementation of the hardware specific structure +// containing all the necessary driver parameters +// will be returned as a void pointer from the _configurexPWM functions +// will be provided to the _writeDutyCyclexPWM() as a void pointer +typedef struct GenericDriverParams { + int pins[6]; + long pwm_frequency; + float dead_zone; +} GenericDriverParams; + + +/** + * Configuring PWM frequency, resolution and alignment + * - Stepper driver - 2PWM setting + * - hardware specific + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param pinA pinA pwm pin + * + * @return -1 if failed, or pointer to internal driver parameters struct if successful + */ +void* _configure1PWM(long pwm_frequency, const int pinA); + +/** + * Configuring PWM frequency, resolution and alignment + * - Stepper driver - 2PWM setting + * - hardware specific + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param pinA pinA bldc driver + * @param pinB pinB bldc driver + * + * @return -1 if failed, or pointer to internal driver parameters struct if successful + */ +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB); + +/** + * Configuring PWM frequency, resolution and alignment + * - BLDC driver - 3PWM setting + * - hardware specific + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param pinA pinA bldc driver + * @param pinB pinB bldc driver + * @param pinC pinC bldc driver + * + * @return -1 if failed, or pointer to internal driver parameters struct if successful + */ +void* _configure3PWM(long pwm_frequency, const int pinA, const int pinB, const int pinC); + +/** + * Configuring PWM frequency, resolution and alignment + * - Stepper driver - 4PWM setting + * - hardware specific + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param pin1A pin1A stepper driver + * @param pin1B pin1B stepper driver + * @param pin2A pin2A stepper driver + * @param pin2B pin2B stepper driver + * + * @return -1 if failed, or pointer to internal driver parameters struct if successful + */ +void* _configure4PWM(long pwm_frequency, const int pin1A, const int pin1B, const int pin2A, const int pin2B); + +/** + * Configuring PWM frequency, resolution and alignment + * - BLDC driver - 6PWM setting + * - hardware specific + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param dead_zone duty cycle protection zone [0, 1] - both low and high side low - if applicable + * @param pinA_h pinA high-side bldc driver + * @param pinA_l pinA low-side bldc driver + * @param pinB_h pinA high-side bldc driver + * @param pinB_l pinA low-side bldc driver + * @param pinC_h pinA high-side bldc driver + * @param pinC_l pinA low-side bldc driver + * + * @return -1 if failed, or pointer to internal driver parameters struct if successful + */ +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l); + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - Stepper driver - 2PWM setting + * - hardware specific + * + * @param dc_a duty cycle phase A [0, 1] + * @param dc_b duty cycle phase B [0, 1] + * @param params the driver parameters + */ +void _writeDutyCycle1PWM(float dc_a, void* params); + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - Stepper driver - 2PWM setting + * - hardware specific + * + * @param dc_a duty cycle phase A [0, 1] + * @param dc_b duty cycle phase B [0, 1] + * @param params the driver parameters + */ +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params); + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - BLDC driver - 3PWM setting + * - hardware specific + * + * @param dc_a duty cycle phase A [0, 1] + * @param dc_b duty cycle phase B [0, 1] + * @param dc_c duty cycle phase C [0, 1] + * @param params the driver parameters + */ +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params); + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - Stepper driver - 4PWM setting + * - hardware specific + * + * @param dc_1a duty cycle phase 1A [0, 1] + * @param dc_1b duty cycle phase 1B [0, 1] + * @param dc_2a duty cycle phase 2A [0, 1] + * @param dc_2b duty cycle phase 2B [0, 1] + * @param params the driver parameters + */ +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params); + + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - BLDC driver - 6PWM setting + * - hardware specific + * + * @param dc_a duty cycle phase A [0, 1] + * @param dc_b duty cycle phase B [0, 1] + * @param dc_c duty cycle phase C [0, 1] + * @param phase_state pointer to PhaseState[3] array + * @param params the driver parameters + * + */ +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params); + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega2560_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega2560_mcu.cpp new file mode 100644 index 0000000..8a7fbbe --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega2560_mcu.cpp @@ -0,0 +1,278 @@ +#include "../../hardware_api.h" + +#if defined(__AVR_ATmega2560__) || defined(AVR_ATmega1280) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for Arduino/ATmega2560 or Arduino/ATmega1280") +#pragma message("") + + +#define _PWM_FREQUENCY 32000 +#define _PWM_FREQUENCY_MAX 32000 +#define _PWM_FREQUENCY_MIN 4000 + +// set pwm frequency to 32KHz +void _pinHighFrequency(const int pin, const long frequency){ + bool high_fq = false; + // set 32kHz frequency if requested freq is higher than the middle of the range (14kHz) + // else set the 4kHz + if(frequency >= 0.5*(_PWM_FREQUENCY_MAX-_PWM_FREQUENCY_MIN)) high_fq=true; + // High PWM frequency + // https://sites.google.com/site/qeewiki/books/avr-guide/timers-on-the-ATmega2560 + // https://forum.arduino.cc/index.php?topic=72092.0 + if (pin == 13 || pin == 4 ) { + TCCR0A = ((TCCR0A & 0b11111100) | 0x01); // configure the pwm phase-corrected mode + if(high_fq) TCCR0B = ((TCCR0B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR0B = ((TCCR0B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + } + else if (pin == 12 || pin == 11 ) + if(high_fq) TCCR1B = ((TCCR1B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR1B = ((TCCR1B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + else if (pin == 10 || pin == 9 ) + if(high_fq) TCCR2B = ((TCCR2B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR2B = ((TCCR2B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + else if (pin == 5 || pin == 3 || pin == 2) + if(high_fq) TCCR3B = ((TCCR3B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR3B = ((TCCR3B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + else if (pin == 8 || pin == 7 || pin == 6) + if(high_fq) TCCR4B = ((TCCR4B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR4B = ((TCCR4B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + else if (pin == 44 || pin == 45 || pin == 46) + if(high_fq) TCCR5B = ((TCCR5B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR5B = ((TCCR5B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware specific +// supports Arduino/ATmega2560 +void* _configure1PWM(long pwm_frequency,const int pinA) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 32kHz + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); // constrain to 4-32kHz max + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pinA, pwm_frequency); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware specific +// supports Arduino/ATmega2560 +void* _configure2PWM(long pwm_frequency,const int pinA, const int pinB) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 32kHz + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); // constrain to 4-32kHz max + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pinA, pwm_frequency); + _pinHighFrequency(pinB, pwm_frequency); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware specific +// supports Arduino/ATmega2560 +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 32kHz + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); // constrain to 4-32kHz max + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pinA, pwm_frequency); + _pinHighFrequency(pinB, pwm_frequency); + _pinHighFrequency(pinC, pwm_frequency); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC }, + .pwm_frequency = pwm_frequency + }; + // _syncAllTimers(); + return params; +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware specific +void _writeDutyCycle1PWM(float dc_a, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware specific +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); +} + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware specific +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_c); +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware specific +void* _configure4PWM(long pwm_frequency,const int pin1A, const int pin1B, const int pin2A, const int pin2B) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 32kHz + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); // constrain to 4-32kHz max + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pin1A,pwm_frequency); + _pinHighFrequency(pin1B,pwm_frequency); + _pinHighFrequency(pin2A,pwm_frequency); + _pinHighFrequency(pin2B,pwm_frequency); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pin1A, pin1B, pin2A, pin2B }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware specific +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params) { + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_1a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_1b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_2a); + analogWrite(((GenericDriverParams*)params)->pins[3], 255.0f*dc_2b); +} + + +// function configuring pair of high-low side pwm channels, 32khz frequency and center aligned pwm +// supports Arduino/ATmega2560 +// https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf +// https://docs.arduino.cc/hacking/hardware/PinMapping2560 +int _configureComplementaryPair(const int pinH,const int pinL, long frequency) { + bool high_fq = false; + // set 32kHz frequency if requested freq is higher than the middle of the range (14kHz) + // else set the 4kHz + if(frequency >= 0.5*(_PWM_FREQUENCY_MAX-_PWM_FREQUENCY_MIN)) high_fq=true; + + // configure pin pairs + if( (pinH == 4 && pinL == 13 ) || (pinH == 13 && pinL == 4 ) ){ + // configure the pwm phase-corrected mode + TCCR0A = ((TCCR0A & 0b11111100) | 0x01); + // configure complementary pwm on low side + if(pinH == 13 ) TCCR0A = 0b10110000 | (TCCR0A & 0b00001111) ; + else TCCR0A = 0b11100000 | (TCCR0A & 0b00001111) ; + // set frequency + if(high_fq) TCCR0B = ((TCCR0B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR0B = ((TCCR0B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + }else if( (pinH == 11 && pinL == 12 ) || (pinH == 12 && pinL == 11 ) ){ + // set frequency + if(high_fq) TCCR1B = ((TCCR1B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR1B = ((TCCR1B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + // configure complementary pwm on low side + if(pinH == 11 ) TCCR1A = 0b10110000 | (TCCR1A & 0b00001111) ; + else TCCR1A = 0b11100000 | (TCCR1A & 0b00001111) ; + }else if((pinH == 10 && pinL == 9 ) || (pinH == 9 && pinL == 10 ) ){ + // set frequency + if(high_fq) TCCR2B = ((TCCR2B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR2B = ((TCCR2B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + // configure complementary pwm on low side + if(pinH == 10 ) TCCR2A = 0b10110000 | (TCCR2A & 0b00001111) ; + else TCCR2A = 0b11100000 | (TCCR2A & 0b00001111) ; + }else if((pinH == 5 && pinL == 2 ) || (pinH == 2 && pinL == 5 ) ){ + // set frequency + if(high_fq) TCCR3B = ((TCCR3B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR3B = ((TCCR3B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + // configure complementary pwm on low side + if(pinH == 5 ) TCCR3A = 0b10110000 | (TCCR3A & 0b00001111) ; + else TCCR3A = 0b11100000 | (TCCR3A & 0b00001111) ; + }else if((pinH == 6 && pinL == 7 ) || (pinH == 7 && pinL == 6 ) ){ + // set frequency + if(high_fq) TCCR4B = ((TCCR4B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR4B = ((TCCR4B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + // configure complementary pwm on low side + if(pinH == 6 ) TCCR4A = 0b10110000 | (TCCR4A & 0b00001111) ; + else TCCR4A = 0b11100000 | (TCCR4A & 0b00001111) ; + }else if((pinH == 46 && pinL == 45 ) || (pinH == 45 && pinL == 46 ) ){ + // set frequency + if(high_fq) TCCR5B = ((TCCR5B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR5B = ((TCCR5B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + // configure complementary pwm on low side + if(pinH == 46 ) TCCR5A = 0b10110000 | (TCCR5A & 0b00001111) ; + else TCCR5A = 0b11100000 | (TCCR5A & 0b00001111) ; + }else{ + return -1; + } + return 0; +} + +// Configuring PWM frequency, resolution and alignment +// - BLDC driver - setting +// - hardware specific +// supports Arduino/ATmega2560 +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 32kHz + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); // constrain to 4-32kHz max + // High PWM frequency + // - always max 32kHz + int ret_flag = 0; + ret_flag += _configureComplementaryPair(pinA_h, pinA_l, pwm_frequency); + ret_flag += _configureComplementaryPair(pinB_h, pinB_l, pwm_frequency); + ret_flag += _configureComplementaryPair(pinC_h, pinC_l, pwm_frequency); + if (ret_flag!=0) return SIMPLEFOC_DRIVER_INIT_FAILED; + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l }, + .pwm_frequency = pwm_frequency, + .dead_zone = dead_zone + }; + // _syncAllTimers(); + return params; +} + +// function setting the +void _setPwmPair(int pinH, int pinL, float val, int dead_time, PhaseState ps) +{ + int pwm_h = _constrain(val-dead_time/2,0,255); + int pwm_l = _constrain(val+dead_time/2,0,255); + // determine the phase state and set the pwm accordingly + // deactivate phases if needed + if((ps == PhaseState::PHASE_OFF) || (ps == PhaseState::PHASE_LO)){ + digitalWrite(pinH, LOW); + }else{ + analogWrite(pinH, pwm_h); + } + if((ps == PhaseState::PHASE_OFF) || (ps == PhaseState::PHASE_HI)){ + digitalWrite(pinL, LOW); + }else{ + if(pwm_l == 255 || pwm_l == 0) + digitalWrite(pinL, pwm_l ? LOW : HIGH); + else + analogWrite(pinL, pwm_l); + } + +} + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - BLDC driver - 6PWM setting +// - hardware specific +// supports Arduino/ATmega328 +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + _setPwmPair(((GenericDriverParams*)params)->pins[0], ((GenericDriverParams*)params)->pins[1], dc_a*255.0, ((GenericDriverParams*)params)->dead_zone*255.0, phase_state[0]); + _setPwmPair(((GenericDriverParams*)params)->pins[2], ((GenericDriverParams*)params)->pins[3], dc_b*255.0, ((GenericDriverParams*)params)->dead_zone*255.0, phase_state[1]); + _setPwmPair(((GenericDriverParams*)params)->pins[4], ((GenericDriverParams*)params)->pins[5], dc_c*255.0, ((GenericDriverParams*)params)->dead_zone*255.0, phase_state[2]); +} + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega328_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega328_mcu.cpp new file mode 100644 index 0000000..53fb108 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega328_mcu.cpp @@ -0,0 +1,255 @@ +#include "../../hardware_api.h" + +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328PB__) + +#pragma message("") +#pragma message("SimpleFOC: compiling for Arduino/ATmega328 ATmega168 ATmega328PB") +#pragma message("") + +#define _PWM_FREQUENCY 32000 +#define _PWM_FREQUENCY_MAX 32000 +#define _PWM_FREQUENCY_MIN 4000 + +// set pwm frequency to 32KHz +void _pinHighFrequency(const int pin, const long frequency){ + bool high_fq = false; + // set 32kHz frequency if requested freq is higher than the middle of the range (14kHz) + // else set the 4kHz + if(frequency >= 0.5*(_PWM_FREQUENCY_MAX-_PWM_FREQUENCY_MIN)) high_fq=true; + // High PWM frequency + // https://www.arxterra.com/9-atmega328p-timers/ + if (pin == 5 || pin == 6 ) { + TCCR0A = ((TCCR0A & 0b11111100) | 0x01); // configure the pwm phase-corrected mode + if(high_fq) TCCR0B = ((TCCR0B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR0B = ((TCCR0B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + }else if (pin == 9 || pin == 10 ){ + if(high_fq) TCCR1B = ((TCCR1B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR1B = ((TCCR1B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + }else if (pin == 3 || pin == 11){ + if(high_fq) TCCR2B = ((TCCR2B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR2B = ((TCCR2B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + } +} + +void _syncAllTimers(){ + GTCCR = (1<pins[0], 255.0f*dc_a); +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware specific +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); +} + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware specific +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_c); +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware specific +// supports Arduino/ATmega328 +void* _configure4PWM(long pwm_frequency,const int pin1A, const int pin1B, const int pin2A, const int pin2B) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 32kHz + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); // constrain to 4-32kHz max + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pin1A,pwm_frequency); + _pinHighFrequency(pin1B,pwm_frequency); + _pinHighFrequency(pin2A,pwm_frequency); + _pinHighFrequency(pin2B,pwm_frequency); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pin1A, pin1B, pin2A, pin2B }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware specific +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_1a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_1b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_2a); + analogWrite(((GenericDriverParams*)params)->pins[3], 255.0f*dc_2b); +} + + +// function configuring pair of high-low side pwm channels, 32khz frequency and center aligned pwm +int _configureComplementaryPair(const int pinH, const int pinL, long frequency) { + bool high_fq = false; + // set 32kHz frequency if requested freq is higher than the middle of the range (14kHz) + // else set the 4kHz + if(frequency >= 0.5*(_PWM_FREQUENCY_MAX-_PWM_FREQUENCY_MIN)) high_fq=true; + + // configure pins + if( (pinH == 5 && pinL == 6 ) || (pinH == 6 && pinL == 5 ) ){ + // configure the pwm phase-corrected mode + TCCR0A = ((TCCR0A & 0b11111100) | 0x01); + // configure complementary pwm on low side + if(pinH == 6 ) TCCR0A = 0b10110000 | (TCCR0A & 0b00001111) ; + else TCCR0A = 0b11100000 | (TCCR0A & 0b00001111) ; + // set frequency + if(high_fq) TCCR0B = ((TCCR0B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR0B = ((TCCR0B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + }else if( (pinH == 9 && pinL == 10 ) || (pinH == 10 && pinL == 9 ) ){ + // set frequency + if(high_fq) TCCR1B = ((TCCR1B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR1B = ((TCCR1B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + // configure complementary pwm on low side + if(pinH == 9 ) TCCR1A = 0b10110000 | (TCCR1A & 0b00001111) ; + else TCCR1A = 0b11100000 | (TCCR1A & 0b00001111) ; + }else if((pinH == 3 && pinL == 11 ) || (pinH == 11 && pinL == 3 ) ){ + // set frequency + if(high_fq) TCCR2B = ((TCCR2B & 0b11110000) | 0x01); // set prescaler to 1 - 32kHz + else TCCR2B = ((TCCR2B & 0b11110000) | 0x02); // set prescaler to 2 - 4kHz + // configure complementary pwm on low side + if(pinH == 11 ) TCCR2A = 0b10110000 | (TCCR2A & 0b00001111) ; + else TCCR2A = 0b11100000 | (TCCR2A & 0b00001111) ; + }else{ + return -1; + } + return 0; +} + +// Configuring PWM frequency, resolution and alignment +// - BLDC driver - setting +// - hardware specific +// supports Arduino/ATmega328 +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 32kHz + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); // constrain to 4-32kHz max + // High PWM frequency + // - always max 32kHz + int ret_flag = 0; + ret_flag += _configureComplementaryPair(pinA_h, pinA_l, pwm_frequency); + ret_flag += _configureComplementaryPair(pinB_h, pinB_l, pwm_frequency); + ret_flag += _configureComplementaryPair(pinC_h, pinC_l, pwm_frequency); + if (ret_flag!=0) return SIMPLEFOC_DRIVER_INIT_FAILED; + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l }, + .pwm_frequency = pwm_frequency, + .dead_zone = dead_zone + }; + _syncAllTimers(); + return params; +} + +// function setting the +void _setPwmPair(int pinH, int pinL, float val, int dead_time, PhaseState ps) +{ + int pwm_h = _constrain(val-dead_time/2,0,255); + int pwm_l = _constrain(val+dead_time/2,0,255); + // determine the phase state and set the pwm accordingly + // deactivate phases if needed + if((ps == PhaseState::PHASE_OFF) || (ps == PhaseState::PHASE_LO)){ + digitalWrite(pinH, LOW); + }else{ + analogWrite(pinH, pwm_h); + } + if((ps == PhaseState::PHASE_OFF) || (ps == PhaseState::PHASE_HI)){ + digitalWrite(pinL, LOW); + }else{ + if(pwm_l == 255 || pwm_l == 0) + digitalWrite(pinL, pwm_l ? LOW : HIGH); + else + analogWrite(pinL, pwm_l); + } + + +} + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - BLDC driver - 6PWM setting +// - hardware specific +// supports Arduino/ATmega328 +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + _setPwmPair(((GenericDriverParams*)params)->pins[0], ((GenericDriverParams*)params)->pins[1], dc_a*255.0, ((GenericDriverParams*)params)->dead_zone*255.0, phase_state[0]); + _setPwmPair(((GenericDriverParams*)params)->pins[2], ((GenericDriverParams*)params)->pins[3], dc_b*255.0, ((GenericDriverParams*)params)->dead_zone*255.0, phase_state[1]); + _setPwmPair(((GenericDriverParams*)params)->pins[4], ((GenericDriverParams*)params)->pins[5], dc_c*255.0, ((GenericDriverParams*)params)->dead_zone*255.0, phase_state[2]); +} + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega32u4_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega32u4_mcu.cpp new file mode 100644 index 0000000..b4ad310 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/atmega/atmega32u4_mcu.cpp @@ -0,0 +1,222 @@ + +#include "../../hardware_api.h" + +#if defined(__AVR_ATmega32U4__) + +#pragma message("") +#pragma message("SimpleFOC: compiling for Arduino/ATmega32U4") +#pragma message("") + +// set pwm frequency to 32KHz +void _pinHighFrequency(const int pin){ + // High PWM frequency + // reference: http://r6500.blogspot.com/2014/12/fast-pwm-on-arduino-leonardo.html + if (pin == 3 || pin == 11 ) { + TCCR0A = ((TCCR0A & 0b11111100) | 0x01); // configure the pwm phase-corrected mode + TCCR0B = ((TCCR0B & 0b11110000) | 0x01); // set prescaler to 1 + } + else if (pin == 9 || pin == 10 ) + TCCR1B = ((TCCR1B & 0b11111000) | 0x01); // set prescaler to 1 + else if (pin == 5 ) + TCCR3B = ((TCCR3B & 0b11111000) | 0x01); // set prescaler to 1 + else if ( pin == 6 || pin == 13 ) { // a bit more complicated 10 bit timer + // PLL Configuration + PLLFRQ= ((PLLFRQ & 0b11001111) | 0x20); // Use 96MHz / 1.5 = 64MHz + TCCR4B = ((TCCR4B & 0b11110000) | 0xB); // configure prescaler to get 64M/2/1024 = 31.25 kHz + TCCR4D = ((TCCR4D & 0b11111100) | 0x01); // configure the pwm phase-corrected mode + + if (pin == 6) TCCR4A = 0x82; // activate channel A - pin 13 + else if (pin == 13) TCCR4C |= 0x09; // Activate channel D - pin 6 + } + +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure1PWM(long pwm_frequency,const int pinA) { + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pinA); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure2PWM(long pwm_frequency,const int pinA, const int pinB) { + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pinA); + _pinHighFrequency(pinB); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pinA); + _pinHighFrequency(pinB); + _pinHighFrequency(pinC); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +void _writeDutyCycle1PWM(float dc_a, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); +} + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware speciffic +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, int pinA, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_c); +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency,const int pin1A, const int pin1B, const int pin2A, const int pin2B) { + // High PWM frequency + // - always max 32kHz + _pinHighFrequency(pin1A); + _pinHighFrequency(pin1B); + _pinHighFrequency(pin2A); + _pinHighFrequency(pin2B); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pin1A, pin1B, pin2A, pin2B }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware speciffic +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_1a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_1b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_2a); + analogWrite(((GenericDriverParams*)params)->pins[3], 255.0f*dc_2b); +} + + + + +// function configuring pair of high-low side pwm channels, 32khz frequency and center aligned pwm +int _configureComplementaryPair(int pinH, int pinL) { + if( (pinH == 3 && pinL == 11 ) || (pinH == 11 && pinL == 3 ) ){ + // configure the pwm phase-corrected mode + TCCR0A = ((TCCR0A & 0b11111100) | 0x01); + // configure complementary pwm on low side + if(pinH == 11 ) TCCR0A = 0b10110000 | (TCCR0A & 0b00001111) ; + else TCCR0A = 0b11100000 | (TCCR0A & 0b00001111) ; + // set prescaler to 1 - 32kHz freq + TCCR0B = ((TCCR0B & 0b11110000) | 0x01); + }else if( (pinH == 9 && pinL == 10 ) || (pinH == 10 && pinL == 9 ) ){ + // set prescaler to 1 - 32kHz freq + TCCR1B = ((TCCR1B & 0b11111000) | 0x01); + // configure complementary pwm on low side + if(pinH == 9 ) TCCR1A = 0b10110000 | (TCCR1A & 0b00001111) ; + else TCCR1A = 0b11100000 | (TCCR1A & 0b00001111) ; + }else if((pinH == 6 && pinL == 13 ) || (pinH == 13 && pinL == 6 ) ){ + // PLL Configuration + PLLFRQ= ((PLLFRQ & 0b11001111) | 0x20); // Use 96MHz / 1.5 = 64MHz + TCCR4B = ((TCCR4B & 0b11110000) | 0xB); // configure prescaler to get 64M/2/1024 = 31.25 kHz + TCCR4D = ((TCCR4D & 0b11111100) | 0x01); // configure the pwm phase-corrected mode + + // configure complementary pwm on low side + if(pinH == 13 ){ + TCCR4A = 0x82; // activate channel A - pin 13 + TCCR4C |= 0x0d; // Activate complementary channel D - pin 6 + }else { + TCCR4C |= 0x09; // Activate channel D - pin 6 + TCCR4A = 0xc2; // activate complementary channel A - pin 13 + } + }else{ + return -1; + } + return 0; +} + + +// Configuring PWM frequency, resolution and alignment +// - BLDC driver - 6PWM setting +// - hardware specific +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + // High PWM frequency + // - always max 32kHz + int ret_flag = 0; + ret_flag += _configureComplementaryPair(pinA_h, pinA_l); + ret_flag += _configureComplementaryPair(pinB_h, pinB_l); + ret_flag += _configureComplementaryPair(pinC_h, pinC_l); + if (ret_flag!=0) return SIMPLEFOC_DRIVER_INIT_FAILED; + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l }, + .pwm_frequency = pwm_frequency, + .dead_zone = dead_zone + }; + return params; +} + +// function setting the +void _setPwmPair(int pinH, int pinL, float val, int dead_time) +{ + int pwm_h = _constrain(val-dead_time/2,0,255); + int pwm_l = _constrain(val+dead_time/2,0,255); + + analogWrite(pinH, pwm_h); + if(pwm_l == 255 || pwm_l == 0) + digitalWrite(pinL, pwm_l ? LOW : HIGH); + else + analogWrite(pinL, pwm_l); +} + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - BLDC driver - 6PWM setting +// - hardware specific +// supports Arudino/ATmega328 +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + _setPwmPair(((GenericDriverParams*)params)->pins[0], ((GenericDriverParams*)params)->pins[1], dc_a*255.0, ((GenericDriverParams*)params)->dead_zone*255.0); + _setPwmPair(((GenericDriverParams*)params)->pins[2], ((GenericDriverParams*)params)->pins[3], dc_b*255.0, ((GenericDriverParams*)params)->dead_zone*255.0); + _setPwmPair(((GenericDriverParams*)params)->pins[4], ((GenericDriverParams*)params)->pins[5], dc_c*255.0, ((GenericDriverParams*)params)->dead_zone*255.0); + + _UNUSED(phase_state); +} + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/due_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/due_mcu.cpp new file mode 100644 index 0000000..4397114 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/due_mcu.cpp @@ -0,0 +1,449 @@ +#include "../hardware_api.h" + +#if defined(__arm__) && defined(__SAM3X8E__) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for Arduino/Due") +#pragma message("") + + +#define _PWM_FREQUENCY 25000 // 25khz +#define _PWM_FREQUENCY_MAX 50000 // 50khz + +#define _PWM_RES_MIN 255 // 50khz + +// pwm frequency and max duty cycle +static unsigned long _pwm_frequency; +static int _max_pwm_value = 1023; + +// array mapping the timer values to the interrupt handlers +static IRQn_Type irq_type[] = {TC0_IRQn, TC0_IRQn, TC1_IRQn, TC1_IRQn, TC2_IRQn, TC2_IRQn, TC3_IRQn, TC3_IRQn, TC4_IRQn, TC4_IRQn, TC5_IRQn, TC5_IRQn, TC6_IRQn, TC6_IRQn, TC7_IRQn, TC7_IRQn, TC8_IRQn, TC8_IRQn}; +// current counter values +static volatile uint32_t pwm_counter_vals[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + +// variables copied from wiring_analog.cpp for arduino due +static uint8_t PWMEnabled = 0; +static uint8_t TCChanEnabled[] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; +static const uint32_t channelToChNo[] = { 0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2 }; +static const uint32_t channelToAB[] = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }; +static Tc *channelToTC[] = { + TC0, TC0, TC0, TC0, TC0, TC0, + TC1, TC1, TC1, TC1, TC1, TC1, + TC2, TC2, TC2, TC2, TC2, TC2 }; +static const uint32_t channelToId[] = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8 }; + + +// function setting the CMR register +static void TC_SetCMR_ChannelA(Tc *tc, uint32_t chan, uint32_t v){ tc->TC_CHANNEL[chan].TC_CMR = (tc->TC_CHANNEL[chan].TC_CMR & 0xFFF0FFFF) | v;} +static void TC_SetCMR_ChannelB(Tc *tc, uint32_t chan, uint32_t v){ tc->TC_CHANNEL[chan].TC_CMR = (tc->TC_CHANNEL[chan].TC_CMR & 0xF0FFFFFF) | v; } + + +// function which starts and syncs the timers +// if the pin is the true PWM pin this function does not do anything +void syncTimers(uint32_t ulPin1,uint32_t ulPin2, uint32_t ulPin3 = -1, uint32_t ulPin4 = -1){ + uint32_t chNo1,chNo2,chNo3,chNo4; + Tc *chTC1 = nullptr,*chTC2 = nullptr,*chTC3 = nullptr,*chTC4 = nullptr; + + // configure timer channel for the first pin if it is a timer pin + uint32_t attr = g_APinDescription[ulPin1].ulPinAttribute; + if ((attr & PIN_ATTR_TIMER) == PIN_ATTR_TIMER) { + ETCChannel channel1 = g_APinDescription[ulPin1].ulTCChannel; + chNo1 = channelToChNo[channel1]; + chTC1 = channelToTC[channel1]; + TCChanEnabled[channelToId[channel1]] = 1; + } + + // configure timer channel for the first pin if it is a timer pin + attr = g_APinDescription[ulPin2].ulPinAttribute; + if ((attr & PIN_ATTR_TIMER) == PIN_ATTR_TIMER) { + ETCChannel channel2 = g_APinDescription[ulPin2].ulTCChannel; + chNo2 = channelToChNo[channel2]; + chTC2 = channelToTC[channel2]; + TCChanEnabled[channelToId[channel2]] = 1; + } + if(ulPin3 > 0 ){ + // configure timer channel for the first pin if it is a timer pin + attr = g_APinDescription[ulPin3].ulPinAttribute; + if ((attr & PIN_ATTR_TIMER) == PIN_ATTR_TIMER) { + ETCChannel channel3 = g_APinDescription[ulPin3].ulTCChannel; + chNo3 = channelToChNo[channel3]; + chTC3 = channelToTC[channel3]; + TCChanEnabled[channelToId[channel3]] = 1; + } + } + if(ulPin4 > 0 ){ + // configure timer channel for the first pin if it is a timer pin + attr = g_APinDescription[ulPin4].ulPinAttribute; + if ((attr & PIN_ATTR_TIMER) == PIN_ATTR_TIMER) { + ETCChannel channel4 = g_APinDescription[ulPin4].ulTCChannel; + chNo4 = channelToChNo[channel4]; + chTC4 = channelToTC[channel4]; + TCChanEnabled[channelToId[channel4]] = 1; + } + } + // start timers and make them synced + if(chTC1){ + TC_Start(chTC1, chNo1); + chTC1->TC_BCR = TC_BCR_SYNC; + } + if(chTC2){ + TC_Start(chTC2, chNo2); + chTC2->TC_BCR = TC_BCR_SYNC; + } + if(chTC3 && ulPin3){ + TC_Start(chTC3, chNo3); + chTC3->TC_BCR = TC_BCR_SYNC; + } + if(chTC4 && ulPin4){ + TC_Start(chTC4, chNo4); + chTC4->TC_BCR = TC_BCR_SYNC; + } +} + +// function configuring the pwm frequency for given pin +// possible to supply the pwm pin and the timer pin +void initPWM(uint32_t ulPin, uint32_t pwm_freq){ + // check which pin type + uint32_t attr = g_APinDescription[ulPin].ulPinAttribute; + if ((attr & PIN_ATTR_PWM) == PIN_ATTR_PWM) { // if pwm pin + + if (!PWMEnabled) { + // PWM Startup code + pmc_enable_periph_clk(PWM_INTERFACE_ID); + // this function does not work too well - I'll rewrite it + // PWMC_ConfigureClocks(PWM_FREQUENCY * _max_pwm_value, 0, VARIANT_MCK); + + // finding the divisors an prescalers form FindClockConfiguration function + uint32_t divisors[11] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}; + uint8_t divisor = 0; + uint32_t prescaler; + + /* Find prescaler and divisor values */ + prescaler = (VARIANT_MCK / divisors[divisor]) / (pwm_freq*_max_pwm_value); + while ((prescaler > 255) && (divisor < 11)) { + divisor++; + prescaler = (VARIANT_MCK / divisors[divisor]) / (pwm_freq*_max_pwm_value); + } + // update the divisor*prescaler value + prescaler = prescaler | (divisor << 8); + + // now calculate the real resolution timer period necessary (pwm resolution) + // pwm_res = bus_freq / (pwm_freq * (prescaler)) + _max_pwm_value = (double)VARIANT_MCK / (double)pwm_freq / (double)(prescaler); + // set the prescaler value + PWM->PWM_CLK = prescaler; + + PWMEnabled = 1; + } + + uint32_t chan = g_APinDescription[ulPin].ulPWMChannel; + if ((g_pinStatus[ulPin] & 0xF) != PIN_STATUS_PWM) { + // Setup PWM for this pin + PIO_Configure(g_APinDescription[ulPin].pPort, + g_APinDescription[ulPin].ulPinType, + g_APinDescription[ulPin].ulPin, + g_APinDescription[ulPin].ulPinConfiguration); + // PWM_CMR_CALG - center align + // PWMC_ConfigureChannel(PWM_INTERFACE, chan, PWM_CMR_CPRE_CLKA, PWM_CMR_CALG, 0); + PWMC_ConfigureChannel(PWM_INTERFACE, chan, PWM_CMR_CPRE_CLKA, 0, 0); + PWMC_SetPeriod(PWM_INTERFACE, chan, _max_pwm_value); + PWMC_SetDutyCycle(PWM_INTERFACE, chan, 0); + PWMC_EnableChannel(PWM_INTERFACE, chan); + g_pinStatus[ulPin] = (g_pinStatus[ulPin] & 0xF0) | PIN_STATUS_PWM; + } + return; + } + + if ((attr & PIN_ATTR_TIMER) == PIN_ATTR_TIMER) { // if timer pin + // We use MCLK/2 as clock. + const uint32_t TC = VARIANT_MCK / 2 / pwm_freq ; + // Setup Timer for this pin + ETCChannel channel = g_APinDescription[ulPin].ulTCChannel; + uint32_t chNo = channelToChNo[channel]; + uint32_t chA = channelToAB[channel]; + Tc *chTC = channelToTC[channel]; + uint32_t interfaceID = channelToId[channel]; + + if (!TCChanEnabled[interfaceID]) { + pmc_enable_periph_clk(TC_INTERFACE_ID + interfaceID); + TC_Configure(chTC, chNo, + TC_CMR_TCCLKS_TIMER_CLOCK1 | + TC_CMR_WAVE | // Waveform mode + TC_CMR_WAVSEL_UP_RC | // Counter running up and reset when equals to RC + TC_CMR_EEVT_XC0 | // Set external events from XC0 (this setup TIOB as output) + TC_CMR_ACPA_CLEAR | TC_CMR_ACPC_CLEAR | + TC_CMR_BCPB_CLEAR | TC_CMR_BCPC_CLEAR); + TC_SetRC(chTC, chNo, TC); + } + + // disable the counter on start + if (chA){ + TC_SetCMR_ChannelA(chTC, chNo, TC_CMR_ACPA_CLEAR | TC_CMR_ACPC_SET); + }else{ + TC_SetCMR_ChannelB(chTC, chNo, TC_CMR_BCPB_CLEAR | TC_CMR_BCPC_SET); + } + // configure input-ouput structure + if ((g_pinStatus[ulPin] & 0xF) != PIN_STATUS_PWM) { + PIO_Configure(g_APinDescription[ulPin].pPort, + g_APinDescription[ulPin].ulPinType, + g_APinDescription[ulPin].ulPin, + g_APinDescription[ulPin].ulPinConfiguration); + g_pinStatus[ulPin] = (g_pinStatus[ulPin] & 0xF0) | PIN_STATUS_PWM; + } + // enable interrupts + chTC->TC_CHANNEL[chNo].TC_IER = TC_IER_CPAS // interrupt on RA compare match + | TC_IER_CPBS // interrupt on RB compare match + | TC_IER_CPCS; // interrupt on RC compare match + chTC->TC_CHANNEL[chNo].TC_IDR = ~TC_IER_CPAS // interrupt on RA compare match + & ~TC_IER_CPBS // interrupt on RB compare match + & ~ TC_IER_CPCS; // interrupt on RC compare match + // enable interrupts for this timer + NVIC_EnableIRQ(irq_type[channel]); + return; + } +} + +// pwm setting function +// it sets the duty cycle for pwm pin or timer pin +void setPwm(uint32_t ulPin, uint32_t ulValue) { + // check pin type + uint32_t attr = g_APinDescription[ulPin].ulPinAttribute; + if ((attr & PIN_ATTR_PWM) == PIN_ATTR_PWM) { // if pwm + uint32_t chan = g_APinDescription[ulPin].ulPWMChannel; + PWMC_SetDutyCycle(PWM_INTERFACE, chan, ulValue); + return; + } + + if ((attr & PIN_ATTR_TIMER) == PIN_ATTR_TIMER) { // if timer pin + // get the timer variables + ETCChannel channel = g_APinDescription[ulPin].ulTCChannel; + Tc *chTC = channelToTC[channel]; + uint32_t chNo = channelToChNo[channel]; + if(!ulValue) { + // if the value 0 disable counter + if (channelToAB[channel]) + TC_SetCMR_ChannelA(chTC, chNo, TC_CMR_ACPA_CLEAR | TC_CMR_ACPC_CLEAR); + else + TC_SetCMR_ChannelB(chTC, chNo, TC_CMR_BCPB_CLEAR | TC_CMR_BCPC_CLEAR); + }else{ + // if the value not zero + // calculate clock + const uint32_t TC = VARIANT_MCK / 2 / _pwm_frequency; + // Map value to Timer ranges 0..max_duty_cycle => 0..TC + // Setup Timer for this pin + ulValue = ulValue * TC ; + pwm_counter_vals[channel] = ulValue / _max_pwm_value; + // enable counter + if (channelToAB[channel]) + TC_SetCMR_ChannelA(chTC, chNo, TC_CMR_ACPA_CLEAR | TC_CMR_ACPC_SET); + else + TC_SetCMR_ChannelB(chTC, chNo, TC_CMR_BCPB_CLEAR | TC_CMR_BCPC_SET); + } + + return; + } +} + +// interrupt handlers for seamless pwm duty-cycle setting +void TC0_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC0, 0); + // update the counters + if(pwm_counter_vals[0]) TC_SetRA(TC0, 0, pwm_counter_vals[0]); + if(pwm_counter_vals[1]) TC_SetRB(TC0, 0, pwm_counter_vals[1]); +} + +void TC1_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC0, 1); + // update the counters + if(pwm_counter_vals[2]) TC_SetRA(TC0, 1, pwm_counter_vals[2]); + if(pwm_counter_vals[3]) TC_SetRB(TC0, 1, pwm_counter_vals[3]); +} + +void TC2_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC0, 2); + // update the counters + if(pwm_counter_vals[4]) TC_SetRA(TC0, 2, pwm_counter_vals[4]); + if(pwm_counter_vals[5]) TC_SetRB(TC0, 2, pwm_counter_vals[5]); +} +void TC3_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC1, 0); + // update the counters + if(pwm_counter_vals[6]) TC_SetRA(TC1, 0, pwm_counter_vals[6]); + if(pwm_counter_vals[7]) TC_SetRB(TC1, 0, pwm_counter_vals[7]); +} + +void TC4_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC1, 1); + // update the counters + if(pwm_counter_vals[8]) TC_SetRA(TC1, 1, pwm_counter_vals[8]); + if(pwm_counter_vals[9]) TC_SetRB(TC1, 1, pwm_counter_vals[9]); +} + +void TC5_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC1, 2); + // update the counters + if(pwm_counter_vals[10]) TC_SetRA(TC1, 2, pwm_counter_vals[10]); + if(pwm_counter_vals[11]) TC_SetRB(TC1, 2, pwm_counter_vals[11]); +} +void TC6_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC2, 0); + // update the counters + if(pwm_counter_vals[12]) TC_SetRA(TC2, 0, pwm_counter_vals[12]); + if(pwm_counter_vals[13]) TC_SetRB(TC2, 0, pwm_counter_vals[13]); +} + +void TC7_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC2, 1); + // update the counters + if(pwm_counter_vals[14]) TC_SetRA(TC2, 1, pwm_counter_vals[14]); + if(pwm_counter_vals[15]) TC_SetRB(TC2, 1, pwm_counter_vals[15]); +} + +void TC8_Handler() +{ + // read/clear interrupt status + TC_GetStatus(TC2, 2); + // update the counters + if(pwm_counter_vals[16]) TC_SetRA(TC2, 2, pwm_counter_vals[16]); + if(pwm_counter_vals[17]) TC_SetRB(TC2, 2, pwm_counter_vals[17]); +} + + + + + +// implementation of the hardware_api.cpp +// --------------------------------------------------------------------------------------------------------------------------------- + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware specific +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 50khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + // save the pwm frequency + _pwm_frequency = pwm_frequency; + // cinfigure pwm pins + initPWM(pinA, _pwm_frequency); + initPWM(pinB, _pwm_frequency); + initPWM(pinC, _pwm_frequency); + // sync the timers if possible + syncTimers(pinA, pinB, pinC); + + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + + +// Configuring PWM frequency, resolution and alignment +//- Stepper driver - 2PWM setting +// - hardware specific +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { + if(!pwm_frequency || !_isset(pwm_frequency)) pwm_frequency = _PWM_FREQUENCY; // default frequency 50khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + // save the pwm frequency + _pwm_frequency = pwm_frequency; + // cinfigure pwm pins + initPWM(pinA, _pwm_frequency); + initPWM(pinB, _pwm_frequency); + // sync the timers if possible + syncTimers(pinA, pinB); + + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC, const int pinD) { + if(!pwm_frequency || !_isset(pwm_frequency)) pwm_frequency = _PWM_FREQUENCY; // default frequency 50khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + // save the pwm frequency + _pwm_frequency = pwm_frequency; + // cinfigure pwm pins + initPWM(pinA, _pwm_frequency); + initPWM(pinB, _pwm_frequency); + initPWM(pinC, _pwm_frequency); + initPWM(pinD, _pwm_frequency); + // sync the timers if possible + syncTimers(pinA, pinB, pinC, pinD); + + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC, pinD }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware speciffic +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* param){ + // transform duty cycle from [0,1] to [0,_max_pwm_value] + GenericDriverParams* p = (GenericDriverParams*)param; + setPwm(p->pins[0], _max_pwm_value*dc_a); + setPwm(p->pins[1], _max_pwm_value*dc_b); + setPwm(p->pins[2], _max_pwm_value*dc_c); +} + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware speciffic +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* param){ + // transform duty cycle from [0,1] to [0,_max_pwm_value] + GenericDriverParams* p = (GenericDriverParams*)param; + setPwm(p->pins[0], _max_pwm_value*dc_1a); + setPwm(p->pins[1], _max_pwm_value*dc_1b); + setPwm(p->pins[2], _max_pwm_value*dc_2a); + setPwm(p->pins[3], _max_pwm_value*dc_2b); +} + + + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - Stepper driver - 2PWM setting +// - hardware specific +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* param){ + // transform duty cycle from [0,1] to [0,_max_pwm_value] + GenericDriverParams* p = (GenericDriverParams*)param; + setPwm(p->pins[0], _max_pwm_value*dc_a); + setPwm(p->pins[1], _max_pwm_value*dc_b); +} + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_driver_mcpwm.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_driver_mcpwm.h new file mode 100644 index 0000000..1049787 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_driver_mcpwm.h @@ -0,0 +1,96 @@ +#ifndef ESP32_DRIVER_MCPWM_H +#define ESP32_DRIVER_MCPWM_H + +#include "../../hardware_api.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && defined(SOC_MCPWM_SUPPORTED) && !defined(SIMPLEFOC_ESP32_USELEDC) + + + +#pragma message("") +#pragma message("SimpleFOC: compiling for ESP32 MCPWM driver") +#pragma message("") + + +#include "driver/mcpwm.h" +#include "soc/mcpwm_reg.h" +#include "soc/mcpwm_struct.h" + +// empty motor slot +#define _EMPTY_SLOT -20 +#define _TAKEN_SLOT -21 + +// ABI bus frequency - would be better to take it from somewhere +// but I did nto find a good exposed variable +#define _MCPWM_FREQ 160e6f + +// preferred pwm resolution default +#define _PWM_RES_DEF 4096 +// min resolution +#define _PWM_RES_MIN 3000 +// max resolution +#define _PWM_RES_MAX 8000 +// pwm frequency +#define _PWM_FREQUENCY 25000 // default +#define _PWM_FREQUENCY_MAX 50000 // mqx + +// structure containing motor slot configuration +// this library supports up to 4 motors +typedef struct { + int pinA; + mcpwm_dev_t* mcpwm_num; + mcpwm_unit_t mcpwm_unit; + mcpwm_operator_t mcpwm_operator; + mcpwm_io_signals_t mcpwm_a; + mcpwm_io_signals_t mcpwm_b; + mcpwm_io_signals_t mcpwm_c; +} bldc_3pwm_motor_slots_t; + +typedef struct { + int pin1A; + mcpwm_dev_t* mcpwm_num; + mcpwm_unit_t mcpwm_unit; + mcpwm_operator_t mcpwm_operator1; + mcpwm_operator_t mcpwm_operator2; + mcpwm_io_signals_t mcpwm_1a; + mcpwm_io_signals_t mcpwm_1b; + mcpwm_io_signals_t mcpwm_2a; + mcpwm_io_signals_t mcpwm_2b; +} stepper_4pwm_motor_slots_t; + +typedef struct { + int pin1pwm; + mcpwm_dev_t* mcpwm_num; + mcpwm_unit_t mcpwm_unit; + mcpwm_operator_t mcpwm_operator; + mcpwm_io_signals_t mcpwm_a; + mcpwm_io_signals_t mcpwm_b; +} stepper_2pwm_motor_slots_t; + +typedef struct { + int pinAH; + mcpwm_dev_t* mcpwm_num; + mcpwm_unit_t mcpwm_unit; + mcpwm_operator_t mcpwm_operator1; + mcpwm_operator_t mcpwm_operator2; + mcpwm_io_signals_t mcpwm_ah; + mcpwm_io_signals_t mcpwm_bh; + mcpwm_io_signals_t mcpwm_ch; + mcpwm_io_signals_t mcpwm_al; + mcpwm_io_signals_t mcpwm_bl; + mcpwm_io_signals_t mcpwm_cl; +} bldc_6pwm_motor_slots_t; + + +typedef struct ESP32MCPWMDriverParams { + long pwm_frequency; + mcpwm_dev_t* mcpwm_dev; + mcpwm_unit_t mcpwm_unit; + mcpwm_operator_t mcpwm_operator1; + mcpwm_operator_t mcpwm_operator2; + float deadtime; +} ESP32MCPWMDriverParams; + + +#endif +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_ledc_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_ledc_mcu.cpp new file mode 100644 index 0000000..a454c05 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_ledc_mcu.cpp @@ -0,0 +1,185 @@ +#include "../../hardware_api.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && ( !defined(SOC_MCPWM_SUPPORTED) || defined(SIMPLEFOC_ESP32_USELEDC) ) + +#pragma message("") +#pragma message("SimpleFOC: compiling for ESP32 LEDC driver") +#pragma message("") + +#include "driver/ledc.h" + +#define _PWM_FREQUENCY 25000 // 25khz +#define _PWM_FREQUENCY_MAX 38000 // 38khz max to be able to have 10 bit pwm resolution +#define _PWM_RES_BIT 10 // 10 bir resolution +#define _PWM_RES 1023 // 2^10-1 = 1023-1 + + +// empty motor slot +#define _EMPTY_SLOT -20 +#define _TAKEN_SLOT -21 + +// figure out how many ledc channels are avaible +// esp32 - 2x8=16 +// esp32s2 - 8 +// esp32c3 - 6 +#include "soc/soc_caps.h" +#ifdef SOC_LEDC_SUPPORT_HS_MODE +#define LEDC_CHANNELS (SOC_LEDC_CHANNEL_NUM<<1) +#else +#define LEDC_CHANNELS (SOC_LEDC_CHANNEL_NUM) +#endif + + +// current channel stack index +// support for multiple motors +// esp32 has 16 channels +// esp32s2 has 8 channels +// esp32c3 has 6 channels +int channel_index = 0; + + + + +typedef struct ESP32LEDCDriverParams { + int channels[6]; + long pwm_frequency; +} ESP32LEDCDriverParams; + + + + + +// configure High PWM frequency +void _setHighFrequency(const long freq, const int pin, const int channel){ + ledcSetup(channel, freq, _PWM_RES_BIT ); + ledcAttachPin(pin, channel); +} + + + + + + +void* _configure1PWM(long pwm_frequency, const int pinA) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + + // check if enough channels available + if ( channel_index + 1 >= LEDC_CHANNELS ) return SIMPLEFOC_DRIVER_INIT_FAILED; + + int ch1 = channel_index++; + _setHighFrequency(pwm_frequency, pinA, ch1); + + ESP32LEDCDriverParams* params = new ESP32LEDCDriverParams { + .channels = { ch1 }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + + + + + + +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + + // check if enough channels available + if ( channel_index + 2 >= LEDC_CHANNELS ) return SIMPLEFOC_DRIVER_INIT_FAILED; + + int ch1 = channel_index++; + int ch2 = channel_index++; + _setHighFrequency(pwm_frequency, pinA, ch1); + _setHighFrequency(pwm_frequency, pinB, ch2); + + ESP32LEDCDriverParams* params = new ESP32LEDCDriverParams { + .channels = { ch1, ch2 }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + + // check if enough channels available + if ( channel_index + 3 >= LEDC_CHANNELS ) return SIMPLEFOC_DRIVER_INIT_FAILED; + + int ch1 = channel_index++; + int ch2 = channel_index++; + int ch3 = channel_index++; + _setHighFrequency(pwm_frequency, pinA, ch1); + _setHighFrequency(pwm_frequency, pinB, ch2); + _setHighFrequency(pwm_frequency, pinC, ch3); + + ESP32LEDCDriverParams* params = new ESP32LEDCDriverParams { + .channels = { ch1, ch2, ch3 }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + +void* _configure4PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC, const int pinD) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + + // check if enough channels available + if ( channel_index + 4 >= LEDC_CHANNELS ) return SIMPLEFOC_DRIVER_INIT_FAILED; + + int ch1 = channel_index++; + int ch2 = channel_index++; + int ch3 = channel_index++; + int ch4 = channel_index++; + _setHighFrequency(pwm_frequency, pinA, ch1); + _setHighFrequency(pwm_frequency, pinB, ch2); + _setHighFrequency(pwm_frequency, pinC, ch3); + _setHighFrequency(pwm_frequency, pinD, ch4); + + ESP32LEDCDriverParams* params = new ESP32LEDCDriverParams { + .channels = { ch1, ch2, ch3, ch4 }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + + +void _writeDutyCycle1PWM(float dc_a, void* params){ + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[0], _constrain(_PWM_RES*dc_a, 0, _PWM_RES)); +} + + + +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[0], _constrain(_PWM_RES*dc_a, 0, _PWM_RES)); + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[1], _constrain(_PWM_RES*dc_b, 0, _PWM_RES)); +} + + + +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[0], _constrain(_PWM_RES*dc_a, 0, _PWM_RES)); + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[1], _constrain(_PWM_RES*dc_b, 0, _PWM_RES)); + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[2], _constrain(_PWM_RES*dc_c, 0, _PWM_RES)); +} + + + +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[0], _constrain(_PWM_RES*dc_1a, 0, _PWM_RES)); + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[1], _constrain(_PWM_RES*dc_1b, 0, _PWM_RES)); + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[2], _constrain(_PWM_RES*dc_2a, 0, _PWM_RES)); + ledcWrite(((ESP32LEDCDriverParams*)params)->channels[3], _constrain(_PWM_RES*dc_2b, 0, _PWM_RES)); +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_mcu.cpp new file mode 100644 index 0000000..0dc23c1 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp32/esp32_mcu.cpp @@ -0,0 +1,431 @@ +#include "esp32_driver_mcpwm.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && defined(SOC_MCPWM_SUPPORTED) && !defined(SIMPLEFOC_ESP32_USELEDC) + +#ifndef SIMPLEFOC_ESP32_HW_DEADTIME + #define SIMPLEFOC_ESP32_HW_DEADTIME true // TODO: Change to false when sw-deadtime & phase_state is approved ready for general use. +#endif + +// define bldc motor slots array +bldc_3pwm_motor_slots_t esp32_bldc_3pwm_motor_slots[4] = { + {_EMPTY_SLOT, &MCPWM0, MCPWM_UNIT_0, MCPWM_OPR_A, MCPWM0A, MCPWM1A, MCPWM2A}, // 1st motor will be MCPWM0 channel A + {_EMPTY_SLOT, &MCPWM0, MCPWM_UNIT_0, MCPWM_OPR_B, MCPWM0B, MCPWM1B, MCPWM2B}, // 2nd motor will be MCPWM0 channel B + {_EMPTY_SLOT, &MCPWM1, MCPWM_UNIT_1, MCPWM_OPR_A, MCPWM0A, MCPWM1A, MCPWM2A}, // 3rd motor will be MCPWM1 channel A + {_EMPTY_SLOT, &MCPWM1, MCPWM_UNIT_1, MCPWM_OPR_B, MCPWM0B, MCPWM1B, MCPWM2B} // 4th motor will be MCPWM1 channel B + }; + +// define stepper motor slots array +bldc_6pwm_motor_slots_t esp32_bldc_6pwm_motor_slots[2] = { + {_EMPTY_SLOT, &MCPWM0, MCPWM_UNIT_0, MCPWM_OPR_A, MCPWM_OPR_B, MCPWM0A, MCPWM1A, MCPWM2A, MCPWM0B, MCPWM1B, MCPWM2B}, // 1st motor will be on MCPWM0 + {_EMPTY_SLOT, &MCPWM1, MCPWM_UNIT_1, MCPWM_OPR_A, MCPWM_OPR_B, MCPWM0A, MCPWM1A, MCPWM2A, MCPWM0B, MCPWM1B, MCPWM2B}, // 1st motor will be on MCPWM0 + }; + +// define 4pwm stepper motor slots array +stepper_4pwm_motor_slots_t esp32_stepper_4pwm_motor_slots[2] = { + {_EMPTY_SLOT, &MCPWM0, MCPWM_UNIT_0, MCPWM_OPR_A, MCPWM_OPR_B, MCPWM0A, MCPWM1A, MCPWM0B, MCPWM1B}, // 1st motor will be on MCPWM0 + {_EMPTY_SLOT, &MCPWM1, MCPWM_UNIT_1, MCPWM_OPR_A, MCPWM_OPR_B, MCPWM0A, MCPWM1A, MCPWM0B, MCPWM1B}, // 1st motor will be on MCPWM1 + }; + +// define 2pwm stepper motor slots array +stepper_2pwm_motor_slots_t esp32_stepper_2pwm_motor_slots[4] = { + {_EMPTY_SLOT, &MCPWM0, MCPWM_UNIT_0, MCPWM_OPR_A, MCPWM0A, MCPWM1A}, // 1st motor will be MCPWM0 channel A + {_EMPTY_SLOT, &MCPWM0, MCPWM_UNIT_0, MCPWM_OPR_B, MCPWM0B, MCPWM1B}, // 2nd motor will be MCPWM0 channel B + {_EMPTY_SLOT, &MCPWM1, MCPWM_UNIT_1, MCPWM_OPR_A, MCPWM0A, MCPWM1A}, // 3rd motor will be MCPWM1 channel A + {_EMPTY_SLOT, &MCPWM1, MCPWM_UNIT_1, MCPWM_OPR_B, MCPWM0B, MCPWM1B} // 4th motor will be MCPWM1 channel B + }; + + +// configuring high frequency pwm timer +// a lot of help from this post from Paul Gauld +// https://hackaday.io/project/169905-esp-32-bldc-robot-actuator-controller +// a short tutorial for v2.0.1+ +// https://kzhead.info/sun/q6uFktWgkYeMeZ8/esp32-arduino.html +// +void _configureTimerFrequency(long pwm_frequency, mcpwm_dev_t* mcpwm_num, mcpwm_unit_t mcpwm_unit, float dead_zone = NOT_SET){ + + mcpwm_config_t pwm_config; + pwm_config.counter_mode = MCPWM_UP_DOWN_COUNTER; // Up-down counter (triangle wave) + pwm_config.duty_mode = (_isset(dead_zone) || SIMPLEFOC_PWM_ACTIVE_HIGH == true) ? MCPWM_DUTY_MODE_0 : MCPWM_DUTY_MODE_1; // Normally Active HIGH (MCPWM_DUTY_MODE_0) + pwm_config.frequency = 2*pwm_frequency; // set the desired freq - just a placeholder for now https://github.com/simplefoc/Arduino-FOC/issues/76 + mcpwm_init(mcpwm_unit, MCPWM_TIMER_0, &pwm_config); //Configure PWM0A & PWM0B with above settings + mcpwm_init(mcpwm_unit, MCPWM_TIMER_1, &pwm_config); //Configure PWM1A & PWM1B with above settings + mcpwm_init(mcpwm_unit, MCPWM_TIMER_2, &pwm_config); //Configure PWM2A & PWM2B with above settings + + if (_isset(dead_zone)){ + // dead zone is configured + + // When using hardware deadtime, setting the phase_state parameter is not supported. + #if SIMPLEFOC_ESP32_HW_DEADTIME == true + float dead_time = (float)(_MCPWM_FREQ / (pwm_frequency)) * dead_zone; + mcpwm_deadtime_type_t pwm_mode; + if ((SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH == true) && (SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH == true)) {pwm_mode = MCPWM_ACTIVE_HIGH_COMPLIMENT_MODE;} // Normal, noninverting driver + else if ((SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH == true) && (SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH == false)){pwm_mode = MCPWM_ACTIVE_HIGH_MODE;} // Inverted lowside driver + else if ((SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH == false) && (SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH == true)) {pwm_mode = MCPWM_ACTIVE_LOW_MODE;} // Inverted highside driver + else if ((SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH == false) && (SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH == false)){pwm_mode = MCPWM_ACTIVE_LOW_COMPLIMENT_MODE;} // Inverted low- & highside driver. Caution: This may short the FETs on reset of the ESP32, as both pins get pulled low! + mcpwm_deadtime_enable(mcpwm_unit, MCPWM_TIMER_0, pwm_mode, dead_time/2.0, dead_time/2.0); + mcpwm_deadtime_enable(mcpwm_unit, MCPWM_TIMER_1, pwm_mode, dead_time/2.0, dead_time/2.0); + mcpwm_deadtime_enable(mcpwm_unit, MCPWM_TIMER_2, pwm_mode, dead_time/2.0, dead_time/2.0); + #else // Software deadtime + for (int i = 0; i < 3; i++){ + if (SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH == true) {mcpwm_set_duty_type(mcpwm_unit, (mcpwm_timer_t) i, MCPWM_GEN_A, MCPWM_DUTY_MODE_0);} // Normal, noninverted highside + else if (SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH == false) {mcpwm_set_duty_type(mcpwm_unit, (mcpwm_timer_t) i, MCPWM_GEN_A, MCPWM_DUTY_MODE_1);} // Inverted highside driver + + if (SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH == true) {mcpwm_set_duty_type(mcpwm_unit, (mcpwm_timer_t) i, MCPWM_GEN_B, MCPWM_DUTY_MODE_1);} // Normal, complementary lowside + else if (SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH == false) {mcpwm_set_duty_type(mcpwm_unit, (mcpwm_timer_t) i, MCPWM_GEN_B, MCPWM_DUTY_MODE_0);} // Inverted lowside driver + } + #endif + + } + _delay(100); + + mcpwm_stop(mcpwm_unit, MCPWM_TIMER_0); + mcpwm_stop(mcpwm_unit, MCPWM_TIMER_1); + mcpwm_stop(mcpwm_unit, MCPWM_TIMER_2); + + // manual configuration due to the lack of config flexibility in mcpwm_init() + mcpwm_num->clk_cfg.clk_prescale = 0; + // calculate prescaler and period + // step 1: calculate the prescaler using the default pwm resolution + // prescaler = bus_freq / (pwm_freq * default_pwm_res) - 1 + int prescaler = ceil((double)_MCPWM_FREQ / (double)_PWM_RES_DEF / 2.0f / (double)pwm_frequency) - 1; + // constrain prescaler + prescaler = _constrain(prescaler, 0, 128); + // now calculate the real resolution timer period necessary (pwm resolution) + // pwm_res = bus_freq / (pwm_freq * (prescaler + 1)) + int resolution_corrected = (double)_MCPWM_FREQ / 2.0f / (double)pwm_frequency / (double)(prescaler + 1); + // if pwm resolution too low lower the prescaler + if(resolution_corrected < _PWM_RES_MIN && prescaler > 0 ) + resolution_corrected = (double)_MCPWM_FREQ / 2.0f / (double)pwm_frequency / (double)(--prescaler + 1); + resolution_corrected = _constrain(resolution_corrected, _PWM_RES_MIN, _PWM_RES_MAX); + + // set prescaler + mcpwm_num->timer[0].timer_cfg0.timer_prescale = prescaler; + mcpwm_num->timer[1].timer_cfg0.timer_prescale = prescaler; + mcpwm_num->timer[2].timer_cfg0.timer_prescale = prescaler; + _delay(1); + //set period + mcpwm_num->timer[0].timer_cfg0.timer_period = resolution_corrected; + mcpwm_num->timer[1].timer_cfg0.timer_period = resolution_corrected; + mcpwm_num->timer[2].timer_cfg0.timer_period = resolution_corrected; + _delay(1); + mcpwm_num->timer[0].timer_cfg0.timer_period_upmethod = 0; + mcpwm_num->timer[1].timer_cfg0.timer_period_upmethod = 0; + mcpwm_num->timer[2].timer_cfg0.timer_period_upmethod = 0; + _delay(1); + // _delay(1); + //restart the timers + mcpwm_start(mcpwm_unit, MCPWM_TIMER_0); + mcpwm_start(mcpwm_unit, MCPWM_TIMER_1); + mcpwm_start(mcpwm_unit, MCPWM_TIMER_2); + _delay(1); + + mcpwm_sync_config_t sync_conf = { + .sync_sig = MCPWM_SELECT_TIMER0_SYNC, + .timer_val = 0, + .count_direction = MCPWM_TIMER_DIRECTION_UP + }; + mcpwm_sync_configure(mcpwm_unit, MCPWM_TIMER_0, &sync_conf); + mcpwm_sync_configure(mcpwm_unit, MCPWM_TIMER_1, &sync_conf); + mcpwm_sync_configure(mcpwm_unit, MCPWM_TIMER_2, &sync_conf); + + // Enable sync event for all timers to be the TEZ of timer0 + mcpwm_set_timer_sync_output(mcpwm_unit, MCPWM_TIMER_0, MCPWM_SWSYNC_SOURCE_TEZ); +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +// supports Arudino/ATmega328, STM32 and ESP32 +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25hz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 40kHz max + + stepper_2pwm_motor_slots_t m_slot = {}; + + // determine which motor are we connecting + // and set the appropriate configuration parameters + int slot_num; + for(slot_num = 0; slot_num < 4; slot_num++){ + if(esp32_stepper_2pwm_motor_slots[slot_num].pin1pwm == _EMPTY_SLOT){ // put the new motor in the first empty slot + esp32_stepper_2pwm_motor_slots[slot_num].pin1pwm = pinA; + m_slot = esp32_stepper_2pwm_motor_slots[slot_num]; + break; + } + } + + // disable all the slots with the same MCPWM + // disable 3pwm bldc motor which would go in the same slot + esp32_bldc_3pwm_motor_slots[slot_num].pinA = _TAKEN_SLOT; + if( slot_num < 2 ){ + // slot 0 of the 4pwm stepper + esp32_stepper_4pwm_motor_slots[0].pin1A = _TAKEN_SLOT; + // slot 0 of the 6pwm bldc + esp32_bldc_6pwm_motor_slots[0].pinAH = _TAKEN_SLOT; + }else{ + // slot 1 of the stepper + esp32_stepper_4pwm_motor_slots[1].pin1A = _TAKEN_SLOT; + // slot 1 of the 6pwm bldc + esp32_bldc_6pwm_motor_slots[1].pinAH = _TAKEN_SLOT; + } + // configure pins + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_a, pinA); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_b, pinB); + + // configure the timer + _configureTimerFrequency(pwm_frequency, m_slot.mcpwm_num, m_slot.mcpwm_unit); + + ESP32MCPWMDriverParams* params = new ESP32MCPWMDriverParams { + .pwm_frequency = pwm_frequency, + .mcpwm_dev = m_slot.mcpwm_num, + .mcpwm_unit = m_slot.mcpwm_unit, + .mcpwm_operator1 = m_slot.mcpwm_operator + }; + return params; +} + + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +// supports Arudino/ATmega328, STM32 and ESP32 +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25hz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 40kHz max + + bldc_3pwm_motor_slots_t m_slot = {}; + + // determine which motor are we connecting + // and set the appropriate configuration parameters + int slot_num; + for(slot_num = 0; slot_num < 4; slot_num++){ + if(esp32_bldc_3pwm_motor_slots[slot_num].pinA == _EMPTY_SLOT){ // put the new motor in the first empty slot + esp32_bldc_3pwm_motor_slots[slot_num].pinA = pinA; + m_slot = esp32_bldc_3pwm_motor_slots[slot_num]; + break; + } + } + // disable all the slots with the same MCPWM + // disable 2pwm steppr motor which would go in the same slot + esp32_stepper_2pwm_motor_slots[slot_num].pin1pwm = _TAKEN_SLOT; + if( slot_num < 2 ){ + // slot 0 of the 4pwm stepper + esp32_stepper_4pwm_motor_slots[0].pin1A = _TAKEN_SLOT; + // slot 0 of the 6pwm bldc + esp32_bldc_6pwm_motor_slots[0].pinAH = _TAKEN_SLOT; + }else{ + // slot 1 of the stepper + esp32_stepper_4pwm_motor_slots[1].pin1A = _TAKEN_SLOT; + // slot 1 of the 6pwm bldc + esp32_bldc_6pwm_motor_slots[1].pinAH = _TAKEN_SLOT; + } + // configure pins + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_a, pinA); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_b, pinB); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_c, pinC); + + // configure the timer + _configureTimerFrequency(pwm_frequency, m_slot.mcpwm_num, m_slot.mcpwm_unit); + + ESP32MCPWMDriverParams* params = new ESP32MCPWMDriverParams { + .pwm_frequency = pwm_frequency, + .mcpwm_dev = m_slot.mcpwm_num, + .mcpwm_unit = m_slot.mcpwm_unit, + .mcpwm_operator1 = m_slot.mcpwm_operator + }; + return params; +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC, const int pinD) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25hz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 40kHz max + stepper_4pwm_motor_slots_t m_slot = {}; + // determine which motor are we connecting + // and set the appropriate configuration parameters + int slot_num; + for(slot_num = 0; slot_num < 2; slot_num++){ + if(esp32_stepper_4pwm_motor_slots[slot_num].pin1A == _EMPTY_SLOT){ // put the new motor in the first empty slot + esp32_stepper_4pwm_motor_slots[slot_num].pin1A = pinA; + m_slot = esp32_stepper_4pwm_motor_slots[slot_num]; + break; + } + } + // disable all the slots with the same MCPWM + if( slot_num == 0 ){ + // slots 0 and 1 of the 3pwm bldc + esp32_bldc_3pwm_motor_slots[0].pinA = _TAKEN_SLOT; + esp32_bldc_3pwm_motor_slots[1].pinA = _TAKEN_SLOT; + // slots 0 and 1 of the 2pwm stepper taken + esp32_stepper_2pwm_motor_slots[0].pin1pwm = _TAKEN_SLOT; + esp32_stepper_2pwm_motor_slots[1].pin1pwm = _TAKEN_SLOT; + // slot 0 of the 6pwm bldc + esp32_bldc_6pwm_motor_slots[0].pinAH = _TAKEN_SLOT; + }else{ + // slots 2 and 3 of the 3pwm bldc + esp32_bldc_3pwm_motor_slots[2].pinA = _TAKEN_SLOT; + esp32_bldc_3pwm_motor_slots[3].pinA = _TAKEN_SLOT; + // slots 2 and 3 of the 2pwm stepper taken + esp32_stepper_2pwm_motor_slots[2].pin1pwm = _TAKEN_SLOT; + esp32_stepper_2pwm_motor_slots[3].pin1pwm = _TAKEN_SLOT; + // slot 1 of the 6pwm bldc + esp32_bldc_6pwm_motor_slots[1].pinAH = _TAKEN_SLOT; + } + + // configure pins + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_1a, pinA); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_1b, pinB); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_2a, pinC); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_2b, pinD); + + // configure the timer + _configureTimerFrequency(pwm_frequency, m_slot.mcpwm_num, m_slot.mcpwm_unit); + + ESP32MCPWMDriverParams* params = new ESP32MCPWMDriverParams { + .pwm_frequency = pwm_frequency, + .mcpwm_dev = m_slot.mcpwm_num, + .mcpwm_unit = m_slot.mcpwm_unit, + .mcpwm_operator1 = m_slot.mcpwm_operator1, + .mcpwm_operator2 = m_slot.mcpwm_operator2 + }; + return params; +} + + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +// ESP32 uses MCPWM +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + // se the PWM on the slot timers + // transform duty cycle from [0,1] to [0,100] + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator1, dc_a*100.0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator1, dc_b*100.0); +} + + + + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware speciffic +// ESP32 uses MCPWM +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // se the PWM on the slot timers + // transform duty cycle from [0,1] to [0,100] + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator1, dc_a*100.0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator1, dc_b*100.0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_2, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator1, dc_c*100.0); +} + + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware speciffic +// ESP32 uses MCPWM +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + // se the PWM on the slot timers + // transform duty cycle from [0,1] to [0,100] + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator1, dc_1a*100.0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator1, dc_1b*100.0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator2, dc_2a*100.0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, ((ESP32MCPWMDriverParams*)params)->mcpwm_operator2, dc_2b*100.0); +} + + + + +// Configuring PWM frequency, resolution and alignment +// - BLDC driver - 6PWM setting +// - hardware specific +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l){ + + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = 20000; // default frequency 20khz - centered pwm has twice lower frequency + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 40kHz max - centered pwm has twice lower frequency + bldc_6pwm_motor_slots_t m_slot = {}; + // determine which motor are we connecting + // and set the appropriate configuration parameters + int slot_num; + for(slot_num = 0; slot_num < 2; slot_num++){ + if(esp32_bldc_6pwm_motor_slots[slot_num].pinAH == _EMPTY_SLOT){ // put the new motor in the first empty slot + esp32_bldc_6pwm_motor_slots[slot_num].pinAH = pinA_h; + m_slot = esp32_bldc_6pwm_motor_slots[slot_num]; + break; + } + } + // if no slots available + if(slot_num >= 2) return SIMPLEFOC_DRIVER_INIT_FAILED; + + // disable all the slots with the same MCPWM + if( slot_num == 0 ){ + // slots 0 and 1 of the 3pwm bldc + esp32_bldc_3pwm_motor_slots[0].pinA = _TAKEN_SLOT; + esp32_bldc_3pwm_motor_slots[1].pinA = _TAKEN_SLOT; + // slot 0 of the 6pwm bldc + esp32_stepper_4pwm_motor_slots[0].pin1A = _TAKEN_SLOT; + }else{ + // slots 2 and 3 of the 3pwm bldc + esp32_bldc_3pwm_motor_slots[2].pinA = _TAKEN_SLOT; + esp32_bldc_3pwm_motor_slots[3].pinA = _TAKEN_SLOT; + // slot 1 of the 6pwm bldc + esp32_stepper_4pwm_motor_slots[1].pin1A = _TAKEN_SLOT; + } + + // configure pins + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_ah, pinA_h); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_al, pinA_l); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_bh, pinB_h); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_bl, pinB_l); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_ch, pinC_h); + mcpwm_gpio_init(m_slot.mcpwm_unit, m_slot.mcpwm_cl, pinC_l); + + // configure the timer + _configureTimerFrequency(pwm_frequency, m_slot.mcpwm_num, m_slot.mcpwm_unit, dead_zone); + // return + ESP32MCPWMDriverParams* params = new ESP32MCPWMDriverParams { + .pwm_frequency = pwm_frequency, + .mcpwm_dev = m_slot.mcpwm_num, + .mcpwm_unit = m_slot.mcpwm_unit, + .mcpwm_operator1 = m_slot.mcpwm_operator1, + .mcpwm_operator2 = m_slot.mcpwm_operator2, + .deadtime = _isset(dead_zone) ? dead_zone : 0 + }; + return params; +} + + + + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - BLDC driver - 6PWM setting +// - hardware specific +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + // set the PWM on the slot timers + // transform duty cycle from [0,1] to [0,100.0] + #if SIMPLEFOC_ESP32_HW_DEADTIME == true + // Hardware deadtime does deadtime insertion internally + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, MCPWM_OPR_A, dc_a*100.0f); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, MCPWM_OPR_B, dc_a*100.0f); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, MCPWM_OPR_A, dc_b*100.0f); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, MCPWM_OPR_B, dc_b*100.0f); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_2, MCPWM_OPR_A, dc_c*100.0f); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_2, MCPWM_OPR_B, dc_c*100.0f); + _UNUSED(phase_state); + #else + float deadtime = 0.5f*((ESP32MCPWMDriverParams*)params)->deadtime; + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, MCPWM_OPR_A, (phase_state[0] == PHASE_ON || phase_state[0] == PHASE_HI) ? _constrain(dc_a-deadtime, 0.0f, 1.0f) * 100.0f : 0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_0, MCPWM_OPR_B, (phase_state[0] == PHASE_ON || phase_state[0] == PHASE_LO) ? _constrain(dc_a+deadtime, 0.0f, 1.0f) * 100.0f : 100.0f); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, MCPWM_OPR_A, (phase_state[1] == PHASE_ON || phase_state[1] == PHASE_HI) ? _constrain(dc_b-deadtime, 0.0f, 1.0f) * 100.0f : 0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_1, MCPWM_OPR_B, (phase_state[1] == PHASE_ON || phase_state[1] == PHASE_LO) ? _constrain(dc_b+deadtime, 0.0f, 1.0f) * 100.0f : 100.0f); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_2, MCPWM_OPR_A, (phase_state[2] == PHASE_ON || phase_state[2] == PHASE_HI) ? _constrain(dc_c-deadtime, 0.0f, 1.0f) * 100.0f : 0); + mcpwm_set_duty(((ESP32MCPWMDriverParams*)params)->mcpwm_unit, MCPWM_TIMER_2, MCPWM_OPR_B, (phase_state[2] == PHASE_ON || phase_state[2] == PHASE_LO) ? _constrain(dc_c+deadtime, 0.0f, 1.0f) * 100.0f : 100.0f); + #endif +} + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp8266_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp8266_mcu.cpp new file mode 100644 index 0000000..23d9411 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/esp8266_mcu.cpp @@ -0,0 +1,121 @@ +#include "../hardware_api.h" + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP8266) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for ESP8266") +#pragma message("") + + +#define _PWM_FREQUENCY 25000 // 25khz +#define _PWM_FREQUENCY_MAX 50000 // 50khz + +// configure High PWM frequency +void _setHighFrequency(const long freq, const int pin){ + analogWrite(pin, 0); + analogWriteFreq(freq); +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure1PWM(long pwm_frequency, const int pinA) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + _setHighFrequency(pwm_frequency, pinB); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + _setHighFrequency(pwm_frequency, pinB); + _setHighFrequency(pwm_frequency, pinC); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC, const int pinD) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + _setHighFrequency(pwm_frequency, pinB); + _setHighFrequency(pwm_frequency, pinC); + _setHighFrequency(pwm_frequency, pinD); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC, pinD }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +void _writeDutyCycle1PWM(float dc_a, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); +} +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); +} +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware speciffic +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_c); +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware speciffic +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_1a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_1b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_2a); + analogWrite(((GenericDriverParams*)params)->pins[3], 255.0f*dc_2b); +} + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/generic_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/generic_mcu.cpp new file mode 100644 index 0000000..b6bc2f0 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/generic_mcu.cpp @@ -0,0 +1,125 @@ + +#include "../hardware_api.h" + +// if the mcu doen't have defiend analogWrite +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) && !defined(analogWrite) + __attribute__((weak)) void analogWrite(uint8_t pin, int value){ }; +#endif + +// function setting the high pwm frequency to the supplied pin +// - Stepper motor - 1PWM setting +// - hardware speciffic +// in generic case dont do anything +__attribute__((weak)) void* _configure1PWM(long pwm_frequency, const int pinA) { + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +// in generic case dont do anything +__attribute__((weak)) void* _configure2PWM(long pwm_frequency,const int pinA, const int pinB) { + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +// in generic case dont do anything +__attribute__((weak)) void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +// in generic case dont do anything +__attribute__((weak)) void* _configure4PWM(long pwm_frequency, const int pin1A, const int pin1B, const int pin2A, const int pin2B) { + GenericDriverParams* params = new GenericDriverParams { + .pins = { pin1A, pin1B, pin2A, pin2B }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// Configuring PWM frequency, resolution and alignment +// - BLDC driver - 6PWM setting +// - hardware specific +__attribute__((weak)) void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l){ + _UNUSED(pwm_frequency); + _UNUSED(dead_zone); + _UNUSED(pinA_h); + _UNUSED(pinA_l); + _UNUSED(pinB_h); + _UNUSED(pinB_l); + _UNUSED(pinC_h); + _UNUSED(pinC_l); + + return SIMPLEFOC_DRIVER_INIT_FAILED; +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 1PWM setting +// - hardware speciffic +__attribute__((weak)) void _writeDutyCycle1PWM(float dc_a, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +__attribute__((weak)) void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); +} + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware speciffic +__attribute__((weak)) void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_c); +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware speciffic +__attribute__((weak)) void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + // transform duty cycle from [0,1] to [0,255] + + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_1a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_1b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_2a); + analogWrite(((GenericDriverParams*)params)->pins[3], 255.0f*dc_2b); +} + + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - BLDC driver - 6PWM setting +// - hardware specific +__attribute__((weak)) void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + _UNUSED(dc_a); + _UNUSED(dc_b); + _UNUSED(dc_c); + _UNUSED(phase_state); + _UNUSED(params); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/nrf52_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/nrf52_mcu.cpp new file mode 100644 index 0000000..a20b828 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/nrf52_mcu.cpp @@ -0,0 +1,397 @@ + +#include "../hardware_api.h" + +#if defined(NRF52_SERIES) + +#pragma message("") +#pragma message("SimpleFOC: compiling for NRF52") +#pragma message("") + + +#define PWM_CLK (16000000) +#define PWM_FREQ (40000) +#define PWM_RESOLUTION (PWM_CLK/PWM_FREQ) +#define PWM_MAX_FREQ (62500) +#define DEAD_ZONE (250) // in ns +#define DEAD_TIME (DEAD_ZONE / (PWM_RESOLUTION * 0.25 * 62.5)) // 62.5ns resolution of PWM + +#ifdef NRF_PWM3 +#define PWM_COUNT 4 +#else +#define PWM_COUNT 3 +#endif + +// empty motor slot +#define _EMPTY_SLOT (-0xAA) +#define _TAKEN_SLOT (-0x55) + +int pwm_range; + + +static NRF_PWM_Type* pwms[PWM_COUNT] = { + NRF_PWM0, + NRF_PWM1, + NRF_PWM2, + #ifdef NRF_PWM3 + NRF_PWM3 + #endif +}; + +typedef struct { + int pinA; + NRF_PWM_Type* mcpwm; + uint16_t mcpwm_channel_sequence[4]; +} bldc_3pwm_motor_slots_t; + +typedef struct { + int pin1A; + NRF_PWM_Type* mcpwm; + uint16_t mcpwm_channel_sequence[4]; +} stepper_motor_slots_t; + +typedef struct { + int pinAH; + NRF_PWM_Type* mcpwm1; + NRF_PWM_Type* mcpwm2; + uint16_t mcpwm_channel_sequence[8]; +} bldc_6pwm_motor_slots_t; + +// define bldc motor slots array +bldc_3pwm_motor_slots_t nrf52_bldc_3pwm_motor_slots[4] = { + {_EMPTY_SLOT, pwms[0], {0,0,0,0}},// 1st motor will be PWM0 + {_EMPTY_SLOT, pwms[1], {0,0,0,0}},// 2nd motor will be PWM1 + {_EMPTY_SLOT, pwms[2], {0,0,0,0}},// 3rd motor will be PWM2 + {_EMPTY_SLOT, pwms[3], {0,0,0,0}} // 4th motor will be PWM3 + }; + +// define stepper motor slots array +stepper_motor_slots_t nrf52_stepper_motor_slots[4] = { + {_EMPTY_SLOT, pwms[0], {0,0,0,0}},// 1st motor will be on PWM0 + {_EMPTY_SLOT, pwms[1], {0,0,0,0}},// 1st motor will be on PWM1 + {_EMPTY_SLOT, pwms[2], {0,0,0,0}},// 1st motor will be on PWM2 + {_EMPTY_SLOT, pwms[3], {0,0,0,0}} // 1st motor will be on PWM3 + }; + +// define BLDC motor slots array +bldc_6pwm_motor_slots_t nrf52_bldc_6pwm_motor_slots[2] = { + {_EMPTY_SLOT, pwms[0], pwms[1], {0,0,0,0,0,0,0,0}},// 1st motor will be on PWM0 & PWM1 + {_EMPTY_SLOT, pwms[2], pwms[3], {0,0,0,0,0,0,0,0}} // 2nd motor will be on PWM1 & PWM2 + }; + + + +typedef struct NRF52DriverParams { + union { + bldc_3pwm_motor_slots_t* slot3pwm; + bldc_6pwm_motor_slots_t* slot6pwm; + stepper_motor_slots_t* slotstep; + } slot; + long pwm_frequency; + float dead_time; +} NRF52DriverParams; + + + + +// configuring high frequency pwm timer +void _configureHwPwm(NRF_PWM_Type* mcpwm1, NRF_PWM_Type* mcpwm2){ + + mcpwm1->ENABLE = (PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos); + mcpwm1->PRESCALER = (PWM_PRESCALER_PRESCALER_DIV_1 << PWM_PRESCALER_PRESCALER_Pos); + mcpwm1->MODE = (PWM_MODE_UPDOWN_UpAndDown << PWM_MODE_UPDOWN_Pos); + mcpwm1->COUNTERTOP = pwm_range; //pwm freq. + mcpwm1->LOOP = (PWM_LOOP_CNT_Disabled << PWM_LOOP_CNT_Pos); + mcpwm1->DECODER = ((uint32_t)PWM_DECODER_LOAD_Individual << PWM_DECODER_LOAD_Pos) | ((uint32_t)PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos); + mcpwm1->SEQ[0].REFRESH = 0; + mcpwm1->SEQ[0].ENDDELAY = 0; + + if(mcpwm1 != mcpwm2){ + mcpwm2->ENABLE = (PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos); + mcpwm2->PRESCALER = (PWM_PRESCALER_PRESCALER_DIV_1 << PWM_PRESCALER_PRESCALER_Pos); + mcpwm2->MODE = (PWM_MODE_UPDOWN_UpAndDown << PWM_MODE_UPDOWN_Pos); + mcpwm2->COUNTERTOP = pwm_range; //pwm freq. + mcpwm2->LOOP = (PWM_LOOP_CNT_Disabled << PWM_LOOP_CNT_Pos); + mcpwm2->DECODER = ((uint32_t)PWM_DECODER_LOAD_Individual << PWM_DECODER_LOAD_Pos) | ((uint32_t)PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos); + mcpwm2->SEQ[0].REFRESH = 0; + mcpwm2->SEQ[0].ENDDELAY = 0; + }else{ + mcpwm1->MODE = (PWM_MODE_UPDOWN_Up << PWM_MODE_UPDOWN_Pos); + } +} + + + +// can we support it using the generic driver on this MCU? Commented out to fall back to generic driver for 2-pwm +// void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { +// return SIMPLEFOC_DRIVER_INIT_FAILED; // not supported +// } + + + + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + + if( !pwm_frequency || pwm_frequency == NOT_SET) pwm_frequency = PWM_FREQ; // default frequency 20khz for a resolution of 800 + else pwm_frequency = _constrain(pwm_frequency, 0, PWM_MAX_FREQ); // constrain to 62.5kHz max for a resolution of 256 + + pwm_range = (PWM_CLK / pwm_frequency); + + int pA = digitalPinToPinName(pinA); //g_ADigitalPinMap[pinA]; + int pB = digitalPinToPinName(pinB); //g_ADigitalPinMap[pinB]; + int pC = digitalPinToPinName(pinC); //g_ADigitalPinMap[pinC]; + + // determine which motor are we connecting + // and set the appropriate configuration parameters + int slot_num; + for(slot_num = 0; slot_num < 4; slot_num++){ + if(nrf52_bldc_3pwm_motor_slots[slot_num].pinA == _EMPTY_SLOT){ // put the new motor in the first empty slot + nrf52_bldc_3pwm_motor_slots[slot_num].pinA = pinA; + break; + } + } + // if no slots available + if(slot_num >= 4) return SIMPLEFOC_DRIVER_INIT_FAILED; + + // disable all the slots with the same MCPWM + if(slot_num < 2){ + // slot 0 of the stepper + nrf52_stepper_motor_slots[slot_num].pin1A = _TAKEN_SLOT; + // slot 0 of the 6pwm bldc + nrf52_bldc_6pwm_motor_slots[0].pinAH = _TAKEN_SLOT; + //NRF_PPI->CHEN &= ~1UL; + }else{ + // slot 1 of the stepper + nrf52_stepper_motor_slots[slot_num].pin1A = _TAKEN_SLOT; + // slot 0 of the 6pwm bldc + nrf52_bldc_6pwm_motor_slots[1].pinAH = _TAKEN_SLOT; + //NRF_PPI->CHEN &= ~2UL; + } + + // configure pwm outputs + + nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm->PSEL.OUT[0] = pA; + nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm->PSEL.OUT[1] = pB; + nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm->PSEL.OUT[2] = pC; + + nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm->SEQ[0].PTR = (uint32_t)&nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm_channel_sequence[0]; + nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm->SEQ[0].CNT = 4; + + // configure the pwm + _configureHwPwm(nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm, nrf52_bldc_3pwm_motor_slots[slot_num].mcpwm); + + NRF52DriverParams* params = new NRF52DriverParams(); + params->slot.slot3pwm = &(nrf52_bldc_3pwm_motor_slots[slot_num]); + params->pwm_frequency = pwm_frequency; + return params; +} + + + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency, const int pinA, const int pinB, const int pinC, const int pinD) { + + if( !pwm_frequency || pwm_frequency == NOT_SET) pwm_frequency = PWM_FREQ; // default frequency 20khz for a resolution of 800 + else pwm_frequency = _constrain(pwm_frequency, 0, PWM_MAX_FREQ); // constrain to 62.5kHz max for a resolution of 256 + + pwm_range = (PWM_CLK / pwm_frequency); + + int pA = digitalPinToPinName(pinA); //g_ADigitalPinMap[pinA]; + int pB = digitalPinToPinName(pinB); //g_ADigitalPinMap[pinB]; + int pC = digitalPinToPinName(pinC); //g_ADigitalPinMap[pinC]; + int pD = digitalPinToPinName(pinD); //g_ADigitalPinMap[pinD]; + + // determine which motor are we connecting + // and set the appropriate configuration parameters + int slot_num; + for(slot_num = 0; slot_num < 4; slot_num++){ + if(nrf52_stepper_motor_slots[slot_num].pin1A == _EMPTY_SLOT){ // put the new motor in the first empty slot + nrf52_stepper_motor_slots[slot_num].pin1A = pinA; + break; + } + } + // if no slots available + if (slot_num >= 4) return SIMPLEFOC_DRIVER_INIT_FAILED; + + // disable all the slots with the same MCPWM + if (slot_num < 2){ + // slots 0 and 1 of the 3pwm bldc + nrf52_bldc_3pwm_motor_slots[slot_num].pinA = _TAKEN_SLOT; + // slot 0 of the 6pwm bldc + nrf52_bldc_6pwm_motor_slots[0].pinAH = _TAKEN_SLOT; + //NRF_PPI->CHEN &= ~1UL; + }else{ + // slots 2 and 3 of the 3pwm bldc + nrf52_bldc_3pwm_motor_slots[slot_num].pinA = _TAKEN_SLOT; + // slot 1 of the 6pwm bldc + nrf52_bldc_6pwm_motor_slots[1].pinAH = _TAKEN_SLOT; + //NRF_PPI->CHEN &= ~2UL; + } + + // configure pwm outputs + + nrf52_stepper_motor_slots[slot_num].mcpwm->PSEL.OUT[0] = pA; + nrf52_stepper_motor_slots[slot_num].mcpwm->PSEL.OUT[1] = pB; + nrf52_stepper_motor_slots[slot_num].mcpwm->PSEL.OUT[2] = pC; + nrf52_stepper_motor_slots[slot_num].mcpwm->PSEL.OUT[3] = pD; + + nrf52_stepper_motor_slots[slot_num].mcpwm->SEQ[0].PTR = (uint32_t)&nrf52_stepper_motor_slots[slot_num].mcpwm_channel_sequence[0]; + nrf52_stepper_motor_slots[slot_num].mcpwm->SEQ[0].CNT = 4; + + // configure the pwm + _configureHwPwm(nrf52_stepper_motor_slots[slot_num].mcpwm, nrf52_stepper_motor_slots[slot_num].mcpwm); + + NRF52DriverParams* params = new NRF52DriverParams(); + params->slot.slotstep = &(nrf52_stepper_motor_slots[slot_num]); + params->pwm_frequency = pwm_frequency; + return params; +} + + + + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware speciffic +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // transform duty cycle from [0,1] to [0,range] + bldc_3pwm_motor_slots_t* p = ((NRF52DriverParams*)params)->slot.slot3pwm; + p->mcpwm_channel_sequence[0] = (int)(dc_a * pwm_range) | 0x8000; + p->mcpwm_channel_sequence[1] = (int)(dc_b * pwm_range) | 0x8000; + p->mcpwm_channel_sequence[2] = (int)(dc_c * pwm_range) | 0x8000; + + p->mcpwm->TASKS_SEQSTART[0] = 1; +} + + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware speciffic +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + + stepper_motor_slots_t* p = ((NRF52DriverParams*)params)->slot.slotstep; + p->mcpwm_channel_sequence[0] = (int)(dc_1a * pwm_range) | 0x8000; + p->mcpwm_channel_sequence[1] = (int)(dc_1b * pwm_range) | 0x8000; + p->mcpwm_channel_sequence[2] = (int)(dc_2a * pwm_range) | 0x8000; + p->mcpwm_channel_sequence[3] = (int)(dc_2b * pwm_range) | 0x8000; + + p->mcpwm->TASKS_SEQSTART[0] = 1; +} + +/* Configuring PWM frequency, resolution and alignment +// - BLDC driver - 6PWM setting +// - hardware specific +*/ +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l){ + + if( !pwm_frequency || pwm_frequency == NOT_SET) pwm_frequency = PWM_FREQ; // default frequency 20khz - centered pwm has twice lower frequency for a resolution of 400 + else pwm_frequency = _constrain(pwm_frequency*2, 0, PWM_MAX_FREQ); // constrain to 62.5kHz max => 31.25kHz for a resolution of 256 + + pwm_range = (PWM_CLK / pwm_frequency); + pwm_range /= 2; // scale the frequency (centered PWM) + + float dead_time; + if (dead_zone != NOT_SET){ + dead_time = dead_zone/2; + }else{ + dead_time = DEAD_TIME/2; + } + + int pA_l = digitalPinToPinName(pinA_l); //g_ADigitalPinMap[pinA_l]; + int pA_h = digitalPinToPinName(pinA_h); //g_ADigitalPinMap[pinA_h]; + int pB_l = digitalPinToPinName(pinB_l); //g_ADigitalPinMap[pinB_l]; + int pB_h = digitalPinToPinName(pinB_h); //g_ADigitalPinMap[pinB_h]; + int pC_l = digitalPinToPinName(pinC_l); //g_ADigitalPinMap[pinC_l]; + int pC_h = digitalPinToPinName(pinC_h); //g_ADigitalPinMap[pinC_h]; + + + // determine which motor are we connecting + // and set the appropriate configuration parameters + int slot_num; + for(slot_num = 0; slot_num < 2; slot_num++){ + if(nrf52_bldc_6pwm_motor_slots[slot_num].pinAH == _EMPTY_SLOT){ // put the new motor in the first empty slot + nrf52_bldc_6pwm_motor_slots[slot_num].pinAH = pinA_h; + break; + } + } + // if no slots available + if(slot_num >= 2) return SIMPLEFOC_DRIVER_INIT_FAILED; + + // disable all the slots with the same MCPWM + if( slot_num == 0 ){ + // slots 0 and 1 of the 3pwm bldc + nrf52_bldc_3pwm_motor_slots[0].pinA = _TAKEN_SLOT; + nrf52_bldc_3pwm_motor_slots[1].pinA = _TAKEN_SLOT; + // slot 0 and 1 of the stepper + nrf52_stepper_motor_slots[0].pin1A = _TAKEN_SLOT; + nrf52_stepper_motor_slots[1].pin1A = _TAKEN_SLOT; + }else{ + // slots 2 and 3 of the 3pwm bldc + nrf52_bldc_3pwm_motor_slots[2].pinA = _TAKEN_SLOT; + nrf52_bldc_3pwm_motor_slots[3].pinA = _TAKEN_SLOT; + // slot 1 of the stepper + nrf52_stepper_motor_slots[2].pin1A = _TAKEN_SLOT; + nrf52_stepper_motor_slots[3].pin1A = _TAKEN_SLOT; + } + + // Configure pwm outputs + + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1->PSEL.OUT[0] = pA_h; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1->PSEL.OUT[1] = pA_l; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1->PSEL.OUT[2] = pB_h; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1->PSEL.OUT[3] = pB_l; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1->SEQ[0].PTR = (uint32_t)&nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm_channel_sequence[0]; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1->SEQ[0].CNT = 4; + + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm2->PSEL.OUT[0] = pC_h; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm2->PSEL.OUT[1] = pC_l; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm2->SEQ[0].PTR = (uint32_t)&nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm_channel_sequence[4]; + nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm2->SEQ[0].CNT = 4; + + // Initializing the PPI peripheral for sync the pwm slots + + NRF_PPI->CH[slot_num].EEP = (uint32_t)&NRF_EGU0->EVENTS_TRIGGERED[0]; + NRF_PPI->CH[slot_num].TEP = (uint32_t)&nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1->TASKS_SEQSTART[0]; + NRF_PPI->FORK[slot_num].TEP = (uint32_t)&nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm2->TASKS_SEQSTART[0]; + NRF_PPI->CHEN = 1UL << slot_num; + + // configure the pwm type + _configureHwPwm(nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm1, nrf52_bldc_6pwm_motor_slots[slot_num].mcpwm2); + + NRF52DriverParams* params = new NRF52DriverParams(); + params->slot.slot6pwm = &(nrf52_bldc_6pwm_motor_slots[slot_num]); + params->pwm_frequency = pwm_frequency; + params->dead_time = dead_time; + return params; +} + + + + +/* Function setting the duty cycle to the pwm pin +// - BLDC driver - 6PWM setting +// - hardware specific +*/ +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + bldc_6pwm_motor_slots_t* p = ((NRF52DriverParams*)params)->slot.slot6pwm; + float dead_time = ((NRF52DriverParams*)params)->dead_time; + p->mcpwm_channel_sequence[0] = (int)(_constrain(dc_a-dead_time,0,1)*pwm_range) | 0x8000; + p->mcpwm_channel_sequence[1] = (int)(_constrain(dc_a+dead_time,0,1)*pwm_range); + p->mcpwm_channel_sequence[2] = (int)(_constrain(dc_b-dead_time,0,1)*pwm_range) | 0x8000; + p->mcpwm_channel_sequence[3] = (int)(_constrain(dc_b+dead_time,0,1)*pwm_range); + p->mcpwm_channel_sequence[4] = (int)(_constrain(dc_c-dead_time,0,1)*pwm_range) | 0x8000; + p->mcpwm_channel_sequence[5] = (int)(_constrain(dc_c+dead_time,0,1)*pwm_range); + NRF_EGU0->TASKS_TRIGGER[0] = 1; + + _UNUSED(phase_state); +} + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/portenta_h7_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/portenta_h7_mcu.cpp new file mode 100644 index 0000000..ad16646 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/portenta_h7_mcu.cpp @@ -0,0 +1,545 @@ + +#include "../hardware_api.h" + +#if defined(TARGET_PORTENTA_H7) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for Arduino/Portenta_H7") +#pragma message("") + + +#include "pwmout_api.h" +#include "pinDefinitions.h" +#include "platform/mbed_critical.h" +#include "platform/mbed_power_mgmt.h" +#include "platform/mbed_assert.h" +#include "PeripheralPins.h" +#include "pwmout_device.h" + +// default pwm parameters +#define _PWM_FREQUENCY 25000 // 25khz +#define _PWM_FREQUENCY_MAX 50000 // 50khz + + +// // 6pwm parameters +// #define _HARDWARE_6PWM 1 +// #define _SOFTWARE_6PWM 0 +// #define _ERROR_6PWM -1 + + + +typedef struct PortentaDriverParams { + pwmout_t pins[4]; + long pwm_frequency; +// float dead_zone; +} PortentaDriverParams; + + + +/* Convert STM32 Cube HAL channel to LL channel */ +uint32_t _TIM_ChannelConvert_HAL2LL(uint32_t channel, pwmout_t *obj) +{ +#if !defined(PWMOUT_INVERTED_NOT_SUPPORTED) + if (obj->inverted) { + switch (channel) { + case TIM_CHANNEL_1 : + return LL_TIM_CHANNEL_CH1N; + case TIM_CHANNEL_2 : + return LL_TIM_CHANNEL_CH2N; + case TIM_CHANNEL_3 : + return LL_TIM_CHANNEL_CH3N; +#if defined(LL_TIM_CHANNEL_CH4N) + case TIM_CHANNEL_4 : + return LL_TIM_CHANNEL_CH4N; +#endif + default : /* Optional */ + return 0; + } + } else +#endif + { + switch (channel) { + case TIM_CHANNEL_1 : + return LL_TIM_CHANNEL_CH1; + case TIM_CHANNEL_2 : + return LL_TIM_CHANNEL_CH2; + case TIM_CHANNEL_3 : + return LL_TIM_CHANNEL_CH3; + case TIM_CHANNEL_4 : + return LL_TIM_CHANNEL_CH4; + default : /* Optional */ + return 0; + } + } +} + + + +// int _pwm_init(pwmout_t *obj, uint32_t pin, long frequency){ +// return _pwm_init(obj, digitalPinToPinName(pin), frequency); +// } + +int _pwm_init(pwmout_t *obj, uint32_t pin, long frequency){ + int peripheral = (int)pinmap_peripheral(digitalPinToPinName(pin), PinMap_PWM); + int function = (int)pinmap_find_function(digitalPinToPinName(pin), PinMap_PWM); + + const PinMap static_pinmap = {digitalPinToPinName(pin), peripheral, function}; + + pwmout_init_direct(obj, &static_pinmap); + + TIM_HandleTypeDef TimHandle; + TimHandle.Instance = (TIM_TypeDef *)(obj->pwm); + RCC_ClkInitTypeDef RCC_ClkInitStruct; + uint32_t PclkFreq = 0; + uint32_t APBxCLKDivider = RCC_HCLK_DIV1; + uint8_t i = 0; + + + __HAL_TIM_DISABLE(&TimHandle); + + // Get clock configuration + // Note: PclkFreq contains here the Latency (not used after) + HAL_RCC_GetClockConfig(&RCC_ClkInitStruct, &PclkFreq); + + /* Parse the pwm / apb mapping table to find the right entry */ + while (pwm_apb_map_table[i].pwm != obj->pwm) i++; + // sanity check + if (pwm_apb_map_table[i].pwm == 0) return -1; + + + if (pwm_apb_map_table[i].pwmoutApb == PWMOUT_ON_APB1) { + PclkFreq = HAL_RCC_GetPCLK1Freq(); + APBxCLKDivider = RCC_ClkInitStruct.APB1CLKDivider; + } else { +#if !defined(PWMOUT_APB2_NOT_SUPPORTED) + PclkFreq = HAL_RCC_GetPCLK2Freq(); + APBxCLKDivider = RCC_ClkInitStruct.APB2CLKDivider; +#endif + } + + long period_us = 500000.0/((float)frequency); + /* By default use, 1us as SW pre-scaler */ + obj->prescaler = 1; + // TIMxCLK = PCLKx when the APB prescaler = 1 else TIMxCLK = 2 * PCLKx + if (APBxCLKDivider == RCC_HCLK_DIV1) { + TimHandle.Init.Prescaler = (((PclkFreq) / 1000000)) - 1; // 1 us tick + } else { + TimHandle.Init.Prescaler = (((PclkFreq * 2) / 1000000)) - 1; // 1 us tick + } + TimHandle.Init.Period = (period_us - 1); + + /* In case period or pre-scalers are out of range, loop-in to get valid values */ + while ((TimHandle.Init.Period > 0xFFFF) || (TimHandle.Init.Prescaler > 0xFFFF)) { + obj->prescaler = obj->prescaler * 2; + if (APBxCLKDivider == RCC_HCLK_DIV1) { + TimHandle.Init.Prescaler = (((PclkFreq) / 1000000) * obj->prescaler) - 1; + } else { + TimHandle.Init.Prescaler = (((PclkFreq * 2) / 1000000) * obj->prescaler) - 1; + } + TimHandle.Init.Period = (period_us - 1) / obj->prescaler; + /* Period decreases and prescaler increases over loops, so check for + * possible out of range cases */ + if ((TimHandle.Init.Period < 0xFFFF) && (TimHandle.Init.Prescaler > 0xFFFF)) { + break; + } + } + + TimHandle.Init.ClockDivision = 0; + TimHandle.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED3; // center aligned + + if (HAL_TIM_PWM_Init(&TimHandle) != HAL_OK) { + return -1; + } + + TIM_OC_InitTypeDef sConfig; + // Configure channels + sConfig.OCMode = TIM_OCMODE_PWM1; + sConfig.Pulse = obj->pulse / obj->prescaler; + sConfig.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfig.OCFastMode = TIM_OCFAST_DISABLE; +#if defined(TIM_OCIDLESTATE_RESET) + sConfig.OCIdleState = TIM_OCIDLESTATE_RESET; +#endif +#if defined(TIM_OCNIDLESTATE_RESET) + sConfig.OCNPolarity = TIM_OCNPOLARITY_HIGH; + sConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET; +#endif + + int channel = 0; + switch (obj->channel) { + case 1: + channel = TIM_CHANNEL_1; + break; + case 2: + channel = TIM_CHANNEL_2; + break; + case 3: + channel = TIM_CHANNEL_3; + break; + case 4: + channel = TIM_CHANNEL_4; + break; + default: + return -1; + } + + if (LL_TIM_CC_IsEnabledChannel(TimHandle.Instance, _TIM_ChannelConvert_HAL2LL(channel, obj)) == 0) { + // If channel is not enabled, proceed to channel configuration + if (HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, channel) != HAL_OK) { + return -1; + } + } + + // Save for future use + obj->period = period_us; +#if !defined(PWMOUT_INVERTED_NOT_SUPPORTED) + if (obj->inverted) { + HAL_TIMEx_PWMN_Start(&TimHandle, channel); + } else +#endif + { + HAL_TIM_PWM_Start(&TimHandle, channel); + } + + return 0; +} + +// setting pwm to hardware pin - instead analogWrite() +void _pwm_write(pwmout_t *obj, float value){ + TIM_HandleTypeDef TimHandle; + int channel = 0; + + TimHandle.Instance = (TIM_TypeDef *)(obj->pwm); + + if (value < (float)0.0) { + value = 0.0; + } else if (value > (float)1.0) { + value = 1.0; + } + + obj->pulse = (uint32_t)((float)obj->period * value + 0.5); + + switch (obj->channel) { + case 1: + channel = TIM_CHANNEL_1; + break; + case 2: + channel = TIM_CHANNEL_2; + break; + case 3: + channel = TIM_CHANNEL_3; + break; + case 4: + channel = TIM_CHANNEL_4; + break; + default: + return; + } + + // If channel already enabled, only update compare value to avoid glitch + __HAL_TIM_SET_COMPARE(&TimHandle, channel, obj->pulse / obj->prescaler); +} + +// init low side pin +// HardwareTimer* _initPinPWMLow(uint32_t PWM_freq, int ulPin) +// { +// PinName pin = digitalPinToPinName(ulPin); +// TIM_TypeDef *Instance = (TIM_TypeDef *)pinmap_peripheral(pin, PinMap_PWM); +// uint32_t index = get_timer_index(Instance); + +// if (HardwareTimer_Handle[index] == NULL) { +// HardwareTimer_Handle[index]->__this = new HardwareTimer((TIM_TypeDef *)pinmap_peripheral(pin, PinMap_PWM)); +// HardwareTimer_Handle[index]->handle.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED3; +// HAL_TIM_Base_Init(&(HardwareTimer_Handle[index]->handle)); +// TIM_OC_InitTypeDef sConfigOC = TIM_OC_InitTypeDef(); +// sConfigOC.OCMode = TIM_OCMODE_PWM2; +// sConfigOC.Pulse = 100; +// sConfigOC.OCPolarity = TIM_OCPOLARITY_LOW; +// sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; +// sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH; +// sConfigOC.OCIdleState = TIM_OCIDLESTATE_SET; +// sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET; +// uint32_t channel = STM_PIN_CHANNEL(pinmap_function(pin, PinMap_PWM)); +// HAL_TIM_PWM_ConfigChannel(&(HardwareTimer_Handle[index]->handle), &sConfigOC, channel); +// } +// HardwareTimer *HT = (HardwareTimer *)(HardwareTimer_Handle[index]->__this); +// uint32_t channel = STM_PIN_CHANNEL(pinmap_function(pin, PinMap_PWM)); +// HT->setMode(channel, TIMER_OUTPUT_COMPARE_PWM2, pin); +// HT->setOverflow(PWM_freq, HERTZ_FORMAT); +// HT->pause(); +// HT->refresh(); +// return HT; +// } + + +// align the timers to end the init +void _alignPWMTimers(pwmout_t *t1, pwmout_t *t2){ + TIM_HandleTypeDef TimHandle1, TimHandle2; + TimHandle1.Instance = (TIM_TypeDef *)(t1->pwm); + TimHandle2.Instance = (TIM_TypeDef *)(t2->pwm); + __HAL_TIM_DISABLE(&TimHandle1); + __HAL_TIM_DISABLE(&TimHandle2); + __HAL_TIM_ENABLE(&TimHandle1); + __HAL_TIM_ENABLE(&TimHandle2); +} + +// align the timers to end the init +void _alignPWMTimers(pwmout_t *t1, pwmout_t *t2, pwmout_t *t3){ + TIM_HandleTypeDef TimHandle1, TimHandle2, TimHandle3; + TimHandle1.Instance = (TIM_TypeDef *)(t1->pwm); + TimHandle2.Instance = (TIM_TypeDef *)(t2->pwm); + TimHandle3.Instance = (TIM_TypeDef *)(t3->pwm); + __HAL_TIM_DISABLE(&TimHandle1); + __HAL_TIM_DISABLE(&TimHandle2); + __HAL_TIM_DISABLE(&TimHandle3); + __HAL_TIM_ENABLE(&TimHandle1); + __HAL_TIM_ENABLE(&TimHandle2); + __HAL_TIM_ENABLE(&TimHandle3); +} + +// align the timers to end the init +void _alignPWMTimers(pwmout_t *t1, pwmout_t *t2, pwmout_t *t3, pwmout_t *t4){ + TIM_HandleTypeDef TimHandle1, TimHandle2, TimHandle3, TimHandle4; + TimHandle1.Instance = (TIM_TypeDef *)(t1->pwm); + TimHandle2.Instance = (TIM_TypeDef *)(t2->pwm); + TimHandle3.Instance = (TIM_TypeDef *)(t3->pwm); + TimHandle4.Instance = (TIM_TypeDef *)(t4->pwm); + __HAL_TIM_DISABLE(&TimHandle1); + __HAL_TIM_DISABLE(&TimHandle2); + __HAL_TIM_DISABLE(&TimHandle3); + __HAL_TIM_DISABLE(&TimHandle4); + __HAL_TIM_ENABLE(&TimHandle1); + __HAL_TIM_ENABLE(&TimHandle2); + __HAL_TIM_ENABLE(&TimHandle3); + __HAL_TIM_ENABLE(&TimHandle4); +} + +// // configure hardware 6pwm interface only one timer with inverted channels +// HardwareTimer* _initHardware6PWMInterface(uint32_t PWM_freq, float dead_zone, int pinA_h, int pinA_l, int pinB_h, int pinB_l, int pinC_h, int pinC_l) +// { +// PinName uhPinName = digitalPinToPinName(pinA_h); +// PinName ulPinName = digitalPinToPinName(pinA_l); +// PinName vhPinName = digitalPinToPinName(pinB_h); +// PinName vlPinName = digitalPinToPinName(pinB_l); +// PinName whPinName = digitalPinToPinName(pinC_h); +// PinName wlPinName = digitalPinToPinName(pinC_l); + +// TIM_TypeDef *Instance = (TIM_TypeDef *)pinmap_peripheral(uhPinName, PinMap_PWM); + +// uint32_t index = get_timer_index(Instance); + +// if (HardwareTimer_Handle[index] == NULL) { +// HardwareTimer_Handle[index]->__this = new HardwareTimer((TIM_TypeDef *)pinmap_peripheral(uhPinName, PinMap_PWM)); +// HardwareTimer_Handle[index]->handle.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED3; +// HAL_TIM_Base_Init(&(HardwareTimer_Handle[index]->handle)); +// ((HardwareTimer *)HardwareTimer_Handle[index]->__this)->setOverflow(PWM_freq, HERTZ_FORMAT); +// } +// HardwareTimer *HT = (HardwareTimer *)(HardwareTimer_Handle[index]->__this); + +// HT->setMode(STM_PIN_CHANNEL(pinmap_function(uhPinName, PinMap_PWM)), TIMER_OUTPUT_COMPARE_PWM1, uhPinName); +// HT->setMode(STM_PIN_CHANNEL(pinmap_function(ulPinName, PinMap_PWM)), TIMER_OUTPUT_COMPARE_PWM1, ulPinName); +// HT->setMode(STM_PIN_CHANNEL(pinmap_function(vhPinName, PinMap_PWM)), TIMER_OUTPUT_COMPARE_PWM1, vhPinName); +// HT->setMode(STM_PIN_CHANNEL(pinmap_function(vlPinName, PinMap_PWM)), TIMER_OUTPUT_COMPARE_PWM1, vlPinName); +// HT->setMode(STM_PIN_CHANNEL(pinmap_function(whPinName, PinMap_PWM)), TIMER_OUTPUT_COMPARE_PWM1, whPinName); +// HT->setMode(STM_PIN_CHANNEL(pinmap_function(wlPinName, PinMap_PWM)), TIMER_OUTPUT_COMPARE_PWM1, wlPinName); + +// // dead time is set in nanoseconds +// uint32_t dead_time_ns = (float)(1e9f/PWM_freq)*dead_zone; +// uint32_t dead_time = __LL_TIM_CALC_DEADTIME(SystemCoreClock, LL_TIM_GetClockDivision(HT->getHandle()->Instance), dead_time_ns); +// LL_TIM_OC_SetDeadTime(HT->getHandle()->Instance, dead_time); // deadtime is non linear! +// LL_TIM_CC_EnableChannel(HT->getHandle()->Instance, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N); + +// HT->pause(); +// HT->refresh(); +// HT->resume(); +// return HT; +// } + + +// // returns 0 if each pair of pwm channels has same channel +// // returns 1 all the channels belong to the same timer - hardware inverted channels +// // returns -1 if neither - avoid configuring - error!!! +// int _interfaceType(const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l){ +// PinName nameAH = digitalPinToPinName(pinA_h); +// PinName nameAL = digitalPinToPinName(pinA_l); +// PinName nameBH = digitalPinToPinName(pinB_h); +// PinName nameBL = digitalPinToPinName(pinB_l); +// PinName nameCH = digitalPinToPinName(pinC_h); +// PinName nameCL = digitalPinToPinName(pinC_l); +// int tim1 = get_timer_index((TIM_TypeDef *)pinmap_peripheral(nameAH, PinMap_PWM)); +// int tim2 = get_timer_index((TIM_TypeDef *)pinmap_peripheral(nameAL, PinMap_PWM)); +// int tim3 = get_timer_index((TIM_TypeDef *)pinmap_peripheral(nameBH, PinMap_PWM)); +// int tim4 = get_timer_index((TIM_TypeDef *)pinmap_peripheral(nameBL, PinMap_PWM)); +// int tim5 = get_timer_index((TIM_TypeDef *)pinmap_peripheral(nameCH, PinMap_PWM)); +// int tim6 = get_timer_index((TIM_TypeDef *)pinmap_peripheral(nameCL, PinMap_PWM)); +// if(tim1 == tim2 && tim2==tim3 && tim3==tim4 && tim4==tim5 && tim5==tim6) +// return _HARDWARE_6PWM; // hardware 6pwm interface - only on timer +// else if(tim1 == tim2 && tim3==tim4 && tim5==tim6) +// return _SOFTWARE_6PWM; // software 6pwm interface - each pair of high-low side same timer +// else +// return _ERROR_6PWM; // might be error avoid configuration +// } + + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure2PWM(long pwm_frequency,const int pinA, const int pinB) { + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + + PortentaDriverParams* params = new PortentaDriverParams(); + params->pwm_frequency = pwm_frequency; + + core_util_critical_section_enter(); + _pwm_init(&(params->pins[0]), pinA, (long)pwm_frequency); + _pwm_init(&(params->pins[1]), pinB, (long)pwm_frequency); + // allign the timers + _alignPWMTimers(&(params->pins[0]), &(params->pins[1])); + core_util_critical_section_exit(); + return params; +} + + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + + PortentaDriverParams* params = new PortentaDriverParams(); + params->pwm_frequency = pwm_frequency; + + core_util_critical_section_enter(); + _pwm_init(&(params->pins[0]), pinA, (long)pwm_frequency); + _pwm_init(&(params->pins[1]), pinB, (long)pwm_frequency); + _pwm_init(&(params->pins[2]), pinC, (long)pwm_frequency); + // allign the timers + _alignPWMTimers(&(params->pins[0]), &(params->pins[1]), &(params->pins[2])); + core_util_critical_section_exit(); + + return params; +} + + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC, const int pinD) { + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + + PortentaDriverParams* params = new PortentaDriverParams(); + params->pwm_frequency = pwm_frequency; + + core_util_critical_section_enter(); + _pwm_init(&(params->pins[0]), pinA, (long)pwm_frequency); + _pwm_init(&(params->pins[1]), pinB, (long)pwm_frequency); + _pwm_init(&(params->pins[2]), pinC, (long)pwm_frequency); + _pwm_init(&(params->pins[3]), pinD, (long)pwm_frequency); + // allign the timers + _alignPWMTimers(&(params->pins[0]), &(params->pins[1]), &(params->pins[2]), &(params->pins[3])); + core_util_critical_section_exit(); + + return params; +} + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +//- hardware speciffic +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + core_util_critical_section_enter(); + _pwm_write(&(((PortentaDriverParams*)params)->pins[0]), (float)dc_a); + _pwm_write(&(((PortentaDriverParams*)params)->pins[1]), (float)dc_b); + core_util_critical_section_exit(); +} + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +//- hardware speciffic +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + core_util_critical_section_enter(); + _pwm_write(&(((PortentaDriverParams*)params)->pins[0]), (float)dc_a); + _pwm_write(&(((PortentaDriverParams*)params)->pins[1]), (float)dc_b); + _pwm_write(&(((PortentaDriverParams*)params)->pins[2]), (float)dc_c); + core_util_critical_section_exit(); +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +//- hardware speciffic +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + core_util_critical_section_enter(); + _pwm_write(&(((PortentaDriverParams*)params)->pins[0]), (float)dc_1a); + _pwm_write(&(((PortentaDriverParams*)params)->pins[1]), (float)dc_1b); + _pwm_write(&(((PortentaDriverParams*)params)->pins[2]), (float)dc_2a); + _pwm_write(&(((PortentaDriverParams*)params)->pins[3]), (float)dc_2b); + core_util_critical_section_exit(); +} + + +// 6-PWM currently not supported, defer to generic, which also doesn't support it ;-) + +// Configuring PWM frequency, resolution and alignment +// - BLDC driver - 6PWM setting +// - hardware specific +//void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l){ + // if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + // else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to |%0kHz max + // // center-aligned frequency is uses two periods + // pwm_frequency *=2; + + // // find configuration + // int config = _interfaceType(pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l); + // // configure accordingly + // switch(config){ + // case _ERROR_6PWM: + // return -1; // fail + // break; + // case _HARDWARE_6PWM: + // _initHardware6PWMInterface(pwm_frequency, dead_zone, pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l); + // break; + // case _SOFTWARE_6PWM: + // HardwareTimer* HT1 = _initPinPWMHigh(pwm_frequency, pinA_h); + // _initPinPWMLow(pwm_frequency, pinA_l); + // HardwareTimer* HT2 = _initPinPWMHigh(pwm_frequency,pinB_h); + // _initPinPWMLow(pwm_frequency, pinB_l); + // HardwareTimer* HT3 = _initPinPWMHigh(pwm_frequency,pinC_h); + // _initPinPWMLow(pwm_frequency, pinC_l); + // _alignPWMTimers(HT1, HT2, HT3); + // break; + // } +// return -1; // success +// } + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - BLDC driver - 6PWM setting +// - hardware specific +//void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, void* params){ + // // find configuration + // int config = _interfaceType(pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l); + // // set pwm accordingly + // switch(config){ + // case _HARDWARE_6PWM: + // _setPwm(pinA_h, _PWM_RANGE*dc_a, _PWM_RESOLUTION); + // _setPwm(pinB_h, _PWM_RANGE*dc_b, _PWM_RESOLUTION); + // _setPwm(pinC_h, _PWM_RANGE*dc_c, _PWM_RESOLUTION); + // break; + // case _SOFTWARE_6PWM: + // _setPwm(pinA_l, _constrain(dc_a + dead_zone/2, 0, 1)*_PWM_RANGE, _PWM_RESOLUTION); + // _setPwm(pinA_h, _constrain(dc_a - dead_zone/2, 0, 1)*_PWM_RANGE, _PWM_RESOLUTION); + // _setPwm(pinB_l, _constrain(dc_b + dead_zone/2, 0, 1)*_PWM_RANGE, _PWM_RESOLUTION); + // _setPwm(pinB_h, _constrain(dc_b - dead_zone/2, 0, 1)*_PWM_RANGE, _PWM_RESOLUTION); + // _setPwm(pinC_l, _constrain(dc_c + dead_zone/2, 0, 1)*_PWM_RANGE, _PWM_RESOLUTION); + // _setPwm(pinC_h, _constrain(dc_c - dead_zone/2, 0, 1)*_PWM_RANGE, _PWM_RESOLUTION); + // break; + // } +//} +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.cpp new file mode 100644 index 0000000..f90a4c5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.cpp @@ -0,0 +1,609 @@ + +#include "./renesas.h" + +#if defined(ARDUINO_UNOR4_WIFI) || defined(ARDUINO_UNOR4_MINIMA) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for Arduino/Renesas (UNO R4)") +#pragma message("") + + + +#include "communication/SimpleFOCDebug.h" +#include "FspTimer.h" + +#define GPT_OPEN (0x00475054ULL) + +/* + We use the GPT timers, there are 2 channels (32 bit) + 6 channels (16 bit) + Each channel has 2 outputs (GTIOCAx and GTIOCBx) which can be complimentary. + + So each timer channel can handle one half-bridge, using either a single (3-PWM) or + two complimentary PWM signals (6-PWM). + + For 1-PWM through 4-PWM, we need as many channels as PWM signals, and we can use + either output A or B of the timer (we can set the polarity) - but not both. + + For 6-PWM we need 3 channels, and use both outputs A and B of each channel, then + we can do hardware dead-time. + Or we can use seperate channels for high and low side, with software dead-time. + Each phase can be either hardware (1 channel) or software (2 channels) dead-time + individually, they don't all have to be one or the other. + + Selected channels can be started together, so we can keep the phases in sync for + low-side current sensing and software 6-PWM. + + The event system should permit low side current sensing without needing interrupts, + but this will be handled by the current sense driver. + + Supported: + - arbitrary PWM frequencies between 1Hz (minimum we can set with our integer based API) + and around 48kHz (more would be possible but the range will be low) + - PWM range at 24kHz (default) is 1000 + - PWM range at 48kHz is 500 + - polarity setting is supported, in all modes + - phase state setting is supported, in 3-PWM, 6-PWM hardware dead-time and 6-PWM software dead-time + + TODOs: + - change setDutyCycle to use register access for speed + - add event system support for low-side current sensing + - perhaps add support to reserve timers used also in + Arduino Pwm.h code, for compatibility with analogWrite() + - check if there is a better way for phase-state setting + */ + + +// track which channels are used +bool channel_used[GPT_HOWMANY] = { false }; + + +struct RenesasTimerConfig { + timer_cfg_t timer_cfg; + gpt_instance_ctrl_t ctrl; + gpt_extended_cfg_t ext_cfg; + gpt_extended_pwm_cfg_t pwm_cfg; + gpt_io_pin_t duty_pin; +}; + +struct ClockDivAndRange { + timer_source_div_t clk_div; + uint32_t range; +}; + +ClockDivAndRange getClockDivAndRange(uint32_t pwm_frequency, uint8_t timer_channel) { + ClockDivAndRange result; + uint32_t max_count = (timer_channel < GTP32_HOWMANY)? 4294967295 : 65535; + uint32_t freq_hz = R_FSP_SystemClockHzGet(FSP_PRIV_CLOCK_PCLKD); + float range = (float) freq_hz / ((float) pwm_frequency * 2.0f); + if(range / 1.0 < max_count) { + result.range = (uint32_t) (range / 1.0); + result.clk_div = TIMER_SOURCE_DIV_1; + } + else if (range / 2.0 < max_count) { + result.range = (uint32_t) (range / 2.0); + result.clk_div = TIMER_SOURCE_DIV_2; + } + else if(range / 4.0 < max_count) { + result.range = (uint32_t) (range / 4.0); + result.clk_div = TIMER_SOURCE_DIV_4; + } + else if(range / 8.0 < max_count) { + result.range = (uint32_t) (range / 8.0 ); + result.clk_div = TIMER_SOURCE_DIV_8; + } + else if(range / 16.0 < max_count) { + result.range = (uint32_t) (range / 16.0 ); + result.clk_div = TIMER_SOURCE_DIV_16; + } + else if (range / 32.0 < max_count) { + result.range = (uint32_t) (range / 32.0 ); + result.clk_div = TIMER_SOURCE_DIV_32; + } + else if(range / 64.0 < max_count) { + result.range = (uint32_t) (range / 64.0 ); + result.clk_div = TIMER_SOURCE_DIV_64; + } + else if(range / 128.0 < max_count) { + result.range = (uint32_t) (range / 128.0 ); + result.clk_div = TIMER_SOURCE_DIV_128; + } + else if(range / 256.0 < max_count) { + result.range = (uint32_t) (range / 256.0 ); + result.clk_div = TIMER_SOURCE_DIV_256; + } + else if(range / 512.0 < max_count) { + result.range = (uint32_t) (range / 512.0 ); + result.clk_div = TIMER_SOURCE_DIV_512; + } + else if(range / 1024.0 < max_count) { + result.range = (uint32_t) (range / 1024.0 ); + result.clk_div = TIMER_SOURCE_DIV_1024; + } + else { + SimpleFOCDebug::println("DRV: PWM frequency too low"); + } + return result; +}; + + +bool configureTimerPin(RenesasHardwareDriverParams* params, uint8_t index, bool active_high, bool complementary = false, bool complementary_active_high = true) { + uint8_t pin = params->pins[index]; + uint8_t pin_C; + std::array pinCfgs = getPinCfgs(pin, PIN_CFG_REQ_PWM); + std::array pinCfgs_C; + if(pinCfgs[0] == 0) { + SIMPLEFOC_DEBUG("DRV: no PWM on pin ", pin); + return false; + } + if (IS_PIN_AGT_PWM(pinCfgs[0])) { + SIMPLEFOC_DEBUG("DRV: AGT timer not supported"); + return false; + } + // get the timer channel + uint8_t timer_channel = GET_CHANNEL(pinCfgs[0]); + // check its not used + if (channel_used[timer_channel]) { + SIMPLEFOC_DEBUG("DRV: channel in use"); + return false; + } + + if (complementary) { + pin_C = params->pins[index+1]; + pinCfgs_C = getPinCfgs(pin_C, PIN_CFG_REQ_PWM); + if(pinCfgs_C[0] == 0) { + SIMPLEFOC_DEBUG("DRV: no PWM on pin ", pin_C); + return false; + } + if (IS_PIN_AGT_PWM(pinCfgs_C[0]) || GET_CHANNEL(pinCfgs_C[0])!=timer_channel) { + SIMPLEFOC_DEBUG("DRV: comp. channel different"); + return false; + } + } + TimerPWMChannel_t pwm_output = IS_PWM_ON_A(pinCfgs[0]) ? CHANNEL_A : CHANNEL_B; + if (complementary) { + TimerPWMChannel_t pwm_output_C = IS_PWM_ON_A(pinCfgs_C[0]) ? CHANNEL_A : CHANNEL_B; + if (pwm_output_C != CHANNEL_A || pwm_output != CHANNEL_B) { + SIMPLEFOC_DEBUG("DRV: output A/B mismatch"); + return false; + } + } + + // configure GPIO pin + fsp_err_t err = R_IOPORT_PinCfg(&g_ioport_ctrl, g_pin_cfg[pin].pin, (uint32_t) (IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_GPT1)); + if ((err == FSP_SUCCESS) && complementary) + err = R_IOPORT_PinCfg(&g_ioport_ctrl, g_pin_cfg[pin_C].pin, (uint32_t) (IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_GPT1)); + if (err != FSP_SUCCESS) { + SIMPLEFOC_DEBUG("DRV: pin config failed"); + return false; + } + + + // configure timer channel - frequency / top value + ClockDivAndRange timings = getClockDivAndRange(params->pwm_frequency, timer_channel); + #if defined(SIMPLEFOC_RENESAS_DEBUG) + SimpleFOCDebug::println("---PWM Config---"); + SimpleFOCDebug::println("DRV: pwm pin: ", pin); + if (complementary) + SimpleFOCDebug::println("DRV: compl. pin: ", pin_C); + SimpleFOCDebug::println("DRV: pwm channel: ", timer_channel); + SimpleFOCDebug::print("DRV: pwm A/B: "); SimpleFOCDebug::println(complementary?"A+B":((pwm_output==CHANNEL_A)?"A":"B")); + SimpleFOCDebug::println("DRV: pwm freq: ", (int)params->pwm_frequency); + SimpleFOCDebug::println("DRV: pwm range: ", (int)timings.range); + SimpleFOCDebug::println("DRV: pwm clkdiv: ", timings.clk_div); + #endif + + RenesasTimerConfig* t = new RenesasTimerConfig(); + // configure timer channel - count mode + t->timer_cfg.channel = timer_channel; + t->timer_cfg.mode = TIMER_MODE_TRIANGLE_WAVE_SYMMETRIC_PWM; + t->timer_cfg.source_div = timings.clk_div; + t->timer_cfg.period_counts = timings.range; + t->timer_cfg.duty_cycle_counts = 0; + t->timer_cfg.p_callback = nullptr; + t->timer_cfg.p_context = nullptr; + t->timer_cfg.p_extend = &(t->ext_cfg); + t->timer_cfg.cycle_end_ipl = BSP_IRQ_DISABLED; + t->timer_cfg.cycle_end_irq = FSP_INVALID_VECTOR; + + t->ext_cfg.p_pwm_cfg = &(t->pwm_cfg); + t->pwm_cfg.trough_ipl = BSP_IRQ_DISABLED; + t->pwm_cfg.trough_irq = FSP_INVALID_VECTOR; + t->pwm_cfg.poeg_link = GPT_POEG_LINK_POEG0; + t->pwm_cfg.output_disable = GPT_OUTPUT_DISABLE_NONE; + t->pwm_cfg.adc_trigger = GPT_ADC_TRIGGER_NONE; + t->pwm_cfg.dead_time_count_up = 0; + t->pwm_cfg.dead_time_count_down = 0; + t->pwm_cfg.adc_a_compare_match = 0; + t->pwm_cfg.adc_b_compare_match = 0; + t->pwm_cfg.interrupt_skip_source = GPT_INTERRUPT_SKIP_SOURCE_NONE; + t->pwm_cfg.interrupt_skip_count = GPT_INTERRUPT_SKIP_COUNT_0; + t->pwm_cfg.interrupt_skip_adc = GPT_INTERRUPT_SKIP_ADC_NONE; + t->pwm_cfg.gtioca_disable_setting = GPT_GTIOC_DISABLE_PROHIBITED; + t->pwm_cfg.gtiocb_disable_setting = GPT_GTIOC_DISABLE_PROHIBITED; + // configure dead-time if both outputs are used + if (complementary) { + uint32_t dt = params->dead_zone * timings.range; + t->pwm_cfg.dead_time_count_up = dt; + t->pwm_cfg.dead_time_count_down = dt; + } + + // configure timer channel - outputs and polarity + t->ext_cfg.gtior_setting.gtior = 0L; + if (!complementary) { + if(pwm_output == CHANNEL_A) { + t->duty_pin = GPT_IO_PIN_GTIOCA; + t->ext_cfg.gtioca.output_enabled = true; + t->ext_cfg.gtiocb.output_enabled = false; + t->ext_cfg.gtior_setting.gtior_b.gtioa = 0x03 | (active_high ? 0x00 : 0x10); + t->ext_cfg.gtior_setting.gtior_b.oadflt = active_high ? 0x00 : 0x01; + // t->ext_cfg.gtior_setting.gtior_b.oahld = 0x0; + // t->ext_cfg.gtior_setting.gtior_b.oadf = 0x0; + // t->ext_cfg.gtior_setting.gtior_b.nfaen = 0x0; + } + else { + t->duty_pin = GPT_IO_PIN_GTIOCB; + t->ext_cfg.gtiocb.output_enabled = true; + t->ext_cfg.gtioca.output_enabled = false; + t->ext_cfg.gtior_setting.gtior_b.gtiob = 0x03 | (active_high ? 0x00 : 0x10); + t->ext_cfg.gtior_setting.gtior_b.obdflt = active_high ? 0x00 : 0x01; + } + } + else { + t->duty_pin = GPT_IO_PIN_GTIOCA_AND_GTIOCB; + t->ext_cfg.gtioca.output_enabled = true; + t->ext_cfg.gtiocb.output_enabled = true; + t->ext_cfg.gtior_setting.gtior_b.gtioa = 0x03 | (!complementary_active_high ? 0x00 : 0x10); + t->ext_cfg.gtior_setting.gtior_b.oadflt = !complementary_active_high ? 0x00 : 0x01; + t->ext_cfg.gtior_setting.gtior_b.gtiob = 0x03 | (active_high ? 0x00 : 0x10); + t->ext_cfg.gtior_setting.gtior_b.obdflt = active_high ? 0x00 : 0x01; + } + + // lets stop the timer in case its running + if (GPT_OPEN == t->ctrl.open) { + if (R_GPT_Stop(&(t->ctrl)) != FSP_SUCCESS) { + SIMPLEFOC_DEBUG("DRV: timer stop failed"); + return false; + } + } + + memset(&(t->ctrl), 0, sizeof(gpt_instance_ctrl_t)); + err = R_GPT_Open(&(t->ctrl),&(t->timer_cfg)); + if ((err != FSP_ERR_ALREADY_OPEN) && (err != FSP_SUCCESS)) { + SIMPLEFOC_DEBUG("DRV: open failed"); + return false; + } + #if defined(SIMPLEFOC_RESENSAS_DEBUG) + if (err == FSP_ERR_ALREADY_OPEN) { + SimpleFOCDebug::println("DRV: timer already open"); + } + #endif + err = R_GPT_PeriodSet(&(t->ctrl), t->timer_cfg.period_counts); + if (err != FSP_SUCCESS) { + SIMPLEFOC_DEBUG("DRV: period set failed"); + return false; + } + err = R_GPT_OutputEnable(&(t->ctrl), t->duty_pin); + if (err != FSP_SUCCESS) { + SIMPLEFOC_DEBUG("DRV: pin enable failed"); + return false; + } + + channel_used[timer_channel] = true; + params->timer_config[index] = t; + params->channels[index] = timer_channel; + if (complementary) { + params->timer_config[index+1] = t; + params->channels[index+1] = timer_channel; + } + + return true; +} + + +// start the timer channels for the motor, synchronously +bool startTimerChannels(RenesasHardwareDriverParams* params, int num_channels) { + uint32_t mask = 0; + for (int i = 0; i < num_channels; i++) { + // RenesasTimerConfig* t = params->timer_config[i]; + // if (R_GPT_Start(&(t->ctrl)) != FSP_SUCCESS) { + // SIMPLEFOC_DEBUG("DRV: timer start failed"); + // return false; + // } + mask |= (1 << params->channels[i]); +#if defined(SIMPLEFOC_RENESAS_DEBUG) + SimpleFOCDebug::println("DRV: starting timer: ", params->channels[i]); +#endif + } + params->timer_config[0]->ctrl.p_reg->GTSTR |= mask; + #if defined(SIMPLEFOC_RENESAS_DEBUG) + SimpleFOCDebug::println("DRV: timers started"); + #endif + return true; +} + + +// check if the given pins are on the same timer channel +bool isHardware6Pwm(const int pin1, const int pin2) { + std::array pinCfgs1 = getPinCfgs(pin1, PIN_CFG_REQ_PWM); + std::array pinCfgs2 = getPinCfgs(pin2, PIN_CFG_REQ_PWM); + if(pinCfgs1[0] == 0 || pinCfgs2[0] == 0) + return false; + if (IS_PIN_AGT_PWM(pinCfgs1[0]) || IS_PIN_AGT_PWM(pinCfgs2[0])) + return false; + uint8_t timer_channel1 = GET_CHANNEL(pinCfgs1[0]); + uint8_t timer_channel2 = GET_CHANNEL(pinCfgs2[0]); + return timer_channel1==timer_channel2; +} + + + +void* _configure1PWM(long pwm_frequency, const int pinA) { + RenesasHardwareDriverParams* params = new RenesasHardwareDriverParams; + params->pins[0] = pinA; + params->pwm_frequency = (pwm_frequency==NOT_SET)?RENESAS_DEFAULT_PWM_FREQUENCY:pwm_frequency; + bool success = true; + success = configureTimerPin(params, 0, SIMPLEFOC_PWM_ACTIVE_HIGH); + if (success) + success = startTimerChannels(params, 1); + if (!success) + return SIMPLEFOC_DRIVER_INIT_FAILED; + return params; +} + + +void* _configure2PWM(long pwm_frequency,const int pinA, const int pinB) { + RenesasHardwareDriverParams* params = new RenesasHardwareDriverParams; + params->pins[0] = pinA; params->pins[1] = pinB; + params->pwm_frequency = (pwm_frequency==NOT_SET)?RENESAS_DEFAULT_PWM_FREQUENCY:pwm_frequency; + bool success = true; + success = configureTimerPin(params, 0, SIMPLEFOC_PWM_ACTIVE_HIGH); + success &= configureTimerPin(params, 1, SIMPLEFOC_PWM_ACTIVE_HIGH); + if (!success) + success &= startTimerChannels(params, 2); + if (!success) + return SIMPLEFOC_DRIVER_INIT_FAILED; + return params; +} + + +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + RenesasHardwareDriverParams* params = new RenesasHardwareDriverParams; + params->pins[0] = pinA; params->pins[1] = pinB; params->pins[2] = pinC; + params->pwm_frequency = (pwm_frequency==NOT_SET)?RENESAS_DEFAULT_PWM_FREQUENCY:pwm_frequency; + bool success = true; + success = configureTimerPin(params, 0, SIMPLEFOC_PWM_ACTIVE_HIGH); + success &= configureTimerPin(params, 1, SIMPLEFOC_PWM_ACTIVE_HIGH); + success &= configureTimerPin(params, 2, SIMPLEFOC_PWM_ACTIVE_HIGH); + if (success) + success = startTimerChannels(params, 3); + if (!success) + return SIMPLEFOC_DRIVER_INIT_FAILED; + return params; +} + + +void* _configure4PWM(long pwm_frequency, const int pin1A, const int pin1B, const int pin2A, const int pin2B) { + RenesasHardwareDriverParams* params = new RenesasHardwareDriverParams; + params->pins[0] = pin1A; params->pins[1] = pin1B; params->pins[2] = pin2A; params->pins[3] = pin2B; + params->pwm_frequency = (pwm_frequency==NOT_SET)?RENESAS_DEFAULT_PWM_FREQUENCY:pwm_frequency; + bool success = true; + success = configureTimerPin(params, 0, SIMPLEFOC_PWM_ACTIVE_HIGH); + success &= configureTimerPin(params, 1, SIMPLEFOC_PWM_ACTIVE_HIGH); + success &= configureTimerPin(params, 2, SIMPLEFOC_PWM_ACTIVE_HIGH); + success &= configureTimerPin(params, 3, SIMPLEFOC_PWM_ACTIVE_HIGH); + if (success) + success = startTimerChannels(params, 4); + if (!success) + return SIMPLEFOC_DRIVER_INIT_FAILED; + return params; +} + + +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l){ + RenesasHardwareDriverParams* params = new RenesasHardwareDriverParams; + params->pins[0] = pinA_h; params->pins[1] = pinA_l; params->pins[2] = pinB_h; params->pins[3] = pinB_l; params->pins[4] = pinC_h; params->pins[5] = pinC_l; + params->pwm_frequency = (pwm_frequency==NOT_SET)?RENESAS_DEFAULT_PWM_FREQUENCY:pwm_frequency; + params->dead_zone = (dead_zone==NOT_SET)?RENESAS_DEFAULT_DEAD_ZONE:dead_zone; + + bool success = true; + if (isHardware6Pwm(pinA_h, pinA_l)) + success &= configureTimerPin(params, 0, SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH, true, SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH); + else { + success &= configureTimerPin(params, 0, SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH); + success &= configureTimerPin(params, 1, !SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH); // reverse polarity on low side gives desired active high/low behaviour + } + + if (isHardware6Pwm(pinB_h, pinB_l)) + success &= configureTimerPin(params, 2, SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH, true, SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH); + else { + success &= configureTimerPin(params, 2, SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH); + success &= configureTimerPin(params, 3, !SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH); + } + + if (isHardware6Pwm(pinC_h, pinC_l)) + success &= configureTimerPin(params, 4, SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH, true, SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH); + else { + success &= configureTimerPin(params, 4, SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH); + success &= configureTimerPin(params, 5, !SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH); + } + + if (success) + success = startTimerChannels(params, 6); + if (!success) + return SIMPLEFOC_DRIVER_INIT_FAILED; + return params; +} + + + + +void _writeDutyCycle1PWM(float dc_a, void* params){ + RenesasTimerConfig* t = ((RenesasHardwareDriverParams*)params)->timer_config[0]; + uint32_t duty_cycle_counts = (uint32_t)(dc_a * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } +} + + +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + RenesasTimerConfig* t = ((RenesasHardwareDriverParams*)params)->timer_config[0]; + uint32_t duty_cycle_counts = (uint32_t)(dc_a * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } + t = ((RenesasHardwareDriverParams*)params)->timer_config[1]; + duty_cycle_counts = (uint32_t)(dc_b * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } +} + + +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + RenesasTimerConfig* t = ((RenesasHardwareDriverParams*)params)->timer_config[0]; + uint32_t duty_cycle_counts = (uint32_t)(dc_a * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } + t = ((RenesasHardwareDriverParams*)params)->timer_config[1]; + duty_cycle_counts = (uint32_t)(dc_b * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } + t = ((RenesasHardwareDriverParams*)params)->timer_config[2]; + duty_cycle_counts = (uint32_t)(dc_c * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } +} + + +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + RenesasTimerConfig* t = ((RenesasHardwareDriverParams*)params)->timer_config[0]; + uint32_t duty_cycle_counts = (uint32_t)(dc_1a * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } + t = ((RenesasHardwareDriverParams*)params)->timer_config[1]; + duty_cycle_counts = (uint32_t)(dc_1b * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } + t = ((RenesasHardwareDriverParams*)params)->timer_config[2]; + duty_cycle_counts = (uint32_t)(dc_2a * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } + t = ((RenesasHardwareDriverParams*)params)->timer_config[3]; + duty_cycle_counts = (uint32_t)(dc_2b * (float)(t->timer_cfg.period_counts)); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } +} + + + +void _setSinglePhaseState(RenesasTimerConfig* hi, RenesasTimerConfig* lo, PhaseState state) { + gpt_gtior_setting_t gtior; + gtior.gtior = hi->ctrl.p_reg->GTIOR; + bool on = (state==PHASE_ON) || (state==PHASE_HI); + + if (hi->duty_pin == GPT_IO_PIN_GTIOCA_AND_GTIOCB) { + bool ch = false; + if (gtior.gtior_b.obe != on) { + gtior.gtior_b.obe = on; + ch = true; + } // B is high side + on = (state==PHASE_ON) || (state==PHASE_LO); + if (gtior.gtior_b.oae != on) { + gtior.gtior_b.oae = on; + ch = true; + } + if (ch) + hi->ctrl.p_reg->GTIOR = gtior.gtior; + return; + } + + if (hi->duty_pin == GPT_IO_PIN_GTIOCA) { + if (gtior.gtior_b.oae != on) { + gtior.gtior_b.oae = on; + hi->ctrl.p_reg->GTIOR = gtior.gtior; + } + } + else if (hi->duty_pin == GPT_IO_PIN_GTIOCB) { + if (gtior.gtior_b.obe != on) { + gtior.gtior_b.obe = on; + hi->ctrl.p_reg->GTIOR = gtior.gtior; + } + } + + gtior.gtior = lo->ctrl.p_reg->GTIOR; + on = (state==PHASE_ON) || (state==PHASE_LO); + if (lo->duty_pin == GPT_IO_PIN_GTIOCA) { + if (gtior.gtior_b.oae != on) { + gtior.gtior_b.oae = on; + lo->ctrl.p_reg->GTIOR = gtior.gtior; + } + } + else if (lo->duty_pin == GPT_IO_PIN_GTIOCB) { + if (gtior.gtior_b.obe != on) { + gtior.gtior_b.obe = on; + lo->ctrl.p_reg->GTIOR = gtior.gtior; + } + } + +} + + +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + RenesasTimerConfig* t = ((RenesasHardwareDriverParams*)params)->timer_config[0]; + RenesasTimerConfig* t1 = ((RenesasHardwareDriverParams*)params)->timer_config[1]; + uint32_t dt = (uint32_t)(((RenesasHardwareDriverParams*)params)->dead_zone * (float)(t->timer_cfg.period_counts)); + uint32_t duty_cycle_counts = (uint32_t)(dc_a * (float)(t->timer_cfg.period_counts)); + bool hw_deadtime = ((RenesasHardwareDriverParams*)params)->channels[0] == ((RenesasHardwareDriverParams*)params)->channels[1]; + uint32_t dt_act = (duty_cycle_counts>0 && !hw_deadtime)?dt:0; + _setSinglePhaseState(t, t1, phase_state[0]); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts - dt_act, t->duty_pin) != FSP_SUCCESS) { + // error + } + if (!hw_deadtime) { + if (R_GPT_DutyCycleSet(&(t1->ctrl), duty_cycle_counts + dt_act, t1->duty_pin) != FSP_SUCCESS) { + // error + } + } + + t = ((RenesasHardwareDriverParams*)params)->timer_config[2]; + t1 = ((RenesasHardwareDriverParams*)params)->timer_config[3]; + duty_cycle_counts = (uint32_t)(dc_b * (float)(t->timer_cfg.period_counts)); + hw_deadtime = ((RenesasHardwareDriverParams*)params)->channels[2] == ((RenesasHardwareDriverParams*)params)->channels[3]; + dt_act = (duty_cycle_counts>0 && !hw_deadtime)?dt:0; + _setSinglePhaseState(t, t1, phase_state[1]); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts - dt_act, t->duty_pin) != FSP_SUCCESS) { + // error + } + if (!hw_deadtime) { + if (R_GPT_DutyCycleSet(&(t1->ctrl), duty_cycle_counts + dt_act, t1->duty_pin) != FSP_SUCCESS) { + // error + } + } + + t = ((RenesasHardwareDriverParams*)params)->timer_config[4]; + t1 = ((RenesasHardwareDriverParams*)params)->timer_config[5]; + duty_cycle_counts = (uint32_t)(dc_c * (float)(t->timer_cfg.period_counts)); + hw_deadtime = ((RenesasHardwareDriverParams*)params)->channels[4] == ((RenesasHardwareDriverParams*)params)->channels[5]; + dt_act = (duty_cycle_counts>0 && !hw_deadtime)?dt:0; + _setSinglePhaseState(t, t1, phase_state[2]); + if (R_GPT_DutyCycleSet(&(t->ctrl), duty_cycle_counts, t->duty_pin) != FSP_SUCCESS) { + // error + } + if (!hw_deadtime) { + if (R_GPT_DutyCycleSet(&(t1->ctrl), duty_cycle_counts + dt_act, t1->duty_pin) != FSP_SUCCESS) { + // error + } + } + +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.h new file mode 100644 index 0000000..91bacdc --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/renesas/renesas.h @@ -0,0 +1,28 @@ +#pragma once + + +#include "../../hardware_api.h" + + +#if defined(ARDUINO_UNOR4_WIFI) || defined(ARDUINO_UNOR4_MINIMA) + +// uncomment to enable debug output from Renesas driver +// can set this as build-flag in Arduino IDE or PlatformIO +#define SIMPLEFOC_RENESAS_DEBUG + +#define RENESAS_DEFAULT_PWM_FREQUENCY 24000 +#define RENESAS_DEFAULT_DEAD_ZONE 0.05f + +struct RenesasTimerConfig; + +typedef struct RenesasHardwareDriverParams { + uint8_t pins[6]; + uint8_t channels[6]; + RenesasTimerConfig* timer_config[6]; + long pwm_frequency; + float dead_zone; +} RenesasHardwareDriverParams; + + + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.cpp new file mode 100644 index 0000000..eee5797 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.cpp @@ -0,0 +1,237 @@ + +/** + * Support for the RP2040 MCU, as found on the Raspberry Pi Pico. + */ +#if defined(TARGET_RP2040) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for RP2040") +#pragma message("") + + +#define SIMPLEFOC_DEBUG_RP2040 + +#include "../../hardware_api.h" +#include "./rp2040_mcu.h" +#include "hardware/pwm.h" +#include "hardware/clocks.h" + +#define _PWM_FREQUENCY 24000 +#define _PWM_FREQUENCY_MAX 66000 +#define _PWM_FREQUENCY_MIN 1 + + + +// until I can figure out if this can be quickly read from some register, keep it here. +// it also serves as a marker for what slices are already used. +uint16_t wrapvalues[NUM_PWM_SLICES]; + + +// TODO add checks which channels are already used... + +void setupPWM(int pin, long pwm_frequency, bool invert, RP2040DriverParams* params, uint8_t index) { + gpio_set_function(pin, GPIO_FUNC_PWM); + uint slice = pwm_gpio_to_slice_num(pin); + uint chan = pwm_gpio_to_channel(pin); + params->pins[index] = pin; + params->slice[index] = slice; + params->chan[index] = chan; + uint32_t sysclock_hz = frequency_count_khz(CLOCKS_FC0_SRC_VALUE_CLK_SYS) * 1000; + uint32_t factor = 4096 * 2 * pwm_frequency; + uint32_t div = sysclock_hz / factor; + if (sysclock_hz % factor !=0) div+=1; + if (div < 16) div = 16; + uint32_t wrapvalue = (sysclock_hz * 8) / div / pwm_frequency - 1; +#ifdef SIMPLEFOC_DEBUG_RP2040 + SimpleFOCDebug::print("Configuring pin "); + SimpleFOCDebug::print(pin); + SimpleFOCDebug::print(" slice "); + SimpleFOCDebug::print((int)slice); + SimpleFOCDebug::print(" channel "); + SimpleFOCDebug::print((int)chan); + SimpleFOCDebug::print(" frequency "); + SimpleFOCDebug::print((int)pwm_frequency); + SimpleFOCDebug::print(" divisor "); + SimpleFOCDebug::print((int)(div>>4)); + SimpleFOCDebug::print("."); + SimpleFOCDebug::print((int)(div&0xF)); + SimpleFOCDebug::print(" top value "); + SimpleFOCDebug::println((int)wrapvalue); +#endif + if (wrapvalue < 999) + SimpleFOCDebug::println("Warning: PWM resolution is low."); + pwm_set_clkdiv_int_frac(slice, div>>4, div&0xF); + pwm_set_phase_correct(slice, true); + pwm_set_wrap(slice, wrapvalue); + wrapvalues[slice] = wrapvalue; + if (invert) { + if (chan==0) + hw_write_masked(&pwm_hw->slice[slice].csr, 0x1 << PWM_CH0_CSR_A_INV_LSB, PWM_CH0_CSR_A_INV_BITS); + else + hw_write_masked(&pwm_hw->slice[slice].csr, 0x1 << PWM_CH0_CSR_B_INV_LSB, PWM_CH0_CSR_B_INV_BITS); + } + pwm_set_chan_level(slice, chan, 0); // switch off initially +} + + +void syncSlices() { + for (uint i=0;ipwm_frequency = pwm_frequency; + setupPWM(pinA, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 0); + syncSlices(); + return params; +} + + + +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { + RP2040DriverParams* params = new RP2040DriverParams(); + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); + params->pwm_frequency = pwm_frequency; + setupPWM(pinA, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 0); + setupPWM(pinB, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 1); + syncSlices(); + return params; +} + + + +void* _configure3PWM(long pwm_frequency, const int pinA, const int pinB, const int pinC) { + RP2040DriverParams* params = new RP2040DriverParams(); + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); + params->pwm_frequency = pwm_frequency; + setupPWM(pinA, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 0); + setupPWM(pinB, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 1); + setupPWM(pinC, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 2); + syncSlices(); + return params; +} + + + + +void* _configure4PWM(long pwm_frequency, const int pin1A, const int pin1B, const int pin2A, const int pin2B) { + RP2040DriverParams* params = new RP2040DriverParams(); + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); + params->pwm_frequency = pwm_frequency; + setupPWM(pin1A, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 0); + setupPWM(pin1B, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 1); + setupPWM(pin2A, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 2); + setupPWM(pin2B, pwm_frequency, !SIMPLEFOC_PWM_ACTIVE_HIGH, params, 3); + syncSlices(); + return params; +} + + +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + // non-PIO solution... + RP2040DriverParams* params = new RP2040DriverParams(); + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; + else pwm_frequency = _constrain(pwm_frequency, _PWM_FREQUENCY_MIN, _PWM_FREQUENCY_MAX); + params->pwm_frequency = pwm_frequency; + params->dead_zone = dead_zone; + setupPWM(pinA_h, pwm_frequency, !SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH, params, 0); + setupPWM(pinB_h, pwm_frequency, !SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH, params, 2); + setupPWM(pinC_h, pwm_frequency, !SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH, params, 4); + setupPWM(pinA_l, pwm_frequency, SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH, params, 1); + setupPWM(pinB_l, pwm_frequency, SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH, params, 3); + setupPWM(pinC_l, pwm_frequency, SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH, params, 5); + syncSlices(); + return params; +} + + + + + +void writeDutyCycle(float val, uint slice, uint chan) { + pwm_set_chan_level(slice, chan, (wrapvalues[slice]+1) * val); +} + + + + +void _writeDutyCycle1PWM(float dc_a, void* params) { + writeDutyCycle(dc_a, ((RP2040DriverParams*)params)->slice[0], ((RP2040DriverParams*)params)->chan[0]); +} + + + + +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params) { + writeDutyCycle(dc_a, ((RP2040DriverParams*)params)->slice[0], ((RP2040DriverParams*)params)->chan[0]); + writeDutyCycle(dc_b, ((RP2040DriverParams*)params)->slice[1], ((RP2040DriverParams*)params)->chan[1]); +} + + + +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params) { + writeDutyCycle(dc_a, ((RP2040DriverParams*)params)->slice[0], ((RP2040DriverParams*)params)->chan[0]); + writeDutyCycle(dc_b, ((RP2040DriverParams*)params)->slice[1], ((RP2040DriverParams*)params)->chan[1]); + writeDutyCycle(dc_c, ((RP2040DriverParams*)params)->slice[2], ((RP2040DriverParams*)params)->chan[2]); +} + + + +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params) { + writeDutyCycle(dc_1a, ((RP2040DriverParams*)params)->slice[0], ((RP2040DriverParams*)params)->chan[0]); + writeDutyCycle(dc_1b, ((RP2040DriverParams*)params)->slice[1], ((RP2040DriverParams*)params)->chan[1]); + writeDutyCycle(dc_2a, ((RP2040DriverParams*)params)->slice[2], ((RP2040DriverParams*)params)->chan[2]); + writeDutyCycle(dc_2b, ((RP2040DriverParams*)params)->slice[3], ((RP2040DriverParams*)params)->chan[3]); +} + +inline float swDti(float val, float dt) { + float ret = dt+val; + if (ret>1.0) ret = 1.0f; + return ret; +} + +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params) { + if (phase_state[0]==PhaseState::PHASE_ON || phase_state[0]==PhaseState::PHASE_HI) + writeDutyCycle(dc_a, ((RP2040DriverParams*)params)->slice[0], ((RP2040DriverParams*)params)->chan[0]); + else + writeDutyCycle(0.0f, ((RP2040DriverParams*)params)->slice[0], ((RP2040DriverParams*)params)->chan[0]); + if (phase_state[0]==PhaseState::PHASE_ON || phase_state[0]==PhaseState::PHASE_LO) + writeDutyCycle(swDti(dc_a, ((RP2040DriverParams*)params)->dead_zone), ((RP2040DriverParams*)params)->slice[1], ((RP2040DriverParams*)params)->chan[1]); + else + writeDutyCycle(0.0f, ((RP2040DriverParams*)params)->slice[1], ((RP2040DriverParams*)params)->chan[1]); + + if (phase_state[1]==PhaseState::PHASE_ON || phase_state[1]==PhaseState::PHASE_HI) + writeDutyCycle(dc_b, ((RP2040DriverParams*)params)->slice[2], ((RP2040DriverParams*)params)->chan[2]); + else + writeDutyCycle(0.0f, ((RP2040DriverParams*)params)->slice[2], ((RP2040DriverParams*)params)->chan[2]); + if (phase_state[1]==PhaseState::PHASE_ON || phase_state[1]==PhaseState::PHASE_LO) + writeDutyCycle(swDti(dc_b, ((RP2040DriverParams*)params)->dead_zone), ((RP2040DriverParams*)params)->slice[3], ((RP2040DriverParams*)params)->chan[3]); + else + writeDutyCycle(0.0f, ((RP2040DriverParams*)params)->slice[3], ((RP2040DriverParams*)params)->chan[3]); + + if (phase_state[2]==PhaseState::PHASE_ON || phase_state[2]==PhaseState::PHASE_HI) + writeDutyCycle(dc_c, ((RP2040DriverParams*)params)->slice[4], ((RP2040DriverParams*)params)->chan[4]); + else + writeDutyCycle(0.0f, ((RP2040DriverParams*)params)->slice[4], ((RP2040DriverParams*)params)->chan[4]); + if (phase_state[2]==PhaseState::PHASE_ON || phase_state[2]==PhaseState::PHASE_LO) + writeDutyCycle(swDti(dc_c, ((RP2040DriverParams*)params)->dead_zone), ((RP2040DriverParams*)params)->slice[5], ((RP2040DriverParams*)params)->chan[5]); + else + writeDutyCycle(0.0f, ((RP2040DriverParams*)params)->slice[5], ((RP2040DriverParams*)params)->chan[5]); + + _UNUSED(phase_state); +} + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.h new file mode 100644 index 0000000..bbfb387 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/rp2040/rp2040_mcu.h @@ -0,0 +1,22 @@ + + +#pragma once + +#include "Arduino.h" + +#if defined(TARGET_RP2040) + + + +typedef struct RP2040DriverParams { + int pins[6]; + uint slice[6]; + uint chan[6]; + long pwm_frequency; + float dead_zone; +} RP2040DriverParams; + + + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd21_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd21_mcu.cpp new file mode 100644 index 0000000..d59a309 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd21_mcu.cpp @@ -0,0 +1,353 @@ + + + +#include "./samd_mcu.h" + + +#ifdef _SAMD21_ + + +#pragma message("") +#pragma message("SimpleFOC: compiling for SAMD21") +#pragma message("") + + +#ifndef TCC3_CH0 +#define TCC3_CH0 NOT_ON_TIMER +#endif +#ifndef TCC3_CH1 +#define TCC3_CH1 NOT_ON_TIMER +#endif +#ifndef TCC3_CH2 +#define TCC3_CH2 NOT_ON_TIMER +#endif +#ifndef TCC3_CH3 +#define TCC3_CH3 NOT_ON_TIMER +#endif +#ifndef TCC3_CH4 +#define TCC3_CH4 NOT_ON_TIMER +#endif +#ifndef TCC3_CH5 +#define TCC3_CH5 NOT_ON_TIMER +#endif +#ifndef TCC3_CH6 +#define TCC3_CH6 NOT_ON_TIMER +#endif +#ifndef TCC3_CH7 +#define TCC3_CH7 NOT_ON_TIMER +#endif +#ifndef TC6_CH0 +#define TC6_CH0 NOT_ON_TIMER +#endif +#ifndef TC6_CH1 +#define TC6_CH1 NOT_ON_TIMER +#endif +#ifndef TC7_CH0 +#define TC7_CH0 NOT_ON_TIMER +#endif +#ifndef TC7_CH1 +#define TC7_CH1 NOT_ON_TIMER +#endif + + + +#define NUM_WO_ASSOCIATIONS 48 + +/* + * For SAM D21 A/B/C/D Variant Devices and SAM DA1 A/B Variant Devices + * Good for SAMD2xE, SAMD2xG and SAMD2xJ devices. Other SAMD21s currently not supported in arduino anyway? + * + * Note: only the pins which have timers associated are listed in this table. + * You can use the values from g_APinDescription.ulPort and g_APinDescription.ulPin to find the correct row in the table. + * + * See Microchip Technology datasheet DS40001882F-page 30 + */ +struct wo_association WO_associations[] = { + + { PORTA, 0, TCC2_CH0, 0, NOT_ON_TIMER, 0}, + { PORTA, 1, TCC2_CH1, 1, NOT_ON_TIMER, 0}, + { PORTA, 2, NOT_ON_TIMER, 0, TCC3_CH0, 0}, + { PORTA, 3, NOT_ON_TIMER, 0, TCC3_CH1, 1}, + // PB04, PB05, PB06, PB07 - no timers + { PORTB, 8, TC4_CH0, 0, TCC3_CH6, 6}, + { PORTB, 9, TC4_CH1, 1, TCC3_CH7, 7}, + { PORTA, 4, TCC0_CH0, 0, TCC3_CH2, 2}, + { PORTA, 5, TCC0_CH1, 1, TCC3_CH3, 3}, + { PORTA, 6, TCC1_CH0, 0, TCC3_CH4, 4}, + { PORTA, 7, TCC1_CH1, 1, TCC3_CH5, 5}, + { PORTA, 8, TCC0_CH0, 0, TCC1_CH2, 2}, + { PORTA, 9, TCC0_CH1, 1, TCC1_CH3, 3}, + { PORTA, 10, TCC1_CH0, 0, TCC0_CH2, 2}, + { PORTA, 11, TCC1_CH1, 1, TCC0_CH3, 3}, + { PORTB, 10, TC5_CH0, 0, TCC0_CH4, 4}, + { PORTB, 11, TC5_CH1, 1, TCC0_CH5, 5}, + { PORTB, 12, TC4_CH0, 0, TCC0_CH6, 6}, + { PORTB, 13, TC4_CH1, 1, TCC0_CH7, 7}, + { PORTB, 14, TC5_CH0, 0, NOT_ON_TIMER, 0}, + { PORTB, 15, TC5_CH1, 1, NOT_ON_TIMER, 0}, + { PORTA, 12, TCC2_CH0, 0, TCC0_CH6, 6}, + { PORTA, 13, TCC2_CH1, 1, TCC0_CH7, 7}, + { PORTA, 14, TC3_CH0, 0, TCC0_CH4, 4}, + { PORTA, 15, TC3_CH1, 1, TCC0_CH5, 5}, + { PORTA, 16, TCC2_CH0, 0, TCC0_CH6, 6}, + { PORTA, 17, TCC2_CH1, 1, TCC0_CH7, 7}, + { PORTA, 18, TC3_CH0, 0, TCC0_CH2, 2}, + { PORTA, 19, TC3_CH1, 1, TCC0_CH3, 3}, + { PORTB, 16, TC6_CH0, 0, TCC0_CH4, 4}, + { PORTB, 17, TC6_CH1, 1, TCC0_CH5, 5}, + { PORTA, 20, TC7_CH0, 0, TCC0_CH6, 6}, + { PORTA, 21, TC7_CH1, 1, TCC0_CH7, 7}, + { PORTA, 22, TC4_CH0, 0, TCC0_CH4, 4}, + { PORTA, 23, TC4_CH1, 1, TCC0_CH5, 5}, + { PORTA, 24, TC5_CH0, 0, TCC1_CH2, 2}, + { PORTA, 25, TC5_CH1, 1, TCC1_CH3, 3}, + { PORTB, 22, TC7_CH0, 0, TCC3_CH0, 0}, + { PORTB, 23, TC7_CH1, 1, TCC3_CH1, 1}, + { PORTA, 27, NOT_ON_TIMER, 0, TCC3_CH6, 6}, + { PORTA, 28, NOT_ON_TIMER, 0, TCC3_CH7, 7}, + { PORTA, 30, TCC1_CH0, 0, TCC3_CH4, 4}, + { PORTA, 31, TCC1_CH1, 1, TCC3_CH5, 5}, + { PORTB, 30, TCC0_CH0, 0, TCC1_CH2, 2}, + { PORTB, 31, TCC0_CH1, 1, TCC1_CH3, 3}, + { PORTB, 0, TC7_CH0, 0, NOT_ON_TIMER, 0}, + { PORTB, 1, TC7_CH1, 1, NOT_ON_TIMER, 0}, + { PORTB, 2, TC6_CH0, 0, TCC3_CH2, 2}, + { PORTB, 3, TC6_CH1, 1, TCC3_CH3, 3} +}; +wo_association ASSOCIATION_NOT_FOUND = { NOT_A_PORT, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}; + + + +struct wo_association& getWOAssociation(EPortType port, uint32_t pin) { + for (int i=0;i>pin_position)&0x01)==0x1?PIO_TIMER_ALT:PIO_TIMER; +} + + + + + +void syncTCC(Tcc* TCCx) { + while (TCCx->SYNCBUSY.reg & TCC_SYNCBUSY_MASK); // Wait for synchronization of registers between the clock domains +} + + + +/** + * Configure Clock 4 - we want all simplefoc PWMs to use the same clock. This ensures that + * any compatible pin combination can be used without having to worry about configuring different + * clocks. + */ +void configureSAMDClock() { + + // TODO investigate using the FDPLL96M clock to get 96MHz timer clocks... this + // would enable 48KHz PWM clocks, and setting the frequency between 24Khz with resolution 2000, to 48KHz with resolution 1000 + + if (!SAMDClockConfigured) { + SAMDClockConfigured = true; // mark clock as configured + for (int i=0;iSTATUS.bit.SYNCBUSY); // Wait for synchronization + + REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC | // Set the duty cycle to 50/50 HIGH/LOW + GCLK_GENCTRL_GENEN | // Enable GCLK4 + GCLK_GENCTRL_SRC_DFLL48M | // Set the 48MHz clock source + // GCLK_GENCTRL_SRC_FDPLL | // Set the 96MHz clock source + GCLK_GENCTRL_ID(4); // Select GCLK4 + while (GCLK->STATUS.bit.SYNCBUSY); // Wait for synchronization + +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Configured clock..."); +#endif + } +} + + + + +/** + * Configure a TCC unit + * pwm_frequency is fixed at 24kHz for now. We could go slower, but going + * faster won't be possible without sacrificing resolution. + */ +void configureTCC(tccConfiguration& tccConfig, long pwm_frequency, bool negate, float hw6pwm) { + + long pwm_resolution = (24000000) / pwm_frequency; + if (pwm_resolution>SIMPLEFOC_SAMD_MAX_PWM_RESOLUTION) + pwm_resolution = SIMPLEFOC_SAMD_MAX_PWM_RESOLUTION; + if (pwm_resolution>1) { + case 0: GCLK_CLKCTRL_ID_ofthistcc = GCLK_CLKCTRL_ID(GCM_TCC0_TCC1); break; //GCLK_CLKCTRL_ID_TCC0_TCC1; + case 1: GCLK_CLKCTRL_ID_ofthistcc = GCLK_CLKCTRL_ID(GCM_TCC2_TC3); break; //GCLK_CLKCTRL_ID_TCC2_TC3; + case 2: GCLK_CLKCTRL_ID_ofthistcc = GCLK_CLKCTRL_ID(GCM_TC4_TC5); break; //GCLK_CLKCTRL_ID_TC4_TC5; + case 3: GCLK_CLKCTRL_ID_ofthistcc = GCLK_CLKCTRL_ID(GCM_TC6_TC7); break; + default: return; + } + + // Feed GCLK4 to TCC + REG_GCLK_CLKCTRL = (uint16_t) GCLK_CLKCTRL_CLKEN | // Enable GCLK4 + GCLK_CLKCTRL_GEN_GCLK4 | // Select GCLK4 + GCLK_CLKCTRL_ID_ofthistcc; // Feed GCLK4 to tcc + while (GCLK->STATUS.bit.SYNCBUSY); // Wait for synchronization + + tccConfigured[tccConfig.tcc.tccn] = true; + + if (tccConfig.tcc.tccn>=TCC_INST_NUM) { + Tc* tc = (Tc*)GetTC(tccConfig.tcc.chaninfo); + // disable + tc->COUNT8.CTRLA.bit.ENABLE = 0; + while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // unfortunately we need the 8-bit counter mode to use the PER register... + tc->COUNT8.CTRLA.reg |= TC_CTRLA_MODE_COUNT8 | TC_CTRLA_WAVEGEN_NPWM ; + while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // meaning prescaler of 8, since TC-Unit has no up/down mode, and has resolution of 250 rather than 1000... + tc->COUNT8.CTRLA.bit.PRESCALER = TC_CTRLA_PRESCALER_DIV8_Val ; + while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // period is 250, period cannot be higher than 256! + tc->COUNT8.PER.reg = SIMPLEFOC_SAMD_PWM_TC_RESOLUTION-1; + while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // initial duty cycle is 0 + tc->COUNT8.CC[tccConfig.tcc.chan].reg = 0; + while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // enable + tc->COUNT8.CTRLA.bit.ENABLE = 1; + while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Initialized TC ", tccConfig.tcc.tccn); +#endif + } + else { + Tcc* tcc = (Tcc*)GetTC(tccConfig.tcc.chaninfo); + + uint8_t invenMask = ~(1<DRVCTRL.vec.INVEN = (tcc->DRVCTRL.vec.INVEN&invenMask)|invenVal; + syncTCC(tcc); // wait for sync + + tcc->WAVE.reg |= TCC_WAVE_POL(0xF)|TCC_WAVEB_WAVEGENB_DSBOTH; // Set wave form configuration + while ( tcc->SYNCBUSY.bit.WAVE == 1 ); // wait for sync + + if (hw6pwm>0.0) { + tcc->WEXCTRL.vec.DTIEN |= (1<WEXCTRL.bit.DTLS = hw6pwm*(pwm_resolution-1); + tcc->WEXCTRL.bit.DTHS = hw6pwm*(pwm_resolution-1); + syncTCC(tcc); // wait for sync + } + + tcc->PER.reg = pwm_resolution - 1; // Set counter Top using the PER register + while ( tcc->SYNCBUSY.bit.PER == 1 ); // wait for sync + + // set all channels to 0% + uint8_t chanCount = (tccConfig.tcc.tccn==1||tccConfig.tcc.tccn==2)?2:4; + for (int i=0;iCC[i].reg = 0; // start off at 0% duty cycle + uint32_t chanbit = 0x1<<(TCC_SYNCBUSY_CC0_Pos+i); + while ( (tcc->SYNCBUSY.reg & chanbit) > 0 ); + } + + // Enable TC + tcc->CTRLA.reg |= TCC_CTRLA_ENABLE | TCC_CTRLA_PRESCALER_DIV1; //48Mhz/1=48Mhz/2(up/down)=24MHz/1024=24KHz + while ( tcc->SYNCBUSY.bit.ENABLE == 1 ); // wait for sync + +#if defined(SIMPLEFOC_SAMD_DEBUG) && !defined(SIMPLEFOC_DISABLE_DEBUG) + SimpleFOCDebug::print("SAMD: Initialized TCC "); + SimpleFOCDebug::print(tccConfig.tcc.tccn); + SimpleFOCDebug::print("-"); + SimpleFOCDebug::print(tccConfig.tcc.chan); + SimpleFOCDebug::print("["); + SimpleFOCDebug::print(tccConfig.wo); + SimpleFOCDebug::print("] pwm res "); + SimpleFOCDebug::print((int)pwm_resolution); + SimpleFOCDebug::println(); +#endif + } + } + else if (tccConfig.tcc.tccnCTRLA.bit.ENABLE = 0; + while ( tcc->SYNCBUSY.bit.ENABLE == 1 ); + + uint8_t invenMask = ~(1<DRVCTRL.vec.INVEN = (tcc->DRVCTRL.vec.INVEN&invenMask)|invenVal; + syncTCC(tcc); // wait for sync + + if (hw6pwm>0.0) { + tcc->WEXCTRL.vec.DTIEN |= (1<WEXCTRL.bit.DTLS = hw6pwm*(pwm_resolution-1); + tcc->WEXCTRL.bit.DTHS = hw6pwm*(pwm_resolution-1); + syncTCC(tcc); // wait for sync + } + + tcc->CTRLA.bit.ENABLE = 1; + while ( tcc->SYNCBUSY.bit.ENABLE == 1 ); + +#if defined(SIMPLEFOC_SAMD_DEBUG) && !defined(SIMPLEFOC_DISABLE_DEBUG) + SimpleFOCDebug::print("SAMD: (Re-)Initialized TCC "); + SimpleFOCDebug::print(tccConfig.tcc.tccn); + SimpleFOCDebug::print("-"); + SimpleFOCDebug::print(tccConfig.tcc.chan); + SimpleFOCDebug::print("["); + SimpleFOCDebug::print(tccConfig.wo); + SimpleFOCDebug::print("] pwm res "); + SimpleFOCDebug::print((int)pwm_resolution); + SimpleFOCDebug::println(); +#endif + } + + +} + + + + + +void writeSAMDDutyCycle(tccConfiguration* info, float dc) { + uint8_t tccn = GetTCNumber(info->tcc.chaninfo); + uint8_t chan = GetTCChannelNumber(info->tcc.chaninfo); + if (tccntcc.chaninfo); + // set via CC +// tcc->CC[chan].reg = (uint32_t)((SIMPLEFOC_SAMD_PWM_RESOLUTION-1) * dc); +// uint32_t chanbit = 0x1<<(TCC_SYNCBUSY_CC0_Pos+chan); +// while ( (tcc->SYNCBUSY.reg & chanbit) > 0 ); + // set via CCB + //while ( (tcc->SYNCBUSY.vec.CC & (0x1< 0 ); + tcc->CCB[chan].reg = (uint32_t)((info->pwm_res-1) * dc); +// while ( (tcc->SYNCBUSY.vec.CCB & (0x1< 0 ); +// tcc->STATUS.vec.CCBV |= (0x1<SYNCBUSY.bit.STATUS > 0 ); +// tcc->CTRLBSET.reg |= TCC_CTRLBSET_CMD(TCC_CTRLBSET_CMD_UPDATE_Val); +// while ( tcc->SYNCBUSY.bit.CTRLB > 0 ); + } + else { + Tc* tc = (Tc*)GetTC(info->tcc.chaninfo); + tc->COUNT8.CC[chan].reg = (uint8_t)((SIMPLEFOC_SAMD_PWM_TC_RESOLUTION-1) * dc); + while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + } +} + + + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd51_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd51_mcu.cpp new file mode 100644 index 0000000..71bf0b8 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd51_mcu.cpp @@ -0,0 +1,351 @@ + + +#include "./samd_mcu.h" + + +#if defined(_SAMD51_)||defined(_SAME51_) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for SAMD51/SAME51") +#pragma message("") + + + +// expected frequency on DPLL, since we don't configure it ourselves. Typically this is the CPU frequency. +// for custom boards or overclockers you can override it using this define. +#ifndef SIMPLEFOC_SAMD51_DPLL_FREQ +#define SIMPLEFOC_SAMD51_DPLL_FREQ 120000000 +#endif + + +#ifndef TCC3_CH0 +#define TCC3_CH0 NOT_ON_TIMER +#define TCC3_CH1 NOT_ON_TIMER +#endif + +#ifndef TCC4_CH0 +#define TCC4_CH0 NOT_ON_TIMER +#define TCC4_CH1 NOT_ON_TIMER +#endif + + +#ifndef TC4_CH0 +#define TC4_CH0 NOT_ON_TIMER +#define TC4_CH1 NOT_ON_TIMER +#endif + +#ifndef TC5_CH0 +#define TC5_CH0 NOT_ON_TIMER +#define TC5_CH1 NOT_ON_TIMER +#endif + +#ifndef TC6_CH0 +#define TC6_CH0 NOT_ON_TIMER +#define TC6_CH1 NOT_ON_TIMER +#endif + +#ifndef TC7_CH0 +#define TC7_CH0 NOT_ON_TIMER +#define TC7_CH1 NOT_ON_TIMER +#endif + + + +// TCC# Channels WO_NUM Counter size Fault Dithering Output matrix DTI SWAP Pattern generation +// 0 6 8 24-bit Yes Yes Yes Yes Yes Yes +// 1 4 8 24-bit Yes Yes Yes Yes Yes Yes +// 2 3 3 16-bit Yes - Yes - - - +// 3 2 2 16-bit Yes - - - - - +// 4 2 2 16-bit Yes - - - - - + + +#define NUM_WO_ASSOCIATIONS 72 + +struct wo_association WO_associations[] = { + + { PORTB, 9, TC4_CH1, 1, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, + { PORTA, 4, TC0_CH0, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, + { PORTA, 5, TC0_CH1, 1, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, + { PORTA, 6, TC1_CH0, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, + { PORTA, 7, TC1_CH1, 1, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, + { PORTC, 4, NOT_ON_TIMER, 0, TCC0_CH0, 0, NOT_ON_TIMER, 0}, + // PC05, PC06, PC07 -> no timers + { PORTA, 8, TC0_CH0, 0, TCC0_CH0, 0, TCC1_CH0, 4}, + { PORTA, 9, TC0_CH1, 1, TCC0_CH1, 1, TCC1_CH1, 5}, + { PORTA, 10, TC1_CH0, 0, TCC0_CH2, 2, TCC1_CH2, 6}, + { PORTA, 11, TC1_CH1, 1, TCC0_CH3, 3, TCC1_CH3, 7}, + { PORTB, 10, TC5_CH0, 0, TCC0_CH4, 4, TCC1_CH0, 0}, + { PORTB, 11, TC5_CH1, 1, TCC0_CH5, 5, TCC1_CH1, 1}, + { PORTB, 12, TC4_CH0, 0, TCC3_CH0, 0, TCC0_CH0, 0}, + { PORTB, 13, TC4_CH1, 1, TCC3_CH1, 1, TCC0_CH1, 1}, + { PORTB, 14, TC5_CH0, 0, TCC4_CH0, 0, TCC0_CH2, 2}, + { PORTB, 15, TC5_CH1, 1, TCC4_CH1, 1, TCC0_CH3, 3}, + { PORTD, 8, NOT_ON_TIMER, 0, TCC0_CH1, 1, NOT_ON_TIMER, 0}, + { PORTD, 9, NOT_ON_TIMER, 0, TCC0_CH2, 2, NOT_ON_TIMER, 0}, + { PORTD, 10, NOT_ON_TIMER, 0, TCC0_CH3, 3, NOT_ON_TIMER, 0}, + { PORTD, 11, NOT_ON_TIMER, 0, TCC0_CH4, 4, NOT_ON_TIMER, 0}, + { PORTD, 12, NOT_ON_TIMER, 0, TCC0_CH5, 5, NOT_ON_TIMER, 0}, + { PORTC, 10, NOT_ON_TIMER, 0, TCC0_CH0, 0, TCC1_CH0, 4}, + { PORTC, 11, NOT_ON_TIMER, 0, TCC0_CH1, 1, TCC1_CH1, 5}, + { PORTC, 12, NOT_ON_TIMER, 0, TCC0_CH2, 2, TCC1_CH2, 6}, + { PORTC, 13, NOT_ON_TIMER, 0, TCC0_CH3, 3, TCC1_CH3, 7}, + { PORTC, 14, NOT_ON_TIMER, 0, TCC0_CH4, 4, TCC1_CH0, 0}, + { PORTC, 15, NOT_ON_TIMER, 0, TCC0_CH5, 5, TCC1_CH1, 1}, + { PORTA, 12, TC2_CH0, 0, TCC0_CH0, 6, TCC1_CH2, 2}, + { PORTA, 13, TC2_CH1, 1, TCC0_CH1, 7, TCC1_CH3, 3}, + { PORTA, 14, TC3_CH0, 0, TCC2_CH0, 0, TCC1_CH2, 2}, + { PORTA, 15, TC3_CH1, 1, TCC2_CH1, 1, TCC1_CH3, 3}, + { PORTA, 16, TC2_CH0, 0, TCC1_CH0, 0, TCC0_CH4, 4}, + { PORTA, 17, TC2_CH1, 1, TCC1_CH1, 1, TCC0_CH5, 5}, + { PORTA, 18, TC3_CH0, 0, TCC1_CH2, 2, TCC0_CH0, 6}, + { PORTA, 19, TC3_CH1, 1, TCC1_CH3, 3, TCC0_CH1, 7}, + { PORTC, 16, NOT_ON_TIMER, 0, TCC0_CH0, 0, NOT_ON_TIMER, 0}, // PDEC0 + { PORTC, 17, NOT_ON_TIMER, 0, TCC0_CH1, 1, NOT_ON_TIMER, 0}, // PDEC1 + { PORTC, 18, NOT_ON_TIMER, 0, TCC0_CH2, 2, NOT_ON_TIMER, 0}, // PDEC2 + { PORTC, 19, NOT_ON_TIMER, 0, TCC0_CH3, 3, NOT_ON_TIMER, 0}, + { PORTC, 20, NOT_ON_TIMER, 0, TCC0_CH4, 4, NOT_ON_TIMER, 0}, + { PORTC, 21, NOT_ON_TIMER, 0, TCC0_CH5, 5, NOT_ON_TIMER, 0}, + { PORTC, 22, NOT_ON_TIMER, 0, TCC0_CH0, 6, NOT_ON_TIMER, 0}, + { PORTC, 23, NOT_ON_TIMER, 0, TCC0_CH1, 7, NOT_ON_TIMER, 0}, + { PORTD, 20, NOT_ON_TIMER, 0, TCC1_CH0, 0, NOT_ON_TIMER, 0}, + { PORTD, 21, NOT_ON_TIMER, 0, TCC1_CH1, 1, NOT_ON_TIMER, 0}, + { PORTB, 16, TC6_CH0, 0, TCC3_CH0, 0, TCC0_CH4, 4}, + { PORTB, 17, TC6_CH1, 1, TCC3_CH1, 1, TCC0_CH5, 5}, + { PORTB, 18, NOT_ON_TIMER, 0, TCC1_CH0, 0, NOT_ON_TIMER, 0}, // PDEC0 + { PORTB, 19, NOT_ON_TIMER, 0, TCC1_CH1, 1, NOT_ON_TIMER, 0}, // PDEC1 + { PORTB, 20, NOT_ON_TIMER, 0, TCC1_CH2, 2, NOT_ON_TIMER, 0}, // PDEC2 + { PORTB, 21, NOT_ON_TIMER, 0, TCC1_CH3, 3, NOT_ON_TIMER, 0}, + { PORTA, 20, TC7_CH0, 0, TCC1_CH0, 4, TCC0_CH0, 0}, + { PORTA, 21, TC7_CH1, 1, TCC1_CH1, 5, TCC0_CH1, 1}, + { PORTA, 22, TC4_CH0, 0, TCC1_CH2, 6, TCC0_CH2, 2}, + { PORTA, 23, TC4_CH1, 1, TCC1_CH3, 7, TCC0_CH3, 3}, + { PORTA, 24, TC5_CH0, 0, TCC2_CH2, 2, NOT_ON_TIMER, 0}, // PDEC0 + { PORTA, 25, TC5_CH1, 1, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, // PDEC1 + { PORTB, 22, TC7_CH0, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, // PDEC2 + { PORTB, 23, TC7_CH1, 1, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, // PDEC0 + { PORTB, 24, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, // PDEC1 + { PORTB, 25, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, // PDEC2 + { PORTB, 26, NOT_ON_TIMER, 0, TCC1_CH2, 2, NOT_ON_TIMER, 0}, + { PORTB, 27, NOT_ON_TIMER, 0, TCC1_CH3, 3, NOT_ON_TIMER, 0}, + { PORTB, 28, NOT_ON_TIMER, 0, TCC1_CH0, 4, NOT_ON_TIMER, 0}, + { PORTB, 29, NOT_ON_TIMER, 0, TCC1_CH1, 5, NOT_ON_TIMER, 0}, + // PC24-PC28, PA27, RESET -> no TC/TCC peripherals + { PORTA, 30, TC6_CH0, 0, TCC2_CH0, 0, NOT_ON_TIMER, 0}, + { PORTA, 31, TC6_CH1, 1, TCC2_CH1, 1, NOT_ON_TIMER, 0}, + { PORTB, 30, TC0_CH0, 0, TCC4_CH0, 0, TCC0_CH0, 6}, + { PORTB, 31, TC0_CH1, 1, TCC4_CH1, 1, TCC0_CH1, 7}, + // PC30, PC31 -> no TC/TCC peripherals + { PORTB, 0, TC7_CH0, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, + { PORTB, 1, TC7_CH1, 1, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}, + { PORTB, 2, TC6_CH0, 0, TCC2_CH2, 2, NOT_ON_TIMER, 0}, + +}; + +wo_association ASSOCIATION_NOT_FOUND = { NOT_A_PORT, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0, NOT_ON_TIMER, 0}; + +#ifndef TCC3_CC_NUM +uint8_t TCC_CHANNEL_COUNT[] = { TCC0_CC_NUM, TCC1_CC_NUM, TCC2_CC_NUM }; +#else +uint8_t TCC_CHANNEL_COUNT[] = { TCC0_CC_NUM, TCC1_CC_NUM, TCC2_CC_NUM, TCC3_CC_NUM, TCC4_CC_NUM }; +#endif + + +struct wo_association& getWOAssociation(EPortType port, uint32_t pin) { + for (int i=0;i>pin_position)&0x01)==0x1?PIO_TCC_PDEC:PIO_TIMER_ALT; +} + + + +void syncTCC(Tcc* TCCx) { + while (TCCx->SYNCBUSY.reg & TCC_SYNCBUSY_MASK); +} + + + + +void writeSAMDDutyCycle(tccConfiguration* info, float dc) { + uint8_t tccn = GetTCNumber(info->tcc.chaninfo); + uint8_t chan = GetTCChannelNumber(info->tcc.chaninfo); + if (tccntcc.chaninfo); + // set via CCBUF +// while ( (tcc->SYNCBUSY.vec.CC & (0x1< 0 ); + tcc->CCBUF[chan].reg = (uint32_t)((info->pwm_res-1) * dc); // TODO pwm frequency! + } + else { + // we don't support the TC channels on SAMD51, isn't worth it. + } +} + + +#define DPLL_CLOCK_NUM 2 // use GCLK2 +#define PWM_CLOCK_NUM 3 // use GCLK3 + + +/** + * Configure Clock 4 - we want all simplefoc PWMs to use the same clock. This ensures that + * any compatible pin combination can be used without having to worry about configuring different + * clocks. + */ +void configureSAMDClock() { + if (!SAMDClockConfigured) { + SAMDClockConfigured = true; // mark clock as configured + for (int i=0;iGENCTRL[DPLL_CLOCK_NUM].reg = GCLK_GENCTRL_GENEN | GCLK_GENCTRL_DIV(1) + // | GCLK_GENCTRL_SRC(GCLK_GENCTRL_SRC_DFLL_Val); + // while (GCLK->SYNCBUSY.vec.GENCTRL&(0x1<PCHCTRL[1].reg = GCLK_PCHCTRL_GEN(DPLL_CLOCK_NUM)|GCLK_PCHCTRL_CHEN; + // while (GCLK->SYNCBUSY.vec.GENCTRL&(0x1<Dpll[0].DPLLCTRLA.bit.ENABLE = 0; + // while (OSCCTRL->Dpll[0].DPLLSYNCBUSY.reg!=0x0); + + // OSCCTRL->Dpll[0].DPLLCTRLB.bit.REFCLK = OSCCTRL_DPLLCTRLB_REFCLK_GCLK_Val; + // while (OSCCTRL->Dpll[0].DPLLSYNCBUSY.reg!=0x0); + // OSCCTRL->Dpll[0].DPLLRATIO.reg = 3; + // while (OSCCTRL->Dpll[0].DPLLSYNCBUSY.reg!=0x0); + + // OSCCTRL->Dpll[0].DPLLCTRLA.bit.ENABLE = 1; + // while (OSCCTRL->Dpll[0].DPLLSYNCBUSY.reg!=0x0); + + GCLK->GENCTRL[PWM_CLOCK_NUM].bit.GENEN = 0; + while (GCLK->SYNCBUSY.vec.GENCTRL&(0x1<GENCTRL[PWM_CLOCK_NUM].reg = GCLK_GENCTRL_GENEN | GCLK_GENCTRL_DIV(1) | GCLK_GENCTRL_IDC + //| GCLK_GENCTRL_SRC(GCLK_GENCTRL_SRC_DFLL_Val); + | GCLK_GENCTRL_SRC(GCLK_GENCTRL_SRC_DPLL0_Val); + while (GCLK->SYNCBUSY.vec.GENCTRL&(0x1<PCHCTRL[GCLK_CLKCTRL_ID_ofthistcc].reg = GCLK_PCHCTRL_GEN(PWM_CLOCK_NUM)|GCLK_PCHCTRL_CHEN; + while (GCLK->SYNCBUSY.vec.GENCTRL&(0x1<CTRLA.bit.ENABLE = 0; //switch off tcc + while ( tcc->SYNCBUSY.bit.ENABLE == 1 ); // wait for sync + + uint8_t invenMask = ~(1<DRVCTRL.vec.INVEN = (tcc->DRVCTRL.vec.INVEN&invenMask)|invenVal; + syncTCC(tcc); // wait for sync + + // work out pwm resolution for desired frequency and constrain to max/min values + long pwm_resolution = (SIMPLEFOC_SAMD51_DPLL_FREQ/2) / pwm_frequency; + if (pwm_resolution>SIMPLEFOC_SAMD_MAX_PWM_RESOLUTION) + pwm_resolution = SIMPLEFOC_SAMD_MAX_PWM_RESOLUTION; + if (pwm_resolution0.0) { + tcc->WEXCTRL.vec.DTIEN |= (1<WEXCTRL.bit.DTLS = hw6pwm*(pwm_resolution-1); + tcc->WEXCTRL.bit.DTHS = hw6pwm*(pwm_resolution-1); + syncTCC(tcc); // wait for sync + } + + if (!tccConfigured[tccConfig.tcc.tccn]) { + tcc->WAVE.reg |= TCC_WAVE_POL(0xF)|TCC_WAVE_WAVEGEN_DSTOP; // Set wave form configuration - TODO check this... why set like this? + while ( tcc->SYNCBUSY.bit.WAVE == 1 ); // wait for sync + + tcc->PER.reg = pwm_resolution - 1; // Set counter Top using the PER register + while ( tcc->SYNCBUSY.bit.PER == 1 ); // wait for sync + + // set all channels to 0% + for (int i=0;iCC[i].reg = 0; // start off at 0% duty cycle + uint32_t chanbit = 0x1<<(TCC_SYNCBUSY_CC0_Pos+i); + while ( (tcc->SYNCBUSY.reg & chanbit) > 0 ); + } + } + + // Enable TCC + tcc->CTRLA.reg |= TCC_CTRLA_ENABLE | TCC_CTRLA_PRESCALER_DIV1; //48Mhz/1=48Mhz/2(up/down)=24MHz/1024=24KHz + while ( tcc->SYNCBUSY.bit.ENABLE == 1 ); // wait for sync + +#if defined(SIMPLEFOC_SAMD_DEBUG) && !defined(SIMPLEFOC_DISABLE_DEBUG) + SimpleFOCDebug::print("SAMD: (Re-)Initialized TCC "); + SimpleFOCDebug::print(tccConfig.tcc.tccn); + SimpleFOCDebug::print("-"); + SimpleFOCDebug::print(tccConfig.tcc.chan); + SimpleFOCDebug::print("["); + SimpleFOCDebug::print(tccConfig.wo); + SimpleFOCDebug::print("] pwm res "); + SimpleFOCDebug::print((int)pwm_resolution); + SimpleFOCDebug::println(); +#endif + } + else if (tccConfig.tcc.tccn>=TCC_INST_NUM) { + //Tc* tc = (Tc*)GetTC(tccConfig.tcc.chaninfo); + + // disable + // tc->COUNT8.CTRLA.bit.ENABLE = 0; + // while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // // unfortunately we need the 8-bit counter mode to use the PER register... + // tc->COUNT8.CTRLA.reg |= TC_CTRLA_MODE_COUNT8 | TC_CTRLA_WAVEGEN_NPWM ; + // while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // // meaning prescaler of 8, since TC-Unit has no up/down mode, and has resolution of 250 rather than 1000... + // tc->COUNT8.CTRLA.bit.PRESCALER = TC_CTRLA_PRESCALER_DIV8_Val ; + // while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // // period is 250, period cannot be higher than 256! + // tc->COUNT8.PER.reg = SIMPLEFOC_SAMD_PWM_TC_RESOLUTION-1; + // while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // // initial duty cycle is 0 + // tc->COUNT8.CC[tccConfig.tcc.chan].reg = 0; + // while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + // // enable + // tc->COUNT8.CTRLA.bit.ENABLE = 1; + // while ( tc->COUNT8.STATUS.bit.SYNCBUSY == 1 ); + + #ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Not initialized: TC ", tccConfig.tcc.tccn); + SIMPLEFOC_DEBUG("SAMD: TC units not supported on SAMD51"); + #endif + } + + // set as configured + tccConfigured[tccConfig.tcc.tccn] = true; + + +} + + + + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.cpp new file mode 100644 index 0000000..f697891 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.cpp @@ -0,0 +1,914 @@ + + + +#include "./samd_mcu.h" + +#if defined(_SAMD21_)||defined(_SAMD51_)||defined(_SAME51_) + + + +/** + * Global state + */ +tccConfiguration tccPinConfigurations[SIMPLEFOC_SAMD_MAX_TCC_PINCONFIGURATIONS]; +uint8_t numTccPinConfigurations = 0; +bool SAMDClockConfigured = false; +bool tccConfigured[TCC_INST_NUM+TC_INST_NUM]; + + + + + +/** + * Attach the TCC to the pin + */ +bool attachTCC(tccConfiguration& tccConfig) { + if (numTccPinConfigurations>=SIMPLEFOC_SAMD_MAX_TCC_PINCONFIGURATIONS) + return false; + pinMode(tccConfig.pin, OUTPUT); + + pinPeripheral(tccConfig.pin, tccConfig.peripheral); + tccPinConfigurations[numTccPinConfigurations++] = tccConfig; + return true; +} + + + + + +int getPermutationNumber(int pins) { + int num = 1; + for (int i=0;i=TCC_INST_NUM) + return false; + + if (pinAh.tcc.chan==pinBh.tcc.chan || pinAh.tcc.chan==pinBl.tcc.chan || pinAh.tcc.chan==pinCh.tcc.chan || pinAh.tcc.chan==pinCl.tcc.chan) + return false; + if (pinBh.tcc.chan==pinCh.tcc.chan || pinBh.tcc.chan==pinCl.tcc.chan) + return false; + if (pinAl.tcc.chan==pinBh.tcc.chan || pinAl.tcc.chan==pinBl.tcc.chan || pinAl.tcc.chan==pinCh.tcc.chan || pinAl.tcc.chan==pinCl.tcc.chan) + return false; + if (pinBl.tcc.chan==pinCh.tcc.chan || pinBl.tcc.chan==pinCl.tcc.chan) + return false; + + if (pinAh.tcc.chan!=pinAl.tcc.chan || pinBh.tcc.chan!=pinBl.tcc.chan || pinCh.tcc.chan!=pinCl.tcc.chan) + return false; + if (pinAh.wo==pinAl.wo || pinBh.wo==pinBl.wo || pinCh.wo!=pinCl.wo) + return false; + + return true; +} + + + + +bool checkPeripheralPermutationCompatible(tccConfiguration pins[], uint8_t num) { + for (int i=0;i=TCC_INST_NUM || pinAl.tcc.tccn>=TCC_INST_NUM || pinBh.tcc.tccn>=TCC_INST_NUM + || pinBl.tcc.tccn>=TCC_INST_NUM || pinCh.tcc.tccn>=TCC_INST_NUM || pinCl.tcc.tccn>=TCC_INST_NUM) + return false; + + // check we're not in use + if (inUse(pinAh) || inUse(pinAl) || inUse(pinBh) || inUse(pinBl) || inUse(pinCh) || inUse(pinCl)) + return false; + + // check pins are all different tccs/channels + if (pinAh.tcc.chaninfo==pinBh.tcc.chaninfo || pinAh.tcc.chaninfo==pinBl.tcc.chaninfo || pinAh.tcc.chaninfo==pinCh.tcc.chaninfo || pinAh.tcc.chaninfo==pinCl.tcc.chaninfo) + return false; + if (pinAl.tcc.chaninfo==pinBh.tcc.chaninfo || pinAl.tcc.chaninfo==pinBl.tcc.chaninfo || pinAl.tcc.chaninfo==pinCh.tcc.chaninfo || pinAl.tcc.chaninfo==pinCl.tcc.chaninfo) + return false; + if (pinBh.tcc.chaninfo==pinCh.tcc.chaninfo || pinBh.tcc.chaninfo==pinCl.tcc.chaninfo) + return false; + if (pinBl.tcc.chaninfo==pinCh.tcc.chaninfo || pinBl.tcc.chaninfo==pinCl.tcc.chaninfo) + return false; + + // check H/L pins are on same timer + if (pinAh.tcc.tccn!=pinAl.tcc.tccn || pinBh.tcc.tccn!=pinBl.tcc.tccn || pinCh.tcc.tccn!=pinCl.tcc.tccn) + return false; + + // check H/L pins aren't on both the same timer and wo + if (pinAh.wo==pinAl.wo || pinBh.wo==pinBl.wo || pinCh.wo==pinCl.wo) + return false; + + return true; +} + + + + + +int checkHardware6PWM(const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + for (int i=0;i<64;i++) { + tccConfiguration pinAh = getTCCChannelNr(pinA_h, getPeripheralOfPermutation(i, 0)); + tccConfiguration pinAl = getTCCChannelNr(pinA_l, getPeripheralOfPermutation(i, 1)); + tccConfiguration pinBh = getTCCChannelNr(pinB_h, getPeripheralOfPermutation(i, 2)); + tccConfiguration pinBl = getTCCChannelNr(pinB_l, getPeripheralOfPermutation(i, 3)); + tccConfiguration pinCh = getTCCChannelNr(pinC_h, getPeripheralOfPermutation(i, 4)); + tccConfiguration pinCl = getTCCChannelNr(pinC_l, getPeripheralOfPermutation(i, 5)); + if (checkPeripheralPermutationSameTCC6(pinAh, pinAl, pinBh, pinBl, pinCh, pinCl)) + return i; + } + return -1; +} + + + + +int checkSoftware6PWM(const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + for (int i=0;i<64;i++) { + tccConfiguration pinAh = getTCCChannelNr(pinA_h, getPeripheralOfPermutation(i, 0)); + tccConfiguration pinAl = getTCCChannelNr(pinA_l, getPeripheralOfPermutation(i, 1)); + tccConfiguration pinBh = getTCCChannelNr(pinB_h, getPeripheralOfPermutation(i, 2)); + tccConfiguration pinBl = getTCCChannelNr(pinB_l, getPeripheralOfPermutation(i, 3)); + tccConfiguration pinCh = getTCCChannelNr(pinC_h, getPeripheralOfPermutation(i, 4)); + tccConfiguration pinCl = getTCCChannelNr(pinC_l, getPeripheralOfPermutation(i, 5)); + if (checkPeripheralPermutationCompatible6(pinAh, pinAl, pinBh, pinBl, pinCh, pinCl)) + return i; + } + return -1; +} + + + +int scorePermutation(tccConfiguration pins[], uint8_t num) { + uint32_t usedtccs = 0; + for (int i=0;i>1; + } + for (int i=0;i>1; + } + return score; +} + + + + + + + + +int checkPermutations(uint8_t num, int pins[], bool (*checkFunc)(tccConfiguration[], uint8_t) ) { + tccConfiguration tccConfs[num]; + int best = -1; + int bestscore = 1000000; + for (int i=0;i<(0x1<pwm_res = tccConfs[0].pwm_res; + getTccPinConfiguration(pinB)->pwm_res = tccConfs[1].pwm_res; +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Configured TCCs..."); +#endif + + SAMDHardwareDriverParams* params = new SAMDHardwareDriverParams { + .tccPinConfigurations = { getTccPinConfiguration(pinA), getTccPinConfiguration(pinB) }, + .pwm_frequency = (uint32_t)pwm_frequency + }; // Someone with a stepper-setup who can test it? + return params; +} + + + + + + + + + + + + +/** + * Configuring PWM frequency, resolution and alignment + * - BLDC driver - 3PWM setting + * - hardware specific + * + * SAMD21 will support up to 2 BLDC motors in 3-PWM: + * one on TCC0 using 3 of the channels 0,1,2 or 3 + * one on TCC3 using 3 of the channels 0,1,2 or 3 + * i.e. 8 different pins can be used, but only 4 different signals (WO[x]) on those 8 pins + * WO[0] and WO[4] are the same + * WO[1] and WO[5] are the same + * WO[2] and WO[6] are the same + * WO[3] and WO[7] are the same + * + * If you're on the Arduino Nano33 IoT, please see the Nano33 IoT pinout diagram to see which TCC0/WO[x] + * signal is on which pin of the Nano. You can drive one motor on TCC0. For other boards, consult their documentation. + * + * Note: + * That's if we want to keep the signals strictly in sync. + * + * If we can accept out-of-sync PWMs on the different phases, we could drive up to 4 BLDCs in 3-PWM mode, + * using all the TCC channels. (TCC0 & TCC3 - 4 channels each, TCC1 & TCC2 - 2 channels each) + * + * All channels will use the same resolution, prescaler and clock, but they will have different start-times leading + * to misaligned signals. + * + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param pinA pinA bldc driver + * @param pinB pinB bldc driver + * @param pinC pinC bldc driver + */ +void* _configure3PWM(long pwm_frequency, const int pinA, const int pinB, const int pinC) { +#ifdef SIMPLEFOC_SAMD_DEBUG + printAllPinInfos(); +#endif + int pins[3] = { pinA, pinB, pinC }; + int compatibility = checkPermutations(3, pins, checkPeripheralPermutationCompatible); + if (compatibility<0) { + // no result! +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Bad pin combination!"); +#endif + return SIMPLEFOC_DRIVER_INIT_FAILED; + } + + tccConfiguration tccConfs[3] = { getTCCChannelNr(pinA, getPeripheralOfPermutation(compatibility, 0)), + getTCCChannelNr(pinB, getPeripheralOfPermutation(compatibility, 1)), + getTCCChannelNr(pinC, getPeripheralOfPermutation(compatibility, 2)) }; + + +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Found configuration: score=", scorePermutation(tccConfs, 3)); + printTCCConfiguration(tccConfs[0]); + printTCCConfiguration(tccConfs[1]); + printTCCConfiguration(tccConfs[2]); +#endif + + // attach pins to timer peripherals + attachTCC(tccConfs[0]); // in theory this can fail, but there is no way to signal it... + attachTCC(tccConfs[1]); + attachTCC(tccConfs[2]); +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Attached pins..."); +#endif + + // set up clock - Note: if we did this right it should be possible to get all TCC units synchronized? + // e.g. attach all the timers, start them, and then start the clock... but this would require API-changes in SimpleFOC... + configureSAMDClock(); + + if (pwm_frequency==NOT_SET) { + // use default frequency + pwm_frequency = SIMPLEFOC_SAMD_DEFAULT_PWM_FREQUENCY_HZ; + } + + // configure the TCC (waveform, top-value, pre-scaler = frequency) + configureTCC(tccConfs[0], pwm_frequency); + configureTCC(tccConfs[1], pwm_frequency); + configureTCC(tccConfs[2], pwm_frequency); + getTccPinConfiguration(pinA)->pwm_res = tccConfs[0].pwm_res; + getTccPinConfiguration(pinB)->pwm_res = tccConfs[1].pwm_res; + getTccPinConfiguration(pinC)->pwm_res = tccConfs[2].pwm_res; +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Configured TCCs..."); +#endif + + return new SAMDHardwareDriverParams { + .tccPinConfigurations = { getTccPinConfiguration(pinA), getTccPinConfiguration(pinB), getTccPinConfiguration(pinC) }, + .pwm_frequency = (uint32_t)pwm_frequency + }; + +} + + + + + + + + +/** + * Configuring PWM frequency, resolution and alignment + * - Stepper driver - 4PWM setting + * - hardware specific + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param pin1A pin1A stepper driver + * @param pin1B pin1B stepper driver + * @param pin2A pin2A stepper driver + * @param pin2B pin2B stepper driver + */ +void* _configure4PWM(long pwm_frequency, const int pin1A, const int pin1B, const int pin2A, const int pin2B) { +#ifdef SIMPLEFOC_SAMD_DEBUG + printAllPinInfos(); +#endif + int pins[4] = { pin1A, pin1B, pin2A, pin2B }; + int compatibility = checkPermutations(4, pins, checkPeripheralPermutationCompatible); + if (compatibility<0) { + // no result! +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Bad pin combination!"); +#endif + return SIMPLEFOC_DRIVER_INIT_FAILED; + } + + tccConfiguration tccConfs[4] = { getTCCChannelNr(pin1A, getPeripheralOfPermutation(compatibility, 0)), + getTCCChannelNr(pin1B, getPeripheralOfPermutation(compatibility, 1)), + getTCCChannelNr(pin2A, getPeripheralOfPermutation(compatibility, 2)), + getTCCChannelNr(pin2B, getPeripheralOfPermutation(compatibility, 3)) }; + + +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Found configuration: score=", scorePermutation(tccConfs, 4)); + printTCCConfiguration(tccConfs[0]); + printTCCConfiguration(tccConfs[1]); + printTCCConfiguration(tccConfs[2]); + printTCCConfiguration(tccConfs[3]); +#endif + + // attach pins to timer peripherals + attachTCC(tccConfs[0]); // in theory this can fail, but there is no way to signal it... + attachTCC(tccConfs[1]); + attachTCC(tccConfs[2]); + attachTCC(tccConfs[3]); +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Attached pins..."); +#endif + + // set up clock - Note: if we did this right it should be possible to get all TCC units synchronized? + // e.g. attach all the timers, start them, and then start the clock... but this would require API-changes in SimpleFOC... + configureSAMDClock(); + + if (pwm_frequency==NOT_SET) { + // use default frequency + pwm_frequency = SIMPLEFOC_SAMD_DEFAULT_PWM_FREQUENCY_HZ; + } + + // configure the TCC (waveform, top-value, pre-scaler = frequency) + configureTCC(tccConfs[0], pwm_frequency); + configureTCC(tccConfs[1], pwm_frequency); + configureTCC(tccConfs[2], pwm_frequency); + configureTCC(tccConfs[3], pwm_frequency); + getTccPinConfiguration(pin1A)->pwm_res = tccConfs[0].pwm_res; + getTccPinConfiguration(pin2A)->pwm_res = tccConfs[1].pwm_res; + getTccPinConfiguration(pin1B)->pwm_res = tccConfs[2].pwm_res; + getTccPinConfiguration(pin2B)->pwm_res = tccConfs[3].pwm_res; +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Configured TCCs..."); +#endif + + return new SAMDHardwareDriverParams { + .tccPinConfigurations = { getTccPinConfiguration(pin1A), getTccPinConfiguration(pin1B), getTccPinConfiguration(pin2A), getTccPinConfiguration(pin2B) }, + .pwm_frequency = (uint32_t)pwm_frequency + }; +} + + + + + + + + + +/** + * Configuring PWM frequency, resolution and alignment + * - BLDC driver - 6PWM setting + * - hardware specific + * + * SAMD21 will support up to 2 BLDC motors in 6-PWM: + * one on TCC0 using 3 of the channels 0,1,2 or 3 + * one on TCC3 using 3 of the channels 0,1,2 or 3 + * i.e. 6 out of 8 pins must be used, in the following high/low side pairs: + * WO[0] & WO[4] (high side & low side) + * WO[1] & WO[5] + * WO[2] & WO[6] + * WO[3] & WO[7] + * + * If you're on the Arduino Nano33 IoT, please see the Nano33 IoT pinout diagram to see which TCC0/WO[x] + * signal is on which pin of the Nano. You can drive 1 BLDC on TCC0. For other boards, consult their documentation. + * + * + * @param pwm_frequency - frequency in hertz - if applicable + * @param dead_zone duty cycle protection zone [0, 1] - both low and high side low - if applicable + * @param pinA_h pinA high-side bldc driver + * @param pinA_l pinA low-side bldc driver + * @param pinB_h pinA high-side bldc driver + * @param pinB_l pinA low-side bldc driver + * @param pinC_h pinA high-side bldc driver + * @param pinC_l pinA low-side bldc driver + * + * @return 0 if config good, -1 if failed + */ +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + // we want to use a TCC channel with 1 non-inverted and 1 inverted output for each phase, with dead-time insertion +#ifdef SIMPLEFOC_SAMD_DEBUG + printAllPinInfos(); +#endif + int compatibility = checkHardware6PWM(pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l); + if (compatibility<0) { + compatibility = checkSoftware6PWM(pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l); + if (compatibility<0) { + // no result! +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Bad pin combination!"); +#endif + return SIMPLEFOC_DRIVER_INIT_FAILED; + } + } + + tccConfiguration pinAh = getTCCChannelNr(pinA_h, getPeripheralOfPermutation(compatibility, 0)); + tccConfiguration pinAl = getTCCChannelNr(pinA_l, getPeripheralOfPermutation(compatibility, 1)); + tccConfiguration pinBh = getTCCChannelNr(pinB_h, getPeripheralOfPermutation(compatibility, 2)); + tccConfiguration pinBl = getTCCChannelNr(pinB_l, getPeripheralOfPermutation(compatibility, 3)); + tccConfiguration pinCh = getTCCChannelNr(pinC_h, getPeripheralOfPermutation(compatibility, 4)); + tccConfiguration pinCl = getTCCChannelNr(pinC_l, getPeripheralOfPermutation(compatibility, 5)); + +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Found configuration: "); + printTCCConfiguration(pinAh); + printTCCConfiguration(pinAl); + printTCCConfiguration(pinBh); + printTCCConfiguration(pinBl); + printTCCConfiguration(pinCh); + printTCCConfiguration(pinCl); +#endif + + // attach pins to timer peripherals + bool allAttached = true; + allAttached |= attachTCC(pinAh); // in theory this can fail, but there is no way to signal it... + allAttached |= attachTCC(pinAl); + allAttached |= attachTCC(pinBh); + allAttached |= attachTCC(pinBl); + allAttached |= attachTCC(pinCh); + allAttached |= attachTCC(pinCl); + if (!allAttached) + return SIMPLEFOC_DRIVER_INIT_FAILED; +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Attached pins..."); +#endif + // set up clock - if we did this right it should be possible to get all TCC units synchronized? + // e.g. attach all the timers, start them, and then start the clock... but this would require API changes in SimpleFOC driver API + configureSAMDClock(); + + if (pwm_frequency==NOT_SET) { + // use default frequency + pwm_frequency = SIMPLEFOC_SAMD_DEFAULT_PWM_FREQUENCY_HZ; + } + + // configure the TCC(s) + configureTCC(pinAh, pwm_frequency, false, (pinAh.tcc.chaninfo==pinAl.tcc.chaninfo)?dead_zone:-1); + if ((pinAh.tcc.chaninfo!=pinAl.tcc.chaninfo)) + configureTCC(pinAl, pwm_frequency, true, -1.0); + configureTCC(pinBh, pwm_frequency, false, (pinBh.tcc.chaninfo==pinBl.tcc.chaninfo)?dead_zone:-1); + if ((pinBh.tcc.chaninfo!=pinBl.tcc.chaninfo)) + configureTCC(pinBl, pwm_frequency, true, -1.0); + configureTCC(pinCh, pwm_frequency, false, (pinCh.tcc.chaninfo==pinCl.tcc.chaninfo)?dead_zone:-1); + if ((pinCh.tcc.chaninfo!=pinCl.tcc.chaninfo)) + configureTCC(pinCl, pwm_frequency, true, -1.0); + getTccPinConfiguration(pinA_h)->pwm_res = pinAh.pwm_res; + getTccPinConfiguration(pinA_l)->pwm_res = pinAh.pwm_res; // use the high phase resolution, in case we didn't set it + getTccPinConfiguration(pinB_h)->pwm_res = pinBh.pwm_res; + getTccPinConfiguration(pinB_l)->pwm_res = pinBh.pwm_res; + getTccPinConfiguration(pinC_h)->pwm_res = pinCh.pwm_res; + getTccPinConfiguration(pinC_l)->pwm_res = pinCh.pwm_res; +#ifdef SIMPLEFOC_SAMD_DEBUG + SIMPLEFOC_DEBUG("SAMD: Configured TCCs..."); +#endif + + return new SAMDHardwareDriverParams { + .tccPinConfigurations = { getTccPinConfiguration(pinA_h), getTccPinConfiguration(pinA_l), getTccPinConfiguration(pinB_h), getTccPinConfiguration(pinB_l), getTccPinConfiguration(pinC_h), getTccPinConfiguration(pinC_l) }, + .pwm_frequency = (uint32_t)pwm_frequency, + .dead_zone = dead_zone, + }; +} + + + + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - Stepper driver - 2PWM setting + * - hardware specific + * + * @param dc_a duty cycle phase A [0, 1] + * @param dc_b duty cycle phase B [0, 1] + * @param pinA phase A hardware pin number + * @param pinB phase B hardware pin number + */ +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params) { + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[0], dc_a); + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[1], dc_b); + return; +} + + + + + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - BLDC driver - 3PWM setting + * - hardware specific + * + * @param dc_a duty cycle phase A [0, 1] + * @param dc_b duty cycle phase B [0, 1] + * @param dc_c duty cycle phase C [0, 1] + * @param pinA phase A hardware pin number + * @param pinB phase B hardware pin number + * @param pinC phase C hardware pin number + */ +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params) { + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[0], dc_a); + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[1], dc_b); + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[2], dc_c); + return; +} + + + + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - Stepper driver - 4PWM setting + * - hardware specific + * + * @param dc_1a duty cycle phase 1A [0, 1] + * @param dc_1b duty cycle phase 1B [0, 1] + * @param dc_2a duty cycle phase 2A [0, 1] + * @param dc_2b duty cycle phase 2B [0, 1] + * @param pin1A phase 1A hardware pin number + * @param pin1B phase 1B hardware pin number + * @param pin2A phase 2A hardware pin number + * @param pin2B phase 2B hardware pin number + */ +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[0], dc_1a); + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[1], dc_1b); + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[2], dc_2a); + writeSAMDDutyCycle(((SAMDHardwareDriverParams*)params)->tccPinConfigurations[3], dc_2b); + return; +} + + + + +/** + * Function setting the duty cycle to the pwm pin (ex. analogWrite()) + * - BLDC driver - 6PWM setting + * - hardware specific + * + * Note: dead-time must be setup in advance, so parameter "dead_zone" is ignored + * the low side pins are automatically driven by the SAMD DTI module, so it is enough to set the high-side + * duty cycle. + * No sanity checks are perfomed to ensure the pinA, pinB, pinC are the same pins you used in configure method... + * so use appropriately. + * + * @param dc_a duty cycle phase A [0, 1] + * @param dc_b duty cycle phase B [0, 1] + * @param dc_c duty cycle phase C [0, 1] + * @param dead_zone duty cycle protection zone [0, 1] - both low and high side low + * @param pinA_h phase A high-side hardware pin number + * @param pinA_l phase A low-side hardware pin number + * @param pinB_h phase B high-side hardware pin number + * @param pinB_l phase B low-side hardware pin number + * @param pinC_h phase C high-side hardware pin number + * @param pinC_l phase C low-side hardware pin number + * + */ +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + SAMDHardwareDriverParams* p = (SAMDHardwareDriverParams*)params; + tccConfiguration* tcc1 = p->tccPinConfigurations[0]; + tccConfiguration* tcc2 = p->tccPinConfigurations[1]; + uint32_t pwm_res =p->tccPinConfigurations[0]->pwm_res; + if (tcc1->tcc.chaninfo!=tcc2->tcc.chaninfo) { + // low-side on a different pin of same TCC - do dead-time in software... + float ls = dc_a+(p->dead_zone * (pwm_res-1)); // TODO resolution!!! + if (ls>1.0) ls = 1.0f; // no off-time is better than too-short dead-time + writeSAMDDutyCycle(tcc1, dc_a); + writeSAMDDutyCycle(tcc2, ls); + } + else + writeSAMDDutyCycle(tcc1, dc_a); // dead-time is done is hardware, no need to set low side pin explicitly + + tcc1 = p->tccPinConfigurations[2]; + tcc2 = p->tccPinConfigurations[3]; + if (tcc1->tcc.chaninfo!=tcc2->tcc.chaninfo) { + float ls = dc_b+(p->dead_zone * (pwm_res-1)); + if (ls>1.0) ls = 1.0f; // no off-time is better than too-short dead-time + writeSAMDDutyCycle(tcc1, dc_b); + writeSAMDDutyCycle(tcc2, ls); + } + else + writeSAMDDutyCycle(tcc1, dc_b); + + tcc1 = p->tccPinConfigurations[4]; + tcc2 = p->tccPinConfigurations[5]; + if (tcc1->tcc.chaninfo!=tcc2->tcc.chaninfo) { + float ls = dc_c+(p->dead_zone * (pwm_res-1)); + if (ls>1.0) ls = 1.0f; // no off-time is better than too-short dead-time + writeSAMDDutyCycle(tcc1, dc_c); + writeSAMDDutyCycle(tcc2, ls); + } + else + writeSAMDDutyCycle(tcc1, dc_c); + return; + + _UNUSED(phase_state); +} + + + + +#ifdef SIMPLEFOC_SAMD_DEBUG + +/** + * Prints a table of pin assignments for your SAMD MCU. Very useful since the + * board pinout descriptions and variant.cpp are usually quite wrong, and this + * saves you hours of cross-referencing with the datasheet. + */ +void printAllPinInfos() { + SimpleFOCDebug::println(); + for (uint8_t pin=0;pin=TCC_INST_NUM) + SimpleFOCDebug::print(": TC Peripheral"); + else + SimpleFOCDebug::print(": TCC Peripheral"); + switch (info.peripheral) { + case PIO_TIMER: + SimpleFOCDebug::print(" E "); break; + case PIO_TIMER_ALT: + SimpleFOCDebug::print(" F "); break; +#if defined(_SAMD51_)||defined(_SAME51_) + case PIO_TCC_PDEC: + SimpleFOCDebug::print(" G "); break; +#endif + default: + SimpleFOCDebug::print(" ? "); break; + } + if (info.tcc.tccn>=0) { + SimpleFOCDebug::print(info.tcc.tccn); + SimpleFOCDebug::print("-"); + SimpleFOCDebug::print(info.tcc.chan); + SimpleFOCDebug::print("["); + SimpleFOCDebug::print(info.wo); + SimpleFOCDebug::println("]"); + } + else + SimpleFOCDebug::println(" None"); +} + + + +#endif + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.h new file mode 100644 index 0000000..74004d6 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/samd/samd_mcu.h @@ -0,0 +1,127 @@ + +#ifndef SAMD_MCU_H +#define SAMD_MCU_H + + +// uncomment to enable debug output from SAMD driver +// can set this as build-flag in Arduino IDE or PlatformIO +// #define SIMPLEFOC_SAMD_DEBUG + +#include "../../hardware_api.h" + + +#if defined(__SAME51J19A__) || defined(__ATSAME51J19A__) +#ifndef _SAME51_ +#define _SAME51_ +#endif +#endif + + +#if defined(_SAMD21_)||defined(_SAMD51_)||defined(_SAME51_) + + +#include "Arduino.h" +#include "variant.h" +#include "wiring_private.h" + + +#ifndef SIMPLEFOC_SAMD_PWM_RESOLUTION +#define SIMPLEFOC_SAMD_PWM_RESOLUTION 1000 +#endif + +#define SIMPLEFOC_SAMD_DEFAULT_PWM_FREQUENCY_HZ 24000 +// arbitrary maximum. On SAMD51 with 120MHz clock this means 2kHz minimum pwm frequency +#define SIMPLEFOC_SAMD_MAX_PWM_RESOLUTION 30000 +// lets not go too low - 400 with clock speed of 120MHz on SAMD51 means 150kHz maximum PWM frequency... +// 400 with 48MHz clock on SAMD21 means 60kHz maximum PWM frequency... +#define SIMPLEFOC_SAMD_MIN_PWM_RESOLUTION 400 +// this is the most we can support on the TC units +#define SIMPLEFOC_SAMD_PWM_TC_RESOLUTION 250 + +#ifndef SIMPLEFOC_SAMD_MAX_TCC_PINCONFIGURATIONS +#define SIMPLEFOC_SAMD_MAX_TCC_PINCONFIGURATIONS 24 +#endif + + + +struct tccConfiguration { + uint8_t pin; + EPioType peripheral; // 1=true, 0=false + uint8_t wo; + union tccChanInfo { + struct { + int8_t chan; + int8_t tccn; + }; + uint16_t chaninfo; + } tcc; + uint16_t pwm_res; +}; + + + + + + +struct wo_association { + EPortType port; + uint32_t pin; + ETCChannel tccE; + uint8_t woE; + ETCChannel tccF; + uint8_t woF; +#if defined(_SAMD51_)||defined(_SAME51_) + ETCChannel tccG; + uint8_t woG; +#endif +}; + + + +typedef struct SAMDHardwareDriverParams { + tccConfiguration* tccPinConfigurations[6]; + uint32_t pwm_frequency; + float dead_zone; +} SAMDHardwareDriverParams; + + + + +#if defined(_SAMD21_) +#define NUM_PIO_TIMER_PERIPHERALS 2 +#elif defined(_SAMD51_)||defined(_SAME51_) +#define NUM_PIO_TIMER_PERIPHERALS 3 +#endif + + + +/** + * Global state + */ +extern struct wo_association WO_associations[]; +extern uint8_t TCC_CHANNEL_COUNT[]; +extern tccConfiguration tccPinConfigurations[SIMPLEFOC_SAMD_MAX_TCC_PINCONFIGURATIONS]; +extern uint8_t numTccPinConfigurations; +extern bool SAMDClockConfigured; +extern bool tccConfigured[TCC_INST_NUM+TC_INST_NUM]; + + + +struct wo_association& getWOAssociation(EPortType port, uint32_t pin); +void writeSAMDDutyCycle(tccConfiguration* info, float dc); +void configureSAMDClock(); +void configureTCC(tccConfiguration& tccConfig, long pwm_frequency, bool negate=false, float hw6pwm=-1); +__inline__ void syncTCC(Tcc* TCCx) __attribute__((always_inline, unused)); +EPioType getPeripheralOfPermutation(int permutation, int pin_position); + +#ifdef SIMPLEFOC_SAMD_DEBUG +void printTCCConfiguration(tccConfiguration& info); +void printAllPinInfos(); +#endif + + + +#endif + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.cpp new file mode 100644 index 0000000..65dad9f --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.cpp @@ -0,0 +1,952 @@ + +#include "../../hardware_api.h" +#include "stm32_mcu.h" + +#if defined(_STM32_DEF_) + +#pragma message("") +#pragma message("SimpleFOC: compiling for STM32") +#pragma message("") + + +//#define SIMPLEFOC_STM32_DEBUG + +#ifdef SIMPLEFOC_STM32_DEBUG +void printTimerCombination(int numPins, PinMap* timers[], int score); +int getTimerNumber(int timerIndex); +#endif + + + + +#ifndef SIMPLEFOC_STM32_MAX_PINTIMERSUSED +#define SIMPLEFOC_STM32_MAX_PINTIMERSUSED 12 +#endif +int numTimerPinsUsed; +PinMap* timerPinsUsed[SIMPLEFOC_STM32_MAX_PINTIMERSUSED]; + + + + + + +// setting pwm to hardware pin - instead analogWrite() +void _setPwm(HardwareTimer *HT, uint32_t channel, uint32_t value, int resolution) +{ + // TODO - remove commented code + // PinName pin = digitalPinToPinName(ulPin); + // TIM_TypeDef *Instance = (TIM_TypeDef *)pinmap_peripheral(pin, PinMap_PWM); + // uint32_t index = get_timer_index(Instance); + // HardwareTimer *HT = (HardwareTimer *)(HardwareTimer_Handle[index]->__this); + + HT->setCaptureCompare(channel, value, (TimerCompareFormat_t)resolution); +} + + + + +int getLLChannel(PinMap* timer) { +#if defined(TIM_CCER_CC1NE) + if (STM_PIN_INVERTED(timer->function)) { + switch (STM_PIN_CHANNEL(timer->function)) { + case 1: return LL_TIM_CHANNEL_CH1N; + case 2: return LL_TIM_CHANNEL_CH2N; + case 3: return LL_TIM_CHANNEL_CH3N; +#if defined(LL_TIM_CHANNEL_CH4N) + case 4: return LL_TIM_CHANNEL_CH4N; +#endif + default: return -1; + } + } else +#endif + { + switch (STM_PIN_CHANNEL(timer->function)) { + case 1: return LL_TIM_CHANNEL_CH1; + case 2: return LL_TIM_CHANNEL_CH2; + case 3: return LL_TIM_CHANNEL_CH3; + case 4: return LL_TIM_CHANNEL_CH4; + default: return -1; + } + } + return -1; +} + + + + + +// init pin pwm +HardwareTimer* _initPinPWM(uint32_t PWM_freq, PinMap* timer) { + // sanity check + if (timer==NP) + return NP; + uint32_t index = get_timer_index((TIM_TypeDef*)timer->peripheral); + bool init = false; + if (HardwareTimer_Handle[index] == NULL) { + HardwareTimer_Handle[index]->__this = new HardwareTimer((TIM_TypeDef*)timer->peripheral); + HardwareTimer_Handle[index]->handle.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED3; + HardwareTimer_Handle[index]->handle.Init.RepetitionCounter = 1; + HAL_TIM_Base_Init(&(HardwareTimer_Handle[index]->handle)); + init = true; + } + HardwareTimer *HT = (HardwareTimer *)(HardwareTimer_Handle[index]->__this); + uint32_t channel = STM_PIN_CHANNEL(timer->function); + HT->pause(); + if (init) + HT->setOverflow(PWM_freq, HERTZ_FORMAT); + HT->setMode(channel, TIMER_OUTPUT_COMPARE_PWM1, timer->pin); + #if SIMPLEFOC_PWM_ACTIVE_HIGH==false + LL_TIM_OC_SetPolarity(HT->getHandle()->Instance, getLLChannel(timer), LL_TIM_OCPOLARITY_LOW); + #endif +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-DRV: Configuring high timer ", (int)getTimerNumber(get_timer_index(HardwareTimer_Handle[index]->handle.Instance))); + SIMPLEFOC_DEBUG("STM32-DRV: Configuring high channel ", (int)channel); +#endif + return HT; +} + + + + + + + +// init high side pin +HardwareTimer* _initPinPWMHigh(uint32_t PWM_freq, PinMap* timer) { + HardwareTimer* HT = _initPinPWM(PWM_freq, timer); + #if SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH==false && SIMPLEFOC_PWM_ACTIVE_HIGH==true + LL_TIM_OC_SetPolarity(HT->getHandle()->Instance, getLLChannel(timer), LL_TIM_OCPOLARITY_LOW); + #endif + return HT; +} + +// init low side pin +HardwareTimer* _initPinPWMLow(uint32_t PWM_freq, PinMap* timer) +{ + uint32_t index = get_timer_index((TIM_TypeDef*)timer->peripheral); + + bool init = false; + if (HardwareTimer_Handle[index] == NULL) { + HardwareTimer_Handle[index]->__this = new HardwareTimer((TIM_TypeDef*)timer->peripheral); + HardwareTimer_Handle[index]->handle.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED3; + HardwareTimer_Handle[index]->handle.Init.RepetitionCounter = 1; + HAL_TIM_Base_Init(&(HardwareTimer_Handle[index]->handle)); + init = true; + } + HardwareTimer *HT = (HardwareTimer *)(HardwareTimer_Handle[index]->__this); + uint32_t channel = STM_PIN_CHANNEL(timer->function); + +#ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-DRV: Configuring low timer ", (int)getTimerNumber(get_timer_index(HardwareTimer_Handle[index]->handle.Instance))); + SIMPLEFOC_DEBUG("STM32-DRV: Configuring low channel ", (int)channel); +#endif + + HT->pause(); + if (init) + HT->setOverflow(PWM_freq, HERTZ_FORMAT); + // sets internal fields of HT, but we can't set polarity here + HT->setMode(channel, TIMER_OUTPUT_COMPARE_PWM2, timer->pin); + #if SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH==false + LL_TIM_OC_SetPolarity(HT->getHandle()->Instance, getLLChannel(timer), LL_TIM_OCPOLARITY_LOW); + #endif + return HT; +} + + + +// align the timers to end the init +void _alignPWMTimers(HardwareTimer *HT1, HardwareTimer *HT2, HardwareTimer *HT3) +{ + HT1->pause(); + HT1->refresh(); + HT2->pause(); + HT2->refresh(); + HT3->pause(); + HT3->refresh(); + HT1->resume(); + HT2->resume(); + HT3->resume(); +} + + + + +// align the timers to end the init +void _alignPWMTimers(HardwareTimer *HT1, HardwareTimer *HT2, HardwareTimer *HT3, HardwareTimer *HT4) +{ + HT1->pause(); + HT1->refresh(); + HT2->pause(); + HT2->refresh(); + HT3->pause(); + HT3->refresh(); + HT4->pause(); + HT4->refresh(); + HT1->resume(); + HT2->resume(); + HT3->resume(); + HT4->resume(); +} + + +// align the timers to end the init +void _stopTimers(HardwareTimer **timers_to_stop, int timer_num) +{ + // TODO - stop each timer only once + // stop timers + for (int i=0; i < timer_num; i++) { + if(timers_to_stop[i] == NP) return; + timers_to_stop[i]->pause(); + timers_to_stop[i]->refresh(); + #ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-DRV: Stopping timer ", getTimerNumber(get_timer_index(timers_to_stop[i]->getHandle()->Instance))); + #endif + } +} + +// align the timers to end the init +void _startTimers(HardwareTimer **timers_to_start, int timer_num) +{ + // TODO - sart each timer only once + // sart timers + for (int i=0; i < timer_num; i++) { + if(timers_to_start[i] == NP) return; + timers_to_start[i]->resume(); + #ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-DRV: Starting timer ", getTimerNumber(get_timer_index(timers_to_start[i]->getHandle()->Instance))); + #endif + } +} + +void _alignTimersNew() { + int numTimers = 0; + HardwareTimer *timers[numTimerPinsUsed]; + + // reset timer counters + for (int i=0; iperipheral); + HardwareTimer *timer = (HardwareTimer *)(HardwareTimer_Handle[index]->__this); + bool found = false; + for (int j=0; jpause(); + timers[i]->refresh(); + #ifdef SIMPLEFOC_STM32_DEBUG + SIMPLEFOC_DEBUG("STM32-DRV: Restarting timer ", getTimerNumber(get_timer_index(timers[i]->getHandle()->Instance))); + #endif + } + + for (int i=0; iresume(); + } + +} + + + + + +// configure hardware 6pwm for a complementary pair of channels +STM32DriverParams* _initHardware6PWMPair(long PWM_freq, float dead_zone, PinMap* pinH, PinMap* pinL, STM32DriverParams* params, int paramsPos) { + // sanity check + if (pinH==NP || pinL==NP) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + +#if defined(STM32L0xx) // L0 boards dont have hardware 6pwm interface + return SIMPLEFOC_DRIVER_INIT_FAILED; // return nothing +#endif + + uint32_t channel1 = STM_PIN_CHANNEL(pinH->function); + uint32_t channel2 = STM_PIN_CHANNEL(pinL->function); + + // more sanity check + if (channel1!=channel2 || pinH->peripheral!=pinL->peripheral) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + + uint32_t index = get_timer_index((TIM_TypeDef*)pinH->peripheral); + + if (HardwareTimer_Handle[index] == NULL) { + HardwareTimer_Handle[index]->__this = new HardwareTimer((TIM_TypeDef*)pinH->peripheral); + HardwareTimer_Handle[index]->handle.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED3; + HardwareTimer_Handle[index]->handle.Init.RepetitionCounter = 1; + // HardwareTimer_Handle[index]->handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE; + HAL_TIM_Base_Init(&(HardwareTimer_Handle[index]->handle)); + ((HardwareTimer *)HardwareTimer_Handle[index]->__this)->setOverflow((uint32_t)PWM_freq, HERTZ_FORMAT); + } + HardwareTimer *HT = (HardwareTimer *)(HardwareTimer_Handle[index]->__this); + + HT->setMode(channel1, TIMER_OUTPUT_COMPARE_PWM1, pinH->pin); + HT->setMode(channel2, TIMER_OUTPUT_COMPARE_PWM1, pinL->pin); + + // dead time is set in nanoseconds + uint32_t dead_time_ns = (float)(1e9f/PWM_freq)*dead_zone; + uint32_t dead_time = __LL_TIM_CALC_DEADTIME(SystemCoreClock, LL_TIM_GetClockDivision(HT->getHandle()->Instance), dead_time_ns); + if (dead_time>255) dead_time = 255; + if (dead_time==0 && dead_zone>0) { + dead_time = 255; // LL_TIM_CALC_DEADTIME returns 0 if dead_time_ns is too large + SIMPLEFOC_DEBUG("STM32-DRV: WARN: dead time too large, setting to max"); + } + LL_TIM_OC_SetDeadTime(HT->getHandle()->Instance, dead_time); // deadtime is non linear! + #if SIMPLEFOC_PWM_HIGHSIDE_ACTIVE_HIGH==false + LL_TIM_OC_SetPolarity(HT->getHandle()->Instance, getLLChannel(pinH), LL_TIM_OCPOLARITY_LOW); + #endif + #if SIMPLEFOC_PWM_LOWSIDE_ACTIVE_HIGH==false + LL_TIM_OC_SetPolarity(HT->getHandle()->Instance, getLLChannel(pinL), LL_TIM_OCPOLARITY_LOW); + #endif + LL_TIM_CC_EnableChannel(HT->getHandle()->Instance, getLLChannel(pinH) | getLLChannel(pinL)); + HT->pause(); + + // make sure timer output goes to LOW when timer channels are temporarily disabled + LL_TIM_SetOffStates(HT->getHandle()->Instance, LL_TIM_OSSI_DISABLE, LL_TIM_OSSR_ENABLE); + + params->timers[paramsPos] = HT; + params->timers[paramsPos+1] = HT; + params->channels[paramsPos] = channel1; + params->channels[paramsPos+1] = channel2; + return params; +} + + + + +STM32DriverParams* _initHardware6PWMInterface(long PWM_freq, float dead_zone, PinMap* pinA_h, PinMap* pinA_l, PinMap* pinB_h, PinMap* pinB_l, PinMap* pinC_h, PinMap* pinC_l) { + STM32DriverParams* params = new STM32DriverParams { + .timers = { NP, NP, NP, NP, NP, NP }, + .channels = { 0, 0, 0, 0, 0, 0 }, + .pwm_frequency = PWM_freq, + .dead_zone = dead_zone, + .interface_type = _HARDWARE_6PWM + }; + + if (_initHardware6PWMPair(PWM_freq, dead_zone, pinA_h, pinA_l, params, 0) == SIMPLEFOC_DRIVER_INIT_FAILED) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + if(_initHardware6PWMPair(PWM_freq, dead_zone, pinB_h, pinB_l, params, 2) == SIMPLEFOC_DRIVER_INIT_FAILED) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + if (_initHardware6PWMPair(PWM_freq, dead_zone, pinC_h, pinC_l, params, 4) == SIMPLEFOC_DRIVER_INIT_FAILED) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + + return params; +} + + + + + + +/* + timer combination scoring function + assigns a score, and also checks the combination is valid + returns <0 if combination is invalid, >=0 if combination is valid. lower (but positive) score is better + for 6 pwm, hardware 6-pwm is preferred over software 6-pwm + hardware 6-pwm is possible if each low channel is the inverted counterpart of its high channel + inverted channels are not allowed except when using hardware 6-pwm (in theory they could be but lets not complicate things) +*/ +int scoreCombination(int numPins, PinMap* pinTimers[]) { + // check already used - TODO move this to outer loop also... + for (int i=0; iperipheral == timerPinsUsed[i]->peripheral + && STM_PIN_CHANNEL(pinTimers[i]->function) == STM_PIN_CHANNEL(timerPinsUsed[i]->function)) + return -2; // bad combination - timer channel already used + } + + // TODO LPTIM and HRTIM should be ignored for now + + // check for inverted channels + if (numPins < 6) { + for (int i=0; ifunction)) + return -3; // bad combination - inverted channel used in non-hardware 6pwm + } + } + // check for duplicated channels + for (int i=0; iperipheral == pinTimers[j]->peripheral + && STM_PIN_CHANNEL(pinTimers[i]->function) == STM_PIN_CHANNEL(pinTimers[j]->function) + && STM_PIN_INVERTED(pinTimers[i]->function) == STM_PIN_INVERTED(pinTimers[j]->function)) + return -4; // bad combination - duplicated channel + } + } + int score = 0; + for (int i=0; iperipheral == pinTimers[j]->peripheral) + found = true; + } + if (!found) score++; + } + if (numPins==6) { + // check for inverted channels - best: 1 timer, 3 channels, 3 matching inverted channels + // >1 timer, 3 channels, 3 matching inverted channels + // 1 timer, 6 channels (no inverted channels) + // >1 timer, 6 channels (no inverted channels) + // check for inverted high-side channels - TODO is this a configuration we should allow? what if all 3 high side channels are inverted and the low-side non-inverted? + if (STM_PIN_INVERTED(pinTimers[0]->function) || STM_PIN_INVERTED(pinTimers[2]->function) || STM_PIN_INVERTED(pinTimers[4]->function)) + return -5; // bad combination - inverted channel used on high-side channel + if (pinTimers[0]->peripheral == pinTimers[1]->peripheral + && pinTimers[2]->peripheral == pinTimers[3]->peripheral + && pinTimers[4]->peripheral == pinTimers[5]->peripheral + && STM_PIN_CHANNEL(pinTimers[0]->function) == STM_PIN_CHANNEL(pinTimers[1]->function) + && STM_PIN_CHANNEL(pinTimers[2]->function) == STM_PIN_CHANNEL(pinTimers[3]->function) + && STM_PIN_CHANNEL(pinTimers[4]->function) == STM_PIN_CHANNEL(pinTimers[5]->function) + && STM_PIN_INVERTED(pinTimers[1]->function) && STM_PIN_INVERTED(pinTimers[3]->function) && STM_PIN_INVERTED(pinTimers[5]->function)) { + // hardware 6pwm, score <10 + + // TODO F37xxx doesn't support dead-time insertion, it has no TIM1/TIM8 + // F301, F302 --> 6 channels, but only 1-3 have dead-time insertion + // TIM2/TIM3/TIM4/TIM5 don't do dead-time insertion + // TIM15/TIM16/TIM17 do dead-time insertion only on channel 1 + + // TODO check these defines + #if defined(STM32F4xx_HAL_TIM_H) || defined(STM32F3xx_HAL_TIM_H) || defined(STM32F2xx_HAL_TIM_H) || defined(STM32F1xx_HAL_TIM_H) || defined(STM32F100_HAL_TIM_H) || defined(STM32FG0x1_HAL_TIM_H) || defined(STM32G0x0_HAL_TIM_H) + if (STM_PIN_CHANNEL(pinTimers[0]->function)>3 || STM_PIN_CHANNEL(pinTimers[2]->function)>3 || STM_PIN_CHANNEL(pinTimers[4]->function)>3 ) + return -8; // channel 4 does not have dead-time insertion + #endif + #ifdef STM32G4xx_HAL_TIM_H + if (STM_PIN_CHANNEL(pinTimers[0]->function)>4 || STM_PIN_CHANNEL(pinTimers[2]->function)>4 || STM_PIN_CHANNEL(pinTimers[4]->function)>4 ) + return -8; // channels 5 & 6 do not have dead-time insertion + #endif + } + else { + // check for inverted low-side channels + if (STM_PIN_INVERTED(pinTimers[1]->function) || STM_PIN_INVERTED(pinTimers[3]->function) || STM_PIN_INVERTED(pinTimers[5]->function)) + return -6; // bad combination - inverted channel used on low-side channel in software 6-pwm + if (pinTimers[0]->peripheral != pinTimers[1]->peripheral + || pinTimers[2]->peripheral != pinTimers[3]->peripheral + || pinTimers[4]->peripheral != pinTimers[5]->peripheral) + return -7; // bad combination - non-matching timers for H/L side in software 6-pwm + score += 10; // software 6pwm, score >10 + } + } + return score; +} + + + + +int findIndexOfFirstPinMapEntry(int pin) { + PinName pinName = digitalPinToPinName(pin); + int i = 0; + while (PinMap_TIM[i].pin!=NC) { + if (pinName == PinMap_TIM[i].pin) + return i; + i++; + } + return -1; +} + + +int findIndexOfLastPinMapEntry(int pin) { + PinName pinName = digitalPinToPinName(pin); + int i = 0; + while (PinMap_TIM[i].pin!=NC) { + if ( pinName == (PinMap_TIM[i].pin & ~ALTX_MASK) + && pinName != (PinMap_TIM[i+1].pin & ~ALTX_MASK)) + return i; + i++; + } + return -1; +} + + + + + + +#define NOT_FOUND 1000 + +int findBestTimerCombination(int numPins, int index, int pins[], PinMap* pinTimers[]) { + PinMap* searchArray[numPins]; + for (int j=0;j=0 && score= 0) { + #ifdef SIMPLEFOC_STM32_DEBUG + SimpleFOCDebug::print("STM32-DRV: best: "); + printTimerCombination(numPins, pinTimers, bestScore); + #endif + } + return bestScore; +}; + + + +void* _configure1PWM(long pwm_frequency, const int pinA) { + if (numTimerPinsUsed+1 > SIMPLEFOC_STM32_MAX_PINTIMERSUSED) { + SIMPLEFOC_DEBUG("STM32-DRV: ERR: too many pins used"); + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + } + + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + // center-aligned frequency is uses two periods + pwm_frequency *=2; + + int pins[1] = { pinA }; + PinMap* pinTimers[1] = { NP }; + if (findBestTimerCombination(1, pins, pinTimers)<0) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + + HardwareTimer* HT1 = _initPinPWM(pwm_frequency, pinTimers[0]);\ + // allign the timers + _alignTimersNew(); + + uint32_t channel1 = STM_PIN_CHANNEL(pinTimers[0]->function); + + STM32DriverParams* params = new STM32DriverParams { + .timers = { HT1 }, + .channels = { channel1 }, + .pwm_frequency = pwm_frequency + }; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[0]; + return params; +} + + + + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { + if (numTimerPinsUsed+2 > SIMPLEFOC_STM32_MAX_PINTIMERSUSED) { + SIMPLEFOC_DEBUG("STM32-DRV: ERR: too many pins used"); + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + } + + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + // center-aligned frequency is uses two periods + pwm_frequency *=2; + + int pins[2] = { pinA, pinB }; + PinMap* pinTimers[2] = { NP, NP }; + if (findBestTimerCombination(2, pins, pinTimers)<0) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + + HardwareTimer* HT1 = _initPinPWM(pwm_frequency, pinTimers[0]); + HardwareTimer* HT2 = _initPinPWM(pwm_frequency, pinTimers[1]); + // allign the timers + _alignPWMTimers(HT1, HT2, HT2); + + uint32_t channel1 = STM_PIN_CHANNEL(pinTimers[0]->function); + uint32_t channel2 = STM_PIN_CHANNEL(pinTimers[1]->function); + + STM32DriverParams* params = new STM32DriverParams { + .timers = { HT1, HT2 }, + .channels = { channel1, channel2 }, + .pwm_frequency = pwm_frequency + }; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[0]; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[1]; + return params; +} + + + + + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if (numTimerPinsUsed+3 > SIMPLEFOC_STM32_MAX_PINTIMERSUSED) { + SIMPLEFOC_DEBUG("STM32-DRV: ERR: too many pins used"); + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + } + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + // center-aligned frequency is uses two periods + pwm_frequency *=2; + + int pins[3] = { pinA, pinB, pinC }; + PinMap* pinTimers[3] = { NP, NP, NP }; + if (findBestTimerCombination(3, pins, pinTimers)<0) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + + HardwareTimer* HT1 = _initPinPWM(pwm_frequency, pinTimers[0]); + HardwareTimer* HT2 = _initPinPWM(pwm_frequency, pinTimers[1]); + HardwareTimer* HT3 = _initPinPWM(pwm_frequency, pinTimers[2]); + + uint32_t channel1 = STM_PIN_CHANNEL(pinTimers[0]->function); + uint32_t channel2 = STM_PIN_CHANNEL(pinTimers[1]->function); + uint32_t channel3 = STM_PIN_CHANNEL(pinTimers[2]->function); + + STM32DriverParams* params = new STM32DriverParams { + .timers = { HT1, HT2, HT3 }, + .channels = { channel1, channel2, channel3 }, + .pwm_frequency = pwm_frequency + }; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[0]; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[1]; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[2]; + + _alignTimersNew(); + + return params; +} + + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC, const int pinD) { + if (numTimerPinsUsed+4 > SIMPLEFOC_STM32_MAX_PINTIMERSUSED) { + SIMPLEFOC_DEBUG("STM32-DRV: ERR: too many pins used"); + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + } + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + // center-aligned frequency is uses two periods + pwm_frequency *=2; + + int pins[4] = { pinA, pinB, pinC, pinD }; + PinMap* pinTimers[4] = { NP, NP, NP, NP }; + if (findBestTimerCombination(4, pins, pinTimers)<0) + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + + HardwareTimer* HT1 = _initPinPWM(pwm_frequency, pinTimers[0]); + HardwareTimer* HT2 = _initPinPWM(pwm_frequency, pinTimers[1]); + HardwareTimer* HT3 = _initPinPWM(pwm_frequency, pinTimers[2]); + HardwareTimer* HT4 = _initPinPWM(pwm_frequency, pinTimers[3]); + // allign the timers + _alignPWMTimers(HT1, HT2, HT3, HT4); + + uint32_t channel1 = STM_PIN_CHANNEL(pinTimers[0]->function); + uint32_t channel2 = STM_PIN_CHANNEL(pinTimers[1]->function); + uint32_t channel3 = STM_PIN_CHANNEL(pinTimers[2]->function); + uint32_t channel4 = STM_PIN_CHANNEL(pinTimers[3]->function); + + STM32DriverParams* params = new STM32DriverParams { + .timers = { HT1, HT2, HT3, HT4 }, + .channels = { channel1, channel2, channel3, channel4 }, + .pwm_frequency = pwm_frequency + }; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[0]; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[1]; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[2]; + timerPinsUsed[numTimerPinsUsed++] = pinTimers[3]; + return params; +} + + + +// function setting the pwm duty cycle to the hardware +// - DC motor - 1PWM setting +// - hardware speciffic +void _writeDutyCycle1PWM(float dc_a, void* params){ + // transform duty cycle from [0,1] to [0,255] + _setPwm(((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], _PWM_RANGE*dc_a, _PWM_RESOLUTION); +} + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +//- hardware speciffic +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params){ + // transform duty cycle from [0,1] to [0,4095] + _setPwm(((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], _PWM_RANGE*dc_a, _PWM_RESOLUTION); + _setPwm(((STM32DriverParams*)params)->timers[1], ((STM32DriverParams*)params)->channels[1], _PWM_RANGE*dc_b, _PWM_RESOLUTION); +} + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +//- hardware speciffic +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // transform duty cycle from [0,1] to [0,4095] + _setPwm(((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], _PWM_RANGE*dc_a, _PWM_RESOLUTION); + _setPwm(((STM32DriverParams*)params)->timers[1], ((STM32DriverParams*)params)->channels[1], _PWM_RANGE*dc_b, _PWM_RESOLUTION); + _setPwm(((STM32DriverParams*)params)->timers[2], ((STM32DriverParams*)params)->channels[2], _PWM_RANGE*dc_c, _PWM_RESOLUTION); +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +//- hardware speciffic +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + // transform duty cycle from [0,1] to [0,4095] + _setPwm(((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], _PWM_RANGE*dc_1a, _PWM_RESOLUTION); + _setPwm(((STM32DriverParams*)params)->timers[1], ((STM32DriverParams*)params)->channels[1], _PWM_RANGE*dc_1b, _PWM_RESOLUTION); + _setPwm(((STM32DriverParams*)params)->timers[2], ((STM32DriverParams*)params)->channels[2], _PWM_RANGE*dc_2a, _PWM_RESOLUTION); + _setPwm(((STM32DriverParams*)params)->timers[3], ((STM32DriverParams*)params)->channels[3], _PWM_RANGE*dc_2b, _PWM_RESOLUTION); +} + + + + +// Configuring PWM frequency, resolution and alignment +// - BLDC driver - 6PWM setting +// - hardware specific +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l){ + if (numTimerPinsUsed+6 > SIMPLEFOC_STM32_MAX_PINTIMERSUSED) { + SIMPLEFOC_DEBUG("STM32-DRV: ERR: too many pins used"); + return (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + } + if( !pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to |%0kHz max + // center-aligned frequency is uses two periods + pwm_frequency *=2; + + // find configuration + int pins[6] = { pinA_h, pinA_l, pinB_h, pinB_l, pinC_h, pinC_l }; + PinMap* pinTimers[6] = { NP, NP, NP, NP, NP, NP }; + int score = findBestTimerCombination(6, pins, pinTimers); + + STM32DriverParams* params; + // configure accordingly + if (score<0) + params = (STM32DriverParams*)SIMPLEFOC_DRIVER_INIT_FAILED; + else if (score<10) // hardware pwm + params = _initHardware6PWMInterface(pwm_frequency, dead_zone, pinTimers[0], pinTimers[1], pinTimers[2], pinTimers[3], pinTimers[4], pinTimers[5]); + else { // software pwm + HardwareTimer* HT1 = _initPinPWMHigh(pwm_frequency, pinTimers[0]); + HardwareTimer* HT2 = _initPinPWMLow(pwm_frequency, pinTimers[1]); + HardwareTimer* HT3 = _initPinPWMHigh(pwm_frequency, pinTimers[2]); + HardwareTimer* HT4 = _initPinPWMLow(pwm_frequency, pinTimers[3]); + HardwareTimer* HT5 = _initPinPWMHigh(pwm_frequency, pinTimers[4]); + HardwareTimer* HT6 = _initPinPWMLow(pwm_frequency, pinTimers[5]); + uint32_t channel1 = STM_PIN_CHANNEL(pinTimers[0]->function); + uint32_t channel2 = STM_PIN_CHANNEL(pinTimers[1]->function); + uint32_t channel3 = STM_PIN_CHANNEL(pinTimers[2]->function); + uint32_t channel4 = STM_PIN_CHANNEL(pinTimers[3]->function); + uint32_t channel5 = STM_PIN_CHANNEL(pinTimers[4]->function); + uint32_t channel6 = STM_PIN_CHANNEL(pinTimers[5]->function); + params = new STM32DriverParams { + .timers = { HT1, HT2, HT3, HT4, HT5, HT6 }, + .channels = { channel1, channel2, channel3, channel4, channel5, channel6 }, + .pwm_frequency = pwm_frequency, + .dead_zone = dead_zone, + .interface_type = _SOFTWARE_6PWM + }; + } + if (score>=0) { + for (int i=0; i<6; i++) + timerPinsUsed[numTimerPinsUsed++] = pinTimers[i]; + _alignTimersNew(); + } + return params; // success +} + + + +void _setSinglePhaseState(PhaseState state, HardwareTimer *HT, int channel1,int channel2) { + _UNUSED(channel2); + switch (state) { + case PhaseState::PHASE_OFF: + // Due to a weird quirk in the arduino timer API, pauseChannel only disables the complementary channel (e.g. CC1NE). + // To actually make the phase floating, we must also set pwm to 0. + HT->pauseChannel(channel1); + break; + default: + HT->resumeChannel(channel1); + break; + } +} + + +// Function setting the duty cycle to the pwm pin (ex. analogWrite()) +// - BLDC driver - 6PWM setting +// - hardware specific +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState* phase_state, void* params){ + switch(((STM32DriverParams*)params)->interface_type){ + case _HARDWARE_6PWM: + // phase a + _setSinglePhaseState(phase_state[0], ((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], ((STM32DriverParams*)params)->channels[1]); + if(phase_state[0] == PhaseState::PHASE_OFF) dc_a = 0.0f; + _setPwm(((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], _PWM_RANGE*dc_a, _PWM_RESOLUTION); + // phase b + _setSinglePhaseState(phase_state[1], ((STM32DriverParams*)params)->timers[2], ((STM32DriverParams*)params)->channels[2], ((STM32DriverParams*)params)->channels[3]); + if(phase_state[1] == PhaseState::PHASE_OFF) dc_b = 0.0f; + _setPwm(((STM32DriverParams*)params)->timers[2], ((STM32DriverParams*)params)->channels[2], _PWM_RANGE*dc_b, _PWM_RESOLUTION); + // phase c + _setSinglePhaseState(phase_state[2], ((STM32DriverParams*)params)->timers[4], ((STM32DriverParams*)params)->channels[4], ((STM32DriverParams*)params)->channels[5]); + if(phase_state[2] == PhaseState::PHASE_OFF) dc_c = 0.0f; + _setPwm(((STM32DriverParams*)params)->timers[4], ((STM32DriverParams*)params)->channels[4], _PWM_RANGE*dc_c, _PWM_RESOLUTION); + break; + case _SOFTWARE_6PWM: + float dead_zone = ((STM32DriverParams*)params)->dead_zone / 2.0f; + if (phase_state[0] == PhaseState::PHASE_ON || phase_state[0] == PhaseState::PHASE_HI) + _setPwm(((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], _constrain(dc_a - dead_zone, 0.0f, 1.0f)*_PWM_RANGE, _PWM_RESOLUTION); + else + _setPwm(((STM32DriverParams*)params)->timers[0], ((STM32DriverParams*)params)->channels[0], 0.0f, _PWM_RESOLUTION); + if (phase_state[0] == PhaseState::PHASE_ON || phase_state[0] == PhaseState::PHASE_LO) + _setPwm(((STM32DriverParams*)params)->timers[1], ((STM32DriverParams*)params)->channels[1], _constrain(dc_a + dead_zone, 0.0f, 1.0f)*_PWM_RANGE, _PWM_RESOLUTION); + else + _setPwm(((STM32DriverParams*)params)->timers[1], ((STM32DriverParams*)params)->channels[1], 0.0f, _PWM_RESOLUTION); + + if (phase_state[1] == PhaseState::PHASE_ON || phase_state[1] == PhaseState::PHASE_HI) + _setPwm(((STM32DriverParams*)params)->timers[2], ((STM32DriverParams*)params)->channels[2], _constrain(dc_b - dead_zone, 0.0f, 1.0f)*_PWM_RANGE, _PWM_RESOLUTION); + else + _setPwm(((STM32DriverParams*)params)->timers[2], ((STM32DriverParams*)params)->channels[2], 0.0f, _PWM_RESOLUTION); + if (phase_state[1] == PhaseState::PHASE_ON || phase_state[1] == PhaseState::PHASE_LO) + _setPwm(((STM32DriverParams*)params)->timers[3], ((STM32DriverParams*)params)->channels[3], _constrain(dc_b + dead_zone, 0.0f, 1.0f)*_PWM_RANGE, _PWM_RESOLUTION); + else + _setPwm(((STM32DriverParams*)params)->timers[3], ((STM32DriverParams*)params)->channels[3], 0.0f, _PWM_RESOLUTION); + + if (phase_state[2] == PhaseState::PHASE_ON || phase_state[2] == PhaseState::PHASE_HI) + _setPwm(((STM32DriverParams*)params)->timers[4], ((STM32DriverParams*)params)->channels[4], _constrain(dc_c - dead_zone, 0.0f, 1.0f)*_PWM_RANGE, _PWM_RESOLUTION); + else + _setPwm(((STM32DriverParams*)params)->timers[4], ((STM32DriverParams*)params)->channels[4], 0.0f, _PWM_RESOLUTION); + if (phase_state[2] == PhaseState::PHASE_ON || phase_state[2] == PhaseState::PHASE_LO) + _setPwm(((STM32DriverParams*)params)->timers[5], ((STM32DriverParams*)params)->channels[5], _constrain(dc_c + dead_zone, 0.0f, 1.0f)*_PWM_RANGE, _PWM_RESOLUTION); + else + _setPwm(((STM32DriverParams*)params)->timers[5], ((STM32DriverParams*)params)->channels[5], 0.0f, _PWM_RESOLUTION); + break; + } + _UNUSED(phase_state); +} + + + +#ifdef SIMPLEFOC_STM32_DEBUG + +int getTimerNumber(int timerIndex) { + #if defined(TIM1_BASE) + if (timerIndex==TIMER1_INDEX) return 1; + #endif + #if defined(TIM2_BASE) + if (timerIndex==TIMER2_INDEX) return 2; + #endif + #if defined(TIM3_BASE) + if (timerIndex==TIMER3_INDEX) return 3; + #endif + #if defined(TIM4_BASE) + if (timerIndex==TIMER4_INDEX) return 4; + #endif + #if defined(TIM5_BASE) + if (timerIndex==TIMER5_INDEX) return 5; + #endif + #if defined(TIM6_BASE) + if (timerIndex==TIMER6_INDEX) return 6; + #endif + #if defined(TIM7_BASE) + if (timerIndex==TIMER7_INDEX) return 7; + #endif + #if defined(TIM8_BASE) + if (timerIndex==TIMER8_INDEX) return 8; + #endif + #if defined(TIM9_BASE) + if (timerIndex==TIMER9_INDEX) return 9; + #endif + #if defined(TIM10_BASE) + if (timerIndex==TIMER10_INDEX) return 10; + #endif + #if defined(TIM11_BASE) + if (timerIndex==TIMER11_INDEX) return 11; + #endif + #if defined(TIM12_BASE) + if (timerIndex==TIMER12_INDEX) return 12; + #endif + #if defined(TIM13_BASE) + if (timerIndex==TIMER13_INDEX) return 13; + #endif + #if defined(TIM14_BASE) + if (timerIndex==TIMER14_INDEX) return 14; + #endif + #if defined(TIM15_BASE) + if (timerIndex==TIMER15_INDEX) return 15; + #endif + #if defined(TIM16_BASE) + if (timerIndex==TIMER16_INDEX) return 16; + #endif + #if defined(TIM17_BASE) + if (timerIndex==TIMER17_INDEX) return 17; + #endif + #if defined(TIM18_BASE) + if (timerIndex==TIMER18_INDEX) return 18; + #endif + #if defined(TIM19_BASE) + if (timerIndex==TIMER19_INDEX) return 19; + #endif + #if defined(TIM20_BASE) + if (timerIndex==TIMER20_INDEX) return 20; + #endif + #if defined(TIM21_BASE) + if (timerIndex==TIMER21_INDEX) return 21; + #endif + #if defined(TIM22_BASE) + if (timerIndex==TIMER22_INDEX) return 22; + #endif + return -1; +} + + +void printTimerCombination(int numPins, PinMap* timers[], int score) { + for (int i=0; iperipheral))); + SimpleFOCDebug::print("-CH"); + SimpleFOCDebug::print(STM_PIN_CHANNEL(timers[i]->function)); + if (STM_PIN_INVERTED(timers[i]->function)) + SimpleFOCDebug::print("N"); + } + SimpleFOCDebug::print(" "); + } + SimpleFOCDebug::println("score: ", score); +} + +#endif + + + + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.h new file mode 100644 index 0000000..fa6280e --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/stm32/stm32_mcu.h @@ -0,0 +1,32 @@ +#ifndef STM32_DRIVER_MCU_DEF +#define STM32_DRIVER_MCU_DEF +#include "../../hardware_api.h" + +#if defined(_STM32_DEF_) + +// default pwm parameters +#define _PWM_RESOLUTION 12 // 12bit +#define _PWM_RANGE 4095.0f // 2^12 -1 = 4095 +#define _PWM_FREQUENCY 25000 // 25khz +#define _PWM_FREQUENCY_MAX 50000 // 50khz + +// 6pwm parameters +#define _HARDWARE_6PWM 1 +#define _SOFTWARE_6PWM 0 +#define _ERROR_6PWM -1 + + +typedef struct STM32DriverParams { + HardwareTimer* timers[6] = {NULL}; + uint32_t channels[6]; + long pwm_frequency; + float dead_zone; + uint8_t interface_type; +} STM32DriverParams; + +// timer synchornisation functions +void _stopTimers(HardwareTimer **timers_to_stop, int timer_num=6); +void _startTimers(HardwareTimer **timers_to_start, int timer_num=6); + +#endif +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy3_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy3_mcu.cpp new file mode 100644 index 0000000..3a7b5de --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy3_mcu.cpp @@ -0,0 +1,228 @@ +#include "teensy_mcu.h" + +// if defined +// - Teensy 3.0 MK20DX128 +// - Teensy 3.1/3.2 MK20DX256 +// - Teensy 3.5 MK20DX128 +// - Teensy LC MKL26Z64 +// - Teensy 3.5 MK64FX512 +// - Teensy 3.6 MK66FX1M0 +#if defined(__arm__) && defined(CORE_TEENSY) && (defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for Teensy 3.x") +#pragma message("") + +// pin definition from https://github.com/PaulStoffregen/cores/blob/286511f3ec849a6c9e0ec8b73ad6a2fada52e44c/teensy3/pins_teensy.c +#if defined(__MK20DX128__) +#define FTM0_CH0_PIN 22 +#define FTM0_CH1_PIN 23 +#define FTM0_CH2_PIN 9 +#define FTM0_CH3_PIN 10 +#define FTM0_CH4_PIN 6 +#define FTM0_CH5_PIN 20 +#define FTM0_CH6_PIN 21 +#define FTM0_CH7_PIN 5 +#define FTM1_CH0_PIN 3 +#define FTM1_CH1_PIN 4 +#elif defined(__MK20DX256__) +#define FTM0_CH0_PIN 22 +#define FTM0_CH1_PIN 23 +#define FTM0_CH2_PIN 9 +#define FTM0_CH3_PIN 10 +#define FTM0_CH4_PIN 6 +#define FTM0_CH5_PIN 20 +#define FTM0_CH6_PIN 21 +#define FTM0_CH7_PIN 5 +#define FTM1_CH0_PIN 3 +#define FTM1_CH1_PIN 4 +#define FTM2_CH0_PIN 32 +#define FTM2_CH1_PIN 25 +#elif defined(__MKL26Z64__) +#define FTM0_CH0_PIN 22 +#define FTM0_CH1_PIN 23 +#define FTM0_CH2_PIN 9 +#define FTM0_CH3_PIN 10 +#define FTM0_CH4_PIN 6 +#define FTM0_CH5_PIN 20 +#define FTM1_CH0_PIN 16 +#define FTM1_CH1_PIN 17 +#define FTM2_CH0_PIN 3 +#define FTM2_CH1_PIN 4 +#elif defined(__MK64FX512__) +#define FTM0_CH0_PIN 22 +#define FTM0_CH1_PIN 23 +#define FTM0_CH2_PIN 9 +#define FTM0_CH3_PIN 10 +#define FTM0_CH4_PIN 6 +#define FTM0_CH5_PIN 20 +#define FTM0_CH6_PIN 21 +#define FTM0_CH7_PIN 5 +#define FTM1_CH0_PIN 3 +#define FTM1_CH1_PIN 4 +#define FTM2_CH0_PIN 29 +#define FTM2_CH1_PIN 30 +#define FTM3_CH0_PIN 2 +#define FTM3_CH1_PIN 14 +#define FTM3_CH2_PIN 7 +#define FTM3_CH3_PIN 8 +#define FTM3_CH4_PIN 35 +#define FTM3_CH5_PIN 36 +#define FTM3_CH6_PIN 37 +#define FTM3_CH7_PIN 38 +#elif defined(__MK66FX1M0__) +#define FTM0_CH0_PIN 22 +#define FTM0_CH1_PIN 23 +#define FTM0_CH2_PIN 9 +#define FTM0_CH3_PIN 10 +#define FTM0_CH4_PIN 6 +#define FTM0_CH5_PIN 20 +#define FTM0_CH6_PIN 21 +#define FTM0_CH7_PIN 5 +#define FTM1_CH0_PIN 3 +#define FTM1_CH1_PIN 4 +#define FTM2_CH0_PIN 29 +#define FTM2_CH1_PIN 30 +#define FTM3_CH0_PIN 2 +#define FTM3_CH1_PIN 14 +#define FTM3_CH2_PIN 7 +#define FTM3_CH3_PIN 8 +#define FTM3_CH4_PIN 35 +#define FTM3_CH5_PIN 36 +#define FTM3_CH6_PIN 37 +#define FTM3_CH7_PIN 38 +#define TPM1_CH0_PIN 16 +#define TPM1_CH1_PIN 17 +#endif + +int _findTimer( const int Ah, const int Al, const int Bh, const int Bl, const int Ch, const int Cl){ + + if((Ah == FTM0_CH0_PIN && Al == FTM0_CH1_PIN) || + (Ah == FTM0_CH2_PIN && Al == FTM0_CH3_PIN) || + (Ah == FTM0_CH4_PIN && Al == FTM0_CH5_PIN) ){ + if((Bh == FTM0_CH0_PIN && Bl == FTM0_CH1_PIN) || + (Bh == FTM0_CH2_PIN && Bl == FTM0_CH3_PIN) || + (Bh == FTM0_CH4_PIN && Bl == FTM0_CH5_PIN) ){ + if((Ch == FTM0_CH0_PIN && Cl == FTM0_CH1_PIN) || + (Ch == FTM0_CH2_PIN && Cl == FTM0_CH3_PIN) || + (Ch == FTM0_CH4_PIN && Cl == FTM0_CH5_PIN) ){ +#ifdef SIMPLEFOC_TEENSY_DEBUG + SIMPLEFOC_DEBUG("TEENSY-DRV: Using timer FTM0."); +#endif + // timer FTM0 + return 0; + } + } + } + + #ifdef FTM3_SC // if the board has FTM3 timer + if((Ah == FTM3_CH0_PIN && Al == FTM3_CH1_PIN) || + (Ah == FTM3_CH2_PIN && Al == FTM3_CH3_PIN) || + (Ah == FTM3_CH4_PIN && Al == FTM3_CH5_PIN) ){ + if((Bh == FTM3_CH0_PIN && Bl == FTM3_CH1_PIN) || + (Bh == FTM3_CH2_PIN && Bl == FTM3_CH3_PIN) || + (Bh == FTM3_CH4_PIN && Bl == FTM3_CH5_PIN) ){ + if((Ch == FTM3_CH0_PIN && Cl == FTM3_CH1_PIN) || + (Ch == FTM3_CH2_PIN && Cl == FTM3_CH3_PIN) || + (Ch == FTM3_CH4_PIN && Cl == FTM3_CH5_PIN) ){ + // timer FTM3 +#ifdef SIMPLEFOC_TEENSY_DEBUG + SIMPLEFOC_DEBUG("TEENSY-DRV: Using timer FTM3."); +#endif + return 3; + } + } + } + #endif + +#ifdef SIMPLEFOC_TEENSY_DEBUG + SIMPLEFOC_DEBUG("TEENSY-DRV: ERR: Pins not on timers FTM0 or FTM3!"); +#endif + return -1; + +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 6PWM setting +// - hardware specific +void* _configure6PWM(long pwm_frequency, float dead_zone, const int pinA_h, const int pinA_l, const int pinB_h, const int pinB_l, const int pinC_h, const int pinC_l) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + unsigned long pwm_freq = 2*pwm_frequency; // center-aligned pwm has 4 times lower freq + _setHighFrequency(pwm_freq, pinA_h); + _setHighFrequency(pwm_freq, pinA_l); + _setHighFrequency(pwm_freq, pinB_h); + _setHighFrequency(pwm_freq, pinB_l); + _setHighFrequency(pwm_freq, pinC_h); + _setHighFrequency(pwm_freq, pinC_l); + + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA_h,pinA_l, pinB_h,pinB_l, pinC_h, pinC_l }, + .pwm_frequency = pwm_frequency + }; + + + int timer = _findTimer(pinA_h,pinA_l,pinB_h,pinB_l,pinC_h,pinC_l); + if(timer<0) return SIMPLEFOC_DRIVER_INIT_FAILED; + + // find the best combination of prescalers and counter value + double dead_time = dead_zone/pwm_freq; + int prescaler = 1; // initial prescaler (1,4 or 16) + double count = 1; // inital count (1 - 63) + for (; prescaler<=16; prescaler*=4){ + count = dead_time*((double)F_CPU)/((double)prescaler); + if(count < 64) break; // found the solution + } + count = _constrain(count, 1, 63); + + // configure the timer + if(timer==0){ + // Configure FTM0 + // // inverting and deadtime insertion for FTM1 + FTM0_COMBINE = 0x00121212; // 0x2 - complemetary mode, 0x1 - dead timer insertion enabled + + // Deadtime config + FTM0_DEADTIME = (int)count; // set counter - 1-63 + FTM0_DEADTIME |= ((prescaler>1) << 7) | ((prescaler>4) << 6); // set prescaler (0b01 - 1, 0b10 - 4, 0b11 - 16) + + // configure center aligned PWM + FTM0_SC = 0x00000028; // 0x2 - center-alignment, 0x8 - fixed clock freq + }else if(timer==3){ + // Configure FTM3 + // inverting and deadtime insertion for FTM1 + FTM3_COMBINE = 0x00121212; // 0x2 - complemetary mode, 0x1 - dead timer insertion enabled + + // Deadtime config + FTM3_DEADTIME = (int)count; // set counter - 1-63 + FTM3_DEADTIME |= ((prescaler>1) << 7) | ((prescaler>4) << 6); // set prescaler (0b01 - 1, 0b10 - 4, 0b11 - 16) + + // configure center aligned PWM + FTM3_SC = 0x00000028; // 0x2 - center-alignment, 0x8 - fixed clock freq + } + + return params; +} + + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 6PWM setting +// - hardware specific +void _writeDutyCycle6PWM(float dc_a, float dc_b, float dc_c, PhaseState *phase_state, void* params){ + _UNUSED(phase_state); + // transform duty cycle from [0,1] to [0,255] + // phase A + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_a); + + // phase B + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_b); + analogWrite(((GenericDriverParams*)params)->pins[3], 255.0f*dc_b); + + // phase C + analogWrite(((GenericDriverParams*)params)->pins[4], 255.0f*dc_c); + analogWrite(((GenericDriverParams*)params)->pins[5], 255.0f*dc_c); +} +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.cpp new file mode 100644 index 0000000..322d5a3 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.cpp @@ -0,0 +1,306 @@ +#include "teensy_mcu.h" +#include "teensy4_mcu.h" +#include "../../../communication/SimpleFOCDebug.h" + +// if defined +// - Teensy 4.0 +// - Teensy 4.1 +#if defined(__arm__) && defined(CORE_TEENSY) && ( defined(__IMXRT1062__) || defined(ARDUINO_TEENSY40) || defined(ARDUINO_TEENSY41) || defined(ARDUINO_TEENSY_MICROMOD) ) + + +#pragma message("") +#pragma message("SimpleFOC: compiling for Teensy 4.x") +#pragma message("") + + +// half_cycle of the PWM variable +int half_cycle = 0; + + +// function which finds the flexpwm instance for a pair of pins +// if they do not belong to the same timer it returns a nullpointer +IMXRT_FLEXPWM_t* get_flexpwm(uint8_t pin, uint8_t pin1){ + + const struct pwm_pin_info_struct *info; + if (pin >= CORE_NUM_DIGITAL || pin1 >= CORE_NUM_DIGITAL) { +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[60]; + sprintf (s, "TEENSY-DRV: ERR: Pins: %d, %d not Flextimer pins!", pin, pin1); + SIMPLEFOC_DEBUG(s); +#endif + return nullptr; + } + info = pwm_pin_info + pin; + // FlexPWM pin + IMXRT_FLEXPWM_t *flexpwm1,*flexpwm2; + switch ((info->module >> 4) & 3) { + case 0: flexpwm1 = &IMXRT_FLEXPWM1; break; + case 1: flexpwm1 = &IMXRT_FLEXPWM2; break; + case 2: flexpwm1 = &IMXRT_FLEXPWM3; break; + default: flexpwm1 = &IMXRT_FLEXPWM4; + } + + info = pwm_pin_info + pin1; + switch ((info->module >> 4) & 3) { + case 0: flexpwm2 = &IMXRT_FLEXPWM1; break; + case 1: flexpwm2 = &IMXRT_FLEXPWM2; break; + case 2: flexpwm2 = &IMXRT_FLEXPWM3; break; + default: flexpwm2 = &IMXRT_FLEXPWM4; + } + if(flexpwm1 == flexpwm2){ + char s[60]; + sprintf (s, "TEENSY-DRV: Pins: %d, %d on Flextimer %d.", pin, pin1, ((info->module >> 4) & 3) + 1); + SIMPLEFOC_DEBUG(s); + return flexpwm1; + } else { +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[60]; + sprintf (s, "TEENSY-DRV: ERR: Pins: %d, %d not in same Flextimer!", pin, pin1); + SIMPLEFOC_DEBUG(s); +#endif + return nullptr; + } +} + + +// function which finds the timer submodule for a pair of pins +// if they do not belong to the same submodule it returns a -1 +int get_submodule(uint8_t pin, uint8_t pin1){ + + const struct pwm_pin_info_struct *info; + if (pin >= CORE_NUM_DIGITAL || pin1 >= CORE_NUM_DIGITAL){ +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[60]; + sprintf (s, "TEENSY-DRV: ERR: Pins: %d, %d not Flextimer pins!", pin, pin1); + SIMPLEFOC_DEBUG(s); +#endif + return -1; + } + + info = pwm_pin_info + pin; + int sm1 = info->module&0x3; + info = pwm_pin_info + pin1; + int sm2 = info->module&0x3; + + if (sm1 == sm2) { + char s[60]; + sprintf (s, "TEENSY-DRV: Pins: %d, %d on submodule %d.", pin, pin1, sm1); + SIMPLEFOC_DEBUG(s); + return sm1; + } else { +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[50]; + sprintf (s, "TEENSY-DRV: ERR: Pins: %d, %d not in same submodule!", pin, pin1); + SIMPLEFOC_DEBUG(s); +#endif + return -1; + } +} + + +// function which finds the timer submodule for a pair of pins +// if they do not belong to the same submodule it returns a -1 +int get_inverted_channel(uint8_t pin, uint8_t pin1){ + + const struct pwm_pin_info_struct *info; + if (pin >= CORE_NUM_DIGITAL || pin1 >= CORE_NUM_DIGITAL){ +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[60]; + sprintf (s, "TEENSY-DRV: ERR: Pins: %d, %d not Flextimer pins!", pin, pin1); + SIMPLEFOC_DEBUG(s); +#endif + return -1; + } + + info = pwm_pin_info + pin; + int ch1 = info->channel; + info = pwm_pin_info + pin1; + int ch2 = info->channel; + + if (ch1 != 1) { +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[60]; + sprintf (s, "TEENSY-DRV: ERR: Pin: %d on channel %s - only A supported", pin1, ch1==2 ? "B" : "X"); + SIMPLEFOC_DEBUG(s); +#endif + return -1; + } else if (ch2 != 2) { +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[60]; + sprintf (s, "TEENSY-DRV: ERR: Inverted pin: %d on channel %s - only B supported", pin1, ch2==1 ? "A" : "X"); + SIMPLEFOC_DEBUG(s); +#endif + return -1; + } else { +#ifdef SIMPLEFOC_TEENSY_DEBUG + char s[60]; + sprintf (s, "TEENSY-DRV: Pin: %d on channel B inverted.", pin1); + SIMPLEFOC_DEBUG(s); +#endif +return ch2; + } +} + +// Helper to set up A/B pair on a FlexPWM submodule. +// can configure sync, prescale and B inversion. +// sets the desired frequency of the PWM +// sets the center-aligned pwm +void setup_pwm_pair (IMXRT_FLEXPWM_t * flexpwm, int submodule, const long frequency, float dead_zone ) +{ + int submodule_mask = 1 << submodule ; + flexpwm->MCTRL &= ~ FLEXPWM_MCTRL_RUN (submodule_mask) ; // stop it if its already running + flexpwm->MCTRL |= FLEXPWM_MCTRL_CLDOK (submodule_mask) ; // clear load OK + + + // calculate the counter and prescaler for the desired pwm frequency + uint32_t newdiv = (uint32_t)((float)F_BUS_ACTUAL / frequency + 0.5f); + uint32_t prescale = 0; + //printf(" div=%lu\n", newdiv); + while (newdiv > 65535 && prescale < 7) { + newdiv = newdiv >> 1; + prescale = prescale + 1; + } + if (newdiv > 65535) { + newdiv = 65535; + } else if (newdiv < 2) { + newdiv = 2; + } + + // the halfcycle of the PWM + half_cycle = int(newdiv/2.0f); + int dead_time = int(dead_zone*half_cycle); //default dead-time - 2% + int mid_pwm = int((half_cycle)/2.0f); + + // setup the timer + // https://github.com/PaulStoffregen/cores/blob/master/teensy4/imxrt.h + flexpwm->SM[submodule].CTRL2 = FLEXPWM_SMCTRL2_WAITEN | FLEXPWM_SMCTRL2_DBGEN | + FLEXPWM_SMCTRL2_FRCEN | FLEXPWM_SMCTRL2_INIT_SEL(0) | FLEXPWM_SMCTRL2_FORCE_SEL(6); + flexpwm->SM[submodule].CTRL = FLEXPWM_SMCTRL_FULL | FLEXPWM_SMCTRL_HALF | FLEXPWM_SMCTRL_PRSC(prescale) ; + // https://github.com/PaulStoffregen/cores/blob/70ba01accd728abe75ebfc8dcd8b3d3a8f3e3f25/teensy4/imxrt.h#L4948 + flexpwm->SM[submodule].OCTRL = 0;//channel_to_invert==2 ? 0 : FLEXPWM_SMOCTRL_POLA | FLEXPWM_SMOCTRL_POLB ; + flexpwm->SM[submodule].DTCNT0 = dead_time ; // should try this out (deadtime control) + flexpwm->SM[submodule].DTCNT1 = dead_time ; // should try this out (deadtime control) + // flexpwm->SM[submodule].TCTRL = FLEXPWM_SMTCTRL_OUT_TRIG_EN (0b000010) ; // sync trig out on VAL1 match. + flexpwm->SM[submodule].INIT = -half_cycle; // count from -HALFCYCLE to +HALFCYCLE + flexpwm->SM[submodule].VAL0 = 0 ; + flexpwm->SM[submodule].VAL1 = half_cycle ; + flexpwm->SM[submodule].VAL2 = -mid_pwm ; + flexpwm->SM[submodule].VAL3 = +mid_pwm ; + // flexpwm->SM[submodule].VAL4 = -mid_pwm ; + // flexpwm->SM[submodule].VAL5 = +mid_pwm ; + + flexpwm->MCTRL |= FLEXPWM_MCTRL_LDOK (submodule_mask) ; // loading reenabled + flexpwm->MCTRL |= FLEXPWM_MCTRL_RUN (submodule_mask) ; // start it running +} + + +// staring the PWM on A and B channels of the submodule +void startup_pwm_pair (IMXRT_FLEXPWM_t * flexpwm, int submodule) +{ + int submodule_mask = 1 << submodule ; + + flexpwm->OUTEN |= FLEXPWM_OUTEN_PWMA_EN (submodule_mask); // enable A output + flexpwm->OUTEN |= FLEXPWM_OUTEN_PWMB_EN (submodule_mask); // enable B output +} + + + +// PWM setting on the high and low pair of the PWM channels +void write_pwm_pair(IMXRT_FLEXPWM_t * flexpwm, int submodule, float duty){ + + int mid_pwm = int((half_cycle)/2.0f); + int count_pwm = int(mid_pwm*(duty*2-1)) + mid_pwm; + + flexpwm->SM[submodule].VAL2 = count_pwm; // A on + flexpwm->SM[submodule].VAL3 = -count_pwm ; // A off + // flexpwm->SM[submodule].VAL4 = - count_pwm ; // B off (assuming B inverted) + // flexpwm->SM[submodule].VAL5 = + count_pwm ; // B on + flexpwm->MCTRL |= FLEXPWM_MCTRL_LDOK (1<flextimers[0], ((Teensy4DriverParams*)params)->submodules[0], dc_a); + write_pwm_pair (((Teensy4DriverParams*)params)->flextimers[1], ((Teensy4DriverParams*)params)->submodules[1], dc_b); + write_pwm_pair (((Teensy4DriverParams*)params)->flextimers[2], ((Teensy4DriverParams*)params)->submodules[2], dc_c); +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.h new file mode 100644 index 0000000..5e38462 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy4_mcu.h @@ -0,0 +1,110 @@ +#include "teensy_mcu.h" + +// if defined +// - Teensy 4.0 +// - Teensy 4.1 +#if defined(__arm__) && defined(CORE_TEENSY) && ( defined(__IMXRT1062__) || defined(ARDUINO_TEENSY40) || defined(ARDUINO_TEENSY41) || defined(ARDUINO_TEENSY_MICROMOD) ) + +// teensy 4 driver configuration parameters +typedef struct Teensy4DriverParams { + IMXRT_FLEXPWM_t* flextimers[3] = {NULL}; + int submodules[3]; + long pwm_frequency; + float dead_zone; +} Teensy4DriverParams; + + +// pin definition from https://github.com/PaulStoffregen/cores/blob/master/teensy4/pwm.c +struct pwm_pin_info_struct { + uint8_t type; // 0=no pwm, 1=flexpwm, 2=quad + uint8_t module; // 0-3, 0-3 + uint8_t channel; // 0=X, 1=A, 2=B + uint8_t muxval; // +}; +#define M(a, b) ((((a) - 1) << 4) | (b)) +#if defined(__IMXRT1062__) +const struct pwm_pin_info_struct pwm_pin_info[] = { + {1, M(1, 1), 0, 4}, // FlexPWM1_1_X 0 // AD_B0_03 + {1, M(1, 0), 0, 4}, // FlexPWM1_0_X 1 // AD_B0_02 + {1, M(4, 2), 1, 1}, // FlexPWM4_2_A 2 // EMC_04 + {1, M(4, 2), 2, 1}, // FlexPWM4_2_B 3 // EMC_05 + {1, M(2, 0), 1, 1}, // FlexPWM2_0_A 4 // EMC_06 + {1, M(2, 1), 1, 1}, // FlexPWM2_1_A 5 // EMC_08 + {1, M(2, 2), 1, 2}, // FlexPWM2_2_A 6 // B0_10 + {1, M(1, 3), 2, 6}, // FlexPWM1_3_B 7 // B1_01 + {1, M(1, 3), 1, 6}, // FlexPWM1_3_A 8 // B1_00 + {1, M(2, 2), 2, 2}, // FlexPWM2_2_B 9 // B0_11 + {2, M(1, 0), 0, 1}, // QuadTimer1_0 10 // B0_00 + {2, M(1, 2), 0, 1}, // QuadTimer1_2 11 // B0_02 + {2, M(1, 1), 0, 1}, // QuadTimer1_1 12 // B0_01 + {2, M(2, 0), 0, 1}, // QuadTimer2_0 13 // B0_03 + {2, M(3, 2), 0, 1}, // QuadTimer3_2 14 // AD_B1_02 + {2, M(3, 3), 0, 1}, // QuadTimer3_3 15 // AD_B1_03 + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {2, M(3, 1), 0, 1}, // QuadTimer3_1 18 // AD_B1_01 + {2, M(3, 0), 0, 1}, // QuadTimer3_0 19 // AD_B1_00 + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {1, M(4, 0), 1, 1}, // FlexPWM4_0_A 22 // AD_B1_08 + {1, M(4, 1), 1, 1}, // FlexPWM4_1_A 23 // AD_B1_09 + {1, M(1, 2), 0, 4}, // FlexPWM1_2_X 24 // AD_B0_12 + {1, M(1, 3), 0, 4}, // FlexPWM1_3_X 25 // AD_B0_13 + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {1, M(3, 1), 2, 1}, // FlexPWM3_1_B 28 // EMC_32 + {1, M(3, 1), 1, 1}, // FlexPWM3_1_A 29 // EMC_31 + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {1, M(2, 0), 2, 1}, // FlexPWM2_0_B 33 // EMC_07 +#ifdef ARDUINO_TEENSY40 + {1, M(1, 1), 2, 1}, // FlexPWM1_1_B 34 // SD_B0_03 + {1, M(1, 1), 1, 1}, // FlexPWM1_1_A 35 // SD_B0_02 + {1, M(1, 0), 2, 1}, // FlexPWM1_0_B 36 // SD_B0_01 + {1, M(1, 0), 1, 1}, // FlexPWM1_0_A 37 // SD_B0_00 + {1, M(1, 2), 2, 1}, // FlexPWM1_2_B 38 // SD_B0_05 + {1, M(1, 2), 1, 1}, // FlexPWM1_2_A 39 // SD_B0_04 +#endif +#ifdef ARDUINO_TEENSY41 + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {1, M(2, 3), 1, 6}, // FlexPWM2_3_A 36 // B1_00 + {1, M(2, 3), 2, 6}, // FlexPWM2_3_B 37 // B1_01 + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {0, M(1, 0), 0, 0}, + {1, M(1, 1), 2, 1}, // FlexPWM1_1_B 42 // SD_B0_03 + {1, M(1, 1), 1, 1}, // FlexPWM1_1_A 43 // SD_B0_02 + {1, M(1, 0), 2, 1}, // FlexPWM1_0_B 44 // SD_B0_01 + {1, M(1, 0), 1, 1}, // FlexPWM1_0_A 45 // SD_B0_00 + {1, M(1, 2), 2, 1}, // FlexPWM1_2_B 46 // SD_B0_05 + {1, M(1, 2), 1, 1}, // FlexPWM1_2_A 47 // SD_B0_04 + {0, M(1, 0), 0, 0}, // duplicate FlexPWM1_0_B + {0, M(1, 0), 0, 0}, // duplicate FlexPWM1_2_A + {0, M(1, 0), 0, 0}, // duplicate FlexPWM1_2_B + {1, M(3, 3), 2, 1}, // FlexPWM3_3_B 51 // EMC_22 + {0, M(1, 0), 0, 0}, // duplicate FlexPWM1_1_B + {0, M(1, 0), 0, 0}, // duplicate FlexPWM1_1_A + {1, M(3, 0), 1, 1}, // FlexPWM3_0_A 54 // EMC_29 +#endif +#ifdef ARDUINO_TEENSY_MICROMOD + {1, M(1, 1), 2, 1}, // FlexPWM1_1_B 34 // SD_B0_03 + {1, M(1, 1), 1, 1}, // FlexPWM1_1_A 35 // SD_B0_02 + {1, M(1, 0), 2, 1}, // FlexPWM1_0_B 36 // SD_B0_01 + {1, M(1, 0), 1, 1}, // FlexPWM1_0_A 37 // SD_B0_00 + {1, M(1, 2), 1, 1}, // FlexPWM1_2_A 38 // SD_B0_04 + {1, M(1, 2), 2, 1}, // FlexPWM1_2_B 39 // SD_B0_05 + {2, M(2, 1), 0, 1}, // QuadTimer2_1 40 // B0_04 + {2, M(2, 2), 0, 1}, // QuadTimer2_2 41 // B0_05 + {0, M(1, 0), 0, 0}, // duplicate QuadTimer3_0 + {0, M(1, 0), 0, 0}, // duplicate QuadTimer3_1 + {0, M(1, 0), 0, 0}, // duplicate QuadTimer3_2 + {2, M(4, 0), 0, 1}, // QuadTimer4_0 45 // B0_09 +#endif +}; + +#endif + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.cpp b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.cpp new file mode 100644 index 0000000..dcfa3e1 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.cpp @@ -0,0 +1,116 @@ +#include "teensy_mcu.h" + +#if defined(__arm__) && defined(CORE_TEENSY) + +// configure High PWM frequency +void _setHighFrequency(const long freq, const int pin){ + analogWrite(pin, 0); + analogWriteFrequency(pin, freq); +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure1PWM(long pwm_frequency, const int pinA) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 2PWM setting +// - hardware speciffic +void* _configure2PWM(long pwm_frequency, const int pinA, const int pinB) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + _setHighFrequency(pwm_frequency, pinB); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - BLDC motor - 3PWM setting +// - hardware speciffic +void* _configure3PWM(long pwm_frequency,const int pinA, const int pinB, const int pinC) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + _setHighFrequency(pwm_frequency, pinB); + _setHighFrequency(pwm_frequency, pinC); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC }, + .pwm_frequency = pwm_frequency + }; + return params; +} + +// function setting the high pwm frequency to the supplied pins +// - Stepper motor - 4PWM setting +// - hardware speciffic +void* _configure4PWM(long pwm_frequency, const int pinA, const int pinB, const int pinC, const int pinD) { + if(!pwm_frequency || !_isset(pwm_frequency) ) pwm_frequency = _PWM_FREQUENCY; // default frequency 25khz + else pwm_frequency = _constrain(pwm_frequency, 0, _PWM_FREQUENCY_MAX); // constrain to 50kHz max + _setHighFrequency(pwm_frequency, pinA); + _setHighFrequency(pwm_frequency, pinB); + _setHighFrequency(pwm_frequency, pinC); + _setHighFrequency(pwm_frequency, pinD); + GenericDriverParams* params = new GenericDriverParams { + .pins = { pinA, pinB, pinC, pinD }, + .pwm_frequency = pwm_frequency + }; + return params; +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +void _writeDutyCycle1PWM(float dc_a, void* params) { + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); +} + + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 2PWM setting +// - hardware speciffic +void _writeDutyCycle2PWM(float dc_a, float dc_b, void* params) { + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); +} + + +// function setting the pwm duty cycle to the hardware +// - BLDC motor - 3PWM setting +// - hardware speciffic +void _writeDutyCycle3PWM(float dc_a, float dc_b, float dc_c, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_c); +} + +// function setting the pwm duty cycle to the hardware +// - Stepper motor - 4PWM setting +// - hardware speciffic +void _writeDutyCycle4PWM(float dc_1a, float dc_1b, float dc_2a, float dc_2b, void* params){ + // transform duty cycle from [0,1] to [0,255] + analogWrite(((GenericDriverParams*)params)->pins[0], 255.0f*dc_1a); + analogWrite(((GenericDriverParams*)params)->pins[1], 255.0f*dc_1b); + analogWrite(((GenericDriverParams*)params)->pins[2], 255.0f*dc_2a); + analogWrite(((GenericDriverParams*)params)->pins[3], 255.0f*dc_2b); +} + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.h b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.h new file mode 100644 index 0000000..7956ea9 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/drivers/hardware_specific/teensy/teensy_mcu.h @@ -0,0 +1,14 @@ +#include "../../hardware_api.h" + +#if defined(__arm__) && defined(CORE_TEENSY) + +#define _PWM_FREQUENCY 25000 // 25khz +#define _PWM_FREQUENCY_MAX 50000 // 50khz + +// debugging output +#define SIMPLEFOC_TEENSY_DEBUG + +// configure High PWM frequency +void _setHighFrequency(const long freq, const int pin); + +#endif \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/sensors/Encoder.cpp b/firmware/lib/Arduino-FOC/src/sensors/Encoder.cpp new file mode 100644 index 0000000..fa4b8e7 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/Encoder.cpp @@ -0,0 +1,229 @@ +#include "Encoder.h" + + +/* + Encoder(int encA, int encB , int cpr, int index) + - encA, encB - encoder A and B pins + - cpr - counts per rotation number (cpm=ppm*4) + - index pin - (optional input) +*/ + +Encoder::Encoder(int _encA, int _encB , float _ppr, int _index){ + + // Encoder measurement structure init + // hardware pins + pinA = _encA; + pinB = _encB; + // counter setup + pulse_counter = 0; + pulse_timestamp = 0; + + cpr = _ppr; + A_active = 0; + B_active = 0; + I_active = 0; + // index pin + index_pin = _index; // its 0 if not used + + // velocity calculation variables + prev_Th = 0; + pulse_per_second = 0; + prev_pulse_counter = 0; + prev_timestamp_us = _micros(); + + // extern pullup as default + pullup = Pullup::USE_EXTERN; + // enable quadrature encoder by default + quadrature = Quadrature::ON; +} + +// Encoder interrupt callback functions +// A channel +void Encoder::handleA() { + bool A = digitalRead(pinA); + switch (quadrature){ + case Quadrature::ON: + // CPR = 4xPPR + if ( A != A_active ) { + pulse_counter += (A_active == B_active) ? 1 : -1; + pulse_timestamp = _micros(); + A_active = A; + } + break; + case Quadrature::OFF: + // CPR = PPR + if(A && !digitalRead(pinB)){ + pulse_counter++; + pulse_timestamp = _micros(); + } + break; + } +} +// B channel +void Encoder::handleB() { + bool B = digitalRead(pinB); + switch (quadrature){ + case Quadrature::ON: + // // CPR = 4xPPR + if ( B != B_active ) { + pulse_counter += (A_active != B_active) ? 1 : -1; + pulse_timestamp = _micros(); + B_active = B; + } + break; + case Quadrature::OFF: + // CPR = PPR + if(B && !digitalRead(pinA)){ + pulse_counter--; + pulse_timestamp = _micros(); + } + break; + } +} + +// Index channel +void Encoder::handleIndex() { + if(hasIndex()){ + bool I = digitalRead(index_pin); + if(I && !I_active){ + index_found = true; + // align encoder on each index + long tmp = pulse_counter; + // corrent the counter value + pulse_counter = round((double)pulse_counter/(double)cpr)*cpr; + // preserve relative speed + prev_pulse_counter += pulse_counter - tmp; + } + I_active = I; + } +} + + +// Sensor update function. Safely copy volatile interrupt variables into Sensor base class state variables. +void Encoder::update() { + // Copy volatile variables in minimal-duration blocking section to ensure no interrupts are missed + noInterrupts(); + angle_prev_ts = pulse_timestamp; + long copy_pulse_counter = pulse_counter; + interrupts(); + // TODO: numerical precision issue here if the pulse_counter overflows the angle will be lost + full_rotations = copy_pulse_counter / (int)cpr; + angle_prev = _2PI * ((copy_pulse_counter) % ((int)cpr)) / ((float)cpr); +} + +/* + Shaft angle calculation +*/ +float Encoder::getSensorAngle(){ + return _2PI * (pulse_counter) / ((float)cpr); +} + + + +/* + Shaft velocity calculation + function using mixed time and frequency measurement technique +*/ +float Encoder::getVelocity(){ + // Copy volatile variables in minimal-duration blocking section to ensure no interrupts are missed + noInterrupts(); + long copy_pulse_counter = pulse_counter; + long copy_pulse_timestamp = pulse_timestamp; + interrupts(); + // timestamp + long timestamp_us = _micros(); + // sampling time calculation + float Ts = (timestamp_us - prev_timestamp_us) * 1e-6f; + // quick fix for strange cases (micros overflow) + if(Ts <= 0 || Ts > 0.5f) Ts = 1e-3f; + + // time from last impulse + float Th = (timestamp_us - copy_pulse_timestamp) * 1e-6f; + long dN = copy_pulse_counter - prev_pulse_counter; + + // Pulse per second calculation (Eq.3.) + // dN - impulses received + // Ts - sampling time - time in between function calls + // Th - time from last impulse + // Th_1 - time form last impulse of the previous call + // only increment if some impulses received + float dt = Ts + prev_Th - Th; + pulse_per_second = (dN != 0 && dt > Ts/2) ? dN / dt : pulse_per_second; + + // if more than 0.05f passed in between impulses + if ( Th > 0.1f) pulse_per_second = 0; + + // velocity calculation + float velocity = pulse_per_second / ((float)cpr) * (_2PI); + + // save variables for next pass + prev_timestamp_us = timestamp_us; + // save velocity calculation variables + prev_Th = Th; + prev_pulse_counter = copy_pulse_counter; + return velocity; +} + +// getter for index pin +// return -1 if no index +int Encoder::needsSearch(){ + return hasIndex() && !index_found; +} + +// private function used to determine if encoder has index +int Encoder::hasIndex(){ + return index_pin != 0; +} + + +// encoder initialisation of the hardware pins +// and calculation variables +void Encoder::init(){ + + // Encoder - check if pullup needed for your encoder + if(pullup == Pullup::USE_INTERN){ + pinMode(pinA, INPUT_PULLUP); + pinMode(pinB, INPUT_PULLUP); + if(hasIndex()) pinMode(index_pin,INPUT_PULLUP); + }else{ + pinMode(pinA, INPUT); + pinMode(pinB, INPUT); + if(hasIndex()) pinMode(index_pin,INPUT); + } + + // counter setup + pulse_counter = 0; + pulse_timestamp = _micros(); + // velocity calculation variables + prev_Th = 0; + pulse_per_second = 0; + prev_pulse_counter = 0; + prev_timestamp_us = _micros(); + + // initial cpr = PPR + // change it if the mode is quadrature + if(quadrature == Quadrature::ON) cpr = 4*cpr; + + // we don't call Sensor::init() here because init is handled in Encoder class. +} + +// function enabling hardware interrupts of the for the callback provided +// if callback is not provided then the interrupt is not enabled +void Encoder::enableInterrupts(void (*doA)(), void(*doB)(), void(*doIndex)()){ + // attach interrupt if functions provided + switch(quadrature){ + case Quadrature::ON: + // A callback and B callback + if(doA != nullptr) attachInterrupt(digitalPinToInterrupt(pinA), doA, CHANGE); + if(doB != nullptr) attachInterrupt(digitalPinToInterrupt(pinB), doB, CHANGE); + break; + case Quadrature::OFF: + // A callback and B callback + if(doA != nullptr) attachInterrupt(digitalPinToInterrupt(pinA), doA, RISING); + if(doB != nullptr) attachInterrupt(digitalPinToInterrupt(pinB), doB, RISING); + break; + } + + // if index used initialize the index interrupt + if(hasIndex() && doIndex != nullptr) attachInterrupt(digitalPinToInterrupt(index_pin), doIndex, CHANGE); +} diff --git a/firmware/lib/Arduino-FOC/src/sensors/Encoder.h b/firmware/lib/Arduino-FOC/src/sensors/Encoder.h new file mode 100644 index 0000000..af6a5ab --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/Encoder.h @@ -0,0 +1,91 @@ +#ifndef ENCODER_LIB_H +#define ENCODER_LIB_H + +#include "Arduino.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/base_classes/Sensor.h" + + +/** + * Quadrature mode configuration structure + */ +enum Quadrature : uint8_t { + ON = 0x00, //!< Enable quadrature mode CPR = 4xPPR + OFF = 0x01 //!< Disable quadrature mode / CPR = PPR +}; + +class Encoder: public Sensor{ + public: + /** + Encoder class constructor + @param encA encoder B pin + @param encB encoder B pin + @param ppr impulses per rotation (cpr=ppr*4) + @param index index pin number (optional input) + */ + Encoder(int encA, int encB , float ppr, int index = 0); + + /** encoder initialise pins */ + void init() override; + /** + * function enabling hardware interrupts for the encoder channels with provided callback functions + * if callback is not provided then the interrupt is not enabled + * + * @param doA pointer to the A channel interrupt handler function + * @param doB pointer to the B channel interrupt handler function + * @param doIndex pointer to the Index channel interrupt handler function + * + */ + void enableInterrupts(void (*doA)() = nullptr, void(*doB)() = nullptr, void(*doIndex)() = nullptr); + + // Encoder interrupt callback functions + /** A channel callback function */ + void handleA(); + /** B channel callback function */ + void handleB(); + /** Index channel callback function */ + void handleIndex(); + + + // pins A and B + int pinA; //!< encoder hardware pin A + int pinB; //!< encoder hardware pin B + int index_pin; //!< index pin + + // Encoder configuration + Pullup pullup; //!< Configuration parameter internal or external pullups + Quadrature quadrature;//!< Configuration parameter enable or disable quadrature mode + float cpr;//!< encoder cpr number + + // Abstract functions of the Sensor class implementation + /** get current angle (rad) */ + float getSensorAngle() override; + /** get current angular velocity (rad/s) */ + float getVelocity() override; + virtual void update() override; + + /** + * returns 0 if it does need search for absolute zero + * 0 - encoder without index + * 1 - ecoder with index + */ + int needsSearch() override; + + private: + int hasIndex(); //!< function returning 1 if encoder has index pin and 0 if not. + + volatile long pulse_counter;//!< current pulse counter + volatile long pulse_timestamp;//!< last impulse timestamp in us + volatile int A_active; //!< current active states of A channel + volatile int B_active; //!< current active states of B channel + volatile int I_active; //!< current active states of Index channel + volatile bool index_found = false; //!< flag stating that the index has been found + + // velocity calculation variables + float prev_Th, pulse_per_second; + volatile long prev_pulse_counter, prev_timestamp_us; +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/sensors/GenericSensor.cpp b/firmware/lib/Arduino-FOC/src/sensors/GenericSensor.cpp new file mode 100644 index 0000000..3d4025f --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/GenericSensor.cpp @@ -0,0 +1,26 @@ +#include "GenericSensor.h" + + +/* + GenericSensor( float (*readCallback)() ) + - readCallback - pointer to the function which reads the sensor angle. +*/ + +GenericSensor::GenericSensor(float (*readCallback)(), void (*initCallback)()){ + // if function provided add it to the + if(readCallback != nullptr) this->readCallback = readCallback; + if(initCallback != nullptr) this->initCallback = initCallback; +} + +void GenericSensor::init(){ + // if init callback specified run it + if(initCallback != nullptr) this->initCallback(); + this->Sensor::init(); // call base class init +} + +/* + Shaft angle calculation +*/ +float GenericSensor::getSensorAngle(){ + return this->readCallback(); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/sensors/GenericSensor.h b/firmware/lib/Arduino-FOC/src/sensors/GenericSensor.h new file mode 100644 index 0000000..ba0dfe5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/GenericSensor.h @@ -0,0 +1,31 @@ +#ifndef GENERIC_SENSOR_LIB_H +#define GENERIC_SENSOR_LIB_H + +#include "Arduino.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" +#include "../common/base_classes/Sensor.h" + + +class GenericSensor: public Sensor{ + public: + /** + GenericSensor class constructor + * @param readCallback pointer to the function reading the sensor angle + * @param initCallback pointer to the function initialising the sensor + */ + GenericSensor(float (*readCallback)() = nullptr, void (*initCallback)() = nullptr); + + float (*readCallback)() = nullptr; //!< function pointer to sensor reading + void (*initCallback)() = nullptr; //!< function pointer to sensor initialisation + + void init() override; + + // Abstract functions of the Sensor class implementation + /** get current angle (rad) */ + float getSensorAngle() override; + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/sensors/HallSensor.cpp b/firmware/lib/Arduino-FOC/src/sensors/HallSensor.cpp new file mode 100644 index 0000000..38767d5 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/HallSensor.cpp @@ -0,0 +1,173 @@ +#include "HallSensor.h" + + +/* + HallSensor(int hallA, int hallB , int cpr, int index) + - hallA, hallB, hallC - HallSensor A, B and C pins + - pp - pole pairs +*/ +HallSensor::HallSensor(int _hallA, int _hallB, int _hallC, int _pp){ + + // hardware pins + pinA = _hallA; + pinB = _hallB; + pinC = _hallC; + + // hall has 6 segments per electrical revolution + cpr = _pp * 6; + + // extern pullup as default + pullup = Pullup::USE_EXTERN; +} + +// HallSensor interrupt callback functions +// A channel +void HallSensor::handleA() { + A_active= digitalRead(pinA); + updateState(); +} +// B channel +void HallSensor::handleB() { + B_active = digitalRead(pinB); + updateState(); +} + +// C channel +void HallSensor::handleC() { + C_active = digitalRead(pinC); + updateState(); +} + +/** + * Updates the state and sector following an interrupt + */ +void HallSensor::updateState() { + long new_pulse_timestamp = _micros(); + + int8_t new_hall_state = C_active + (B_active << 1) + (A_active << 2); + + // glitch avoidance #1 - sometimes we get an interrupt but pins haven't changed + if (new_hall_state == hall_state) { + return; + } + hall_state = new_hall_state; + + int8_t new_electric_sector = ELECTRIC_SECTORS[hall_state]; + static Direction old_direction; + if (new_electric_sector - electric_sector > 3) { + //underflow + direction = Direction::CCW; + electric_rotations += direction; + } else if (new_electric_sector - electric_sector < (-3)) { + //overflow + direction = Direction::CW; + electric_rotations += direction; + } else { + direction = (new_electric_sector > electric_sector)? Direction::CW : Direction::CCW; + } + electric_sector = new_electric_sector; + + // glitch avoidance #2 changes in direction can cause velocity spikes. Possible improvements needed in this area + if (direction == old_direction) { + // not oscilating or just changed direction + pulse_diff = new_pulse_timestamp - pulse_timestamp; + } else { + pulse_diff = 0; + } + + pulse_timestamp = new_pulse_timestamp; + total_interrupts++; + old_direction = direction; + if (onSectorChange != nullptr) onSectorChange(electric_sector); +} + +/** + * Optionally set a function callback to be fired when sector changes + * void onSectorChange(int sector) { + * ... // for debug or call driver directly? + * } + * sensor.attachSectorCallback(onSectorChange); + */ +void HallSensor::attachSectorCallback(void (*_onSectorChange)(int sector)) { + onSectorChange = _onSectorChange; +} + + + +// Sensor update function. Safely copy volatile interrupt variables into Sensor base class state variables. +void HallSensor::update() { + // Copy volatile variables in minimal-duration blocking section to ensure no interrupts are missed + noInterrupts(); + angle_prev_ts = pulse_timestamp; + long last_electric_rotations = electric_rotations; + int8_t last_electric_sector = electric_sector; + interrupts(); + angle_prev = ((float)((last_electric_rotations * 6 + last_electric_sector) % cpr) / (float)cpr) * _2PI ; + full_rotations = (int32_t)((last_electric_rotations * 6 + last_electric_sector) / cpr); +} + + + +/* + Shaft angle calculation + TODO: numerical precision issue here if the electrical rotation overflows the angle will be lost +*/ +float HallSensor::getSensorAngle() { + return ((float)(electric_rotations * 6 + electric_sector) / (float)cpr) * _2PI ; +} + +/* + Shaft velocity calculation + function using mixed time and frequency measurement technique +*/ +float HallSensor::getVelocity(){ + noInterrupts(); + long last_pulse_timestamp = pulse_timestamp; + long last_pulse_diff = pulse_diff; + interrupts(); + if (last_pulse_diff == 0 || ((long)(_micros() - last_pulse_timestamp) > last_pulse_diff*2) ) { // last velocity isn't accurate if too old + return 0; + } else { + return direction * (_2PI / (float)cpr) / (last_pulse_diff / 1000000.0f); + } + +} + +// HallSensor initialisation of the hardware pins +// and calculation variables +void HallSensor::init(){ + // initialise the electrical rotations to 0 + electric_rotations = 0; + + // HallSensor - check if pullup needed for your HallSensor + if(pullup == Pullup::USE_INTERN){ + pinMode(pinA, INPUT_PULLUP); + pinMode(pinB, INPUT_PULLUP); + pinMode(pinC, INPUT_PULLUP); + }else{ + pinMode(pinA, INPUT); + pinMode(pinB, INPUT); + pinMode(pinC, INPUT); + } + + // init hall_state + A_active= digitalRead(pinA); + B_active = digitalRead(pinB); + C_active = digitalRead(pinC); + updateState(); + + pulse_timestamp = _micros(); + + // we don't call Sensor::init() here because init is handled in HallSensor class. +} + +// function enabling hardware interrupts for the callback provided +// if callback is not provided then the interrupt is not enabled +void HallSensor::enableInterrupts(void (*doA)(), void(*doB)(), void(*doC)()){ + // attach interrupt if functions provided + + // A, B and C callback + if(doA != nullptr) attachInterrupt(digitalPinToInterrupt(pinA), doA, CHANGE); + if(doB != nullptr) attachInterrupt(digitalPinToInterrupt(pinB), doB, CHANGE); + if(doC != nullptr) attachInterrupt(digitalPinToInterrupt(pinC), doC, CHANGE); +} diff --git a/firmware/lib/Arduino-FOC/src/sensors/HallSensor.h b/firmware/lib/Arduino-FOC/src/sensors/HallSensor.h new file mode 100644 index 0000000..ad50c7d --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/HallSensor.h @@ -0,0 +1,98 @@ +#ifndef HALL_SENSOR_LIB_H +#define HALL_SENSOR_LIB_H + +#include "Arduino.h" +#include "../common/base_classes/Sensor.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" + +// seq 1 > 5 > 4 > 6 > 2 > 3 > 1 000 001 010 011 100 101 110 111 +const int8_t ELECTRIC_SECTORS[8] = { -1, 0, 4, 5, 2, 1, 3 , -1 }; + +class HallSensor: public Sensor{ + public: + /** + HallSensor class constructor + @param encA HallSensor A pin + @param encB HallSensor B pin + @param encC HallSensor C pin + @param pp pole pairs (e.g hoverboard motor has 15pp and small gimbals often have 7pp) + @param index index pin number (optional input) + */ + HallSensor(int encA, int encB, int encC, int pp); + + /** HallSensor initialise pins */ + void init(); + /** + * function enabling hardware interrupts for the HallSensor channels with provided callback functions + * if callback is not provided then the interrupt is not enabled + * + * @param doA pointer to the A channel interrupt handler function + * @param doB pointer to the B channel interrupt handler function + * @param doIndex pointer to the Index channel interrupt handler function + * + */ + void enableInterrupts(void (*doA)() = nullptr, void(*doB)() = nullptr, void(*doC)() = nullptr); + + // HallSensor interrupt callback functions + /** A channel callback function */ + void handleA(); + /** B channel callback function */ + void handleB(); + /** C channel callback function */ + void handleC(); + + + // pins A and B + int pinA; //!< HallSensor hardware pin A + int pinB; //!< HallSensor hardware pin B + int pinC; //!< HallSensor hardware pin C + + // HallSensor configuration + Pullup pullup; //!< Configuration parameter internal or external pullups + int cpr;//!< HallSensor cpr number + + // Abstract functions of the Sensor class implementation + /** Interrupt-safe update */ + void update() override; + /** get current angle (rad) */ + float getSensorAngle() override; + /** get current angular velocity (rad/s) */ + float getVelocity() override; + + // whether last step was CW (+1) or CCW (-1). + Direction direction; + + void attachSectorCallback(void (*onSectorChange)(int a) = nullptr); + + // the current 3bit state of the hall sensors + volatile int8_t hall_state; + // the current sector of the sensor. Each sector is 60deg electrical + volatile int8_t electric_sector; + // the number of electric rotations + volatile long electric_rotations; + // this is sometimes useful to identify interrupt issues (e.g. weak or no pullup resulting in 1000s of interrupts) + volatile long total_interrupts; + + // variable used to filter outliers - rad/s + float velocity_max = 1000.0f; + + private: + + Direction decodeDirection(int oldState, int newState); + void updateState(); + + volatile unsigned long pulse_timestamp;//!< last impulse timestamp in us + volatile int A_active; //!< current active states of A channel + volatile int B_active; //!< current active states of B channel + volatile int C_active; //!< current active states of C channel + + // function pointer for on sector change call back + void (*onSectorChange)(int sector) = nullptr; + + volatile long pulse_diff; + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.cpp b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.cpp new file mode 100644 index 0000000..d4adad6 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.cpp @@ -0,0 +1,42 @@ +#include "MagneticSensorAnalog.h" + +/** MagneticSensorAnalog(uint8_t _pinAnalog, int _min, int _max) + * @param _pinAnalog the pin that is reading the pwm from magnetic sensor + * @param _min_raw_count the smallest expected reading. Whilst you might expect it to be 0 it is often ~15. Getting this wrong results in a small click once per revolution + * @param _max_raw_count the largest value read. whilst you might expect it to be 2^10 = 1023 it is often ~ 1020. Note: For ESP32 (with 12bit ADC the value will be nearer 4096) + */ +MagneticSensorAnalog::MagneticSensorAnalog(uint8_t _pinAnalog, int _min_raw_count, int _max_raw_count){ + + pinAnalog = _pinAnalog; + + cpr = _max_raw_count - _min_raw_count; + min_raw_count = _min_raw_count; + max_raw_count = _max_raw_count; + + if(pullup == Pullup::USE_INTERN){ + pinMode(pinAnalog, INPUT_PULLUP); + }else{ + pinMode(pinAnalog, INPUT); + } + +} + + +void MagneticSensorAnalog::init(){ + raw_count = getRawCount(); + + this->Sensor::init(); // call base class init +} + +// Shaft angle calculation +// angle is in radians [rad] +float MagneticSensorAnalog::getSensorAngle(){ + // raw data from the sensor + raw_count = getRawCount(); + return ( (float) (raw_count) / (float)cpr) * _2PI; +} + +// function reading the raw counter of the magnetic sensor +int MagneticSensorAnalog::getRawCount(){ + return analogRead(pinAnalog); +} diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.h b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.h new file mode 100644 index 0000000..6f787b9 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorAnalog.h @@ -0,0 +1,51 @@ +#ifndef MAGNETICSENSORANALOG_LIB_H +#define MAGNETICSENSORANALOG_LIB_H + +#include "Arduino.h" +#include "../common/base_classes/Sensor.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" + +/** + * This sensor has been tested with AS5600 running in 'analog mode'. This is where output pin of AS6000 is connected to an analog pin on your microcontroller. + * This approach is very simple but you may more accurate results with MagneticSensorI2C if that is also supported as its skips the DAC -> ADC conversion (ADC supports MagneticSensorI2C) + */ +class MagneticSensorAnalog: public Sensor{ + public: + /** + * MagneticSensorAnalog class constructor + * @param _pinAnalog the pin to read the PWM signal + */ + MagneticSensorAnalog(uint8_t _pinAnalog, int _min = 0, int _max = 0); + + + /** sensor initialise pins */ + void init(); + + int pinAnalog; //!< encoder hardware pin A + + // Encoder configuration + Pullup pullup; + + // implementation of abstract functions of the Sensor class + /** get current angle (rad) */ + float getSensorAngle() override; + /** raw count (typically in range of 0-1023), useful for debugging resolution issues */ + int raw_count; + + private: + int min_raw_count; + int max_raw_count; + int cpr; + int read(); + + /** + * Function getting current angle register value + * it uses angle_register variable + */ + int getRawCount(); + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.cpp b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.cpp new file mode 100644 index 0000000..ac2b273 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.cpp @@ -0,0 +1,156 @@ +#include "MagneticSensorI2C.h" + +/** Typical configuration for the 12bit AMS AS5600 magnetic sensor over I2C interface */ +MagneticSensorI2CConfig_s AS5600_I2C = { + .chip_address = 0x36, + .bit_resolution = 12, + .angle_register = 0x0C, + .data_start_bit = 11 +}; + +/** Typical configuration for the 12bit AMS AS5048 magnetic sensor over I2C interface */ +MagneticSensorI2CConfig_s AS5048_I2C = { + .chip_address = 0x40, // highly configurable. if A1 and A2 are held low, this is probable value + .bit_resolution = 14, + .angle_register = 0xFE, + .data_start_bit = 15 +}; + + +// MagneticSensorI2C(uint8_t _chip_address, float _cpr, uint8_t _angle_register_msb) +// @param _chip_address I2C chip address +// @param _bit_resolution bit resolution of the sensor +// @param _angle_register_msb angle read register +// @param _bits_used_msb number of used bits in msb +MagneticSensorI2C::MagneticSensorI2C(uint8_t _chip_address, int _bit_resolution, uint8_t _angle_register_msb, int _bits_used_msb){ + // chip I2C address + chip_address = _chip_address; + // angle read register of the magnetic sensor + angle_register_msb = _angle_register_msb; + // register maximum value (counts per revolution) + cpr = _powtwo(_bit_resolution); + + // depending on the sensor architecture there are different combinations of + // LSB and MSB register used bits + // AS5600 uses 0..7 LSB and 8..11 MSB + // AS5048 uses 0..5 LSB and 6..13 MSB + // used bits in LSB + lsb_used = _bit_resolution - _bits_used_msb; + // extraction masks + lsb_mask = (uint8_t)( (2 << lsb_used) - 1 ); + msb_mask = (uint8_t)( (2 << _bits_used_msb) - 1 ); + wire = &Wire; +} + +MagneticSensorI2C::MagneticSensorI2C(MagneticSensorI2CConfig_s config){ + chip_address = config.chip_address; + + // angle read register of the magnetic sensor + angle_register_msb = config.angle_register; + // register maximum value (counts per revolution) + cpr = _powtwo(config.bit_resolution); + + int bits_used_msb = config.data_start_bit - 7; + lsb_used = config.bit_resolution - bits_used_msb; + // extraction masks + lsb_mask = (uint8_t)( (2 << lsb_used) - 1 ); + msb_mask = (uint8_t)( (2 << bits_used_msb) - 1 ); + wire = &Wire; +} + +void MagneticSensorI2C::init(TwoWire* _wire){ + + wire = _wire; + + // I2C communication begin + wire->begin(); + + this->Sensor::init(); // call base class init +} + +// Shaft angle calculation +// angle is in radians [rad] +float MagneticSensorI2C::getSensorAngle(){ + // (number of full rotations)*2PI + current sensor angle + return ( getRawCount() / (float)cpr) * _2PI ; +} + + + +// function reading the raw counter of the magnetic sensor +int MagneticSensorI2C::getRawCount(){ + return (int)MagneticSensorI2C::read(angle_register_msb); +} + +// I2C functions +/* +* Read a register from the sensor +* Takes the address of the register as a uint8_t +* Returns the value of the register +*/ +int MagneticSensorI2C::read(uint8_t angle_reg_msb) { + // read the angle register first MSB then LSB + byte readArray[2]; + uint16_t readValue = 0; + // notify the device that is aboout to be read + wire->beginTransmission(chip_address); + wire->write(angle_reg_msb); + currWireError = wire->endTransmission(false); + + // read the data msb and lsb + wire->requestFrom(chip_address, (uint8_t)2); + for (byte i=0; i < 2; i++) { + readArray[i] = wire->read(); + } + + // depending on the sensor architecture there are different combinations of + // LSB and MSB register used bits + // AS5600 uses 0..7 LSB and 8..11 MSB + // AS5048 uses 0..5 LSB and 6..13 MSB + readValue = ( readArray[1] & lsb_mask ); + readValue += ( ( readArray[0] & msb_mask ) << lsb_used ); + return readValue; +} + +/* +* Checks whether other devices have locked the bus. Can clear SDA locks. +* This should be called before sensor.init() on devices that suffer i2c slaves locking sda +* e.g some stm32 boards with AS5600 chips +* Takes the sda_pin and scl_pin +* Returns 0 for OK, 1 for other master and 2 for unfixable sda locked LOW +*/ +int MagneticSensorI2C::checkBus(byte sda_pin, byte scl_pin) { + + pinMode(scl_pin, INPUT_PULLUP); + pinMode(sda_pin, INPUT_PULLUP); + delay(250); + + if (digitalRead(scl_pin) == LOW) { + // Someone else has claimed master!"); + return 1; + } + + if(digitalRead(sda_pin) == LOW) { + // slave is communicating and awaiting clocks, we are blocked + pinMode(scl_pin, OUTPUT); + for (byte i = 0; i < 16; i++) { + // toggle clock for 2 bytes of data + digitalWrite(scl_pin, LOW); + delayMicroseconds(20); + digitalWrite(scl_pin, HIGH); + delayMicroseconds(20); + } + pinMode(sda_pin, INPUT); + delayMicroseconds(20); + if (digitalRead(sda_pin) == LOW) { + // SDA still blocked + return 2; + } + _delay(1000); + } + // SDA is clear (HIGH) + pinMode(sda_pin, INPUT); + pinMode(scl_pin, INPUT); + + return 0; +} diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.h b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.h new file mode 100644 index 0000000..f8b189f --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorI2C.h @@ -0,0 +1,84 @@ +#ifndef MAGNETICSENSORI2C_LIB_H +#define MAGNETICSENSORI2C_LIB_H + +#include "Arduino.h" +#include +#include "../common/base_classes/Sensor.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" + +struct MagneticSensorI2CConfig_s { + int chip_address; + int bit_resolution; + int angle_register; + int data_start_bit; +}; +// some predefined structures +extern MagneticSensorI2CConfig_s AS5600_I2C,AS5048_I2C; + +#if defined(TARGET_RP2040) +#define SDA I2C_SDA +#define SCL I2C_SCL +#endif + + +class MagneticSensorI2C: public Sensor{ + public: + /** + * MagneticSensorI2C class constructor + * @param chip_address I2C chip address + * @param bits number of bits of the sensor resolution + * @param angle_register_msb angle read register msb + * @param _bits_used_msb number of used bits in msb + */ + MagneticSensorI2C(uint8_t _chip_address, int _bit_resolution, uint8_t _angle_register_msb, int _msb_bits_used); + + /** + * MagneticSensorI2C class constructor + * @param config I2C config + */ + MagneticSensorI2C(MagneticSensorI2CConfig_s config); + + static MagneticSensorI2C AS5600(); + + /** sensor initialise pins */ + void init(TwoWire* _wire = &Wire); + + // implementation of abstract functions of the Sensor class + /** get current angle (rad) */ + float getSensorAngle() override; + + /** experimental function to check and fix SDA locked LOW issues */ + int checkBus(byte sda_pin , byte scl_pin ); + + /** current error code from Wire endTransmission() call **/ + uint8_t currWireError = 0; + + private: + float cpr; //!< Maximum range of the magnetic sensor + uint16_t lsb_used; //!< Number of bits used in LSB register + uint8_t lsb_mask; + uint8_t msb_mask; + + // I2C variables + uint8_t angle_register_msb; //!< I2C angle register to read + uint8_t chip_address; //!< I2C chip select pins + + // I2C functions + /** Read one I2C register value */ + int read(uint8_t angle_register_msb); + + /** + * Function getting current angle register value + * it uses angle_register variable + */ + int getRawCount(); + + /* the two wire instance for this sensor */ + TwoWire* wire; + + +}; + + +#endif diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.cpp b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.cpp new file mode 100644 index 0000000..cf21164 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.cpp @@ -0,0 +1,117 @@ +#include "MagneticSensorPWM.h" +#include "Arduino.h" + +/** MagneticSensorPWM(uint8_t _pinPWM, int _min, int _max) + * @param _pinPWM the pin that is reading the pwm from magnetic sensor + * @param _min_raw_count the smallest expected reading + * @param _max_raw_count the largest expected reading + */ +MagneticSensorPWM::MagneticSensorPWM(uint8_t _pinPWM, int _min_raw_count, int _max_raw_count){ + + pinPWM = _pinPWM; + + cpr = _max_raw_count - _min_raw_count + 1; + min_raw_count = _min_raw_count; + max_raw_count = _max_raw_count; + + // define if the sensor uses interrupts + is_interrupt_based = false; + + // define as not set + last_call_us = _micros(); +} + + +/** MagneticSensorPWM(uint8_t _pinPWM, int freqHz, int _total_pwm_clocks, int _min_pwm_clocks, int _max_pwm_clocks) + * + * Constructor that computes the min and max raw counts based on the PWM frequency and the number of PWM clocks in one period + * + * @param _pinPWM the pin that is reading the pwm from magnetic sensor + * @param freqHz the frequency of the PWM signal, in Hz, e.g. 115, 230, 460 or 920 for the AS5600, depending on the PWM frequency setting + * @param _total_pwm_clocks the total number of PWM clocks in one period, e.g. 4351 for the AS5600 + * @param _min_pwm_clocks the 0 value returned by the sensor, in PWM clocks, e.g. 128 for the AS5600 + * @param _max_pwm_clocks the largest value returned by the sensor, in PWM clocks, e.g. 4223 for the AS5600 + */ +MagneticSensorPWM::MagneticSensorPWM(uint8_t _pinPWM, int freqHz, int _total_pwm_clocks, int _min_pwm_clocks, int _max_pwm_clocks){ + + pinPWM = _pinPWM; + + min_raw_count = lroundf(1000000.0f/freqHz/_total_pwm_clocks*_min_pwm_clocks); + max_raw_count = lroundf(1000000.0f/freqHz/_total_pwm_clocks*_max_pwm_clocks); + cpr = max_raw_count - min_raw_count + 1; + + // define if the sensor uses interrupts + is_interrupt_based = false; + + min_elapsed_time = 1.0f/freqHz; // set the minimum time between two readings + + // define as not set + last_call_us = _micros(); +} + + + +void MagneticSensorPWM::init(){ + + // initial hardware + pinMode(pinPWM, INPUT); + raw_count = getRawCount(); + pulse_timestamp = _micros(); + + this->Sensor::init(); // call base class init +} + +// Sensor update function. Safely copy volatile interrupt variables into Sensor base class state variables. +void MagneticSensorPWM::update() { + if (is_interrupt_based) + noInterrupts(); + Sensor::update(); + angle_prev_ts = pulse_timestamp; // Timestamp of actual sample, before the time-consuming PWM communication + if (is_interrupt_based) + interrupts(); +} + +// get current angle (rad) +float MagneticSensorPWM::getSensorAngle(){ + // raw data from sensor + raw_count = getRawCount(); + if (raw_count > max_raw_count) raw_count = max_raw_count; + if (raw_count < min_raw_count) raw_count = min_raw_count; + return( (float) (raw_count - min_raw_count) / (float)cpr) * _2PI; +} + + +// read the raw counter of the magnetic sensor +int MagneticSensorPWM::getRawCount(){ + if (!is_interrupt_based){ // if it's not interrupt based read the value in a blocking way + pulse_timestamp = _micros(); // ideally this should be done right at the rising edge of the pulse + pulse_length_us = pulseIn(pinPWM, HIGH, 1200); // 1200us timeout, should this be configurable? + } + return pulse_length_us; +} + + +void MagneticSensorPWM::handlePWM() { + // unsigned long now_us = ticks(); + unsigned long now_us = _micros(); + + // if falling edge, calculate the pulse length + if (!digitalRead(pinPWM)) { + pulse_length_us = now_us - last_call_us; + pulse_timestamp = last_call_us; // angle was sampled at the rising edge of the pulse, so use that timestamp + } + + // save the currrent timestamp for the next call + last_call_us = now_us; + is_interrupt_based = true; // set the flag to true +} + +// function enabling hardware interrupts of the for the callback provided +// if callback is not provided then the interrupt is not enabled +void MagneticSensorPWM::enableInterrupt(void (*doPWM)()){ + // declare it's interrupt based + is_interrupt_based = true; + + // enable interrupts on pwm input pin + attachInterrupt(digitalPinToInterrupt(pinPWM), doPWM, CHANGE); +} \ No newline at end of file diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.h b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.h new file mode 100644 index 0000000..48492c8 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorPWM.h @@ -0,0 +1,73 @@ +#ifndef MAGNETICSENSORPWM_LIB_H +#define MAGNETICSENSORPWM_LIB_H + +#include "Arduino.h" +#include "../common/base_classes/Sensor.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" + +// This sensor has been tested with AS5048a running in PWM mode. + +class MagneticSensorPWM: public Sensor{ + public: + /** MagneticSensorPWM(uint8_t _pinPWM, int _min, int _max) + * @param _pinPWM the pin that is reading the pwm from magnetic sensor + * @param _min_raw_count the smallest expected reading + * @param _max_raw_count the largest expected reading + */ + MagneticSensorPWM(uint8_t _pinPWM,int _min = 0, int _max = 0); + /** MagneticSensorPWM(uint8_t _pinPWM, int freqHz, int _total_pwm_clocks, int _min_pwm_clocks, int _max_pwm_clocks) + * + * Constructor that computes the min and max raw counts based on the PWM frequency and the number of PWM clocks in one period + * + * @param _pinPWM the pin that is reading the pwm from magnetic sensor + * @param freqHz the frequency of the PWM signal, in Hz, e.g. 115, 230, 460 or 920 for the AS5600, depending on the PWM frequency setting + * @param _total_pwm_clocks the total number of PWM clocks in one period, e.g. 4351 for the AS5600 + * @param _min_pwm_clocks the 0 value returned by the sensor, in PWM clocks, e.g. 128 for the AS5600 + * @param _max_pwm_clocks the largest value returned by the sensor, in PWM clocks, e.g. 4223 for the AS5600 + */ + MagneticSensorPWM(uint8_t _pinPWM, int freqHz, int _total_pwm_clocks, int _min_pwm_clocks, int _max_pwm_clocks); + + // initialize the sensor hardware + void init(); + + int pinPWM; + + // Interrupt-safe update + void update() override; + + // get current angle (rad) + float getSensorAngle() override; + + // pwm handler + void handlePWM(); + void enableInterrupt(void (*doPWM)()); + unsigned long pulse_length_us; + + private: + // raw count (typically in range of 0-1023) + int raw_count; + int min_raw_count; + int max_raw_count; + int cpr; + + // flag saying if the readings are interrupt based or not + bool is_interrupt_based; + + int read(); + + /** + * Function getting current angle register value + * it uses angle_register variable + */ + int getRawCount(); + + // time tracking variables + unsigned long last_call_us; + // unsigned long pulse_length_us; + unsigned long pulse_timestamp; + + +}; + +#endif diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.cpp b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.cpp new file mode 100644 index 0000000..52febc3 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.cpp @@ -0,0 +1,161 @@ + +#include "MagneticSensorSPI.h" + +/** Typical configuration for the 14bit AMS AS5147 magnetic sensor over SPI interface */ +MagneticSensorSPIConfig_s AS5147_SPI = { + .spi_mode = SPI_MODE1, + .clock_speed = 1000000, + .bit_resolution = 14, + .angle_register = 0x3FFF, + .data_start_bit = 13, + .command_rw_bit = 14, + .command_parity_bit = 15 +}; +// AS5048 and AS5047 are the same as AS5147 +MagneticSensorSPIConfig_s AS5048_SPI = AS5147_SPI; +MagneticSensorSPIConfig_s AS5047_SPI = AS5147_SPI; + +/** Typical configuration for the 14bit MonolithicPower MA730 magnetic sensor over SPI interface */ +MagneticSensorSPIConfig_s MA730_SPI = { + .spi_mode = SPI_MODE0, + .clock_speed = 1000000, + .bit_resolution = 14, + .angle_register = 0x0000, + .data_start_bit = 15, + .command_rw_bit = 0, // not required + .command_parity_bit = 0 // parity not implemented +}; + + +// MagneticSensorSPI(int cs, float _bit_resolution, int _angle_register) +// cs - SPI chip select pin +// _bit_resolution sensor resolution bit number +// _angle_register - (optional) angle read register - default 0x3FFF +MagneticSensorSPI::MagneticSensorSPI(int cs, int _bit_resolution, int _angle_register){ + + chip_select_pin = cs; + // angle read register of the magnetic sensor + angle_register = _angle_register ? _angle_register : DEF_ANGLE_REGISTER; + // register maximum value (counts per revolution) + cpr = _powtwo(_bit_resolution); + spi_mode = SPI_MODE1; + clock_speed = 1000000; + bit_resolution = _bit_resolution; + + command_parity_bit = 15; // for backwards compatibilty + command_rw_bit = 14; // for backwards compatibilty + data_start_bit = 13; // for backwards compatibilty +} + +MagneticSensorSPI::MagneticSensorSPI(MagneticSensorSPIConfig_s config, int cs){ + chip_select_pin = cs; + // angle read register of the magnetic sensor + angle_register = config.angle_register ? config.angle_register : DEF_ANGLE_REGISTER; + // register maximum value (counts per revolution) + cpr = _powtwo(config.bit_resolution); + spi_mode = config.spi_mode; + clock_speed = config.clock_speed; + bit_resolution = config.bit_resolution; + + command_parity_bit = config.command_parity_bit; // for backwards compatibilty + command_rw_bit = config.command_rw_bit; // for backwards compatibilty + data_start_bit = config.data_start_bit; // for backwards compatibilty +} + +void MagneticSensorSPI::init(SPIClass* _spi){ + spi = _spi; + // 1MHz clock (AMS should be able to accept up to 10MHz) + settings = SPISettings(clock_speed, MSBFIRST, spi_mode); + //setup pins + pinMode(chip_select_pin, OUTPUT); + //SPI has an internal SPI-device counter, it is possible to call "begin()" from different devices + spi->begin(); + // do any architectures need to set the clock divider for SPI? Why was this in the code? + //spi->setClockDivider(SPI_CLOCK_DIV8); + digitalWrite(chip_select_pin, HIGH); + + this->Sensor::init(); // call base class init +} + +// Shaft angle calculation +// angle is in radians [rad] +float MagneticSensorSPI::getSensorAngle(){ + return (getRawCount() / (float)cpr) * _2PI; +} + +// function reading the raw counter of the magnetic sensor +int MagneticSensorSPI::getRawCount(){ + return (int)MagneticSensorSPI::read(angle_register); +} + +// SPI functions +/** + * Utility function used to calculate even parity of word + */ +byte MagneticSensorSPI::spiCalcEvenParity(word value){ + byte cnt = 0; + byte i; + + for (i = 0; i < 16; i++) + { + if (value & 0x1) cnt++; + value >>= 1; + } + return cnt & 0x1; +} + + /* + * Read a register from the sensor + * Takes the address of the register as a 16 bit word + * Returns the value of the register + */ +word MagneticSensorSPI::read(word angle_register){ + + word command = angle_register; + + if (command_rw_bit > 0) { + command = angle_register | (1 << command_rw_bit); + } + if (command_parity_bit > 0) { + //Add a parity bit on the the MSB + command |= ((word)spiCalcEvenParity(command) << command_parity_bit); + } + + //SPI - begin transaction + spi->beginTransaction(settings); + + //Send the command + digitalWrite(chip_select_pin, LOW); + spi->transfer16(command); + digitalWrite(chip_select_pin,HIGH); + +#if defined(ESP_H) && defined(ARDUINO_ARCH_ESP32) // if ESP32 board + delayMicroseconds(50); // why do we need to delay 50us on ESP32? In my experience no extra delays are needed, on any of the architectures I've tested... +#else + delayMicroseconds(1); // delay 1us, the minimum time possible in plain arduino. 350ns is the required time for AMS sensors, 80ns for MA730, MA702 +#endif + + //Now read the response + digitalWrite(chip_select_pin, LOW); + word register_value = spi->transfer16(0x00); + digitalWrite(chip_select_pin, HIGH); + + //SPI - end transaction + spi->endTransaction(); + + register_value = register_value >> (1 + data_start_bit - bit_resolution); //this should shift data to the rightmost bits of the word + + const static word data_mask = 0xFFFF >> (16 - bit_resolution); + + return register_value & data_mask; // Return the data, stripping the non data (e.g parity) bits +} + +/** + * Closes the SPI connection + * SPI has an internal SPI-device counter, for each init()-call the close() function must be called exactly 1 time + */ +void MagneticSensorSPI::close(){ + spi->end(); +} + + diff --git a/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.h b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.h new file mode 100644 index 0000000..03ebde4 --- /dev/null +++ b/firmware/lib/Arduino-FOC/src/sensors/MagneticSensorSPI.h @@ -0,0 +1,84 @@ +#ifndef MAGNETICSENSORSPI_LIB_H +#define MAGNETICSENSORSPI_LIB_H + + +#include "Arduino.h" +#include +#include "../common/base_classes/Sensor.h" +#include "../common/foc_utils.h" +#include "../common/time_utils.h" + +#define DEF_ANGLE_REGISTER 0x3FFF + +struct MagneticSensorSPIConfig_s { + int spi_mode; + long clock_speed; + int bit_resolution; + int angle_register; + int data_start_bit; + int command_rw_bit; + int command_parity_bit; +}; +// typical configuration structures +extern MagneticSensorSPIConfig_s AS5147_SPI,AS5048_SPI,AS5047_SPI, MA730_SPI; + +class MagneticSensorSPI: public Sensor{ + public: + /** + * MagneticSensorSPI class constructor + * @param cs SPI chip select pin + * @param bit_resolution sensor resolution bit number + * @param angle_register (optional) angle read register - default 0x3FFF + */ + MagneticSensorSPI(int cs, int bit_resolution, int angle_register = 0); + /** + * MagneticSensorSPI class constructor + * @param config SPI config + * @param cs SPI chip select pin + */ + MagneticSensorSPI(MagneticSensorSPIConfig_s config, int cs); + + /** sensor initialise pins */ + void init(SPIClass* _spi = &SPI); + + // implementation of abstract functions of the Sensor class + /** get current angle (rad) */ + float getSensorAngle() override; + + // returns the spi mode (phase/polarity of read/writes) i.e one of SPI_MODE0 | SPI_MODE1 | SPI_MODE2 | SPI_MODE3 + int spi_mode; + + /* returns the speed of the SPI clock signal */ + long clock_speed; + + + private: + float cpr; //!< Maximum range of the magnetic sensor + // spi variables + int angle_register; //!< SPI angle register to read + int chip_select_pin; //!< SPI chip select pin + SPISettings settings; //!< SPI settings variable + // spi functions + /** Stop SPI communication */ + void close(); + /** Read one SPI register value */ + word read(word angle_register); + /** Calculate parity value */ + byte spiCalcEvenParity(word value); + + /** + * Function getting current angle register value + * it uses angle_register variable + */ + int getRawCount(); + + int bit_resolution; //!< the number of bites of angle data + int command_parity_bit; //!< the bit where parity flag is stored in command + int command_rw_bit; //!< the bit where read/write flag is stored in command + int data_start_bit; //!< the the position of first bit + + SPIClass* spi; +}; + + +#endif

+ + + +