如何使用 Arduino 设置定时器

How to set a timer with Arduino

我正在使用 Arduino 开发板为一个学校项目编写直流电机的驱动程序。带有两个启动/停止按钮以及改变旋转方向的按钮。我还设置了一个条件,以便当我连接到 arduino 板的电流传感器给出的电流值停止高于某个值时电机停止。

我的问题是我不想在引擎启动时考虑第一个传感器电流测量值(输出值)。

我尝试使用计时器,但作为初学者我没能得到想要的结果。我如何编写一个计时器来确保当电机启动时,我的条件 (outputValue> = 0.3) 仅在第一次测量当前值后几秒钟后才有效?

const int controlPin1=2;
const int controlPin2=3;
const int enablePin=9;
const int directionSwitchPin=4;
const int onOffSwitchStateSwitchPin=5;
const int potPin=A0;

int onOffSwitchState=0;
int previousOnOffSwitchState=0;
int directionSwitchState=0;
int previousDirectionSwitchState=0;

int motorEnabled=0;
int motorSpeed=0;
int motorDirection=1;

const int analogInPin = A1; // Analog input pin that the current sensor is attached to
int sensorValue = 0;        // value read from the sensor
float outputValue = 0;

void setup() { 
  pinMode(directionSwitchPin, INPUT);
  pinMode(onOffSwitchStateSwitchPin, INPUT);
  pinMode(controlPin1, OUTPUT);
  pinMode(controlPin2, OUTPUT);
  pinMode(enablePin, OUTPUT);
  digitalWrite(enablePin, LOW);
  Serial.begin(9600);
}

void loop() {
  sensorValue = analogRead(analogInPin); // reads the sensor value and convert it
  outputValue = -(2.5 - (sensorValue * (5.0 / 1024.0)));

  onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
  delay(1);
  directionSwitchState = digitalRead(directionSwitchPin);
  motorSpeed=analogRead(potPin) / 4;

  if  (onOffSwitchState != previousOnOffSwitchState) {
    if (onOffSwitchState == HIGH) {
      motorEnabled=!motorEnabled;
    }
  }

  if (directionSwitchState != previousDirectionSwitchState) {
    if (directionSwitchState == HIGH) {
      motorDirection=!motorDirection;
    }
  }

  if (motorDirection == 1) {
    digitalWrite(controlPin1, HIGH);
    digitalWrite(controlPin2, LOW);
  } else {
    digitalWrite(controlPin1, LOW);
    digitalWrite(controlPin2, HIGH);
  }

  if (motorEnabled == 1) {
    analogWrite(enablePin, motorSpeed);
  } else {
    analogWrite(enablePin, 0);
  }

  if (outputValue >= 0.3) {
    digitalWrite(controlPin1, LOW);
    delay(5000);
  }

  previousDirectionSwitchState = directionSwitchState;
  previousOnOffSwitchState = onOffSwitchState;

  Serial.print("Current Sensor value= " ); // print results
  Serial.print(outputValue);      
  Serial.println("A");      
  delay(200);
}

在第一次测量时存储一个时间戳,如下所示:

unsigned long waitTime = 3000; // ms
unsigned long startTime = millis();

确保您在正确的范围内。

然后稍后,可能在一个循环中

if( millis() - startTime >= waitTime)

做你的事

https://www.arduino.cc/reference/en/language/functions/time/millis/