blob: ec392644c56057259c05a1a68a90cce775e74cbb [file] [log] [blame]
Brian Silverman07ec88e2014-12-28 00:13:08 -08001#ifndef FRC971_WPILIB_GYRO_H_
2#define FRC971_WPILIB_GYRO_H_
3
4#include <stdint.h>
5
6#include <atomic>
7
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include "aos/events/event_loop.h"
9#include "aos/robot_state/robot_state_generated.h"
10#include "frc971/queues/gyro_generated.h"
Brian Silverman07ec88e2014-12-28 00:13:08 -080011#include "frc971/wpilib/gyro_interface.h"
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070012#include "frc971/zeroing/averager.h"
Brian Silverman07ec88e2014-12-28 00:13:08 -080013
14namespace frc971 {
15namespace wpilib {
16
17// Handles reading the gyro over SPI and sending out angles on a queue.
18//
19// This is designed to be passed into ::std::thread's constructor so it will run
20// as a separate thread.
21class GyroSender {
22 public:
Austin Schuhdf6cbb12019-02-02 13:46:52 -080023 GyroSender(::aos::EventLoop *event_loop);
Brian Silverman07ec88e2014-12-28 00:13:08 -080024
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070025 enum class State { INITIALIZING, RUNNING };
Brian Silverman07ec88e2014-12-28 00:13:08 -080026
27 private:
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070028 // Initializes the gyro and then loops until Exit() is called on the event
29 // loop, taking readings.
30 void Loop(const int iterations);
31
Austin Schuhdf6cbb12019-02-02 13:46:52 -080032 ::aos::EventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070033 ::aos::Fetcher<::aos::RobotState> joystick_state_fetcher_;
Austin Schuhcc1010e2019-05-12 20:38:01 -070034 ::aos::Sender<::frc971::sensors::Uid> uid_sender_;
Austin Schuh1ea89bb2019-05-27 16:59:59 -070035 ::aos::Sender<::frc971::sensors::GyroReading> gyro_reading_sender_;
Brian Silverman07ec88e2014-12-28 00:13:08 -080036
37 // Readings per second.
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070038 static constexpr int kReadingRate = 200;
Brian Silverman07ec88e2014-12-28 00:13:08 -080039
40 GyroInterface gyro_;
41
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070042 State state_ = State::INITIALIZING;
43
44 // In radians, ready to send out.
45 double angle_ = 0;
46 // Calibrated offset.
47 double zero_offset_ = 0;
48
49 ::aos::monotonic_clock::time_point last_initialize_time_ =
50 ::aos::monotonic_clock::min_time;
51 int startup_cycles_left_ = 2 * kReadingRate;
52
53 zeroing::Averager<double, 6 * kReadingRate> zeroing_data_;
54
55 bool zeroed_ = false;
Brian Silverman07ec88e2014-12-28 00:13:08 -080056};
57
58} // namespace wpilib
59} // namespace frc971
60
61#endif // FRC971_WPILIB_GYRO_H_