blob: a0048fb7d352f537eefaecfaa1b82ef8ff6ea8d7 [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"
Austin Schuh217a9782019-12-21 23:02:50 -08009#include "aos/events/shm_event_loop.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070010#include "aos/robot_state/robot_state_generated.h"
11#include "frc971/queues/gyro_generated.h"
Tyler Chatow24b5db12020-01-06 21:16:56 -080012#include "frc971/queues/gyro_uid_generated.h"
Brian Silverman07ec88e2014-12-28 00:13:08 -080013#include "frc971/wpilib/gyro_interface.h"
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070014#include "frc971/zeroing/averager.h"
Brian Silverman07ec88e2014-12-28 00:13:08 -080015
16namespace frc971 {
17namespace wpilib {
18
19// Handles reading the gyro over SPI and sending out angles on a queue.
20//
21// This is designed to be passed into ::std::thread's constructor so it will run
22// as a separate thread.
23class GyroSender {
24 public:
Austin Schuh217a9782019-12-21 23:02:50 -080025 GyroSender(::aos::ShmEventLoop *event_loop);
Brian Silverman07ec88e2014-12-28 00:13:08 -080026
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070027 enum class State { INITIALIZING, RUNNING };
Brian Silverman07ec88e2014-12-28 00:13:08 -080028
29 private:
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070030 // Initializes the gyro and then loops until Exit() is called on the event
31 // loop, taking readings.
32 void Loop(const int iterations);
33
Austin Schuhdf6cbb12019-02-02 13:46:52 -080034 ::aos::EventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070035 ::aos::Fetcher<::aos::RobotState> joystick_state_fetcher_;
Austin Schuhcc1010e2019-05-12 20:38:01 -070036 ::aos::Sender<::frc971::sensors::Uid> uid_sender_;
Austin Schuh1ea89bb2019-05-27 16:59:59 -070037 ::aos::Sender<::frc971::sensors::GyroReading> gyro_reading_sender_;
Brian Silverman07ec88e2014-12-28 00:13:08 -080038
39 // Readings per second.
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070040 static constexpr int kReadingRate = 200;
Brian Silverman07ec88e2014-12-28 00:13:08 -080041
42 GyroInterface gyro_;
43
Austin Schuhbd1fe9c2019-06-29 16:35:48 -070044 State state_ = State::INITIALIZING;
45
46 // In radians, ready to send out.
47 double angle_ = 0;
48 // Calibrated offset.
49 double zero_offset_ = 0;
50
51 ::aos::monotonic_clock::time_point last_initialize_time_ =
52 ::aos::monotonic_clock::min_time;
53 int startup_cycles_left_ = 2 * kReadingRate;
54
55 zeroing::Averager<double, 6 * kReadingRate> zeroing_data_;
56
57 bool zeroed_ = false;
Brian Silverman07ec88e2014-12-28 00:13:08 -080058};
59
60} // namespace wpilib
61} // namespace frc971
62
63#endif // FRC971_WPILIB_GYRO_H_