|
|
```
|
|
|
#include <Wire.h>
|
|
|
// this constant won't change. It's the pin number of the sensor's output:
|
|
|
const int pingPin = PA2;
|
|
|
long duration, cm1;
|
|
|
int i = 0;
|
|
|
|
|
|
//On the Arduino Uno (and other ATmega based boards) an int stores a 16-bit (2-byte) value.
|
|
|
//This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).
|
|
|
//Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647.
|
|
|
long cm0 = 100;
|
|
|
int state = 0;
|
|
|
|
|
|
void setup() {
|
|
|
// inits
|
|
|
DDRB |= (1 << PB2); // set data direction register for PB2 as output
|
|
|
Wire.begin(1); /* join i2c bus with address 1 */
|
|
|
Wire.onReceive(receiveEvent); /* register receive event */
|
|
|
Wire.onRequest(requestEvent); /* register request event */
|
|
|
}
|
|
|
|
|
|
void loop() {
|
|
|
// establish variables for duration of the ping, and the distance result
|
|
|
// in inches and centimeters:
|
|
|
// 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(2);
|
|
|
digitalWrite(pingPin, HIGH);
|
|
|
delayMicroseconds(5);
|
|
|
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
|
|
|
|
|
|
cm1 = microsecondsToCentimeters(duration);
|
|
|
|
|
|
if (cm1 < 20 && state != 1) {
|
|
|
state = 1;
|
|
|
PORTB |= (1 << PB2); // turn on led
|
|
|
i++;
|
|
|
delay(500);
|
|
|
}
|
|
|
|
|
|
if (cm1 > 20) {
|
|
|
state = 0;
|
|
|
PORTB = 0; // turn off led
|
|
|
}
|
|
|
|
|
|
cm0 = cm1;
|
|
|
delay(100);
|
|
|
}
|
|
|
|
|
|
// function that executes whenever data is received from master
|
|
|
void receiveEvent(int howMany) {
|
|
|
while (0 < Wire.available())
|
|
|
{
|
|
|
int k = Wire.read();
|
|
|
if (k == 5) {
|
|
|
i = 0;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// function that executes whenever data is requested from master
|
|
|
void requestEvent() {
|
|
|
Wire.write(i); /*send on request */
|
|
|
}
|
|
|
|
|
|
long microsecondsToCentimeters(long microseconds) {
|
|
|
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
|
|
|
// The ping travels out and back, so to find the distance of the object we
|
|
|
// take half of the distance travelled.
|
|
|
return microseconds / 29 / 2;
|
|
|
}
|
|
|
``` |
|
|
\ No newline at end of file |