JOYSTICK.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <M5Stack.h>
  2. #include "Wire.h"
  3. #define FACE_JOY_ADDR 0x5e
  4. void Init() {
  5. Wire.begin();
  6. for (int i = 0; i < 256; i++) {
  7. Wire.beginTransmission(FACE_JOY_ADDR);
  8. Wire.write(i % 4);
  9. Wire.write(random(256) * (256 - i) / 256);
  10. Wire.write(random(256) * (256 - i) / 256);
  11. Wire.write(random(256) * (256 - i) / 256);
  12. Wire.endTransmission();
  13. delay(2);
  14. }
  15. Led(0, 0, 0, 0);
  16. Led(1, 0, 0, 0);
  17. Led(2, 0, 0, 0);
  18. Led(3, 0, 0, 0);
  19. }
  20. void Led(int indexOfLED, int r, int g, int b) {
  21. Wire.beginTransmission(FACE_JOY_ADDR);
  22. Wire.write(indexOfLED);
  23. Wire.write(r);
  24. Wire.write(g);
  25. Wire.write(b);
  26. Wire.endTransmission();
  27. }
  28. void setup() {
  29. M5.begin();
  30. M5.Power.begin();
  31. M5.Lcd.clear();
  32. M5.Lcd.setCursor(60, 0, 4);
  33. M5.Lcd.printf("FACE JOYSTICK");
  34. Init();
  35. }
  36. uint8_t x_data_L;
  37. uint8_t x_data_H;
  38. uint16_t x_data;
  39. uint8_t y_data_L;
  40. uint8_t y_data_H;
  41. uint16_t y_data;
  42. uint8_t button_data;
  43. char data[100];
  44. void loop() {
  45. Wire.requestFrom(FACE_JOY_ADDR, 5);
  46. if (Wire.available()) {
  47. y_data_L = Wire.read();
  48. y_data_H = Wire.read();
  49. x_data_L = Wire.read();
  50. x_data_H = Wire.read();
  51. button_data = Wire.read(); // Z(0: released 1: pressed)
  52. x_data = x_data_H << 8 | x_data_L;
  53. y_data = y_data_H << 8 | y_data_L;
  54. sprintf(data, "x:%d y:%d button:%d\n", x_data, y_data, button_data);
  55. Serial.print(data);
  56. M5.Lcd.setCursor(45, 120);
  57. M5.Lcd.println(data);
  58. if (x_data > 600) {
  59. Led(2, 0, 0, 50);
  60. Led(0, 0, 0, 0);
  61. } else if (x_data < 400) {
  62. Led(0, 0, 0, 50);
  63. Led(2, 0, 0, 0);
  64. } else {
  65. Led(0, 0, 0, 0);
  66. Led(2, 0, 0, 0);
  67. }
  68. if (y_data > 600) {
  69. Led(3, 0, 0, 50);
  70. Led(1, 0, 0, 0);
  71. } else if (y_data < 400) {
  72. Led(1, 0, 0, 50);
  73. Led(3, 0, 0, 0);
  74. } else {
  75. Led(1, 0, 0, 0);
  76. Led(3, 0, 0, 0);
  77. }
  78. }
  79. delay(200);
  80. }