/*
Serial Event example
When new serial data arrives, this sketch adds it to a String.
When a newline is received, the loop prints the string and clears it.
A good test for this is to try it with a GPS receiver that sends out
NMEA 0183 sentences.
NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
other ATmega32U4 based boards.
created 9 May 2011
by Tom Igoe
This example code is in the public domain.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/SerialEvent
*/
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
const int trigPin = 10;
const int echoPin = 11;
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
pinMode(trigPin, OUTPUT); // Ustawiamy pin TRIG jako wyjście
pinMode(echoPin, INPUT); // Ustawiamy pin ECHO jako wejście
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
myservo.write(inputString.toInt());
// clear the string:
inputString = "";
stringComplete = false;
}
long duration, distance; // Zmienne do przechowywania czasu trwania fali i
odległości
// Wysyłamy sygnał ultradźwiękowy
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Odbieramy czas trwania fali ultradźwiękowej
duration = pulseIn(echoPin, HIGH);
// Obliczamy odległość
distance = (duration / 2) / 29.1; // Obliczamy odległość w centymetrach
// Wyświetlamy odległość w monitorze portu szeregowego
Serial.print("Odleglosc: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Czekamy pół sekundy przed kolejnym odczytem
}
/*
SerialEvent occurs whenever a new data comes in the hardware serial RX. This
routine is run between each time loop() runs, so using delay inside loop can
delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}