//based on Elena Cardiel FabAcademy 2019 //FabAcademy 2019 - Jesús López //include the serial communication library #include SoftwareSerial Serial_sonar(0, 1); // tx, rx //define variables and pin numbers #define echoPin 9 // echo conencted to PB1 #define trigPin 10 // trigger connected to PB0 long duration, distance; boolean abierto; //serial communication and pins for input and output void setup() { Serial_sonar.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); abierto = false; } // the actual program loop void loop() { //send the pulse digitalWrite(trigPin, LOW); delayMicroseconds(1000); //each 1 sec we send a pulse digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); //we measuse the time duration = pulseIn(echoPin, HIGH); //formula for cm feedback. The sound speed is 340m/s = 29us/cm. //we divide the pulse time by 58, the time that the pulse takes to go and come back. distance = duration / 58; int msg; if (distance < 10) { if (!abierto) { msg = 1; Serial_sonar.write(msg); abierto = true; } } else { if (abierto) { msg = 0; Serial_sonar.write(msg); abierto = false; } } //send the information to the Serial Monitor //Serial_sonar.write(distance); delay(100); }