NBW5520是筋膜枪电机,该电机最高转速3300rpm,包含正反转控制及pwm转速控制
(占空比0,速度最大,占空比50%,转速越1800rpm)
2024-04-12T08:46:28.png

// #include <Arduino.h>

// // 定义引脚
// const int motorPin = 4; // 电机引脚
// const int feedbackPin = 2; // 反馈线引脚

// // 定义变量
// volatile unsigned long pulseCount = 0; // 用于存储脉冲计数的变量
// volatile unsigned long lastPulseTime = 0; // 上一次脉冲时间

// // 函数原型
// void setup();
// void loop();
// void motorSpeedControl(int speed);
// unsigned long getMotorRPM();

// // 主函数
// void setup() {
//   pinMode(motorPin, OUTPUT); // 设置电机引脚为输出
//   pinMode(feedbackPin, INPUT_PULLUP); // 设置反馈线引脚为输入,并启用内部上拉电阻
//   attachInterrupt(digitalPinToInterrupt(feedbackPin), pulseCounter, RISING); // 当反馈线引脚上升沿时触发中断
//   Serial.begin(9600); // 初始化串口通信,波特率为9600
// }

// // 中断服务函数,用于计算脉冲计数
// void pulseCounter() {
//   unsigned long currentTime = micros(); // 获取当前时间(微秒)
//   if (currentTime - lastPulseTime >= 1000000) { // 如果两次脉冲之间的时间大于1秒
//     pulseCount++; // 增加脉冲计数
//     lastPulseTime = currentTime; // 更新上一次脉冲时间
//   }
// }

// // 控制电机转速的函数
// void motorSpeedControl(int speed) {
//   int pwmValue = map(speed, 0, 100, 0, 255); // 将速度映射到0-255的PWM值
//   analogWrite(motorPin, pwmValue); // 使用PWM控制电机转速
// }

// // 获取电机转速的函数(以RPM为单位)
// unsigned long getMotorRPM() {
//   return (pulseCount * 60000) / (1118 * pulseCount); // 使用 pulseCount 而不是 pulseCounter
// }

// // 主循环
// void loop() {
//   int speed = 50; // 设置电机转速为50%
//   motorSpeedControl(speed); // 控制电机转速
//   delay(1000); // 等待1秒

//   unsigned long rpm = getMotorRPM(); // 获取电机转速
//   Serial.print("Motor RPM: ");
//   Serial.println(rpm); // 打印电机转速
// }

#include <Arduino.h>

const int motorPWMPin = 5;  // 连接电机PWM控制器的引脚
const int feedbackPin = 4;  // 连接电机反馈线的引脚

volatile unsigned long pulseCount = 0;  // 记录反馈脉冲数量
unsigned long previousMillis = 0;  // 用于计算转速的上一个时间戳
const unsigned long interval = 200;  // 转速计算的时间间隔

void IRAM_ATTR handleInterrupt() {
  pulseCount++;
}

void setup() {
  Serial.begin(9600);
  pinMode(motorPWMPin, OUTPUT);
  pinMode(feedbackPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(feedbackPin), handleInterrupt, RISING);
}

void loop() {
  // 设置PWM控制电机转速
  analogWrite(motorPWMPin, 128);  // 0-255范围内的PWM值

  // 计算转速
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    float revolutions = pulseCount / 5.0;  // 每个脉冲对应半个转动
    float rpm = (revolutions / interval) * 60000.0;  // 每分钟的转速
    Serial.print("RPM: ");
    Serial.println(rpm);

    pulseCount = 0;  // 重置脉冲计数
    previousMillis = currentMillis;  // 更新时间戳
  }
}

发表评论