基质喷涂
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.3 KiB

  1. //
  2. // Created by iflyt on 2025/3/13.
  3. //
  4. #include "laser_control.h"
  5. #include <cmath>
  6. #include <stm32f4xx_hal.h>
  7. #include "tim_pwm.h"
  8. #include <base/zbasic.h>
  9. LaserControl::LaserControl() {
  10. }
  11. LaserControl::~LaserControl() {
  12. }
  13. void LaserControl::init(const bool isFlip) {
  14. this->initGPIO();
  15. this->isFlip_ = isFlip;
  16. this->powerOff();
  17. }
  18. void LaserControl::powerOn() {
  19. isPowerOn_ = true;
  20. HAL_GPIO_WritePin(LASER_EN_PORT, LASER_EN_PIN, GPIO_PIN_RESET);
  21. }
  22. void LaserControl::powerOff() {
  23. isPowerOn_ = false;
  24. this->dutyCycle_ = calculateDutyCycle(MIN_POWER);
  25. this->setDutyCycle(dutyCycle_);
  26. HAL_GPIO_WritePin(LASER_EN_PORT, LASER_EN_PIN, GPIO_PIN_SET);
  27. }
  28. void LaserControl::setPower(double power) {
  29. power_ = power;
  30. const int32_t abs_voltage = fabs(power);
  31. this->dutyCycle_ = calculateDutyCycle(abs_voltage);
  32. this->setDutyCycle(dutyCycle_);
  33. ZLOGI("[LASER]", "SET DUTY %d", this->dutyCycle_);
  34. this->powerOn();
  35. }
  36. void LaserControl::initGPIO() {
  37. GPIO_InitTypeDef GPIO_InitStruct = {0};
  38. // 使能 GPIO 时钟
  39. __HAL_RCC_GPIOE_CLK_ENABLE();
  40. // 配置使能引脚
  41. GPIO_InitStruct.Pin = LASER_EN_PIN;
  42. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  43. GPIO_InitStruct.Pull = GPIO_NOPULL;
  44. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  45. HAL_GPIO_Init(LASER_EN_PORT, &GPIO_InitStruct);
  46. }
  47. void LaserControl::setDutyCycle(uint32_t dutyCycle) const {
  48. if(dutyCycle == minVDutyCycle) {
  49. bsp_SetTIMOutPWM(LASER_PWM_PORT, LASER_PWM_PIN, LASER_TIMER_HANDLE, LASER_TIMER_CHANNEL, 0, 0);
  50. }
  51. else if (dutyCycle == maxVDutyCycle){
  52. bsp_SetTIMOutPWM(LASER_PWM_PORT, LASER_PWM_PIN, LASER_TIMER_HANDLE, LASER_TIMER_CHANNEL, 0, 10000);
  53. }
  54. else {
  55. bsp_SetTIMOutPWM(LASER_PWM_PORT, LASER_PWM_PIN, LASER_TIMER_HANDLE, LASER_TIMER_CHANNEL, standardFrequency_, dutyCycle);
  56. }
  57. }
  58. int LaserControl::calculateDutyCycle(int voltage) const {
  59. if (voltage < MIN_POWER) {
  60. voltage = MIN_POWER;
  61. } else if (voltage > MAX_POWER) {
  62. voltage = MAX_POWER;
  63. }
  64. if (isFlip_) {
  65. // 反转关系
  66. return maxVDutyCycle - (voltage - MIN_POWER) * (maxVDutyCycle - minVDutyCycle) / (MAX_POWER - MIN_POWER);
  67. } else {
  68. // 正常关系
  69. return minVDutyCycle + (voltage - MIN_POWER) * (maxVDutyCycle - minVDutyCycle) / (MAX_POWER - MIN_POWER);
  70. }
  71. }