This week Mashi and I are working on the prototype of the midterm project: a Halloween trick or treat installation. I was working on the object to attract user’s attention. The idea is to make a skull which can interact with people pass by by using the distance/IR detection.

This is the prototype I made:

distance detection skull prototype

code:

#include <Servo.h>
Servo myservo;
int ledPin = 10;
int servoPin = 9;
int triggerPin = 11;
int echoPin = 12;
long duration, dist;
bool isOn = false;
float lastTriggerTime = 0;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);
  myservo.attach(servoPin);
}

void loop() {
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(5);
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  dist = (duration / 2) / 29.1;

  Serial.println(" cm");
  if (dist < 30 && !isOn) {
    for (int i = 0; i < 3; i++) {
      digitalWrite(ledPin, HIGH);
      myservo.write(0);
      delay(300);
      
      myservo.write(60);
      digitalWrite(ledPin, LOW);
      delay(300);
    }
    
    digitalWrite(ledPin, HIGH);
    myservo.write(0);
    delay(500);
    digitalWrite(ledPin, LOW);
    
    isOn = true;
    lastTriggerTime = millis();
  }
  if (isOn && millis() > lastTriggerTime + 3000) {
    isOn = false;
  }
}

Some challenges I faced in the process is that I feel hard to make the servo and led move at the same time (or I can not control the light on time of the led correctly). As you can see in the video above, the led lighting time is not sync with the jaw’s movement. What I want is like this:

My goal is to light up the led whenever the servo is moving, however, I found the moving time of the servo is longer than I thought. As a result the led’s on time is not sync with the servo’s movement.

Besides, since I am not sure if I can make aync function calls in Arduino, I am not sure if there is a better way to control multiple outputs.