Teensy Afstandsensor


Code voor het uitlezen van de HC-SR04:


// Define Trig and Echo pin:
#define trigPin 14
#define echoPin 15

// Define variables:
long duration;
int distance;

void setup() {
  // Define inputs and outputs:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  //Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);

  // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  // Calculate the distance:
  distance = duration * 0.034 / 2;

  if (distance > 400) {
    //filter alles boven de 400 cm want de sensor kan niet verder kijken dan dat
    Serial.println("non-valid-distance: " + String(distance));
  } else { 
    // Print the distance on the Serial Monitor (Ctrl+Shift+M):
    Serial.print("distance: ");
    Serial.println(distance);

    //distance 0 - 400
    //verklein het bereik van de afstand naar het bereik van MIDI (0-127)
    int MIDIDistance = map(distance, 0, 400, 0, 127);

    //CC berichten sturen over de USB midi verbinding
    usbMIDI.sendControlChange(1, MIDIDistance, 0);
    delay(50);
  }

}