Sonar sensor on ATtiny85 using Arduino

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

https://fleshandmachines.wordpress.com/2012/09/10/a-tiny-arduino-project/

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);
  }

  delay(100);
}

long readSonar(uint8_t pin)
{
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
  delayMicroseconds(2);
  digitalWrite(pin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pin, LOW);

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

References:

http://hlt.media.mit.edu/?p=1695

https://fleshandmachines.wordpress.com/2011/08/30/sonar-sensor-sen136b5b-from-seeed-studio-with-arduino/

Advertisements

One thought on “Sonar sensor on ATtiny85 using Arduino

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s