/*
Arduino | general-help
j.enifer. — Today at 10:47 AM
hi! im trying to follow a wiring diagram for an ulrasound sensor
and tilt switch + tilt detector
*/
#include <LiquidCrystal.h>
// pin constants
const int RS = 12, EN = 11, D4 = 10, D5 = 9, D6 = 8, D7 = 7;
const int ECHO_PIN = 3;
const int TRIG_PIN = 4;
const int LED_PIN = 5;
const int TILT_PIN = 6;
const int LIGHT_PIN = A0;
// create a parallel LCD object called "lcd"
LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);
void getDistance() {
char distBuffer[16];
// send "ping"
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(5);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// listen for echo
long duration = pulseIn(ECHO_PIN, HIGH);
// convert the time into a distance
int cm = int(((duration / 2) * 0.0343) + 0.5); // Divide by 29.1 or multiply by 0.0343
snprintf(distBuffer, 16, "Range: %3d cm", cm);
lcd.setCursor(0, 0);
lcd.print(distBuffer);
}
void getLight() {
char liteBuffer[12];
int sensorValue = analogRead(LIGHT_PIN);
int liteValue = map(sensorValue, 0, 1023, 100, 0); // range reversed
snprintf(liteBuffer, 12, "Lite: %3d%%", liteValue);
lcd.setCursor(0, 1);
lcd.print(liteBuffer);
}
void getTilt() {
int tilt = !digitalRead(TILT_PIN);
digitalWrite(LED_PIN, tilt);
lcd.setCursor(11, 1);
lcd.print(tilt ? "TILT!" : " ");
}
void setup() {
// start serial
Serial.begin(115200);
// start parallel LCD
lcd.begin(16, 2);
// set pin modes
pinMode(TILT_PIN, INPUT_PULLUP);
pinMode(ECHO_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
// start up message on parallel LCD
lcd.setCursor(3, 0);
lcd.print("Sensor Demo");
lcd.setCursor(6, 1);
lcd.print("V1.0");
delay(2000);
lcd.clear();
}
void loop() {
getDistance();
getLight();
getTilt();
}