From 93385355638df07a6e69fc20048e22badb488820 Mon Sep 17 00:00:00 2001 From: Olli Graf Date: Thu, 30 May 2024 10:31:44 +0200 Subject: [PATCH] Ultraschallsensor HC-SR04 am Uno R4 Wifi. --- .../ultrasonic/ultrasonic.ino | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 arduino/ultrasonic-sensor/ultrasonic/ultrasonic.ino diff --git a/arduino/ultrasonic-sensor/ultrasonic/ultrasonic.ino b/arduino/ultrasonic-sensor/ultrasonic/ultrasonic.ino new file mode 100644 index 0000000..a9eaadb --- /dev/null +++ b/arduino/ultrasonic-sensor/ultrasonic/ultrasonic.ino @@ -0,0 +1,84 @@ +#include "Arduino_LED_Matrix.h" + +# define PIN_TRIGGER 9 // Pin 9: PIN_TRIGGER +# define PIN_ECHO 8 // Pin 8 Empfang + +// LED-Matrix leer initialisieren +byte led_frame[8][12] = {0}; +ArduinoLEDMatrix matrix; + +int maxDistance = 20; + +// Funktion, um die LED-Höhe basierend auf der gemessenen Entfernung zu berechnen +int calc_LED_Height(int distance) { + // Begrenze die Entfernung auf die maximale Entfernung + if (distance > maxDistance) { + distance = maxDistance; + } + // Berechne die Höhe der LEDs + int ledHeight = (distance * 8) / maxDistance; + return ledHeight; +} +void setup() { + + pinMode(PIN_TRIGGER, OUTPUT); + pinMode(PIN_ECHO, INPUT); + Serial.begin(9600); + matrix.begin(); +} + +int count = 0; // Spaltenzähler in der LED-Matrix + +// scroll the frame one column to the left +void scroll_matrix() { + for(int col=1; col < 12;col++) { + for(int row = 0;row <8;row++) { + led_frame[row][col-1] = led_frame[row][col]; + } + } + +} +// draw the LED frame +void draw_matrix(int leds, int count) { +if(count == 12) { + scroll_matrix(); +} + for(int l =7;l >leds; l--) { + led_frame[l][count] = 1; + } + matrix.renderBitmap(led_frame, 8, 12); + +} +void loop() +{ + long distance = 0; + + // Signalstörungen vermeiden, daher einmal kurz Trigger auf LOW + digitalWrite(PIN_TRIGGER, LOW); + delay(5); + + // Signal PIN_TRIGGER + digitalWrite(PIN_TRIGGER, HIGH); + delayMicroseconds(10); + digitalWrite(PIN_TRIGGER, LOW); + + // pulseIn -> Signallaufzeit messen + long Zeit = pulseIn(PIN_ECHO, HIGH); + + // distance in cm berechnen + distance = (Zeit / 2) * 0.03432; + + // distance anzeigen + Serial.print("distance in cm: "); + Serial.println(distance); + + // Anzahl der LEDs in der Spalte berechnen + int leds = calc_LED_Height(distance); + + // Matrix neuzeichnen + draw_matrix(leds,count); + delay(1000); + if( count < 12) { // maximal 12 Spalten, danach wird gescrollt. + count++; + } +} \ No newline at end of file