#include <SoftwareSerial.h>

const byte rxPin = 0;
const byte txPin = 1;

// set up a new serial object
SoftwareSerial mySerial (rxPin, txPin);

// this constant won't change. It's the pin number of the sensor's output:
const int pingPin = PA3;

void setup() {
// initialize serial communication:
mySerial.begin(4800);
}

void loop() {
// establish variables for duration of the ping, and the distance result
// in inches and centimeters:
long duration, cm;

// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(50);
digitalWrite(pingPin, HIGH);
delayMicroseconds(50);
digitalWrite(pingPin, LOW);

// The same pin is used to read the signal from the PING))): a HIGH pulse
// whose duration is the time (in microseconds) from the sending of the ping
// to the reception of its echo off of an object.
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

// convert the time into a distance
cm = microsecondsToCentimeters(duration);

mySerial.print (cm);

if (cm < 5) {
digitalWrite (PA7, HIGH); // mixer ON
delay(500);
digitalWrite (9, HIGH); // H1 ON
digitalWrite (8, HIGH); // H2 ON
digitalWrite (10, HIGH); // H3 ON
digitalWrite (PA4, HIGH); // relay ON
delay(2000);
digitalWrite(9, LOW); // H1 OFF
digitalWrite(PA4, LOW); // relay OFF
delay(1000);
digitalWrite(8, LOW); // H2 OFF
digitalWrite(10, LOW); // H3 OFF
delay(2000);

digitalWrite (PA7, LOW); // mixer OFF
delay(1000);
digitalWrite (PA1, HIGH); // shutter clockwise ON
delay(6000);
digitalWrite (PA1, LOW); // shutter OFF
delay(1500);
digitalWrite (PA0, HIGH); // shutter anticlockwise ON
delay(5500);
digitalWrite (PA0, LOW); // shutter OFF
delay(500);
}
}

long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}