Почему продолжительность всегда 0?C++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Почему продолжительность всегда 0?

Сообщение Anonymous »

Я новичок в C ++ и сделал заголовок и файл CPP, чтобы прочитать расстояние моего ультразвукового датчика, который находится на вершине сервопривода моего Arduino. Цель состояла в том, чтобы позволить сервоприводу повернуть и прочитать расстояние и создать своего рода радар. Я сделал этот проект с платформой, но я получаю только 0 в качестве расстояния и продолжительности от серийного монитора. Единственное, что я попробовал, - это печать переменной расстояния и продолжительности, которую я не мог придумать ни о каком другом методе отладки. < /P>
//Header File
#ifndef SonciSensor_h
#define SonciSensor_h

class SonicSensor
{
private:
int TRIG_PIN; // Trigger pin
int ECHO_PIN; // Echo pin
const float SOUND_SPEED = 0.0343; // Speed of sound in cm/µs
float distance = 0.0; // Distance measured by the ultrasonic sensor (cm)
long duration = 0.0; // Duration for ultrasonic pulse to return (µs)
public:
SonicSensor(); // Constructor
float getDistance();
void attach(int TRIG_PIN, int ECHO_PIN); // Attach the ultrasonic sensor to the pins
void printDistance(); // Print the distance value to the Serial Monitor
};

#endif

//CPP File
#include
#include //Include the Arduino library

SonicSensor::SonicSensor()
{
}

float SonicSensor::getDistance()
{

// Send the Ultra Sonic Wave Pulses (8)
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// get duration and calculate distance
duration = pulseIn(ECHO_PIN, HIGH, 20000); // Get the duration the Echo pin was set to High aka. the time the Ultrasonic pulse travelled (µs)

distance = (duration * SOUND_SPEED) / 2; // Calculate the distance by multiplying duration by speed of sound (cm/µs)
// and halving it because we need the time it took to hit the object
// and not the time it took to hit the object and travel back to the sensor

return distance;
}

void SonicSensor::printDistance()
{
// Print valid distances
if (distance < 400)
{
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
Serial.print("duration: ");
Serial.println(duration);
}
else
{
Serial.println("Faulty distance reading");
}
}

void SonicSensor::attach(int TRIG_PIN, int ECHO_PIN)
{
pinMode(TRIG_PIN, OUTPUT); // Set the Trigger pin as an Output
pinMode(ECHO_PIN, INPUT); // Set the Echo pin as an Input
}


Подробнее здесь: https://stackoverflow.com/questions/795 ... n-always-0
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»