/*
HC-SR04 Ultrasonic Distance Sensor with 7 Segment Display
NTC Temperature Sensor
PushButton to switch displays
+ communication module (optional)
*/
#include <SevSeg.h>
#define TRIG_PIN A3
#define ECHO_PIN A4
#define MAX_DIST 300
#define TEMP_PIN A7
#define BTN_1 A6
#define BETA 3950
#define SOUND_VELOCITY 0.034321 / 2 // 0.03313 //for 0 st. C
SevSeg sevseg;
uint16_t duration = 0;
uint32_t interval = 0;
float distance = 0;
float procent;
int tempAnalog;
float temperature;
int btn = 0;
int btn_status;
void setup()
{
//Serial.begin(115200); // Starts the serial communication
uint8_t numDigits = 4;
// DIG1, DIG2, DIG3, DIG4
uint8_t digitPins[] = {2, 3, 4, 5};
// A, B, C, D, E, F, G, DP
uint8_t segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
uint8_t displayType = COMMON_ANODE; // (Common Anode or Common Cathode)
bool resistorsOnSegments = false;
bool updateWithDelays = false;
bool leadingZeros = false;
bool disableDecPoint = false;
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(TEMP_PIN, INPUT);
pinMode(BTN_1, INPUT_PULLUP);
sevseg.begin(displayType, numDigits, digitPins, segmentPins, resistorsOnSegments,
updateWithDelays, leadingZeros, disableDecPoint);
sevseg.setBrightness(90);
}
void loop()
{
if ((millis() - interval) >= 100) {
interval = millis();
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(5);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read time of the trig and echo pins
duration = pulseIn(ECHO_PIN, HIGH);
tempAnalog = analogRead(TEMP_PIN);
temperature = 1 / (log(1 / (1023. / tempAnalog - 1)) / BETA + 1.0 / 298.15) - 273.15;
// Calculates the distance
//distance = (duration / 2) / 29;
distance = duration * SOUND_VELOCITY;
// Calculate reverse % so if distance is high
// procentage is low
procent = (1-(distance/MAX_DIST))*100;
if ( procent < 0 ) { procent = -1; }
btn_status = analogRead(BTN_1);
if (btn_status == 0 && btn == 0){
btn = 15;
}
if (btn > 0) {
sevseg.setNumberF(temperature,1);
btn = btn -1;
}else{
sevseg.setNumber(procent);
btn = 0;
}
//Serial.println("Distance (cm): " + String(distance) );
//Serial.println("Temperature: " + String(temperature) );
}
sevseg.refreshDisplay();
}