Context
I've started digging into Arduino and different type of sensors which is fun, but I'm worried that that my coding is too explicit. I've lots of experience for coding corporate programs, though it is not in C/C++. I don't consider myself a beginner, but I think something is wrong.
Blocks
I'd place my code in this section. It is using PING))) sensor to detect how far an object is based on the travel time of an emitted ultra-sonic signal. This sketch is taken from the TinkerCad website which can be found here: tinkercad.com.
/*
Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return. The length of the returning pulse is proportional to the distance of the object from the sensor.
The circuit:
* +V connection of the PING))) attached to +5V
* GND connection attached to ground
* SIG connection attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
This example code is in the public domain.
*/
const int speedOfSoundInAirInMetersPerSecond = 343;
const float speedOfSoundInAirInCentimeterPerMicrosecond =
speedOfSoundInAirInMetersPerSecond / 10000.0;
const float centimeterToInchRatio = 2.54;
int inches = 0;
int cm = 0;
long readTravelTimeInMicroseconds(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
// I had to divided that speed by 2 because
// I'm only interested in the time which took
// signal to reach an object. I don't need to know
// how much distance we covered by the signal to the object and back.
cm = (speedOfSoundInAirInCentimeterPerMicrosecond / 2)
* readTravelTimeInMicroseconds(7, 7);
inches = (cm / centimeterToInchRatio);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.println("cm");
delay(100);
}
My thoughts
Am I not being too explicit? I've learnt over the years that it is always better to beexplicit. But, am I not going overboard here?
Are there styles and conventions, styles I should follow when working with Arduino or electronics of this type? My question concerns with the technical side of the code.