tutrc_harurobo_lib
読み取り中…
検索中…
一致する文字列を見つけられません
ps3.hpp
[詳解]
1#pragma once
2
3#include "main.h"
4
5#include <array>
6#include <cstddef>
7#include <cstdint>
8
9#include "uart.hpp"
10#include "utility.hpp"
11
12namespace tutrc_harurobo_lib {
13
14class PS3 {
15public:
16 enum class Axis {
17 LEFT_X,
18 LEFT_Y,
19 RIGHT_X,
20 RIGHT_Y,
21 };
22
23 enum class Key {
24 UP,
25 DOWN,
26 RIGHT,
27 LEFT,
29 CROSS,
30 CIRCLE,
31 SQUARE = 8,
32 L1,
33 L2,
34 R1,
35 R2,
36 START,
37 SELECT,
38 };
39
40 bool init(UART *uart) {
41 uart_ = uart;
42 return true;
43 }
44
45 void update() {
46 keys_prev_ = keys_;
47
48 uint8_t checksum = 0;
49
50 if (!uart_->receive(buf_.data(), buf_.size(), 0)) {
51 return;
52 }
53
54 for (size_t i = 0; i < 8; ++i) {
55 if (buf_[i] == 0x80) {
56 if (i > 0) {
57 // 1周分受信
58 for (size_t j = i; j < 8; ++j) {
59 buf_[j - i] = buf_[j];
60 }
61 if (!uart_->receive(buf_.data() + 8 - i, i, 0)) {
62 return;
63 }
64 }
65
66 for (size_t i = 1; i < 7; ++i) {
67 checksum += buf_[i];
68 }
69
70 if ((checksum & 0x7F) == buf_[7]) {
71 keys_ = (buf_[1] << 8) | buf_[2];
72 if ((keys_ & 0x03) == 0x03) {
73 keys_ &= ~0x03;
74 keys_ |= 1 << 13;
75 }
76 if ((keys_ & 0x0C) == 0x0C) {
77 keys_ &= ~0x0C;
78 keys_ |= 1 << 14;
79 }
80 for (size_t i = 0; i < 4; ++i) {
81 axes_[i] = (static_cast<float>(buf_[i + 3]) - 64) / 64;
82 }
83 }
84 return;
85 }
86 }
87 }
88
89 float get_axis(Axis axis) { return axes_[to_underlying(axis)]; }
90
91 bool get_key(Key key) { return (keys_ & (1 << to_underlying(key))) != 0; }
92
93 bool get_key_down(Key key) {
94 return ((keys_ ^ keys_prev_) & keys_ & (1 << to_underlying(key))) != 0;
95 }
96
97 bool get_key_up(Key key) {
98 return ((keys_ ^ keys_prev_) & keys_prev_ & (1 << to_underlying(key))) != 0;
99 }
100
101private:
102 UART *uart_;
103 std::array<uint8_t, 8> buf_ = {};
104 std::array<float, 4> axes_ = {};
105 uint16_t keys_;
106 uint16_t keys_prev_;
107};
108
109} // namespace tutrc_harurobo_lib
Definition ps3.hpp:14
Key
Definition ps3.hpp:23
Axis
Definition ps3.hpp:16
bool init(UART *uart)
Definition ps3.hpp:40
bool get_key_up(Key key)
Definition ps3.hpp:97
bool get_key(Key key)
Definition ps3.hpp:91
float get_axis(Axis axis)
Definition ps3.hpp:89
void update()
Definition ps3.hpp:45
bool get_key_down(Key key)
Definition ps3.hpp:93
Definition uart.hpp:56
bool receive(uint8_t *data, size_t size, uint32_t timeout)
Definition bno055.hpp:10
constexpr std::underlying_type_t< T > to_underlying(T value) noexcept
Definition utility.hpp:16