2022年9月14日水曜日

ESPNOWを使ったジョイスティックコントローラ

//
// Joystick Remote
// Kiraku Labo 2022
//
#include <M5Atom.h>
#define SDA_PIN 26
#define SCL_PIN 32
#include <WiFi.h>
#include <esp_now.h>
#define GRN 0xf00000
#define RED 0x00f000
#define BLU 0x0000f0
#define CHANNEL 0
#define JOY_ADDR 0x52
uint32_t msecJoy=0;
byte robotMACaddr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
byte xyb[4]; //joystick x, jostick y, joystick button, ATOM button
byte offset[2]; //joystick x,y offset
int16_t xy[2], offset16[2];
const float ROOT2=1.4142;
uint32_t msRcv=0;
char s[100];
void setup() {
M5.begin(true,false,true);
M5.dis.drawpix(0, RED);
Serial.begin(115200);
Wire.begin(SDA_PIN, SCL_PIN, 50000); //SDA, SCL, freq
setupESPNOW();
int16_t x=0, y=0;
for (int i=0; i<10; i++) {
getJoy();
x += xyb[0];
y += xyb[1];
}
offset[0]=(byte)(x/10);
offset[1]=(byte)(y/10);
msecJoy=millis();
}
void loop() {
static int8_t joyData[4];
if (millis()-msecJoy<100) return;
msecJoy=millis();
getJoy();
M5.update();
joyData[0]=offset[0]-xyb[0];
joyData[1]=offset[1]-xyb[1];
joyData[2]=xyb[2];
if (joyData[2]==1) M5.dis.drawpix(0, BLU);
else M5.dis.drawpix(0, RED);
if (M5.Btn.isPressed()) joyData[3]=1; //M5ATOM button (0:off, 1:on)
else joyData[3]=0;
esp_now_send(robotMACaddr, (uint8_t*)joyData, 4);
}
void getJoy() {
Wire.requestFrom(JOY_ADDR, 3); //Request 3 bytes
if (Wire.available()) {
xyb[0] = Wire.read(); //joy x
xyb[1] = Wire.read(); //joy y
xyb[2] = Wire.read(); //joy button (0:off, 1:on for Grove)
}
}
void setupESPNOW() {
Serial.print("MAC=");
Serial.println(WiFi.macAddress());
WiFi.mode(WIFI_STA);
WiFi.disconnect();
esp_now_init();
esp_now_register_recv_cb(onRecv);
esp_now_peer_info_t peerInfo={};
memcpy(peerInfo.peer_addr, robotMACaddr, 6);
peerInfo.channel = CHANNEL;
peerInfo.encrypt = false;
esp_now_add_peer(&peerInfo);
}
void onRecv(const uint8_t * mac, const uint8_t *recvData, int len) {
for (int i=0; i<len; i++) {
s[i]=recvData[i];
}
s[len]='\0';
Serial.flush();
Serial.println(s);
msRcv=millis();
M5.dis.drawpix(0, GRN);
}
void sendData(String s) {
esp_now_send(robotMACaddr, (const byte*)s.c_str(), s.length());
}

0 件のコメント:

コメントを投稿