Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save OsoianMarcel/5ee6e3711b8c754cc24e8360cba18867 to your computer and use it in GitHub Desktop.
Basic Example - How to use Ultrasonic SR04 distance sensor with Atmega8 and Timer0 (8Mhz)
// Notice: 8 Mhz frequency is expected
#define SONIC_DDR DDRC
#define SONIC_PORT PORTC
#define SONIC_PIN PINC
#define SONIC_TRG_PIN PINC0
#define SONIC_ECHO_PIN PINC1
#include <avr/io.h>
#include <util/delay.h>
// Setup sonic pins
void sonic_init(void) {
SONIC_DDR |= 1 << SONIC_TRG_PIN; // Set trigger PIN to output
SONIC_PORT &= ~(1 << SONIC_TRG_PIN); // Set trigger PIN to low
SONIC_DDR &= ~(1 << SONIC_ECHO_PIN); // Set echo PIN to input
}
// Get the distance
// By using timer0 and 8Mhz clock maximum calculated distance is ~139 CM
uint8_t sonic_get_distance_cm(void) {
// Trigger sensor measurement
SONIC_PORT |= (1 << SONIC_TRG_PIN);
_delay_us(10);
SONIC_PORT &= ~(1 << SONIC_TRG_PIN);
// Wait until echo goes up
while(((SONIC_PIN >> SONIC_ECHO_PIN) & 1) == 0);
// Calculate distance by calculating response time
TCNT0 = 0; // Reset timer0
TCCR0 |= 1 << CS02; // Start timer0 (256)
// Wait until echo goes low or timer0 overflow occurred
while(((TIFR >> TOV0) & 1) == 0 && ((SONIC_PIN >> SONIC_ECHO_PIN) & 1) == 1);
TCCR0 = 0; // Stop timer0
// If overflow occurred then return 255
if ((TIFR >> TOV0) & 1) {
TIFR |= 1 << TOV0;
return 255;
}
// Return calculated distance
return TCNT0 * 0.5488; // 0.000032 * (34300 * 0.5) = 0.5488
}
int main(void)
{
sonic_init();
uint8_t dist_cm;
while (1)
{
dist_cm = sonic_get_distance_cm();
// TODO: Use the "dist_cm" variable distance as you want
_delay_ms(333);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment