Sonar sensor on ATtiny85 using Arduino

Not so long ago I did an experiment with an ATtiny85 and Arduino with 3 LEDs.

I set up a small piece of code that’s reading the measures from the sensor and turn on an LED accordingly.

As for the previous one I’m only using the Arduino to program the ATtiny85 chip and for power supply in the video.

A video of it in action:

The code running on the ATtiny85:

const int ledGreen = 3;
const int ledYellow = 1;
const int ledRed = 2;
const int pingPin = 0;

long duration = 0;
long cm = 0;

void setup() {                
  // initialize the digital pins as an output.
  pinMode(ledGreen, OUTPUT);     
  pinMode(ledYellow, OUTPUT);     
  pinMode(ledRed, OUTPUT);     

void loop() 
  cm = readSonar(pingPin);
  if(cm <= 5) // too close, RED   {     digitalWrite(ledGreen, LOW);     digitalWrite(ledYellow, LOW);     digitalWrite(ledRed, HIGH);   }   else if(cm > 5 && cm <= 20)   {     digitalWrite(ledRed, LOW);     digitalWrite(ledGreen, LOW);     digitalWrite(ledYellow, HIGH);   }   else if(cm > 20)
    digitalWrite(ledRed, LOW);
    digitalWrite(ledYellow, LOW);
    digitalWrite(ledGreen, HIGH);


long readSonar(uint8_t pin)
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
  digitalWrite(pin, HIGH);
  digitalWrite(pin, LOW);

  pinMode(pingPin, INPUT);
  duration = pulseIn(pin, HIGH);
  return duration / 29 / 2;


One thought on “Sonar sensor on ATtiny85 using Arduino

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.