Skip to content

Commit

Permalink
Fix Ultrasonic sensor runner thread (wpilibsuite#1598)
Browse files Browse the repository at this point in the history
When there is more than one ultrasonic sensor, only the last sensor
instantiated would work due to incorrect array index management. This
replaces the previous approach with range-based for loops like the C++
implementation.

Supersedes wpilibsuite#1589.
  • Loading branch information
calcmogul authored and amrelk committed Apr 4, 2019
1 parent b7a7a5e commit 996027a
Showing 1 changed file with 9 additions and 21 deletions.
30 changes: 9 additions & 21 deletions wpilibj/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public enum Unit {
// ultrasonic sensor list
private static final List<Ultrasonic> m_sensors = new ArrayList<>();
// automatic round robin mode
private static boolean m_automaticEnabled;
private static volatile boolean m_automaticEnabled;
private DigitalInput m_echoChannel;
private DigitalOutput m_pingChannel;
private boolean m_allocatedChannels;
Expand All @@ -70,30 +70,18 @@ public enum Unit {
private static class UltrasonicChecker extends Thread {
@Override
public synchronized void run() {
int sensorIndex = 0;
Ultrasonic ultrasonic;
while (m_automaticEnabled) {
//lock list to ensure deletion doesn't occur between empty check and retrieving sensor
synchronized (m_sensors) {
if (m_sensors.isEmpty()) {
return;
for (Ultrasonic sensor: m_sensors) {
if (!m_automaticEnabled) {
break;
}
if (sensorIndex >= m_sensors.size()) {
sensorIndex = m_sensors.size() - 1;

if (sensor.isEnabled()) {
sensor.m_pingChannel.pulse(kPingTime); // do the ping
}
ultrasonic = m_sensors.get(sensorIndex);
}
if (ultrasonic.isEnabled()) {
// Do the ping
ultrasonic.m_pingChannel.pulse(kPingTime);
}
if (sensorIndex < m_sensors.size()) {
sensorIndex++;
} else {
sensorIndex = 0;
}

Timer.delay(.1); // wait for ping to return
Timer.delay(0.1); // wait for ping to return
}
}
}
}
Expand Down

0 comments on commit 996027a

Please sign in to comment.