blob: 4abfeaae733854abf88de997cf2b78f21aa1d314 [file] [log] [blame]
Brian Silverman07ec88e2014-12-28 00:13:08 -08001#ifndef FRC971_WPILIB_GYRO_H_
2#define FRC971_WPILIB_GYRO_H_
3
Brian Silverman07ec88e2014-12-28 00:13:08 -08004#include <atomic>
Tyler Chatowbf0609c2021-07-31 16:13:27 -07005#include <cstdint>
Brian Silverman07ec88e2014-12-28 00:13:08 -08006
Alex Perrycb7da4b2019-08-28 19:35:56 -07007#include "aos/events/event_loop.h"
Austin Schuh217a9782019-12-21 23:02:50 -08008#include "aos/events/shm_event_loop.h"
James Kuszmaul7077d342021-06-09 20:23:58 -07009#include "frc971/input/robot_state_generated.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070010#include "frc971/queues/gyro_generated.h"
Tyler Chatow24b5db12020-01-06 21:16:56 -080011#include "frc971/queues/gyro_uid_generated.h"
Brian Silverman07ec88e2014-12-28 00:13:08 -080012#include "frc971/wpilib/gyro_interface.h"
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070013#include "frc971/zeroing/averager.h"
Brian Silverman07ec88e2014-12-28 00:13:08 -080014
15namespace frc971 {
16namespace wpilib {
17
18// Handles reading the gyro over SPI and sending out angles on a queue.
19//
20// This is designed to be passed into ::std::thread's constructor so it will run
21// as a separate thread.
22class GyroSender {
23 public:
Austin Schuh217a9782019-12-21 23:02:50 -080024 GyroSender(::aos::ShmEventLoop *event_loop);
Brian Silverman07ec88e2014-12-28 00:13:08 -080025
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070026 enum class State { INITIALIZING, RUNNING };
Brian Silverman07ec88e2014-12-28 00:13:08 -080027
28 private:
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070029 // Initializes the gyro and then loops until Exit() is called on the event
30 // loop, taking readings.
31 void Loop(const int iterations);
32
Austin Schuhdf6cbb12019-02-02 13:46:52 -080033 ::aos::EventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070034 ::aos::Fetcher<::aos::RobotState> joystick_state_fetcher_;
Austin Schuhcc1010e2019-05-12 20:38:01 -070035 ::aos::Sender<::frc971::sensors::Uid> uid_sender_;
Austin Schuh1ea89bb2019-05-27 16:59:59 -070036 ::aos::Sender<::frc971::sensors::GyroReading> gyro_reading_sender_;
Brian Silverman07ec88e2014-12-28 00:13:08 -080037
38 // Readings per second.
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070039 static constexpr int kReadingRate = 200;
Brian Silverman07ec88e2014-12-28 00:13:08 -080040
41 GyroInterface gyro_;
42
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070043 State state_ = State::INITIALIZING;
44
45 // In radians, ready to send out.
46 double angle_ = 0;
47 // Calibrated offset.
48 double zero_offset_ = 0;
49
50 ::aos::monotonic_clock::time_point last_initialize_time_ =
51 ::aos::monotonic_clock::min_time;
52 int startup_cycles_left_ = 2 * kReadingRate;
53
54 zeroing::Averager<double, 6 * kReadingRate> zeroing_data_;
55
56 bool zeroed_ = false;
Brian Silverman07ec88e2014-12-28 00:13:08 -080057};
58
59} // namespace wpilib
60} // namespace frc971
61
62#endif // FRC971_WPILIB_GYRO_H_