Hola a todos!
Estoy realizando un proyecto de medidas de distancia con el sensor de ultrasonidos PING))), pero tengo un problema.
Aquí el codigo y luego la explicación:
//Variables
int incomingByte;
const int SERVOMOTOR = 9;
const int pingPin = 22;
int n=90, data=1,m=0;
float Degrees, cm,cm_escriure,NumEscan;
long duration;
void setup()
{
pinMode(SERVOMOTOR,OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 0) { // Check to see if there is a new message
incomingByte = Serial.read(); // Put the serial input into the message
if (incomingByte == 'B'){
analogWrite(SERVOMOTOR,90);
data = 1;
Degrees = 0.00;
n=90;
}
switch (incomingByte ){
case '1':
NumEscan = 1.00;
break;
case '2':
NumEscan = 2.00;
break;
case '3':
NumEscan = 3.00;
break;
case '4':
NumEscan = 4.00;
break;
case '5':
NumEscan = 5.00;
break;
}
if (incomingByte == 'A'){ // If a capitol A is received
//For move the motor
analogWrite(SERVOMOTOR,n);
delay(400);
//Sensor
cm_escriure=0;
m=0;
while(m<NumEscan){
pinMode(pingPin,OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
cm_escriure = cm_escriure + cm;
//Serial.println(cm);
//Serial.println(cm_escriure);
m++;
}
cm_escriure = cm_escriure / NumEscan;
Serial.print(NumEscan);
Serial.print("Data: ");
Serial.print(data);
Serial.print("; Degrees: ");
Serial.print(Degrees);
Serial.print("; Distance: ");
Serial.print(cm_escriure);
Serial.print(";");
Serial.print(NumEscan);
Serial.println();
data++;
Degrees = Degrees + 13.3333333333;
n++;
if (n==118)
{n=90;
Degrees=0.00;
data=1;
analogWrite(SERVOMOTOR,n);}
}}
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29.0 / 2.0;
}
Para controlar el Arduino lo hago mediante un programa externo, Visual Studio 2010 con c#, pero esto no es el problema.
En la parte de lectura de la distancia hay la posibilidad de haver una merdida, dos, tres .. hasta 5 y luego hacer la mediana para enviar la dada correctamente.
Lo que mes pasa es algo muy raro, me hace la mediana mal, pero cuando "activo" las siguientes comandas:
//Serial.println(cm);
//Serial.println(cm_escriure);
funciona correctamente y hace la mediana y lo envia bien!
Alguien me puede decir que puede pasar.. es que no tengo ni idea!!
Si quedan dudas, las resolveré! Graciaaaaaaaaaaaaaaaaaaaaas!