Arduino – Sensore di Parcheggio (sketch)

Qui potete trovare l’articolo
Il video può essere visualizzato anche su youtube
Supportami su Patreon!
Seguimi anche sulla pagina di facebook! e sul canale di youtube

Di seguito trovate il codice sorgente:


const int echoPin = 13;
const int triggerPin = 12;
const int piezoPin = 11;
const int greenLedPin = 10;
const int redLedPin = 9;
const int analogControllerPin = A0;
const int switchPin = 2;
unsigned long previousTime = 0;
long timeDiff = 0;
int analogController = 0;
int distance = 0;
int beeped = 0;
int previousSwitchState = 0;
int switchState = 0;

void setup()
{
Serial.begin(9600);
pinMode(echoPin, INPUT);
pinMode(triggerPin, OUTPUT);
pinMode(piezoPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
pinMode(switchPin, INPUT);
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, HIGH);
tone(piezoPin, 330);
delay(200);
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, LOW);
noTone(piezoPin);
delay(200);
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, HIGH);
tone(piezoPin, 330);
delay(200);
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, LOW);
noTone(piezoPin);
delay(200);
}

void loop()
{
unsigned long currentTime = millis();
switchState = digitalRead(switchPin);
Serial.println(switchState);
if(switchState == HIGH)
{
delay(1000);
if(previousSwitchState == 0)
{
previousSwitchState = 1;
} else
{
previousSwitchState = 0;
}
}

if(previousSwitchState == 1)
{
digitalWrite(greenLedPin, HIGH);
analogController = analogRead(analogControllerPin);
Serial.print("Analaog Control: ");
Serial.println(analogController);
if(analogController < 500) { digitalWrite(redLedPin, HIGH); distance = rangeControl(); Serial.println(distance); timeDiff = currentTime - previousTime; beeped = beep(timeDiff, distance); if(beeped == 1) { previousTime = currentTime; } } else { digitalWrite(redLedPin, LOW); noTone(piezoPin); } } else { digitalWrite(greenLedPin, LOW); delay(250); } } int rangeControl() { int duration = 0; int distance = 0; digitalWrite(triggerPin, LOW); delayMicroseconds(2); digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); duration = pulseIn(echoPin, HIGH); distance = duration/59; return distance; } int beep(long timeDiff, int distance) { long interval = 15 * (distance - 2); if(timeDiff > interval)
{
tone(piezoPin, 330);
delay(15);
return 1;
} else
{
noTone(piezoPin);
return 0;
}

}

2 thoughts on “Arduino – Sensore di Parcheggio (sketch)

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *