两个HC-SR04超声波传感器和360度伺服电机问题

对微控制器编码非常陌生,所以请不要攻击我。

两个HC-SR04超声波传感器和360度伺服电机问题

我使用连续 360 度伺服电机来抬起打开滑动面板作为小狗门。门上有一个用于向上位置的停止微动开关,在底部有一个用于向下位置的微动开关。门两侧各有两个 HC-SR04 超声波传感器。如果检测到距离门 20 厘米处有物体,门就会打开并保持打开状态 15 秒,只有在 20 厘米处没有检测到物体时才会关闭。物联网技术知识微信公众号:计算机程序吧物联网技术知识微信公众号:计算机程序吧

 

了解更多,请关注我们微信公众号:计算机程序吧

我在使用这段代码时遇到困难,我不知道出了什么问题,它只是不起作用。舵机抖动,有时转,有时停不下来,到处都是。我不知道如何开始调试这个。

#include <Servo.h>

const int trigPinLeft = 2;   // Trig pin for left ultrasonic sensor
const int echoPinLeft = 3;   // Echo pin for left ultrasonic sensor
const int trigPinRight = 4;  // Trig pin for right ultrasonic sensor
const int echoPinRight = 5;  // Echo pin for right ultrasonic sensor

const int upLimitSwitch = 6;   // Pin for up position limit switch
const int downLimitSwitch = 7; // Pin for down position limit switch

const int servoPin = 9;    // Pin for continuous servo motor

const int detectionDistance = 20; // Distance threshold for object detection in cm
const int doorOpenTime = 15000;   // Time the door stays open in milliseconds (15 seconds)

Servo doorServo;  // Servo motor object

void setup() {
  pinMode(trigPinLeft, OUTPUT);
  pinMode(echoPinLeft, INPUT);
  pinMode(trigPinRight, OUTPUT);
  pinMode(echoPinRight, INPUT);
  pinMode(upLimitSwitch, INPUT_PULLUP);
  pinMode(downLimitSwitch, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(upLimitSwitch) == LOW) {
    // Door is in the up position, check for object in front
    if (isObstacleDetected()) {
      doorServo.attach(servoPin);
      rotateCounterClockwiseUntilDownLimit();
      doorServo.detach();
    }
  } else if (digitalRead(downLimitSwitch) == LOW) {
    // Door is in the down position, check for object in front
    if (isObstacleDetected()) {
      doorServo.attach(servoPin);
      rotateClockwiseUntilUpLimit();
      doorServo.detach();
    }
  }
}

bool isObstacleDetected() {
  int distanceLeft = getDistance(trigPinLeft, echoPinLeft);
  int distanceRight = getDistance(trigPinRight, echoPinRight);
  return (distanceLeft <= detectionDistance || distanceRight <= detectionDistance);
}

int getDistance(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  return pulseIn(echoPin, HIGH) * 0.034 / 2;
}

void rotateCounterClockwiseUntilDownLimit() {
  while (digitalRead(downLimitSwitch) == HIGH) {
    doorServo.write(0);  // Rotate the servo counter-clockwise at full speed
  }
  //doorServo.write(90);  // Stop the servo when the downLimitSwitch is reached
}

void rotateClockwiseUntilUpLimit() {
  while (digitalRead(upLimitSwitch) == HIGH) {
    doorServo.write(180);  // Rotate the servo clockwise at full speed
  }
  //doorServo.write(90);  // Stop the servo when the upLimitSwitch is reached
}