I'm fairly new to electronics, and I've just got myself some sensors to experiment with using the Arduino Uno. I've been using an ultrasonic range sensor (http://www.seeedstudio.com/depot/datasheet/Seeed%20Ultrasonic%20Sensor%20datasheet.pdf), which has a Vcc, GND, and SIG pin.
I assumed the data would be sent as an analog signal, in the same way as you'd read a pot connected to an input on the arduino. This was wrong, and I found some code that gives me a value in the serial monitor for the distance to the sensor. I'm pleased it now works, but I'd really like to understand it properly so that I can improve my knowledge. I'm an experienced programmer, so I understand the code side of things. Just not the concepts of switching inputs with outputs. This is the code, found on the arduino playground:
// * Copyleft 2007 Jason Ch
This code returns the distance in Inches... I think it's more accurate than other code I have seen online and returns more usable results.
Remove the *.39 to return cm instead of inches. You could make float ultrasoundValue = 0;
but then you can't print it unless you transfer it into another type, but it could be used for further calculations.
unsigned long echo = 0;
int ultraSoundSignal = 9; // Ultrasound signal pin
unsigned long ultrasoundValue = 0;
void setup()
{
Serial.begin(9600);
pinMode(ultraSoundSignal,OUTPUT);
}
unsigned long ping()
{
pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff
pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
echo = pulseIn(ultraSoundSignal, HIGH); // Listen for echo
ultrasoundValue = (echo / 58.138); // Convert to CM
return ultrasoundValue;
}
void loop()
{
int x = 0;
x = ping();
Serial.println(x);
delay(250); //delay 1/4 seconds.
}
Why is the same pin used as an input and an output? Why is a low pulse sent, followed by a 2 microsecond gap, followed by a high pulse and then a 5 microsecond gap? What is the pullup resistor?
If someone could explain these things to me, or redirect me to information about this kind of communication, it would be greatly appreciated. Sorry for my inexperienced questions! ;D