ENCODER.ino 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <M5Stack.h>
  2. #define Faces_Encoder_I2C_ADDR 0X5E
  3. int encoder_increment;//positive: clockwise nagtive: anti-clockwise
  4. int encoder_value=0;
  5. uint8_t direction;//0: clockwise 1: anti-clockwise
  6. uint8_t last_button, cur_button;
  7. void GetValue(void){
  8. int temp_encoder_increment;
  9. Wire.requestFrom(Faces_Encoder_I2C_ADDR, 3);
  10. if(Wire.available()){
  11. temp_encoder_increment = Wire.read();
  12. cur_button = Wire.read();
  13. }
  14. if(temp_encoder_increment > 127){//anti-clockwise
  15. direction = 1;
  16. encoder_increment = 256 - temp_encoder_increment;
  17. }
  18. else{
  19. direction = 0;
  20. encoder_increment = temp_encoder_increment;
  21. }
  22. }
  23. void Led(int i, int r, int g, int b){
  24. Wire.beginTransmission(Faces_Encoder_I2C_ADDR);
  25. Wire.write(i);
  26. Wire.write(r);
  27. Wire.write(g);
  28. Wire.write(b);
  29. Wire.endTransmission();
  30. }
  31. void setup()
  32. {
  33. M5.begin();
  34. M5.Power.begin();
  35. Wire.begin();
  36. Serial.begin(115200);
  37. dacWrite(25, 0);
  38. M5.Lcd.setTextFont(2);
  39. M5.Lcd.println("FACES ENCODER I2C Read Example");
  40. Serial.println("FACES ENCODER I2C Read Example");
  41. for(int i=0;i<12;i++)
  42. {
  43. Led(i, 0, 0xff, 0);
  44. delay(10);
  45. }
  46. for(int i=0;i<12;i++)
  47. {
  48. Led(i, 0, 0, 0);
  49. delay(10);
  50. }
  51. }
  52. void loop()
  53. {
  54. int i;
  55. M5.Lcd.setCursor(0,40); M5.Lcd.print("Encoder Value: ");
  56. M5.Lcd.setCursor(0,60); M5.Lcd.print(" Key State : ");
  57. M5.Lcd.setCursor(0,80); M5.Lcd.print(" Key Value : ");
  58. GetValue();
  59. if(last_button != cur_button){
  60. M5.Lcd.fillRect(100,60,100,25,BLACK);
  61. M5.Lcd.fillRect(100,80,100,25,BLACK);
  62. last_button = cur_button;
  63. }
  64. if(cur_button){
  65. M5.Lcd.setCursor(100,60); M5.Lcd.print("released");
  66. M5.Lcd.setCursor(100,80); M5.Lcd.print("1");
  67. for(i=0;i<12;i++){
  68. Led(i, 0, 0, 0);
  69. }
  70. }
  71. else{
  72. M5.Lcd.setCursor(100,60); M5.Lcd.print("pressed");
  73. M5.Lcd.setCursor(100,80); M5.Lcd.print("0");
  74. for(i=0;i<12;i++){
  75. Led(i, 255, 255, 255);
  76. }
  77. }
  78. M5.Lcd.fillRect(100,40,50,25,BLACK);
  79. if(direction){
  80. encoder_value -= encoder_increment;
  81. M5.Lcd.setCursor(100,40); M5.Lcd.print("-");
  82. M5.Lcd.setCursor(100,40); M5.Lcd.print(encoder_value);
  83. Serial.print("encoder_value: "); Serial.print("-"); Serial.print(encoder_value);
  84. }
  85. else{
  86. encoder_value += encoder_increment;
  87. M5.Lcd.setCursor(100,40); M5.Lcd.print(encoder_value);
  88. Serial.print("encoder_value: "); Serial.print(encoder_value);
  89. }
  90. Serial.print(" button_state: "); Serial.println(cur_button);
  91. }