Check out this Arduino Vending Machine!
Move your hand in front of the Ultrasonic Sensor and see what happens.
You are more than welcome to take a souvenir from the chest (3D printed gear)!
Here is the code our team used for the Arduino Vending Machine:
#include <Servo.h>
#define TRIG_PIN 5
#define ECHO_PIN 6
#define SERVO_PIN 7
Servo servo;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
servo.attach(SERVO_PIN);
servo.write(0);
Serial.begin(115200); // Set Baud rate
}
void loop() {
static int current_pos = 0; // Keep track of current position of the servo motor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(5);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
int distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
static int changed = 0;
if (distance < 4) {
if(changed == 0) {
if (current_pos == 0) { // If current position is 0, move to 46
servo.write(46);
current_pos = 46;
} else {
servo.write(0);
current_pos = 0;
}
changed = 1;
}
} else {
changed = 0;
}
delay(200);
}