Skip to content

Instantly share code, notes, and snippets.

@ticapix
Created July 24, 2015 16:06
Show Gist options
  • Select an option

  • Save ticapix/86ea00a03925b91bfae5 to your computer and use it in GitHub Desktop.

Select an option

Save ticapix/86ea00a03925b91bfae5 to your computer and use it in GitHub Desktop.
#include <TimerOne.h>
const uint8_t SYMBOLS[] =
{
0xC0, // 0
0xF9, // 1
0xA4, // 2
0xB0, // 3
0x99, // 4
0x92, // 5
0x82, // 6
0xF8, // 7
0x80, // 8
0x90, // 9
0b10001000, // A
0b10000011, // b
0xC6, // C
0xA1, // d
0b10000110, // E
0b10001110, // F
0b00111111 // -.
};
#define PIN_SCLK 11 // 4DIGITS - CLOCK
#define PIN_RCLK 12 // 4DIGITS - LATCH
#define PIN_DIO 13 // 4DIGITS - DATA
#define PIN_TRIG 9 // SR04 - TRIG
#define PIN_ECHO 10 // SR04 - ECHO
// declared volatile because used in two different places
volatile uint8_t DIGITS[4] = {0, 0, 0, 0};
unsigned long echo_start = 0;
uint8_t digit = 0;
// update one digit at a time
void update_display(void)
{
shiftOut(PIN_DIO, PIN_SCLK, MSBFIRST, DIGITS[digit]);
shiftOut(PIN_DIO, PIN_SCLK, MSBFIRST, 1 << digit);
digitalWrite(PIN_RCLK, LOW);
digitalWrite(PIN_RCLK, HIGH);
digit = ++digit % 4;
}
void echo_interrupt()
{
switch (digitalRead(PIN_ECHO))
{
case HIGH: // start of the echo pulse
echo_start = micros();
break;
case LOW: // end of the echo pulse
unsigned long duration = micros() - echo_start;
update_value(duration / 58.2); // calculate distance in cm
break;
}
}
inline void update_value(unsigned long val) {
for (uint8_t i = 0; i < 4; i++) {
DIGITS[i] = SYMBOLS[val % 10];
val /= 10;
}
}
void setup ()
{
// setup pin for the 4digits display
pinMode(PIN_SCLK, OUTPUT);
pinMode(PIN_RCLK, OUTPUT);
pinMode(PIN_DIO, OUTPUT);
// setup for the HC-SR04 sensor
pinMode(PIN_TRIG, OUTPUT);
digitalWrite(PIN_TRIG, LOW);
pinMode(PIN_ECHO, INPUT);
// setup the timer to update the display
Timer1.initialize(5000); // 5ms
Timer1.attachInterrupt(update_display);
// setup callacbk for the echo signal from the HC-SR04 sensor
attachInterrupt(0, echo_interrupt, CHANGE);
}
void loop()
{
// trigger a distance measurement
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// and wait
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment