Created
September 4, 2020 12:16
-
-
Save bplaat/b177c8fa4e29b46bbf1d99309d4a394d to your computer and use it in GitHub Desktop.
Introductieweek 2020-2021 - Arduino Presentatie - Demo 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // DEMO 3 - De afstand sensor | |
| // Laad servo bibliotheek | |
| #include <Servo.h> | |
| // De pins | |
| #define ECHO_PIN 2 | |
| #define TRIGGER_PIN 3 | |
| #define SERVO_PIN 9 | |
| // De max afstand dat de servo aangaat | |
| #define TRIGGER_AFSTAND_CM 20 | |
| // Een functie die milliseconden naar centimeter omzet | |
| uint32_t msToCm(uint32_t ms) { | |
| return ms / 29 / 2; | |
| } | |
| // Het servo object | |
| Servo servo; | |
| // De tijd en servo variablen | |
| uint32_t printTime; | |
| uint32_t servoTime; | |
| void setup() { | |
| // Begin serial communicatie | |
| Serial.begin(9600); | |
| // Begin en reset de servo | |
| servo.attach(SERVO_PIN); | |
| servo.write(0); | |
| // Zet pinmodes | |
| pinMode(ECHO_PIN, INPUT); | |
| pinMode(TRIGGER_PIN, OUTPUT); | |
| // Slaat de laatste tijden op | |
| printTime = millis(); | |
| servoTime = millis(); | |
| } | |
| void loop() { | |
| // Trigger de trigger pin | |
| digitalWrite(TRIGGER_PIN, LOW); | |
| delayMicroseconds(2); | |
| digitalWrite(TRIGGER_PIN, HIGH); | |
| delayMicroseconds(10); | |
| digitalWrite(TRIGGER_PIN, LOW); | |
| // Lees de duratie | |
| uint32_t duration = pulseIn(ECHO_PIN, HIGH); | |
| uint32_t cm = msToCm(duration); | |
| // Print de afstand 5 keer per minuut | |
| if (millis() - printTime >= 200) { | |
| printTime = millis(); | |
| Serial.print(cm); | |
| Serial.println(" cm"); | |
| } | |
| // Start servo als men te dichtbij is | |
| if (cm < TRIGGER_AFSTAND_CM) { | |
| if (millis() - servoTime >= 500) { | |
| servoTime = millis(); | |
| if (servo.read() == 180) { | |
| servo.write(0); | |
| } else { | |
| servo.write(180); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment