[hal, wpilib] Add initial systemcore counter implementation (#7723)

This commit is contained in:
Thad House
2025-01-28 08:58:34 -08:00
committed by GitHub
parent b799b285b3
commit 48ce2dcc8d
47 changed files with 201 additions and 4357 deletions

View File

@@ -1,322 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Counter.h"
#include <memory>
#include <hal/Counter.h>
#include <hal/FRCUsageReporting.h>
#include <wpi/NullDeleter.h>
#include <wpi/sendable/SendableBuilder.h>
#include <wpi/sendable/SendableRegistry.h>
#include "frc/AnalogTrigger.h"
#include "frc/DigitalInput.h"
#include "frc/Errors.h"
using namespace frc;
Counter::Counter(Mode mode) {
int32_t status = 0;
m_counter = HAL_InitializeCounter(static_cast<HAL_Counter_Mode>(mode),
&m_index, &status);
FRC_CheckErrorStatus(status, "InitializeCounter");
SetMaxPeriod(0.5_s);
HAL_Report(HALUsageReporting::kResourceType_Counter, m_index + 1, mode + 1);
wpi::SendableRegistry::Add(this, "Counter", m_index);
}
Counter::Counter(int channel) : Counter(kTwoPulse) {
SetUpSource(channel);
ClearDownSource();
}
Counter::Counter(DigitalSource* source) : Counter(kTwoPulse) {
SetUpSource(source);
ClearDownSource();
}
Counter::Counter(std::shared_ptr<DigitalSource> source) : Counter(kTwoPulse) {
SetUpSource(source);
ClearDownSource();
}
Counter::Counter(const AnalogTrigger& trigger) : Counter(kTwoPulse) {
SetUpSource(trigger.CreateOutput(AnalogTriggerType::kState));
ClearDownSource();
}
Counter::Counter(EncodingType encodingType, DigitalSource* upSource,
DigitalSource* downSource, bool inverted)
: Counter(encodingType,
std::shared_ptr<DigitalSource>(upSource,
wpi::NullDeleter<DigitalSource>()),
std::shared_ptr<DigitalSource>(downSource,
wpi::NullDeleter<DigitalSource>()),
inverted) {}
Counter::Counter(EncodingType encodingType,
std::shared_ptr<DigitalSource> upSource,
std::shared_ptr<DigitalSource> downSource, bool inverted)
: Counter(kExternalDirection) {
if (encodingType != k1X && encodingType != k2X) {
throw FRC_MakeError(err::ParameterOutOfRange,
"Counter only supports 1X and 2X quadrature decoding");
}
SetUpSource(upSource);
SetDownSource(downSource);
int32_t status = 0;
if (encodingType == k1X) {
SetUpSourceEdge(true, false);
HAL_SetCounterAverageSize(m_counter, 1, &status);
} else {
SetUpSourceEdge(true, true);
HAL_SetCounterAverageSize(m_counter, 2, &status);
}
FRC_CheckErrorStatus(status, "Counter constructor");
SetDownSourceEdge(inverted, true);
}
Counter::~Counter() {
if (m_counter != HAL_kInvalidHandle) {
try {
SetUpdateWhenEmpty(true);
} catch (const RuntimeError& e) {
e.Report();
}
}
}
void Counter::SetUpSource(int channel) {
SetUpSource(std::make_shared<DigitalInput>(channel));
wpi::SendableRegistry::AddChild(this, m_upSource.get());
}
void Counter::SetUpSource(AnalogTrigger* analogTrigger,
AnalogTriggerType triggerType) {
SetUpSource(std::shared_ptr<AnalogTrigger>(analogTrigger,
wpi::NullDeleter<AnalogTrigger>()),
triggerType);
}
void Counter::SetUpSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType) {
SetUpSource(analogTrigger->CreateOutput(triggerType));
}
void Counter::SetUpSource(DigitalSource* source) {
SetUpSource(std::shared_ptr<DigitalSource>(
source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetUpSource(std::shared_ptr<DigitalSource> source) {
m_upSource = source;
int32_t status = 0;
HAL_SetCounterUpSource(m_counter, source->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
source->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "SetUpSource");
}
void Counter::SetUpSource(DigitalSource& source) {
SetUpSource(std::shared_ptr<DigitalSource>(
&source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetUpSourceEdge(bool risingEdge, bool fallingEdge) {
if (m_upSource == nullptr) {
throw FRC_MakeError(
err::NullParameter,
"Must set non-nullptr UpSource before setting UpSourceEdge");
}
int32_t status = 0;
HAL_SetCounterUpSourceEdge(m_counter, risingEdge, fallingEdge, &status);
FRC_CheckErrorStatus(status, "SetUpSourceEdge");
}
void Counter::ClearUpSource() {
m_upSource.reset();
int32_t status = 0;
HAL_ClearCounterUpSource(m_counter, &status);
FRC_CheckErrorStatus(status, "ClearUpSource");
}
void Counter::SetDownSource(int channel) {
SetDownSource(std::make_shared<DigitalInput>(channel));
wpi::SendableRegistry::AddChild(this, m_downSource.get());
}
void Counter::SetDownSource(AnalogTrigger* analogTrigger,
AnalogTriggerType triggerType) {
SetDownSource(std::shared_ptr<AnalogTrigger>(
analogTrigger, wpi::NullDeleter<AnalogTrigger>()),
triggerType);
}
void Counter::SetDownSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType) {
SetDownSource(analogTrigger->CreateOutput(triggerType));
}
void Counter::SetDownSource(DigitalSource* source) {
SetDownSource(std::shared_ptr<DigitalSource>(
source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetDownSource(DigitalSource& source) {
SetDownSource(std::shared_ptr<DigitalSource>(
&source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetDownSource(std::shared_ptr<DigitalSource> source) {
m_downSource = source;
int32_t status = 0;
HAL_SetCounterDownSource(m_counter, source->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
source->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "SetDownSource");
}
void Counter::SetDownSourceEdge(bool risingEdge, bool fallingEdge) {
if (m_downSource == nullptr) {
throw FRC_MakeError(
err::NullParameter,
"Must set non-nullptr DownSource before setting DownSourceEdge");
}
int32_t status = 0;
HAL_SetCounterDownSourceEdge(m_counter, risingEdge, fallingEdge, &status);
FRC_CheckErrorStatus(status, "SetDownSourceEdge");
}
void Counter::ClearDownSource() {
m_downSource.reset();
int32_t status = 0;
HAL_ClearCounterDownSource(m_counter, &status);
FRC_CheckErrorStatus(status, "ClearDownSource");
}
void Counter::SetUpDownCounterMode() {
int32_t status = 0;
HAL_SetCounterUpDownMode(m_counter, &status);
FRC_CheckErrorStatus(status, "SetUpDownCounterMode");
}
void Counter::SetExternalDirectionMode() {
int32_t status = 0;
HAL_SetCounterExternalDirectionMode(m_counter, &status);
FRC_CheckErrorStatus(status, "SetExternalDirectionMode");
}
void Counter::SetSemiPeriodMode(bool highSemiPeriod) {
int32_t status = 0;
HAL_SetCounterSemiPeriodMode(m_counter, highSemiPeriod, &status);
FRC_CheckErrorStatus(status, "SetSemiPeriodMode to {}",
highSemiPeriod ? "true" : "false");
}
void Counter::SetPulseLengthMode(double threshold) {
int32_t status = 0;
HAL_SetCounterPulseLengthMode(m_counter, threshold, &status);
FRC_CheckErrorStatus(status, "SetPulseLengthMode");
}
void Counter::SetReverseDirection(bool reverseDirection) {
int32_t status = 0;
HAL_SetCounterReverseDirection(m_counter, reverseDirection, &status);
FRC_CheckErrorStatus(status, "SetReverseDirection to {}",
reverseDirection ? "true" : "false");
}
void Counter::SetSamplesToAverage(int samplesToAverage) {
if (samplesToAverage < 1 || samplesToAverage > 127) {
throw FRC_MakeError(
err::ParameterOutOfRange,
"Average counter values must be between 1 and 127, {} out of range",
samplesToAverage);
}
int32_t status = 0;
HAL_SetCounterSamplesToAverage(m_counter, samplesToAverage, &status);
FRC_CheckErrorStatus(status, "SetSamplesToAverage to {}", samplesToAverage);
}
int Counter::GetSamplesToAverage() const {
int32_t status = 0;
int samples = HAL_GetCounterSamplesToAverage(m_counter, &status);
FRC_CheckErrorStatus(status, "GetSamplesToAverage");
return samples;
}
int Counter::GetFPGAIndex() const {
return m_index;
}
void Counter::SetDistancePerPulse(double distancePerPulse) {
m_distancePerPulse = distancePerPulse;
}
double Counter::GetDistance() const {
return Get() * m_distancePerPulse;
}
double Counter::GetRate() const {
return m_distancePerPulse / GetPeriod().value();
}
int Counter::Get() const {
int32_t status = 0;
int value = HAL_GetCounter(m_counter, &status);
FRC_CheckErrorStatus(status, "Get");
return value;
}
void Counter::Reset() {
int32_t status = 0;
HAL_ResetCounter(m_counter, &status);
FRC_CheckErrorStatus(status, "Reset");
}
units::second_t Counter::GetPeriod() const {
int32_t status = 0;
double value = HAL_GetCounterPeriod(m_counter, &status);
FRC_CheckErrorStatus(status, "GetPeriod");
return units::second_t{value};
}
void Counter::SetMaxPeriod(units::second_t maxPeriod) {
int32_t status = 0;
HAL_SetCounterMaxPeriod(m_counter, maxPeriod.value(), &status);
FRC_CheckErrorStatus(status, "SetMaxPeriod");
}
void Counter::SetUpdateWhenEmpty(bool enabled) {
int32_t status = 0;
HAL_SetCounterUpdateWhenEmpty(m_counter, enabled, &status);
FRC_CheckErrorStatus(status, "SetUpdateWhenEmpty");
}
bool Counter::GetStopped() const {
int32_t status = 0;
bool value = HAL_GetCounterStopped(m_counter, &status);
FRC_CheckErrorStatus(status, "GetStopped");
return value;
}
bool Counter::GetDirection() const {
int32_t status = 0;
bool value = HAL_GetCounterDirection(m_counter, &status);
FRC_CheckErrorStatus(status, "GetDirection");
return value;
}
void Counter::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Counter");
builder.AddDoubleProperty("Value", [=, this] { return Get(); }, nullptr);
}

View File

@@ -1,203 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Ultrasonic.h"
#include <memory>
#include <utility>
#include <vector>
#include <hal/FRCUsageReporting.h>
#include <wpi/NullDeleter.h>
#include <wpi/sendable/SendableBuilder.h>
#include <wpi/sendable/SendableRegistry.h>
#include "frc/Counter.h"
#include "frc/DigitalInput.h"
#include "frc/DigitalOutput.h"
#include "frc/Errors.h"
#include "frc/Timer.h"
using namespace frc;
// Automatic round robin mode
std::atomic<bool> Ultrasonic::m_automaticEnabled{false};
std::vector<Ultrasonic*> Ultrasonic::m_sensors;
std::thread Ultrasonic::m_thread;
Ultrasonic::Ultrasonic(int pingChannel, int echoChannel)
: m_pingChannel(std::make_shared<DigitalOutput>(pingChannel)),
m_echoChannel(std::make_shared<DigitalInput>(echoChannel)),
m_counter(m_echoChannel) {
Initialize();
wpi::SendableRegistry::AddChild(this, m_pingChannel.get());
wpi::SendableRegistry::AddChild(this, m_echoChannel.get());
}
Ultrasonic::Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel)
: m_pingChannel(pingChannel, wpi::NullDeleter<DigitalOutput>()),
m_echoChannel(echoChannel, wpi::NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
if (!pingChannel) {
throw FRC_MakeError(err::NullParameter, "pingChannel");
}
if (!echoChannel) {
throw FRC_MakeError(err::NullParameter, "echoChannel");
}
Initialize();
}
Ultrasonic::Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel)
: m_pingChannel(&pingChannel, wpi::NullDeleter<DigitalOutput>()),
m_echoChannel(&echoChannel, wpi::NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
Initialize();
}
Ultrasonic::Ultrasonic(std::shared_ptr<DigitalOutput> pingChannel,
std::shared_ptr<DigitalInput> echoChannel)
: m_pingChannel(std::move(pingChannel)),
m_echoChannel(std::move(echoChannel)),
m_counter(m_echoChannel) {
Initialize();
}
Ultrasonic::~Ultrasonic() {
// Delete the instance of the ultrasonic sensor by freeing the allocated
// digital channels. If the system was in automatic mode (round robin), then
// it is stopped, then started again after this sensor is removed (provided
// this wasn't the last sensor).
bool wasAutomaticMode = m_automaticEnabled;
SetAutomaticMode(false);
// No synchronization needed because the background task is stopped.
m_sensors.erase(std::remove(m_sensors.begin(), m_sensors.end(), this),
m_sensors.end());
if (!m_sensors.empty() && wasAutomaticMode) {
SetAutomaticMode(true);
}
}
int Ultrasonic::GetEchoChannel() const {
return m_echoChannel->GetChannel();
}
void Ultrasonic::Ping() {
SetAutomaticMode(false); // turn off automatic round-robin if pinging
// Reset the counter to zero (invalid data now)
m_counter.Reset();
// Do the ping to start getting a single range
m_pingChannel->Pulse(kPingTime);
}
bool Ultrasonic::IsRangeValid() const {
if (m_simRangeValid) {
return m_simRangeValid.Get();
}
return m_counter.Get() > 1;
}
void Ultrasonic::SetAutomaticMode(bool enabling) {
if (enabling == m_automaticEnabled) {
return; // ignore the case of no change
}
m_automaticEnabled = enabling;
if (enabling) {
/* Clear all the counters so no data is valid. No synchronization is needed
* because the background task is stopped.
*/
for (auto& sensor : m_sensors) {
sensor->m_counter.Reset();
}
m_thread = std::thread(&Ultrasonic::UltrasonicChecker);
} else {
// Wait for background task to stop running
if (m_thread.joinable()) {
m_thread.join();
}
// Clear all the counters (data now invalid) since automatic mode is
// disabled. No synchronization is needed because the background task is
// stopped.
for (auto& sensor : m_sensors) {
sensor->m_counter.Reset();
}
}
}
units::meter_t Ultrasonic::GetRange() const {
if (IsRangeValid()) {
if (m_simRange) {
return units::inch_t{m_simRange.Get()};
}
return m_counter.GetPeriod() * kSpeedOfSound / 2.0;
} else {
return 0_m;
}
}
bool Ultrasonic::IsEnabled() const {
return m_enabled;
}
void Ultrasonic::SetEnabled(bool enable) {
m_enabled = enable;
}
void Ultrasonic::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Ultrasonic");
builder.AddDoubleProperty(
"Value", [=, this] { return units::inch_t{GetRange()}.value(); },
nullptr);
}
void Ultrasonic::Initialize() {
m_simDevice = hal::SimDevice("Ultrasonic", m_echoChannel->GetChannel());
if (m_simDevice) {
m_simRangeValid = m_simDevice.CreateBoolean("Range Valid", false, true);
m_simRange = m_simDevice.CreateDouble("Range (in)", false, 0.0);
m_pingChannel->SetSimDevice(m_simDevice);
m_echoChannel->SetSimDevice(m_simDevice);
}
bool originalMode = m_automaticEnabled;
SetAutomaticMode(false); // Kill task when adding a new sensor
// Link this instance on the list
m_sensors.emplace_back(this);
m_counter.SetMaxPeriod(1_s);
m_counter.SetSemiPeriodMode(true);
m_counter.Reset();
m_enabled = true; // Make it available for round robin scheduling
SetAutomaticMode(originalMode);
static int instances = 0;
instances++;
HAL_Report(HALUsageReporting::kResourceType_Ultrasonic, instances);
wpi::SendableRegistry::Add(this, "Ultrasonic", m_echoChannel->GetChannel());
}
void Ultrasonic::UltrasonicChecker() {
while (m_automaticEnabled) {
for (auto& sensor : m_sensors) {
if (!m_automaticEnabled) {
break;
}
if (sensor->IsEnabled()) {
sensor->m_pingChannel->Pulse(kPingTime); // do the ping
}
Wait(100_ms); // wait for ping to return
}
}
}

View File

@@ -1,99 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/counter/ExternalDirectionCounter.h"
#include <memory>
#include <hal/Counter.h>
#include <hal/FRCUsageReporting.h>
#include <wpi/NullDeleter.h>
#include <wpi/sendable/SendableBuilder.h>
#include "frc/DigitalSource.h"
#include "frc/Errors.h"
using namespace frc;
ExternalDirectionCounter::ExternalDirectionCounter(
DigitalSource& countSource, DigitalSource& directionSource)
: ExternalDirectionCounter(
{&countSource, wpi::NullDeleter<DigitalSource>()},
{&directionSource, wpi::NullDeleter<DigitalSource>()}) {}
ExternalDirectionCounter::ExternalDirectionCounter(
std::shared_ptr<DigitalSource> countSource,
std::shared_ptr<DigitalSource> directionSource) {
if (countSource == nullptr) {
throw FRC_MakeError(err::NullParameter, "countSource");
}
if (directionSource == nullptr) {
throw FRC_MakeError(err::NullParameter, "directionSource");
}
m_countSource = countSource;
m_directionSource = directionSource;
int32_t status = 0;
m_handle = HAL_InitializeCounter(
HAL_Counter_Mode::HAL_Counter_kExternalDirection, &m_index, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
HAL_SetCounterUpSource(m_handle, m_countSource->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
m_countSource->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "{}", m_index);
HAL_SetCounterUpSourceEdge(m_handle, true, false, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
HAL_SetCounterDownSource(
m_handle, m_directionSource->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
m_directionSource->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "{}", m_index);
HAL_SetCounterDownSourceEdge(m_handle, false, true, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
Reset();
HAL_Report(HALUsageReporting::kResourceType_Counter, m_index + 1);
wpi::SendableRegistry::Add(this, "External Direction Counter", m_index);
}
int ExternalDirectionCounter::GetCount() const {
int32_t status = 0;
int val = HAL_GetCounter(m_handle, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
return val;
}
void ExternalDirectionCounter::SetReverseDirection(bool reverseDirection) {
int32_t status = 0;
HAL_SetCounterReverseDirection(m_handle, reverseDirection, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
}
void ExternalDirectionCounter::Reset() {
int32_t status = 0;
HAL_ResetCounter(m_handle, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
}
void ExternalDirectionCounter::SetEdgeConfiguration(
EdgeConfiguration configuration) {
int32_t status = 0;
bool rising = configuration == EdgeConfiguration::kRisingEdge ||
configuration == EdgeConfiguration::kBoth;
bool falling = configuration == EdgeConfiguration::kFallingEdge ||
configuration == EdgeConfiguration::kBoth;
HAL_SetCounterUpSourceEdge(m_handle, rising, falling, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
}
void ExternalDirectionCounter::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("External Direction Counter");
builder.AddDoubleProperty("Count", [&] { return GetCount(); }, nullptr);
}

View File

@@ -4,37 +4,35 @@
#include "frc/counter/Tachometer.h"
#include <frc/DigitalSource.h>
#include <string>
#include <hal/Counter.h>
#include <hal/FRCUsageReporting.h>
#include <wpi/NullDeleter.h>
#include <wpi/StackTrace.h>
#include <wpi/sendable/SendableBuilder.h>
#include "frc/Errors.h"
using namespace frc;
Tachometer::Tachometer(DigitalSource& source)
: Tachometer({&source, wpi::NullDeleter<DigitalSource>()}) {}
Tachometer::Tachometer(std::shared_ptr<DigitalSource> source) {
if (source == nullptr) {
throw FRC_MakeError(err::NullParameter, "source");
}
m_source = source;
Tachometer::Tachometer(int channel, EdgeConfiguration configuration)
: m_channel{channel} {
int32_t status = 0;
HAL_SetCounterUpSource(m_handle, m_source->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
m_source->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "{}", m_index);
HAL_SetCounterUpSourceEdge(m_handle, true, false, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
std::string stackTrace = wpi::GetStackTrace(1);
m_handle = HAL_InitializeCounter(
channel, configuration == EdgeConfiguration::kRisingEdge,
stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "{}", channel);
HAL_Report(HALUsageReporting::kResourceType_Counter, m_index + 1);
wpi::SendableRegistry::Add(this, "Tachometer", m_index);
HAL_Report(HALUsageReporting::kResourceType_Counter, channel + 1);
wpi::SendableRegistry::Add(this, "Tachometer", channel);
}
void Tachometer::SetEdgeConfiguration(EdgeConfiguration configuration) {
int32_t status = 0;
bool rising = configuration == EdgeConfiguration::kRisingEdge;
HAL_SetCounterEdgeConfiguration(m_handle, rising, &status);
FRC_CheckErrorStatus(status, "{}", m_channel);
}
units::hertz_t Tachometer::GetFrequency() const {
@@ -48,7 +46,7 @@ units::hertz_t Tachometer::GetFrequency() const {
units::second_t Tachometer::GetPeriod() const {
int32_t status = 0;
double period = HAL_GetCounterPeriod(m_handle, &status);
FRC_CheckErrorStatus(status, "Channel {}", m_source->GetChannel());
FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return units::second_t{period};
}
@@ -79,33 +77,14 @@ units::revolutions_per_minute_t Tachometer::GetRevolutionsPerMinute() const {
bool Tachometer::GetStopped() const {
int32_t status = 0;
bool stopped = HAL_GetCounterStopped(m_handle, &status);
FRC_CheckErrorStatus(status, "Channel {}", m_source->GetChannel());
FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return stopped;
}
int Tachometer::GetSamplesToAverage() const {
int32_t status = 0;
int32_t samplesToAverage = HAL_GetCounterSamplesToAverage(m_handle, &status);
FRC_CheckErrorStatus(status, "Channel {}", m_source->GetChannel());
return samplesToAverage;
}
void Tachometer::SetSamplesToAverage(int samples) {
int32_t status = 0;
HAL_SetCounterSamplesToAverage(m_handle, samples, &status);
FRC_CheckErrorStatus(status, "Channel {}", m_source->GetChannel());
}
void Tachometer::SetMaxPeriod(units::second_t maxPeriod) {
int32_t status = 0;
HAL_SetCounterMaxPeriod(m_handle, maxPeriod.value(), &status);
FRC_CheckErrorStatus(status, "Channel {}", m_source->GetChannel());
}
void Tachometer::SetUpdateWhenEmpty(bool updateWhenEmpty) {
int32_t status = 0;
HAL_SetCounterUpdateWhenEmpty(m_handle, updateWhenEmpty, &status);
FRC_CheckErrorStatus(status, "Channel {}", m_source->GetChannel());
FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void Tachometer::InitSendable(wpi::SendableBuilder& builder) {

View File

@@ -5,10 +5,11 @@
#include "frc/counter/UpDownCounter.h"
#include <memory>
#include <string>
#include <hal/Counter.h>
#include <hal/FRCUsageReporting.h>
#include <wpi/NullDeleter.h>
#include <wpi/StackTrace.h>
#include <wpi/sendable/SendableBuilder.h>
#include "frc/DigitalSource.h"
@@ -16,84 +17,39 @@
using namespace frc;
UpDownCounter::UpDownCounter(DigitalSource& upSource, DigitalSource& downSource)
: UpDownCounter({&upSource, wpi::NullDeleter<DigitalSource>()},
{&downSource, wpi::NullDeleter<DigitalSource>()}) {}
UpDownCounter::UpDownCounter(std::shared_ptr<DigitalSource> upSource,
std::shared_ptr<DigitalSource> downSource) {
m_upSource = upSource;
m_downSource = downSource;
UpDownCounter::UpDownCounter(int channel, EdgeConfiguration configuration)
: m_channel{channel} {
int32_t status = 0;
m_handle = HAL_InitializeCounter(HAL_Counter_Mode::HAL_Counter_kTwoPulse,
&m_index, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
if (m_upSource) {
HAL_SetCounterUpSource(m_handle, m_upSource->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
m_upSource->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "{}", m_index);
HAL_SetCounterUpSourceEdge(m_handle, true, false, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
}
if (m_downSource) {
HAL_SetCounterDownSource(
m_handle, m_downSource->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
m_downSource->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "{}", m_index);
HAL_SetCounterDownSourceEdge(m_handle, true, false, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
}
std::string stackTrace = wpi::GetStackTrace(1);
m_handle = HAL_InitializeCounter(
channel, configuration == EdgeConfiguration::kRisingEdge,
stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "{}", channel);
Reset();
HAL_Report(HALUsageReporting::kResourceType_Counter, m_index + 1);
wpi::SendableRegistry::Add(this, "UpDown Counter", m_index);
HAL_Report(HALUsageReporting::kResourceType_Counter, channel + 1);
wpi::SendableRegistry::Add(this, "UpDown Counter", channel);
}
int UpDownCounter::GetCount() const {
int32_t status = 0;
int val = HAL_GetCounter(m_handle, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
FRC_CheckErrorStatus(status, "{}", m_channel);
return val;
}
void UpDownCounter::SetReverseDirection(bool reverseDirection) {
int32_t status = 0;
HAL_SetCounterReverseDirection(m_handle, reverseDirection, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
}
void UpDownCounter::Reset() {
int32_t status = 0;
HAL_ResetCounter(m_handle, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
FRC_CheckErrorStatus(status, "{}", m_channel);
}
void UpDownCounter::SetUpEdgeConfiguration(EdgeConfiguration configuration) {
void UpDownCounter::SetEdgeConfiguration(EdgeConfiguration configuration) {
int32_t status = 0;
bool rising = configuration == EdgeConfiguration::kRisingEdge ||
configuration == EdgeConfiguration::kBoth;
bool falling = configuration == EdgeConfiguration::kFallingEdge ||
configuration == EdgeConfiguration::kBoth;
HAL_SetCounterUpSourceEdge(m_handle, rising, falling, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
}
void UpDownCounter::SetDownEdgeConfiguration(EdgeConfiguration configuration) {
int32_t status = 0;
bool rising = configuration == EdgeConfiguration::kRisingEdge ||
configuration == EdgeConfiguration::kBoth;
bool falling = configuration == EdgeConfiguration::kFallingEdge ||
configuration == EdgeConfiguration::kBoth;
HAL_SetCounterDownSourceEdge(m_handle, rising, falling, &status);
FRC_CheckErrorStatus(status, "{}", m_index);
bool rising = configuration == EdgeConfiguration::kRisingEdge;
HAL_SetCounterEdgeConfiguration(m_handle, rising, &status);
FRC_CheckErrorStatus(status, "{}", m_channel);
}
void UpDownCounter::InitSendable(wpi::SendableBuilder& builder) {

View File

@@ -1,27 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/UltrasonicSim.h"
#include "frc/Ultrasonic.h"
#include "frc/simulation/SimDeviceSim.h"
using namespace frc::sim;
UltrasonicSim::UltrasonicSim(const frc::Ultrasonic& ultrasonic)
: UltrasonicSim(0, ultrasonic.GetEchoChannel()) {}
UltrasonicSim::UltrasonicSim(int ping, int echo) {
frc::sim::SimDeviceSim deviceSim{"Ultrasonic", echo};
m_simRangeValid = deviceSim.GetBoolean("Range Valid");
m_simRange = deviceSim.GetDouble("Range (in)");
}
void UltrasonicSim::SetRangeValid(bool valid) {
m_simRangeValid.Set(valid);
}
void UltrasonicSim::SetRange(units::inch_t range) {
m_simRange.Set(range.value());
}

View File

@@ -1,469 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <hal/Counter.h>
#include <hal/Types.h>
#include <units/time.h>
#include <wpi/sendable/Sendable.h>
#include <wpi/sendable/SendableHelper.h>
#include "frc/AnalogTrigger.h"
#include "frc/CounterBase.h"
namespace frc {
class DigitalGlitchFilter;
/**
* Class for counting the number of ticks on a digital input channel.
*
* This is a general purpose class for counting repetitive events. It can return
* the number of counts, the period of the most recent cycle, and detect when
* the signal being counted has stopped by supplying a maximum cycle time.
*
* All counters will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
class Counter : public CounterBase,
public wpi::Sendable,
public wpi::SendableHelper<Counter> {
public:
enum Mode {
kTwoPulse = 0,
kSemiperiod = 1,
kPulseLength = 2,
kExternalDirection = 3
};
/**
* Create an instance of a counter where no sources are selected.
*
* They all must be selected by calling functions to specify the up source and
* the down source independently.
*
* This creates a ChipObject counter and initializes status variables
* appropriately.
*
* The counter will start counting immediately.
*
* @param mode The counter mode
*/
explicit Counter(Mode mode = kTwoPulse);
/**
* Create an instance of a Counter object.
*
* Create an up-Counter instance given a channel.
*
* The counter will start counting immediately.
*
* @param channel The DIO channel to use as the up source. 0-9 are on-board,
* 10-25 are on the MXP
*/
explicit Counter(int channel);
/**
* Create an instance of a counter from a Digital Source (such as a Digital
* Input).
*
* This is used if an existing digital input is to be shared by multiple other
* objects such as encoders or if the Digital Source is not a Digital Input
* channel (such as an Analog %Trigger).
*
* The counter will start counting immediately.
* @param source A pointer to the existing DigitalSource object. It will be
* set as the Up Source.
*/
explicit Counter(DigitalSource* source);
/**
* Create an instance of a counter from a Digital Source (such as a Digital
* Input).
*
* This is used if an existing digital input is to be shared by multiple other
* objects such as encoders or if the Digital Source is not a Digital Input
* channel (such as an Analog %Trigger).
*
* The counter will start counting immediately.
*
* @param source A pointer to the existing DigitalSource object. It will be
* set as the Up Source.
*/
explicit Counter(std::shared_ptr<DigitalSource> source);
/**
* Create an instance of a Counter object.
*
* Create an instance of a simple up-Counter given an analog trigger.
* Use the trigger state output from the analog trigger.
*
* The counter will start counting immediately.
*
* @param trigger The reference to the existing AnalogTrigger object.
*/
explicit Counter(const AnalogTrigger& trigger);
/**
* Create an instance of a Counter object.
*
* Creates a full up-down counter given two Digital Sources.
*
* @param encodingType The quadrature decoding mode (1x or 2x)
* @param upSource The pointer to the DigitalSource to set as the up
* source
* @param downSource The pointer to the DigitalSource to set as the down
* source
* @param inverted True to invert the output (reverse the direction)
*/
Counter(EncodingType encodingType, DigitalSource* upSource,
DigitalSource* downSource, bool inverted);
/**
* Create an instance of a Counter object.
*
* Creates a full up-down counter given two Digital Sources.
*
* @param encodingType The quadrature decoding mode (1x or 2x)
* @param upSource The pointer to the DigitalSource to set as the up
* source
* @param downSource The pointer to the DigitalSource to set as the down
* source
* @param inverted True to invert the output (reverse the direction)
*/
Counter(EncodingType encodingType, std::shared_ptr<DigitalSource> upSource,
std::shared_ptr<DigitalSource> downSource, bool inverted);
Counter(Counter&&) = default;
Counter& operator=(Counter&&) = default;
~Counter() override;
/**
* Set the up source for the counter as a digital input channel.
*
* @param channel The DIO channel to use as the up source. 0-9 are on-board,
* 10-25 are on the MXP
*/
void SetUpSource(int channel);
/**
* Set the up counting source to be an analog trigger.
*
* @param analogTrigger The analog trigger object that is used for the Up
* Source
* @param triggerType The analog trigger output that will trigger the
* counter.
*/
void SetUpSource(AnalogTrigger* analogTrigger, AnalogTriggerType triggerType);
/**
* Set the up counting source to be an analog trigger.
*
* @param analogTrigger The analog trigger object that is used for the Up
* Source
* @param triggerType The analog trigger output that will trigger the
* counter.
*/
void SetUpSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType);
void SetUpSource(DigitalSource* source);
/**
* Set the source object that causes the counter to count up.
*
* Set the up counting DigitalSource.
*
* @param source Pointer to the DigitalSource object to set as the up source
*/
void SetUpSource(std::shared_ptr<DigitalSource> source);
/**
* Set the source object that causes the counter to count up.
*
* Set the up counting DigitalSource.
*
* @param source Reference to the DigitalSource object to set as the up source
*/
void SetUpSource(DigitalSource& source);
/**
* Set the edge sensitivity on an up counting source.
*
* Set the up source to either detect rising edges or falling edges or both.
*
* @param risingEdge True to trigger on rising edges
* @param fallingEdge True to trigger on falling edges
*/
void SetUpSourceEdge(bool risingEdge, bool fallingEdge);
/**
* Disable the up counting source to the counter.
*/
void ClearUpSource();
/**
* Set the down counting source to be a digital input channel.
*
* @param channel The DIO channel to use as the up source. 0-9 are on-board,
* 10-25 are on the MXP
*/
void SetDownSource(int channel);
/**
* Set the down counting source to be an analog trigger.
*
* @param analogTrigger The analog trigger object that is used for the Down
* Source
* @param triggerType The analog trigger output that will trigger the
* counter.
*/
void SetDownSource(AnalogTrigger* analogTrigger,
AnalogTriggerType triggerType);
/**
* Set the down counting source to be an analog trigger.
*
* @param analogTrigger The analog trigger object that is used for the Down
* Source
* @param triggerType The analog trigger output that will trigger the
* counter.
*/
void SetDownSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType);
/**
* Set the source object that causes the counter to count down.
*
* Set the down counting DigitalSource.
*
* @param source Pointer to the DigitalSource object to set as the down source
*/
void SetDownSource(DigitalSource* source);
/**
* Set the source object that causes the counter to count down.
*
* Set the down counting DigitalSource.
*
* @param source Reference to the DigitalSource object to set as the down
* source
*/
void SetDownSource(DigitalSource& source);
void SetDownSource(std::shared_ptr<DigitalSource> source);
/**
* Set the edge sensitivity on a down counting source.
*
* Set the down source to either detect rising edges or falling edges.
*
* @param risingEdge True to trigger on rising edges
* @param fallingEdge True to trigger on falling edges
*/
void SetDownSourceEdge(bool risingEdge, bool fallingEdge);
/**
* Disable the down counting source to the counter.
*/
void ClearDownSource();
/**
* Set standard up / down counting mode on this counter.
*
* Up and down counts are sourced independently from two inputs.
*/
void SetUpDownCounterMode();
/**
* Set external direction mode on this counter.
*
* Counts are sourced on the Up counter input.
* The Down counter input represents the direction to count.
*/
void SetExternalDirectionMode();
/**
* Set Semi-period mode on this counter.
*
* Counts up on both rising and falling edges.
*/
void SetSemiPeriodMode(bool highSemiPeriod);
/**
* Configure the counter to count in up or down based on the length of the
* input pulse.
*
* This mode is most useful for direction sensitive gear tooth sensors.
*
* @param threshold The pulse length beyond which the counter counts the
* opposite direction. Units are seconds.
*/
void SetPulseLengthMode(double threshold);
/**
* Set the Counter to return reversed sensing on the direction.
*
* This allows counters to change the direction they are counting in the case
* of 1X and 2X quadrature encoding only. Any other counter mode isn't
* supported.
*
* @param reverseDirection true if the value counted should be negated.
*/
void SetReverseDirection(bool reverseDirection);
/**
* Set the Samples to Average which specifies the number of samples of the
* timer to average when calculating the period. Perform averaging to account
* for mechanical imperfections or as oversampling to increase resolution.
*
* @param samplesToAverage The number of samples to average from 1 to 127.
*/
void SetSamplesToAverage(int samplesToAverage);
/**
* Get the Samples to Average which specifies the number of samples of the
* timer to average when calculating the period.
*
* Perform averaging to account for mechanical imperfections or as
* oversampling to increase resolution.
*
* @return The number of samples being averaged (from 1 to 127)
*/
int GetSamplesToAverage() const;
int GetFPGAIndex() const;
/**
* Set the distance per pulse for this counter. This sets the multiplier used
* to determine the distance driven based on the count value from the encoder.
* Set this value based on the Pulses per Revolution and factor in any gearing
* reductions. This distance can be in any units you like, linear or angular.
*
* @param distancePerPulse The scale factor that will be used to convert
* pulses to useful units.
*/
void SetDistancePerPulse(double distancePerPulse);
/**
* Read the current scaled counter value. Read the value at this instant,
* scaled by the distance per pulse (defaults to 1).
*
* @return The distance since the last reset
*/
double GetDistance() const;
/**
* Get the current rate of the Counter. Read the current rate of the counter
* accounting for the distance per pulse value. The default value for distance
* per pulse (1) yields units of pulses per second.
*
* @return The rate in units/sec
*/
double GetRate() const;
// CounterBase interface
/**
* Read the current counter value.
*
* Read the value at this instant. It may still be running, so it reflects the
* current value. Next time it is read, it might have a different value.
*/
int Get() const override;
/**
* Reset the Counter to zero.
*
* Set the counter value to zero. This doesn't effect the running state of the
* counter, just sets the current value to zero.
*/
void Reset() override;
/**
* Get the Period of the most recent count.
*
* Returns the time interval of the most recent count. This can be used for
* velocity calculations to determine shaft speed.
*
* @returns The period between the last two pulses in units of seconds.
*/
units::second_t GetPeriod() const override;
/**
* Set the maximum period where the device is still considered "moving".
*
* Sets the maximum period where the device is considered moving. This value
* is used to determine the "stopped" state of the counter using the
* GetStopped method.
*
* @param maxPeriod The maximum period where the counted device is considered
* moving in seconds.
*/
void SetMaxPeriod(units::second_t maxPeriod) final;
/**
* Select whether you want to continue updating the event timer output when
* there are no samples captured.
*
* The output of the event timer has a buffer of periods that are averaged and
* posted to a register on the FPGA. When the timer detects that the event
* source has stopped (based on the MaxPeriod) the buffer of samples to be
* averaged is emptied. If you enable the update when empty, you will be
* notified of the stopped source and the event time will report 0 samples.
* If you disable update when empty, the most recent average will remain on
* the output until a new sample is acquired. You will never see 0 samples
* output (except when there have been no events since an FPGA reset) and you
* will likely not see the stopped bit become true (since it is updated at the
* end of an average and there are no samples to average).
*
* @param enabled True to enable update when empty
*/
void SetUpdateWhenEmpty(bool enabled);
/**
* Determine if the clock is stopped.
*
* Determine if the clocked input is stopped based on the MaxPeriod value set
* using the SetMaxPeriod method. If the clock exceeds the MaxPeriod, then the
* device (and counter) are assumed to be stopped and it returns true.
*
* @return Returns true if the most recent counter period exceeds the
* MaxPeriod value set by SetMaxPeriod.
*/
bool GetStopped() const override;
/**
* The last direction the counter value changed.
*
* @return The last direction the counter value changed.
*/
bool GetDirection() const override;
void InitSendable(wpi::SendableBuilder& builder) override;
protected:
/// Makes the counter count up.
std::shared_ptr<DigitalSource> m_upSource;
/// Makes the counter count down.
std::shared_ptr<DigitalSource> m_downSource;
/// The FPGA counter object
hal::Handle<HAL_CounterHandle, HAL_FreeCounter> m_counter;
private:
/// The index of this counter.
int m_index = 0;
/// Distance of travel for each tick.
double m_distancePerPulse = 1;
friend class DigitalGlitchFilter;
};
} // namespace frc

View File

@@ -11,7 +11,6 @@
#include <wpi/sendable/Sendable.h>
#include <wpi/sendable/SendableHelper.h>
#include "frc/Counter.h"
#include "frc/CounterBase.h"
namespace frc {

View File

@@ -1,198 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <atomic>
#include <memory>
#include <thread>
#include <vector>
#include <hal/SimDevice.h>
#include <units/length.h>
#include <units/time.h>
#include <units/velocity.h>
#include <wpi/sendable/Sendable.h>
#include <wpi/sendable/SendableHelper.h>
#include "frc/Counter.h"
namespace frc {
class DigitalInput;
class DigitalOutput;
/**
* Ultrasonic rangefinder class.
*
* The Ultrasonic rangefinder measures absolute distance based on the round-trip
* time of a ping generated by the controller. These sensors use two
* transducers, a speaker and a microphone both tuned to the ultrasonic range. A
* common ultrasonic sensor, the Daventech SRF04 requires a short pulse to be
* generated on a digital channel. This causes the chirp to be emitted. A second
* line becomes high as the ping is transmitted and goes low when the echo is
* received. The time that the line is high determines the round trip distance
* (time of flight).
*/
class Ultrasonic : public wpi::Sendable,
public wpi::SendableHelper<Ultrasonic> {
public:
/**
* Create an instance of the Ultrasonic Sensor.
*
* This is designed to support the Daventech SRF04 and Vex ultrasonic sensors.
*
* @param pingChannel The digital output channel that sends the pulse to
* initiate the sensor sending the ping.
* @param echoChannel The digital input channel that receives the echo. The
* length of time that the echo is high represents the
* round trip time of the ping, and the distance.
*/
Ultrasonic(int pingChannel, int echoChannel);
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput for the ping channel.
*
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
*/
Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel);
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput for the ping channel.
*
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
*/
Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel);
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput for the ping channel.
*
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
*/
Ultrasonic(std::shared_ptr<DigitalOutput> pingChannel,
std::shared_ptr<DigitalInput> echoChannel);
~Ultrasonic() override;
Ultrasonic(Ultrasonic&&) = default;
Ultrasonic& operator=(Ultrasonic&&) = default;
/**
* Returns the echo channel.
*
* @return The echo channel.
*/
int GetEchoChannel() const;
/**
* Single ping to ultrasonic sensor.
*
* Send out a single ping to the ultrasonic sensor. This only works if
* automatic (round robin) mode is disabled. A single ping is sent out, and
* the counter should count the semi-period when it comes in. The counter is
* reset to make the current value invalid.
*/
void Ping();
/**
* Check if there is a valid range measurement.
*
* The ranges are accumulated in a counter that will increment on each edge of
* the echo (return) signal. If the count is not at least 2, then the range
* has not yet been measured, and is invalid.
*/
bool IsRangeValid() const;
/**
* Turn Automatic mode on/off.
*
* When in Automatic mode, all sensors will fire in round robin, waiting a set
* time between each sensor.
*
* @param enabling Set to true if round robin scheduling should start for all
* the ultrasonic sensors. This scheduling method assures that
* the sensors are non-interfering because no two sensors fire
* at the same time. If another scheduling algorithm is
* preferred, it can be implemented by pinging the sensors
* manually and waiting for the results to come back.
*/
static void SetAutomaticMode(bool enabling);
/**
* Get the range from the ultrasonic sensor.
*
* @return Range of the target returned from the ultrasonic sensor. If there
* is no valid value yet, i.e. at least one measurement hasn't
* completed, then return 0.
*/
units::meter_t GetRange() const;
bool IsEnabled() const;
void SetEnabled(bool enable);
void InitSendable(wpi::SendableBuilder& builder) override;
private:
/**
* Initialize the Ultrasonic Sensor.
*
* This is the common code that initializes the ultrasonic sensor given that
* there are two digital I/O channels allocated. If the system was running in
* automatic mode (round robin) when the new sensor is added, it is stopped,
* the sensor is added, then automatic mode is restored.
*/
void Initialize();
/**
* Background task that goes through the list of ultrasonic sensors and pings
* each one in turn. The counter is configured to read the timing of the
* returned echo pulse.
*
* DANGER WILL ROBINSON, DANGER WILL ROBINSON:
* This code runs as a task and assumes that none of the ultrasonic sensors
* will change while it's running. Make sure to disable automatic mode before
* touching the list.
*/
static void UltrasonicChecker();
// Time (usec) for the ping trigger pulse.
static constexpr auto kPingTime = 10_us;
// Max time (ms) between readings.
static constexpr auto kMaxUltrasonicTime = 0.1_s;
static constexpr auto kSpeedOfSound = 1130_fps;
// Thread doing the round-robin automatic sensing
static std::thread m_thread;
// Ultrasonic sensors
static std::vector<Ultrasonic*> m_sensors;
// Automatic round-robin mode
static std::atomic<bool> m_automaticEnabled;
std::shared_ptr<DigitalOutput> m_pingChannel;
std::shared_ptr<DigitalInput> m_echoChannel;
bool m_enabled = false;
Counter m_counter;
hal::SimDevice m_simDevice;
hal::SimBoolean m_simRangeValid;
hal::SimDouble m_simRange;
};
} // namespace frc

View File

@@ -9,13 +9,9 @@ namespace frc {
* Edge configuration.
*/
enum class EdgeConfiguration {
/// No edge configuration (neither rising nor falling).
kNone = 0,
/// Rising edge configuration.
kRisingEdge = 0x1,
kRisingEdge = 0,
/// Falling edge configuration.
kFallingEdge = 0x2,
/// Both rising and falling edges configuration.
kBoth = 0x3
kFallingEdge = 1,
};
} // namespace frc

View File

@@ -1,85 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <hal/Counter.h>
#include <hal/Types.h>
#include <wpi/sendable/Sendable.h>
#include <wpi/sendable/SendableHelper.h>
#include "EdgeConfiguration.h"
namespace frc {
class DigitalSource;
/** Counter using external direction.
*
* <p>This counts on an edge from one digital input and the whether it counts
* up or down based on the state of a second digital input.
*
*/
class ExternalDirectionCounter
: public wpi::Sendable,
public wpi::SendableHelper<ExternalDirectionCounter> {
public:
/**
* Constructs a new ExternalDirectionCounter.
*
* @param countSource The source for counting.
* @param directionSource The source for selecting count direction.
*/
ExternalDirectionCounter(DigitalSource& countSource,
DigitalSource& directionSource);
/**
* Constructs a new ExternalDirectionCounter.
*
* @param countSource The source for counting.
* @param directionSource The source for selecting count direction.
*/
ExternalDirectionCounter(std::shared_ptr<DigitalSource> countSource,
std::shared_ptr<DigitalSource> directionSource);
ExternalDirectionCounter(ExternalDirectionCounter&&) = default;
ExternalDirectionCounter& operator=(ExternalDirectionCounter&&) = default;
~ExternalDirectionCounter() override = default;
/**
* Gets the current count.
*
* @return The current count.
*/
int GetCount() const;
/**
* Sets to reverse the counter direction.
*
* @param reverseDirection True to reverse counting direction.
*/
void SetReverseDirection(bool reverseDirection);
/** Resets the current count. */
void Reset();
/**
* Sets the edge configuration for counting.
*
* @param configuration The counting edge configuration.
*/
void SetEdgeConfiguration(EdgeConfiguration configuration);
protected:
void InitSendable(wpi::SendableBuilder& builder) override;
private:
std::shared_ptr<DigitalSource> m_countSource;
std::shared_ptr<DigitalSource> m_directionSource;
hal::Handle<HAL_CounterHandle, HAL_FreeCounter> m_handle;
int32_t m_index = 0;
};
} // namespace frc

View File

@@ -14,6 +14,8 @@
#include <wpi/sendable/Sendable.h>
#include <wpi/sendable/SendableHelper.h>
#include "EdgeConfiguration.h"
namespace frc {
class DigitalSource;
@@ -32,22 +34,23 @@ class Tachometer : public wpi::Sendable,
/**
* Constructs a new tachometer.
*
* @param source The source.
* @param channel The DIO Channel.
* @param configuration Edge configuration
*/
explicit Tachometer(DigitalSource& source);
/**
* Constructs a new tachometer.
*
* @param source The source.
*/
explicit Tachometer(std::shared_ptr<DigitalSource> source);
Tachometer(int channel, EdgeConfiguration configuration);
Tachometer(Tachometer&&) = default;
Tachometer& operator=(Tachometer&&) = default;
~Tachometer() override = default;
/**
* Sets the configuration for the channel.
*
* @param configuration The channel configuration.
*/
void SetEdgeConfiguration(EdgeConfiguration configuration);
/**
* Gets the tachometer frequency.
*
@@ -101,20 +104,6 @@ class Tachometer : public wpi::Sendable,
*/
bool GetStopped() const;
/**
* Gets the number of sample to average.
*
* @return Samples to average.
*/
int GetSamplesToAverage() const;
/**
* Sets the number of samples to average.
*
* @param samples Samples to average.
*/
void SetSamplesToAverage(int samples);
/**
* Sets the maximum period before the tachometer is considered stopped.
*
@@ -122,20 +111,12 @@ class Tachometer : public wpi::Sendable,
*/
void SetMaxPeriod(units::second_t maxPeriod);
/**
* Sets if to update when empty.
*
* @param updateWhenEmpty True to update when empty.
*/
void SetUpdateWhenEmpty(bool updateWhenEmpty);
protected:
void InitSendable(wpi::SendableBuilder& builder) override;
private:
std::shared_ptr<DigitalSource> m_source;
hal::Handle<HAL_CounterHandle, HAL_FreeCounter> m_handle;
int m_edgesPerRevolution;
int32_t m_index;
int32_t m_channel;
};
} // namespace frc

View File

@@ -28,19 +28,10 @@ class UpDownCounter : public wpi::Sendable,
/**
* Constructs a new UpDown Counter.
*
* @param upSource The up count source (can be null).
* @param downSource The down count source (can be null).
* @param channel The DIO channel
* @param configuration Edge configuration
*/
UpDownCounter(DigitalSource& upSource, DigitalSource& downSource);
/**
* Constructs a new UpDown Counter.
*
* @param upSource The up count source (can be null).
* @param downSource The down count source (can be null).
*/
UpDownCounter(std::shared_ptr<DigitalSource> upSource,
std::shared_ptr<DigitalSource> downSource);
UpDownCounter(int channel, EdgeConfiguration configuration);
UpDownCounter(UpDownCounter&&) = default;
UpDownCounter& operator=(UpDownCounter&&) = default;
@@ -54,38 +45,21 @@ class UpDownCounter : public wpi::Sendable,
*/
int GetCount() const;
/**
* Sets to revert the counter direction.
*
* @param reverseDirection True to reverse counting direction.
*/
void SetReverseDirection(bool reverseDirection);
/** Resets the current count. */
void Reset();
/**
* Sets the configuration for the up source.
* Sets the configuration for the channel.
*
* @param configuration The up source configuration.
* @param configuration The channel configuration.
*/
void SetUpEdgeConfiguration(EdgeConfiguration configuration);
/**
* Sets the configuration for the down source.
*
* @param configuration The down source configuration.
*/
void SetDownEdgeConfiguration(EdgeConfiguration configuration);
void SetEdgeConfiguration(EdgeConfiguration configuration);
protected:
void InitSendable(wpi::SendableBuilder& builder) override;
private:
void InitUpDownCounter();
std::shared_ptr<DigitalSource> m_upSource;
std::shared_ptr<DigitalSource> m_downSource;
hal::Handle<HAL_CounterHandle, HAL_FreeCounter> m_handle;
int32_t m_index = 0;
int32_t m_channel;
};
} // namespace frc

View File

@@ -1,56 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/SimDevice.h>
#include <units/length.h>
namespace frc {
class Ultrasonic;
namespace sim {
/**
* Class to control a simulated {@link Ultrasonic}.
*/
class UltrasonicSim {
public:
/**
* Constructor.
*
* @param ultrasonic The real ultrasonic to simulate
*/
explicit UltrasonicSim(const Ultrasonic& ultrasonic);
/**
* Constructor.
*
* @param ping unused.
* @param echo the ultrasonic's echo channel.
*/
UltrasonicSim(int ping, int echo);
/**
* Sets if the range measurement is valid.
*
* @param valid True if valid
*/
void SetRangeValid(bool valid);
/**
* Sets the range measurement.
*
* @param range The range.
*/
void SetRange(units::inch_t range);
private:
hal::SimBoolean m_simRangeValid;
hal::SimDouble m_simRange;
};
} // namespace sim
} // namespace frc