Я новичок в 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
Почему продолжительность всегда 0? ⇐ C++
Программы на C++. Форум разработчиков
1744510288
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
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79571129/why-is-duration-always-0[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия