Using Ultrasonic Sensor With an ATtiny2313

I want to use a ping ultrasonic sensor which has 4 pins (VCC, Trig, Echo, Gnd) with an ATtiny2313, is it possible to use it with that? I need it to turn on and off 2 motors, when distance is 15cm or more, both motors stay on and when its less than that then 1 motor turns off.

This is the code I am using.

#define ECHOPIN 2
#define TRIGPIN 1

int MotorPin1 = 3;
int MotorPin2 = 4;

void setup()
{
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(MotorPin1, OUTPUT);
  pinMode(MotorPin2, OUTPUT);
}

void loop()
{
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);
  
  
  float distance = pulseIn(ECHOPIN, HIGH);
  distance = distance/56;
  
  
  if (distance >= 15)
  {
   digitalWrite(MotorPin1, HIGH);
   digitalWrite(MotorPin2, HIGH);
   delay(100);
   digitalWrite(MotorPin1, LOW);
   digitalWrite(MotorPin2, LOW);
  } 
 
  if (distance < 15)
  {
   digitalWrite(MotorPin1, HIGH);
   delay(100);
   digitalWrite(MotorPin1, LOW);
  }
}

But for some reason when I connect everything it doesnt work :frowning:

I am connecting the motors to Pin 5 and 6 out of the 20 pins available on the ATtiny2313

(Image = http://avrprogrammers.com/attiny2313bd.php)

Plz help
Thanks

float distance = pulseIn(ECHOPIN, HIGH);

Why "float"?

If you use this core:

https://code.google.com/p/arduino-tiny/

You will be able to make some debug prints that could show what's going on.
I can tell you that your distance variable is between 0 and 3, which is probably not what you think

And as AWOL says why use floats ?
You are using almost the entire flash 1982 bytes out of 2048

What else can we use instead of float? Its a variable so I thought we need to use float.
Does it take up a lot of space?
Thanks

@Erni
I already have that core installed how can I make debug prints? What do you mean by the distance variable is between 0 and 3 are you talking about the trig and echo pins? I am confused now…

What else can we use instead of float? Its a variable so I thought we need to use float.
Does it take up a lot of space?

You could use an integer datatype as a variable, just like the integer variables (why weren't they qualified as "const"?) for the motor pins.
pulseIn returns an unsigned long, IIRC.
A float itself takes only four bytes of RAM, but handling floats requires a lot more code space.

What do you mean by the distance variable is between 0 and 3 are you talking about the trig and echo pins? I am confused now...

.

Sorry for the confusion. I just tried your sketch and printed the value of your variable: distance
With my ultrasonic sensor the results were between 0 and 3, depending on the distance, but ofcourse you may get other results.

how can I make debug prints?

Take a look at this:
http://www.ernstc.dk/arduino/tinycom.html