Commit | Line | Data |
---|---|---|
2db494ce E |
1 | package org.usfirst.frc.team3501.robot; |
2 | ||
3 | import java.util.TimerTask; | |
4 | ||
5 | import edu.wpi.first.wpilibj.I2C; | |
6 | import edu.wpi.first.wpilibj.I2C.Port; | |
7 | import edu.wpi.first.wpilibj.PIDSource; | |
8 | import edu.wpi.first.wpilibj.PIDSourceType; | |
9 | import edu.wpi.first.wpilibj.Timer; | |
10 | ||
11 | public class Lidar implements PIDSource { | |
12 | private I2C i2c; | |
13 | private byte[] distance; | |
14 | private java.util.Timer updater; | |
15 | ||
16 | private final int LIDAR_ADDR = 0x62; | |
17 | private final int LIDAR_CONFIG_REGISTER = 0x00; | |
18 | private final int LIDAR_DISTANCE_REGISTER = 0x8f; | |
19 | ||
20 | public Lidar(Port port) { | |
21 | i2c = new I2C(port, LIDAR_ADDR); | |
22 | ||
23 | distance = new byte[2]; | |
24 | ||
25 | updater = new java.util.Timer(); | |
26 | } | |
27 | ||
28 | // Distance in cm | |
29 | public int getDistance() { | |
30 | return (int) Integer.toUnsignedLong(distance[0] << 8) | |
31 | + Byte.toUnsignedInt(distance[1]); | |
32 | } | |
33 | ||
34 | @Override | |
35 | public double pidGet() { | |
36 | return getDistance(); | |
37 | } | |
38 | ||
39 | // Start 10Hz polling | |
40 | public void start() { | |
41 | updater.scheduleAtFixedRate(new LIDARUpdater(), 0, 100); | |
42 | } | |
43 | ||
44 | // Start polling for period in milliseconds | |
45 | public void start(int period) { | |
46 | updater.scheduleAtFixedRate(new LIDARUpdater(), 0, period); | |
47 | } | |
48 | ||
49 | public void stop() { | |
50 | updater.cancel(); | |
51 | updater = new java.util.Timer(); | |
52 | } | |
53 | ||
54 | // Update distance variable | |
55 | public void update() { | |
56 | i2c.write(LIDAR_CONFIG_REGISTER, 0x04); // Initiate measurement | |
57 | Timer.delay(0.04); // Delay for measurement to be taken | |
58 | i2c.read(LIDAR_DISTANCE_REGISTER, 2, distance); // Read in measurement | |
59 | Timer.delay(0.005); // Delay to prevent over polling | |
60 | } | |
61 | ||
62 | // Timer task to keep distance updated | |
63 | private class LIDARUpdater extends TimerTask { | |
64 | @Override | |
65 | public void run() { | |
66 | while (true) { | |
67 | update(); | |
68 | try { | |
69 | Thread.sleep(10); | |
70 | } catch (InterruptedException e) { | |
71 | e.printStackTrace(); | |
72 | } | |
73 | } | |
74 | } | |
75 | } | |
76 | ||
77 | @Override | |
78 | public void setPIDSourceType(PIDSourceType pidSource) { | |
2db494ce E |
79 | } |
80 | ||
81 | @Override | |
82 | public PIDSourceType getPIDSourceType() { | |
2db494ce E |
83 | return null; |
84 | } | |
85 | } |