├── .gitignore ├── IOFrameworkForXR ├── IOFrameworkForXR.ino ├── MFRC522_I2C.cpp ├── MFRC522_I2C.h └── firmware.bin ├── IOFrameworkSDK.unitypackage ├── LICENSE ├── README.md └── images ├── IOFrameworkAnalogHandler.png ├── IOFrameworkButtonsHandler.png ├── IOFrameworkGestureHandler.png ├── IOFrameworkJoystickHandler.png ├── IOFrameworkOutputHandler.png ├── IOFrameworkTestUI.png ├── STYLY_marker.png ├── control-output-without-sdk.png ├── how-to-layout-sdk-components-in-unity.png └── keyboard-layout.png /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/* 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /IOFrameworkForXR/IOFrameworkForXR.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "MFRC522_I2C.h" 15 | #include "ServoEasing.hpp" 16 | 17 | const String VERSION_STRING = "v1.0.0-beta.7"; 18 | 19 | // Note: the device name should be within 15 characters; 20 | // otherwise, macOS and iOS devices can't discover 21 | // https://github.com/T-vK/ESP32-BLE-Keyboard/issues/51#issuecomment-733886764 22 | const String DEVICE_NAME = "IO Framework M5"; 23 | 24 | // Unit related constants 25 | const int I2C_ADDR_JOYSTICK = 0x52; 26 | const int I2C_ADDR_VL53L0X = 0x29; 27 | const int I2C_ADDR_SGP30 = 0x58; 28 | const int I2C_ADDR_MPR121 = 0x5B; 29 | const int I2C_ADDR_MFRC522 = 0x28; 30 | const int PIN_PORT_B_A = 36; 31 | const int PIN_PORT_B_B = 26; 32 | const int DIST_RANGE_MIN = 0; 33 | const int DIST_RANGE_MAX = 2000; 34 | const int ECO2_RANGE_MIN = 400; 35 | const int ECO2_RANGE_MAX = 2000; 36 | const int UNIT_NONE = 0; 37 | const int UNIT_DUAL_BUTTON = 1; 38 | const int UNIT_ANALOG_IN = 2; 39 | const int UNIT_SERVO = 3; 40 | const int UNIT_VIBRATOR = 4; 41 | const int UNIT_FIRST = UNIT_NONE; 42 | const int UNIT_LAST = UNIT_VIBRATOR; 43 | const int SERVO_PIN = PIN_PORT_B_B; 44 | const int VIBRATOR_PIN = PIN_PORT_B_B; 45 | 46 | // Choose the last LEDC channel to avoid conflict with the timer used for the 47 | // servo 48 | // https://github.com/madhephaestus/ESP32Servo/blob/6807249e7c4f48e082a0fd4ef485dfd13df0cc6b/src/ESP32PWM.cpp#L261-L277 49 | const int LEDC_CHANNEL_FOR_VIBRATOR = 15; 50 | 51 | // Unit related variables 52 | VL53L0X rangingSensor; 53 | Adafruit_SGP30 gasSensor; 54 | MFRC522 rfidReader(I2C_ADDR_MFRC522); 55 | String rfidTagUid[4]; 56 | Adafruit_MPR121 touchSensor = Adafruit_MPR121(); 57 | DFRobot_PAJ7620U2 gestureSensor; 58 | ServoEasing servo; 59 | bool isDualButtonConnected = false; 60 | bool isAnalogSensorConnected = false; 61 | bool isServoConnected = false; 62 | bool isVibratorConnected = false; 63 | bool isJoystickConnected = false; 64 | bool isRangingSensorConnected = false; 65 | bool isGasSensorConnected = false; 66 | bool isRfidReaderConnected = false; 67 | bool isTouchSensorConnected = false; 68 | bool isGestureSensorConnected = false; 69 | int unitOnPortB = UNIT_NONE; 70 | int distRangeMin = DIST_RANGE_MIN; 71 | int distRangeMax = DIST_RANGE_MAX; 72 | int eCO2RangeMin = ECO2_RANGE_MIN; 73 | int eCO2RangeMax = ECO2_RANGE_MAX; 74 | 75 | // Screen related constants 76 | const int LAYOUT_ANALOG_CH_TOP = 40; 77 | const int LAYOUT_JOYSTICK_CH_TOP = 80; 78 | const int LAYOUT_BUTTONS_CH_TOP = 120; 79 | const int LAYOUT_LINE_HEIGHT = 24; 80 | const int SCREEN_MAIN = 0; 81 | const int SCREEN_PREFS_SELECT = 1; 82 | const int SCREEN_PREFS_EDIT = 2; 83 | const int SCREEN_PREFS_RFID = 3; 84 | const int PREFS_MENU_NUM_ITEMS = 9; 85 | const int PREFS_MENU_INDEX_RFID_1 = 5; 86 | const int PREFS_MENU_INC_DEC_UNIT = 10; 87 | 88 | // Screen related variables 89 | int currentMenuItem = 0; 90 | int currentScreenMode = SCREEN_MAIN; 91 | bool isWaitingForNewRfidTag = false; 92 | Preferences preferences; 93 | char analogStatus[30]; 94 | char joystickStatus[30]; 95 | char buttonsStatus1[30]; 96 | char buttonsStatus2[30]; 97 | 98 | // Protocol related constants 99 | const byte KEYS_FOR_ANALOG_CH[] = {'`', '1', '2', '3', '4', '5', 100 | '6', '7', '8', '9', '0'}; 101 | const byte KEYS_FOR_BUTTON_CH[] = {'v', 'b', 'f', 'g', 'r', 't'}; 102 | const byte KEY_JOYSTICK_LEFT_UP = 'y'; 103 | const byte KEY_JOYSTICK_CENTER_UP = 'u'; 104 | const byte KEY_JOYSTICK_RIGHT_UP = 'i'; 105 | const byte KEY_JOYSTICK_LEFT = 'h'; 106 | const byte KEY_JOYSTICK_CENTER = 'j'; 107 | const byte KEY_JOYSTICK_RIGHT = 'k'; 108 | const byte KEY_JOYSTICK_LEFT_DOWN = 'n'; 109 | const byte KEY_JOYSTICK_CENTER_DOWN = 'm'; 110 | const byte KEY_JOYSTICK_RIGHT_DOWN = ','; 111 | const int OFFSET_BUTTON_3 = 2; 112 | const int NUM_BUTTONS = 6; 113 | 114 | // ESP32 BLE Keyboard related variables 115 | BleKeyboard bleKeyboard(DEVICE_NAME.c_str()); 116 | bool isBluetoothConnected = false; 117 | bool isSendingKeyboardEvents = false; 118 | bool sentKeyboardEvent = false; 119 | 120 | // Web server related variables 121 | WebServer server(80); 122 | 123 | volatile int analogValueForReporting = 0; 124 | volatile char joystickValueForReporting[32]; 125 | volatile int buttonValuesForReporting[NUM_BUTTONS]; 126 | volatile bool receivedHttpRequest = false; 127 | 128 | SemaphoreHandle_t mutex = xSemaphoreCreateMutex(); 129 | 130 | void handleInputRequest() { 131 | static char message[100]; 132 | 133 | xSemaphoreTake(mutex, portMAX_DELAY); 134 | receivedHttpRequest = true; 135 | sprintf(message, "%d,%s,%d,%d,%d,%d,%d,%d", analogValueForReporting, 136 | joystickValueForReporting, buttonValuesForReporting[0], 137 | buttonValuesForReporting[1], buttonValuesForReporting[2], 138 | buttonValuesForReporting[3], buttonValuesForReporting[4], 139 | buttonValuesForReporting[5]); 140 | xSemaphoreGive(mutex); 141 | server.send(200, "text/csv", message); 142 | } 143 | 144 | void handleOutputRequest() { 145 | xSemaphoreTake(mutex, portMAX_DELAY); 146 | receivedHttpRequest = true; 147 | xSemaphoreGive(mutex); 148 | 149 | if (server.args() == 1 && server.argName(0).equals("val")) { 150 | int val = server.arg(0).toInt(); 151 | 152 | switch (unitOnPortB) { 153 | // val: servo angle in degree, between 0 and 180 154 | case UNIT_SERVO: 155 | // target degree, degrees per second 156 | servo.startEaseTo(val, 180, START_UPDATE_BY_INTERRUPT); 157 | break; 158 | 159 | // val: on duration in ms, between 0 and 100 160 | case UNIT_VIBRATOR: 161 | val = constrain(val, 0, 100); 162 | // Drive the VIBRATOR with 12.5% power to avoid unwanted reboot due to 163 | // power failures 164 | ledcWrite(LEDC_CHANNEL_FOR_VIBRATOR, 128); 165 | delay(val); 166 | ledcWrite(LEDC_CHANNEL_FOR_VIBRATOR, 0); 167 | break; 168 | 169 | default: 170 | server.send(404, "text/plain", 171 | "Requests are only accepted when SERVO or VIBRATOR is " 172 | "selected for Port B."); 173 | return; 174 | break; 175 | } 176 | } else { 177 | server.send(404, "text/plain", "Bad Request"); 178 | return; 179 | } 180 | server.send(200, "text/plain", "OK"); 181 | } 182 | 183 | void handleNotFound() { 184 | xSemaphoreTake(mutex, portMAX_DELAY); 185 | receivedHttpRequest = true; 186 | xSemaphoreGive(mutex); 187 | 188 | String message = "API Not Found\n\n"; 189 | message += "URI: "; 190 | message += server.uri(); 191 | message += "\nMethod: "; 192 | message += (server.method() == HTTP_GET) ? "GET" : "POST"; 193 | message += "\nArguments: "; 194 | message += server.args(); 195 | message += "\n"; 196 | for (uint8_t i = 0; i < server.args(); i++) { 197 | message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; 198 | } 199 | server.send(404, "text/plain", message); 200 | } 201 | 202 | void setup() { 203 | Serial.begin(115200); 204 | Serial.print("MAC address: "); 205 | Serial.println(WiFi.macAddress()); 206 | 207 | auto cfg = M5.config(); 208 | M5.begin(cfg); 209 | M5.Power.begin(); 210 | Wire.begin(); 211 | M5.Display.init(); 212 | 213 | for (int i = 0; i < NUM_BUTTONS; i++) { 214 | buttonValuesForReporting[i] = 0; 215 | } 216 | 217 | // A workaround. Once the M5Unified library is updated, we should remove it 218 | // for simplicity. 219 | // https://github.com/m5stack/M5Unified/issues/34#issuecomment-1198892349 220 | #if defined(ARDUINO_M5STACK_FIRE) 221 | pinMode(15, OUTPUT_OPEN_DRAIN); 222 | #endif 223 | 224 | // https://docs.espressif.com/projects/arduino-esp32/en/latest/api/wifi.html#usestaticbuffers 225 | WiFi.useStaticBuffers(true); 226 | 227 | WiFi.mode(WIFI_STA); 228 | 229 | M5.Display.startWrite(); 230 | M5.Display.fillScreen(BLACK); 231 | M5.Display.setTextColor(GREEN, BLACK); 232 | M5.Display.setTextSize(2); 233 | M5.Display.drawLine(64, 220, 64, 239, GREEN); 234 | M5.Display.drawLine(60, 235, 64, 239, GREEN); 235 | M5.Display.drawLine(68, 235, 64, 239, GREEN); 236 | M5.Display.setCursor(64, 200); 237 | M5.Display.print("Press to setup Wi-Fi"); 238 | M5.Display.endWrite(); 239 | 240 | int numOfRetriesRemaining = 3; 241 | while (0 < numOfRetriesRemaining) { 242 | M5.update(); 243 | if (M5.BtnA.isPressed()) { 244 | break; 245 | } 246 | 247 | M5.Display.startWrite(); 248 | M5.Display.setCursor(64, 180); 249 | M5.Display.print(numOfRetriesRemaining); 250 | M5.Display.endWrite(); 251 | numOfRetriesRemaining--; 252 | delay(1000); 253 | } 254 | 255 | M5.Display.startWrite(); 256 | M5.Display.clear(); 257 | M5.Display.endWrite(); 258 | 259 | if (M5.BtnA.isPressed()) { 260 | WiFi.beginSmartConfig(); 261 | 262 | M5.Display.startWrite(); 263 | M5.Display.setCursor(0, 0); 264 | M5.Display.print("Waiting for SmartConfig"); 265 | M5.Display.endWrite(); 266 | 267 | while (!WiFi.smartConfigDone()) { 268 | delay(500); 269 | M5.Display.startWrite(); 270 | M5.Display.print("."); 271 | M5.Display.endWrite(); 272 | 273 | if (60000 < millis()) { 274 | ESP.restart(); 275 | } 276 | } 277 | } else { 278 | WiFi.begin(); 279 | } 280 | 281 | M5.Display.startWrite(); 282 | M5.Display.clear(); 283 | M5.Display.setCursor(0, 0); 284 | M5.Display.print("Starting up..."); 285 | M5.Display.setCursor(0, LAYOUT_LINE_HEIGHT); 286 | M5.Display.print(VERSION_STRING); 287 | M5.Display.setCursor(0, LAYOUT_LINE_HEIGHT * 2); 288 | M5.Display.printf("SDK: %s", ESP.getSdkVersion()); 289 | M5.Display.setCursor(0, LAYOUT_LINE_HEIGHT * 3); 290 | M5.Display.printf("MAC: %s", WiFi.macAddress().c_str()); 291 | M5.Display.endWrite(); 292 | 293 | preferences.begin(DEVICE_NAME.c_str(), false); 294 | unitOnPortB = preferences.getInt("unitOnPortB", UNIT_NONE); 295 | distRangeMin = preferences.getInt("distRangeMin", DIST_RANGE_MIN); 296 | distRangeMax = preferences.getInt("distRangeMax", DIST_RANGE_MAX); 297 | eCO2RangeMin = preferences.getInt("eCO2RangeMin", ECO2_RANGE_MIN); 298 | eCO2RangeMax = preferences.getInt("eCO2RangeMax", ECO2_RANGE_MAX); 299 | 300 | rfidTagUid[0] = preferences.getString("rfidTagUid[0]", "**:**:**:**"); 301 | rfidTagUid[1] = preferences.getString("rfidTagUid[1]", "**:**:**:**"); 302 | rfidTagUid[2] = preferences.getString("rfidTagUid[2]", "**:**:**:**"); 303 | rfidTagUid[3] = preferences.getString("rfidTagUid[3]", "**:**:**:**"); 304 | 305 | updateFlagsRegardingPortB(); 306 | 307 | // Disable the speaker noise 308 | M5.Speaker.begin(); 309 | M5.Speaker.setVolume(0); 310 | 311 | // Check if a JOYSTICK Unit is available at the I2C address 312 | Wire.beginTransmission(I2C_ADDR_JOYSTICK); 313 | if (Wire.endTransmission() == 0) { 314 | isJoystickConnected = true; 315 | } 316 | 317 | if (touchSensor.begin(I2C_ADDR_MPR121)) { 318 | isTouchSensorConnected = true; 319 | } 320 | 321 | numOfRetriesRemaining = 5; 322 | while (0 < numOfRetriesRemaining) { 323 | if (gestureSensor.begin() == 0) { 324 | isGestureSensorConnected = true; 325 | gestureSensor.setGestureHighRate(true); 326 | break; 327 | } 328 | 329 | numOfRetriesRemaining--; 330 | delay(100); 331 | } 332 | 333 | if (rangingSensor.init()) { 334 | isRangingSensorConnected = true; 335 | 336 | // Set timeout to 25 ms 337 | rangingSensor.setTimeout(25); 338 | 339 | // Set measurement timing budget to 20000 us = 20 ms 340 | rangingSensor.setMeasurementTimingBudget(20000); 341 | rangingSensor.startContinuous(); 342 | } 343 | 344 | if (gasSensor.begin()) { 345 | isGasSensorConnected = true; 346 | } 347 | 348 | // Check if an RFID Unit is available at the I2C address 349 | Wire.beginTransmission(I2C_ADDR_MFRC522); 350 | if (Wire.endTransmission() == 0) { 351 | rfidReader.PCD_Init(); 352 | isRfidReaderConnected = true; 353 | sprintf(buttonsStatus2, "RFID Tag:None"); 354 | } 355 | 356 | bleKeyboard.begin(); 357 | 358 | unsigned long startTime = millis(); 359 | while (WiFi.status() != WL_CONNECTED) { 360 | delay(500); 361 | unsigned long elapsedTime = millis(); 362 | if (elapsedTime > 10000) { 363 | break; 364 | } 365 | } 366 | 367 | if (WiFi.status() == WL_CONNECTED) { 368 | server.on("/input", handleInputRequest); 369 | server.on("/output", handleOutputRequest); 370 | server.onNotFound(handleNotFound); 371 | 372 | server.begin(); 373 | xTaskCreatePinnedToCore(serverLoop, "serverLoop", 8192, NULL, 374 | CONFIG_ARDUINO_UDP_TASK_PRIORITY, NULL, 0); 375 | } 376 | 377 | M5.Display.startWrite(); 378 | M5.Display.clear(); 379 | drawButtons(currentScreenMode); 380 | M5.Display.endWrite(); 381 | } 382 | 383 | void loop() { 384 | const unsigned long LOOP_INTERVAL = 25; 385 | unsigned long start = millis(); 386 | 387 | M5.update(); 388 | M5.Display.startWrite(); 389 | handleButtons(); 390 | M5.Display.endWrite(); 391 | 392 | isBluetoothConnected = bleKeyboard.isConnected(); 393 | bool requestToSend = isBluetoothConnected && isSendingKeyboardEvents; 394 | 395 | if (isGestureSensorConnected) { 396 | // It uses both the joystick channel and the buttons channel 397 | handleGestureSensor(requestToSend); 398 | } else { 399 | // It uses the joystick channel 400 | if (isJoystickConnected) { 401 | handleJoystick(requestToSend); 402 | } 403 | 404 | // It uses the buttons channel 405 | if (isDualButtonConnected) { 406 | handleDualButton(requestToSend); 407 | } 408 | if (isTouchSensorConnected) { 409 | handleTouchSensor(requestToSend); 410 | } else if (isRfidReaderConnected && !isWaitingForNewRfidTag) { 411 | handleRFID(requestToSend); 412 | } 413 | } 414 | 415 | // It uses the analog channel 416 | if (isGasSensorConnected) { 417 | handleGasSensor(requestToSend); 418 | } else if (isRangingSensorConnected) { 419 | handleRangingSensor(requestToSend); 420 | } else if (isAnalogSensorConnected) { 421 | handleAnalogInput(requestToSend); 422 | } 423 | 424 | M5.Display.startWrite(); 425 | if (currentScreenMode == SCREEN_MAIN) { 426 | drawMainScreen(); 427 | } else { 428 | drawPreferencesScreen(); 429 | } 430 | M5.Display.endWrite(); 431 | 432 | unsigned long now = millis(); 433 | unsigned long elapsed = now - start; 434 | 435 | M5.Display.startWrite(); 436 | if (currentScreenMode == SCREEN_MAIN) { 437 | M5.Display.setTextSize(1); 438 | M5.Display.setCursor(0, 200); 439 | M5.Display.printf("Loop: %3d ms | ", elapsed); 440 | M5.Display.printf("Bat: %3d %%", M5.Power.getBatteryLevel()); 441 | M5.Display.setTextSize(2); 442 | } 443 | M5.Display.endWrite(); 444 | 445 | if (elapsed < LOOP_INTERVAL) { 446 | delay(LOOP_INTERVAL - elapsed); 447 | } else { 448 | delay(1); 449 | } 450 | } 451 | 452 | void serverLoop(void *parameters) { 453 | while (true) { 454 | vTaskDelay(1); 455 | if (WiFi.status() == WL_CONNECTED) { 456 | server.handleClient(); 457 | } 458 | } 459 | } 460 | 461 | void handleButtons() { 462 | if (currentScreenMode != SCREEN_MAIN) { 463 | M5.Display.setCursor(0, 0 + LAYOUT_LINE_HEIGHT * currentMenuItem); 464 | M5.Display.print(">"); 465 | } 466 | 467 | if (M5.BtnA.wasPressed()) { 468 | switch (currentScreenMode) { 469 | case SCREEN_MAIN: 470 | currentScreenMode = SCREEN_PREFS_SELECT; 471 | M5.Display.clear(TFT_BLACK); 472 | drawButtons(currentScreenMode); 473 | break; 474 | case SCREEN_PREFS_SELECT: 475 | currentScreenMode = SCREEN_MAIN; 476 | M5.Display.clear(TFT_BLACK); 477 | drawButtons(currentScreenMode); 478 | break; 479 | case SCREEN_PREFS_EDIT: 480 | switch (currentMenuItem) { 481 | case 0: 482 | unitOnPortB = unitOnPortB - 1; 483 | if (unitOnPortB < 0) { 484 | unitOnPortB = UNIT_LAST; 485 | } 486 | preferences.putInt("unitOnPortB", unitOnPortB); 487 | updateFlagsRegardingPortB(); 488 | break; 489 | case 1: 490 | eCO2RangeMin = constrain((eCO2RangeMin - PREFS_MENU_INC_DEC_UNIT), 491 | ECO2_RANGE_MIN, 492 | eCO2RangeMax - PREFS_MENU_INC_DEC_UNIT); 493 | preferences.putInt("eCO2RangeMin", eCO2RangeMin); 494 | break; 495 | case 2: 496 | eCO2RangeMax = constrain((eCO2RangeMax - PREFS_MENU_INC_DEC_UNIT), 497 | eCO2RangeMin + PREFS_MENU_INC_DEC_UNIT, 498 | ECO2_RANGE_MAX); 499 | preferences.putInt("eCO2RangeMax", eCO2RangeMax); 500 | break; 501 | case 3: 502 | distRangeMin = constrain((distRangeMin - PREFS_MENU_INC_DEC_UNIT), 503 | DIST_RANGE_MIN, 504 | distRangeMax - PREFS_MENU_INC_DEC_UNIT); 505 | preferences.putInt("distRangeMin", distRangeMin); 506 | break; 507 | case 4: 508 | distRangeMax = constrain((distRangeMax - PREFS_MENU_INC_DEC_UNIT), 509 | distRangeMin + PREFS_MENU_INC_DEC_UNIT, 510 | DIST_RANGE_MAX); 511 | preferences.putInt("distRangeMax", distRangeMax); 512 | break; 513 | default: 514 | break; 515 | } 516 | break; 517 | default: 518 | break; 519 | } 520 | } 521 | 522 | int rfidTagIdx = currentMenuItem - PREFS_MENU_INDEX_RFID_1; 523 | 524 | if (M5.BtnC.wasPressed()) { 525 | switch (currentScreenMode) { 526 | case SCREEN_MAIN: 527 | if (isSendingKeyboardEvents) { 528 | isSendingKeyboardEvents = false; 529 | drawButtons(currentScreenMode); 530 | } else { 531 | isSendingKeyboardEvents = true; 532 | drawButtons(currentScreenMode); 533 | } 534 | break; 535 | case SCREEN_PREFS_SELECT: 536 | M5.Display.setCursor(0, 0 + LAYOUT_LINE_HEIGHT * currentMenuItem); 537 | M5.Display.print(" "); 538 | currentMenuItem = (currentMenuItem + 1) % PREFS_MENU_NUM_ITEMS; 539 | M5.Display.setCursor(0, 0 + LAYOUT_LINE_HEIGHT * currentMenuItem); 540 | M5.Display.print(">"); 541 | drawButtons(currentScreenMode); 542 | break; 543 | case SCREEN_PREFS_RFID: 544 | rfidTagUid[rfidTagIdx] = "**:**:**:**"; 545 | putRfidTagUidString(rfidTagIdx, rfidTagUid[rfidTagIdx]); 546 | isWaitingForNewRfidTag = true; 547 | break; 548 | case SCREEN_PREFS_EDIT: 549 | switch (currentMenuItem) { 550 | case 0: 551 | unitOnPortB = unitOnPortB + 1; 552 | if (unitOnPortB > UNIT_LAST) { 553 | unitOnPortB = UNIT_FIRST; 554 | } 555 | preferences.putInt("unitOnPortB", unitOnPortB); 556 | updateFlagsRegardingPortB(); 557 | break; 558 | case 1: 559 | eCO2RangeMin = constrain((eCO2RangeMin + PREFS_MENU_INC_DEC_UNIT), 560 | ECO2_RANGE_MIN, 561 | eCO2RangeMax - PREFS_MENU_INC_DEC_UNIT); 562 | preferences.putInt("eCO2RangeMin", eCO2RangeMin); 563 | break; 564 | case 2: 565 | eCO2RangeMax = constrain((eCO2RangeMax + PREFS_MENU_INC_DEC_UNIT), 566 | eCO2RangeMin + PREFS_MENU_INC_DEC_UNIT, 567 | ECO2_RANGE_MAX); 568 | preferences.putInt("eCO2RangeMax", eCO2RangeMax); 569 | break; 570 | case 3: 571 | distRangeMin = constrain((distRangeMin + PREFS_MENU_INC_DEC_UNIT), 572 | DIST_RANGE_MIN, 573 | distRangeMax - PREFS_MENU_INC_DEC_UNIT); 574 | preferences.putInt("distRangeMin", distRangeMin); 575 | break; 576 | case 4: 577 | distRangeMax = constrain((distRangeMax + PREFS_MENU_INC_DEC_UNIT), 578 | distRangeMin + PREFS_MENU_INC_DEC_UNIT, 579 | DIST_RANGE_MAX); 580 | preferences.putInt("distRangeMax", distRangeMax); 581 | break; 582 | default: 583 | break; 584 | } 585 | break; 586 | default: 587 | break; 588 | } 589 | } 590 | 591 | if (M5.BtnA.pressedFor(500)) { 592 | if (currentScreenMode == SCREEN_PREFS_EDIT) { 593 | switch (currentMenuItem) { 594 | case 1: 595 | eCO2RangeMin = 596 | constrain((eCO2RangeMin - PREFS_MENU_INC_DEC_UNIT), 597 | ECO2_RANGE_MIN, eCO2RangeMax - PREFS_MENU_INC_DEC_UNIT); 598 | break; 599 | case 2: 600 | eCO2RangeMax = 601 | constrain((eCO2RangeMax - PREFS_MENU_INC_DEC_UNIT), 602 | eCO2RangeMin + PREFS_MENU_INC_DEC_UNIT, ECO2_RANGE_MAX); 603 | break; 604 | case 3: 605 | distRangeMin = 606 | constrain((distRangeMin - PREFS_MENU_INC_DEC_UNIT), 607 | DIST_RANGE_MIN, distRangeMax - PREFS_MENU_INC_DEC_UNIT); 608 | break; 609 | case 4: 610 | distRangeMax = 611 | constrain((distRangeMax - PREFS_MENU_INC_DEC_UNIT), 612 | distRangeMin + PREFS_MENU_INC_DEC_UNIT, DIST_RANGE_MAX); 613 | break; 614 | default: 615 | break; 616 | } 617 | } 618 | } 619 | 620 | if (M5.BtnC.pressedFor(500)) { 621 | if (currentScreenMode == SCREEN_PREFS_EDIT) { 622 | switch (currentMenuItem) { 623 | case 1: 624 | eCO2RangeMin = 625 | constrain((eCO2RangeMin + PREFS_MENU_INC_DEC_UNIT), 626 | ECO2_RANGE_MIN, eCO2RangeMax - PREFS_MENU_INC_DEC_UNIT); 627 | break; 628 | case 2: 629 | eCO2RangeMax = 630 | constrain((eCO2RangeMax + PREFS_MENU_INC_DEC_UNIT), 631 | eCO2RangeMin + PREFS_MENU_INC_DEC_UNIT, ECO2_RANGE_MAX); 632 | break; 633 | case 3: 634 | distRangeMin = 635 | constrain((distRangeMin + PREFS_MENU_INC_DEC_UNIT), 636 | DIST_RANGE_MIN, distRangeMax - PREFS_MENU_INC_DEC_UNIT); 637 | break; 638 | case 4: 639 | distRangeMax = 640 | constrain((distRangeMax + PREFS_MENU_INC_DEC_UNIT), 641 | distRangeMin + PREFS_MENU_INC_DEC_UNIT, DIST_RANGE_MAX); 642 | break; 643 | default: 644 | break; 645 | } 646 | } 647 | } 648 | 649 | if (M5.BtnB.wasPressed()) { 650 | switch (currentScreenMode) { 651 | case SCREEN_PREFS_SELECT: 652 | if (currentMenuItem < PREFS_MENU_INDEX_RFID_1) { 653 | currentScreenMode = SCREEN_PREFS_EDIT; 654 | } else { 655 | currentScreenMode = SCREEN_PREFS_RFID; 656 | } 657 | break; 658 | case SCREEN_PREFS_RFID: 659 | isWaitingForNewRfidTag = false; 660 | currentScreenMode = SCREEN_PREFS_SELECT; 661 | break; 662 | case SCREEN_PREFS_EDIT: 663 | currentScreenMode = SCREEN_PREFS_SELECT; 664 | break; 665 | default: 666 | break; 667 | } 668 | 669 | drawButtons(currentScreenMode); 670 | } 671 | } 672 | 673 | void attachVibrator() { 674 | ledcSetup(LEDC_CHANNEL_FOR_VIBRATOR, 10000, 8); 675 | ledcAttachPin(VIBRATOR_PIN, LEDC_CHANNEL_FOR_VIBRATOR); 676 | } 677 | 678 | void detachVibrator() { ledcDetachPin(VIBRATOR_PIN); } 679 | 680 | void updateFlagsRegardingPortB() { 681 | switch (unitOnPortB) { 682 | case UNIT_NONE: 683 | servo.detach(); 684 | detachVibrator(); 685 | isDualButtonConnected = false; 686 | isAnalogSensorConnected = false; 687 | sprintf(analogStatus, " "); 688 | isServoConnected = false; 689 | isVibratorConnected = false; 690 | break; 691 | case UNIT_DUAL_BUTTON: 692 | servo.detach(); 693 | detachVibrator(); 694 | pinMode(PIN_PORT_B_A, INPUT); 695 | pinMode(PIN_PORT_B_B, INPUT); 696 | isDualButtonConnected = true; 697 | isAnalogSensorConnected = false; 698 | sprintf(analogStatus, " "); 699 | isServoConnected = false; 700 | isVibratorConnected = false; 701 | break; 702 | case UNIT_ANALOG_IN: 703 | servo.detach(); 704 | detachVibrator(); 705 | pinMode(PIN_PORT_B_A, INPUT); 706 | pinMode(PIN_PORT_B_B, INPUT); 707 | isDualButtonConnected = false; 708 | isAnalogSensorConnected = true; 709 | isServoConnected = false; 710 | isVibratorConnected = false; 711 | break; 712 | case UNIT_SERVO: 713 | detachVibrator(); 714 | servo.attach(SERVO_PIN, 90); 715 | servo.setEasingType(EASE_CUBIC_IN_OUT); 716 | isDualButtonConnected = false; 717 | isAnalogSensorConnected = false; 718 | sprintf(analogStatus, " "); 719 | isServoConnected = true; 720 | isVibratorConnected = false; 721 | break; 722 | case UNIT_VIBRATOR: 723 | servo.detach(); 724 | attachVibrator(); 725 | isDualButtonConnected = false; 726 | isAnalogSensorConnected = false; 727 | sprintf(analogStatus, " "); 728 | isServoConnected = false; 729 | isVibratorConnected = true; 730 | break; 731 | default: 732 | break; 733 | } 734 | } 735 | 736 | void drawMainScreen() { 737 | if (WiFi.status() == WL_CONNECTED) { 738 | M5.Display.setCursor(0, 0); 739 | M5.Display.printf("B: %s | W: %s", isBluetoothConnected ? "<->" : "-X-", 740 | WiFi.localIP().toString().c_str()); 741 | } else { 742 | M5.Display.setCursor(0, 0); 743 | M5.Display.printf("Bluetooth: %s", 744 | isBluetoothConnected ? "Connected " : "Disconnected"); 745 | } 746 | 747 | M5.Display.setCursor(0, LAYOUT_ANALOG_CH_TOP); 748 | M5.Display.print(analogStatus); 749 | 750 | M5.Display.setCursor(0, LAYOUT_JOYSTICK_CH_TOP); 751 | M5.Display.print(joystickStatus); 752 | 753 | M5.Display.setCursor(0, LAYOUT_BUTTONS_CH_TOP); 754 | if (isDualButtonConnected || isTouchSensorConnected || 755 | isRfidReaderConnected) { 756 | M5.Display.print("BUTTONS:"); 757 | } 758 | 759 | if (isDualButtonConnected) { 760 | M5.Display.setCursor(0, LAYOUT_BUTTONS_CH_TOP + LAYOUT_LINE_HEIGHT); 761 | M5.Display.print(buttonsStatus1); 762 | M5.Display.setCursor(0, LAYOUT_BUTTONS_CH_TOP + LAYOUT_LINE_HEIGHT * 2); 763 | M5.Display.print(buttonsStatus2); 764 | } else { 765 | M5.Display.setCursor(0, LAYOUT_BUTTONS_CH_TOP + LAYOUT_LINE_HEIGHT); 766 | M5.Display.print(buttonsStatus2); 767 | } 768 | 769 | xSemaphoreTake(mutex, portMAX_DELAY); 770 | if (receivedHttpRequest) { 771 | M5.Display.setColor(TFT_GREEN); 772 | M5.Display.fillRect(306, 0, 14, 14); 773 | receivedHttpRequest = false; 774 | } else { 775 | M5.Display.setColor(TFT_BLACK); 776 | M5.Display.fillRect(306, 0, 14, 14); 777 | } 778 | xSemaphoreGive(mutex); 779 | 780 | if (sentKeyboardEvent) { 781 | M5.Display.setColor(TFT_GREEN); 782 | M5.Display.fillRect(306, 221, 14, 14); 783 | sentKeyboardEvent = false; 784 | } else { 785 | M5.Display.setColor(TFT_BLACK); 786 | M5.Display.fillRect(306, 221, 14, 14); 787 | } 788 | } 789 | 790 | void drawPreferencesScreen() { 791 | M5.Display.setCursor(20, 0 + LAYOUT_LINE_HEIGHT * 0); 792 | switch (unitOnPortB) { 793 | case UNIT_NONE: 794 | M5.Display.print("Port B: NONE "); 795 | break; 796 | case UNIT_DUAL_BUTTON: 797 | M5.Display.print("Port B: DUAL BUTTON"); 798 | break; 799 | case UNIT_ANALOG_IN: 800 | M5.Display.print("Port B: ANALOG IN "); 801 | break; 802 | case UNIT_SERVO: 803 | M5.Display.print("Port B: SERVO "); 804 | break; 805 | case UNIT_VIBRATOR: 806 | M5.Display.print("Port B: VIBRATOR "); 807 | break; 808 | default: 809 | break; 810 | } 811 | 812 | M5.Display.setCursor(20, 0 + LAYOUT_LINE_HEIGHT * 1); 813 | M5.Display.printf("eCO2 Range Min: %5d", eCO2RangeMin); 814 | M5.Display.setCursor(20, 0 + LAYOUT_LINE_HEIGHT * 2); 815 | M5.Display.printf(" Max: %5d", eCO2RangeMax); 816 | 817 | M5.Display.setCursor(20, 0 + LAYOUT_LINE_HEIGHT * 3); 818 | M5.Display.printf("Dist Range Min: %5d", distRangeMin); 819 | M5.Display.setCursor(20, 0 + LAYOUT_LINE_HEIGHT * 4); 820 | M5.Display.printf(" Max: %5d", distRangeMax); 821 | 822 | for (int i = 0; i < 4; i++) { 823 | M5.Display.setCursor( 824 | 20, 0 + LAYOUT_LINE_HEIGHT * (PREFS_MENU_INDEX_RFID_1 + i)); 825 | M5.Display.printf("RFID %d: %s", i + 1, rfidTagUid[i].c_str()); 826 | } 827 | 828 | if (!isRfidReaderConnected) { 829 | return; 830 | } 831 | 832 | if (!isWaitingForNewRfidTag) { 833 | return; 834 | } 835 | 836 | if (!rfidReader.PICC_IsNewCardPresent()) { 837 | return; 838 | } 839 | 840 | if (!rfidReader.PICC_ReadCardSerial()) { 841 | return; 842 | } 843 | 844 | if (rfidReader.uid.size < 4) { 845 | return; 846 | } 847 | 848 | int rfidTagIdx = currentMenuItem - PREFS_MENU_INDEX_RFID_1; 849 | rfidTagUid[rfidTagIdx] = getRfidTagUidString(); 850 | putRfidTagUidString(rfidTagIdx, rfidTagUid[rfidTagIdx]); 851 | 852 | isWaitingForNewRfidTag = false; 853 | 854 | if (currentScreenMode == SCREEN_PREFS_RFID) { 855 | currentScreenMode = SCREEN_PREFS_SELECT; 856 | drawButtons(currentScreenMode); 857 | } 858 | } 859 | 860 | void handleDualButton(bool updateRequested) { 861 | const int KEY_ID_RED_BUTTON = 0; 862 | const int KEY_ID_BLUE_BUTTON = 1; 863 | 864 | static bool wasRedButtonPressed = false; 865 | static bool wasBlueButtonPressed = false; 866 | 867 | bool isRedButtonPressed = digitalRead(PIN_PORT_B_B) == LOW; 868 | bool isBlueButtonPressed = digitalRead(PIN_PORT_B_A) == LOW; 869 | 870 | sprintf(buttonsStatus1, "Red:%d Blue:%d", isRedButtonPressed, 871 | isBlueButtonPressed); 872 | 873 | if (updateRequested) { 874 | if (!wasRedButtonPressed && isRedButtonPressed) { 875 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[KEY_ID_RED_BUTTON]); 876 | sentKeyboardEvent = true; 877 | } else if (wasRedButtonPressed && !isRedButtonPressed) { 878 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[KEY_ID_RED_BUTTON]); 879 | sentKeyboardEvent = true; 880 | } 881 | 882 | if (!wasBlueButtonPressed && isBlueButtonPressed) { 883 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[KEY_ID_BLUE_BUTTON]); 884 | sentKeyboardEvent = true; 885 | } else if (wasBlueButtonPressed && !isBlueButtonPressed) { 886 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[KEY_ID_BLUE_BUTTON]); 887 | sentKeyboardEvent = true; 888 | } 889 | } 890 | 891 | wasRedButtonPressed = isRedButtonPressed; 892 | wasBlueButtonPressed = isBlueButtonPressed; 893 | 894 | xSemaphoreTake(mutex, portMAX_DELAY); 895 | buttonValuesForReporting[KEY_ID_RED_BUTTON] = isRedButtonPressed; 896 | buttonValuesForReporting[KEY_ID_BLUE_BUTTON] = isBlueButtonPressed; 897 | xSemaphoreGive(mutex); 898 | } 899 | 900 | void handleAnalogInput(bool updateRequested) { 901 | static int lastAnalogValue = -1; 902 | 903 | // convert from 4096 steps to 11 steps 904 | int sensorReading = analogRead(PIN_PORT_B_A); 905 | int currentAnalogValue = map(sensorReading, 0, 4095, 0, 10); 906 | if (lastAnalogValue != currentAnalogValue) { 907 | sprintf(analogStatus, "ANALOG:%2d (%4d)", currentAnalogValue, 908 | sensorReading); 909 | 910 | if (updateRequested) { 911 | bleKeyboard.write(KEYS_FOR_ANALOG_CH[currentAnalogValue]); 912 | sentKeyboardEvent = true; 913 | } 914 | lastAnalogValue = currentAnalogValue; 915 | } 916 | 917 | xSemaphoreTake(mutex, portMAX_DELAY); 918 | analogValueForReporting = currentAnalogValue; 919 | xSemaphoreGive(mutex); 920 | } 921 | 922 | void handleJoystick(bool updateRequested) { 923 | const byte JOYSTICK_CENTER_RANGE_L = 95; 924 | const byte JOYSTICK_CENTER_RANGE_H = 159; 925 | static int lastJoystickX = -2; 926 | static int lastJoystickY = -2; 927 | static byte xData = 0; 928 | static byte yData = 0; 929 | static byte bData = 0; 930 | 931 | Wire.requestFrom(I2C_ADDR_JOYSTICK, 3); 932 | if (Wire.available()) { 933 | xData = Wire.read(); 934 | yData = Wire.read(); 935 | bData = Wire.read(); 936 | } 937 | 938 | int curJoystickX = 0; 939 | if (xData < JOYSTICK_CENTER_RANGE_L) { 940 | curJoystickX = -1; 941 | } else if (xData > JOYSTICK_CENTER_RANGE_H) { 942 | curJoystickX = 1; 943 | } 944 | 945 | int curJoystickY = 0; 946 | if (yData < JOYSTICK_CENTER_RANGE_L) { 947 | curJoystickY = -1; 948 | } else if (yData > JOYSTICK_CENTER_RANGE_H) { 949 | curJoystickY = 1; 950 | } 951 | 952 | sprintf(joystickStatus, "JOYSTICK:%+d, %+d (%3d, %3d)", curJoystickX, 953 | curJoystickY, xData, yData); 954 | 955 | if (lastJoystickX != curJoystickX || lastJoystickY != curJoystickY) { 956 | if (updateRequested) { 957 | if (curJoystickX == -1 && curJoystickY == 1) { 958 | bleKeyboard.write(KEY_JOYSTICK_LEFT_UP); 959 | } else if (curJoystickX == 0 && curJoystickY == 1) { 960 | bleKeyboard.write(KEY_JOYSTICK_CENTER_UP); 961 | } else if (curJoystickX == 1 && curJoystickY == 1) { 962 | bleKeyboard.write(KEY_JOYSTICK_RIGHT_UP); 963 | } else if (curJoystickX == -1 && curJoystickY == 0) { 964 | bleKeyboard.write(KEY_JOYSTICK_LEFT); 965 | } else if (curJoystickX == 0 && curJoystickY == 0) { 966 | bleKeyboard.write(KEY_JOYSTICK_CENTER); 967 | } else if (curJoystickX == 1 && curJoystickY == 0) { 968 | bleKeyboard.write(KEY_JOYSTICK_RIGHT); 969 | } else if (curJoystickX == -1 && curJoystickY == -1) { 970 | bleKeyboard.write(KEY_JOYSTICK_LEFT_DOWN); 971 | } else if (curJoystickX == 0 && curJoystickY == -1) { 972 | bleKeyboard.write(KEY_JOYSTICK_CENTER_DOWN); 973 | } else if (curJoystickX == 1 && curJoystickY == -1) { 974 | bleKeyboard.write(KEY_JOYSTICK_RIGHT_DOWN); 975 | } 976 | sentKeyboardEvent = true; 977 | } 978 | 979 | lastJoystickX = curJoystickX; 980 | lastJoystickY = curJoystickY; 981 | } 982 | 983 | xSemaphoreTake(mutex, portMAX_DELAY); 984 | if (curJoystickX == -1 && curJoystickY == 1) { 985 | sprintf((char *)joystickValueForReporting, "Left-Up"); 986 | } else if (curJoystickX == 0 && curJoystickY == 1) { 987 | sprintf((char *)joystickValueForReporting, "Center-Up"); 988 | } else if (curJoystickX == 1 && curJoystickY == 1) { 989 | sprintf((char *)joystickValueForReporting, "Right-Up"); 990 | } else if (curJoystickX == -1 && curJoystickY == 0) { 991 | sprintf((char *)joystickValueForReporting, "Left"); 992 | } else if (curJoystickX == 0 && curJoystickY == 0) { 993 | sprintf((char *)joystickValueForReporting, "Center"); 994 | } else if (curJoystickX == 1 && curJoystickY == 0) { 995 | sprintf((char *)joystickValueForReporting, "Right"); 996 | } else if (curJoystickX == -1 && curJoystickY == -1) { 997 | sprintf((char *)joystickValueForReporting, "Left-Down"); 998 | } else if (curJoystickX == 0 && curJoystickY == -1) { 999 | sprintf((char *)joystickValueForReporting, "Center-Down"); 1000 | } else if (curJoystickX == 1 && curJoystickY == -1) { 1001 | sprintf((char *)joystickValueForReporting, "Right-Down"); 1002 | } 1003 | xSemaphoreGive(mutex); 1004 | } 1005 | 1006 | void handleRangingSensor(bool updateRequested) { 1007 | static int lastValue = -1; 1008 | 1009 | unsigned int readRange = rangingSensor.readRangeContinuousMillimeters(); 1010 | // unsigned int readRange = rangingSensor.readRangeSingleMillimeters(); 1011 | if (rangingSensor.timeoutOccurred()) { 1012 | // Ignore the reading since a timeout occurred 1013 | return; 1014 | } 1015 | 1016 | int range = constrain(readRange, distRangeMin, distRangeMax); 1017 | 1018 | // convert to 11 steps 1019 | int currentValue = map(range, distRangeMin, distRangeMax, 0, 10); 1020 | 1021 | sprintf(analogStatus, "ANALOG:%2d (%4d mm)", currentValue, range); 1022 | 1023 | if (lastValue != currentValue) { 1024 | if (updateRequested) { 1025 | bleKeyboard.write(KEYS_FOR_ANALOG_CH[currentValue]); 1026 | sentKeyboardEvent = true; 1027 | } 1028 | lastValue = currentValue; 1029 | } 1030 | 1031 | xSemaphoreTake(mutex, portMAX_DELAY); 1032 | analogValueForReporting = currentValue; 1033 | xSemaphoreGive(mutex); 1034 | } 1035 | 1036 | void handleGasSensor(bool updateRequested) { 1037 | static int lastValue = -1; 1038 | 1039 | if (!gasSensor.IAQmeasure()) { 1040 | return; 1041 | } 1042 | 1043 | int eCO2 = constrain(gasSensor.eCO2, eCO2RangeMin, eCO2RangeMax); 1044 | 1045 | // convert to 11 steps 1046 | int currentValue = map(eCO2, eCO2RangeMin, eCO2RangeMax, 0, 10); 1047 | sprintf(analogStatus, "ANALOG:%2d (%5d ppm)", currentValue, gasSensor.eCO2); 1048 | 1049 | if (lastValue != currentValue) { 1050 | if (updateRequested) { 1051 | bleKeyboard.write(KEYS_FOR_ANALOG_CH[currentValue]); 1052 | sentKeyboardEvent = true; 1053 | } 1054 | lastValue = currentValue; 1055 | } 1056 | 1057 | xSemaphoreTake(mutex, portMAX_DELAY); 1058 | analogValueForReporting = currentValue; 1059 | xSemaphoreGive(mutex); 1060 | } 1061 | 1062 | // Reference: 1063 | // https://github.com/miguelbalboa/rfid/issues/188#issuecomment-495395401 1064 | void handleRFID(bool updateRequested) { 1065 | static int lastRfidTag = -1; 1066 | static bool tagPresents = false; 1067 | static bool couldNotSeeTag = false; 1068 | static int consecutiveCountsOfNotSeeTag = 0; 1069 | 1070 | if (!tagPresents) { 1071 | if (!rfidReader.PICC_IsNewCardPresent()) { 1072 | return; 1073 | } 1074 | 1075 | if (!rfidReader.PICC_ReadCardSerial()) { 1076 | return; 1077 | } 1078 | 1079 | if (rfidReader.uid.size < 4) { 1080 | return; 1081 | } 1082 | 1083 | String curRfidTagUid = getRfidTagUidString(); 1084 | 1085 | for (int i = 0; i < 4; i++) { 1086 | if (rfidTagUid[i] == curRfidTagUid) { 1087 | if (updateRequested) { 1088 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[i + OFFSET_BUTTON_3]); 1089 | sentKeyboardEvent = true; 1090 | } 1091 | sprintf(buttonsStatus2, "RFID Tag:%d ", i); 1092 | lastRfidTag = i; 1093 | 1094 | xSemaphoreTake(mutex, portMAX_DELAY); 1095 | buttonValuesForReporting[i + OFFSET_BUTTON_3] = 1; 1096 | xSemaphoreGive(mutex); 1097 | break; 1098 | } 1099 | } 1100 | 1101 | tagPresents = true; 1102 | couldNotSeeTag = false; 1103 | consecutiveCountsOfNotSeeTag = 0; 1104 | } else { 1105 | bool canNotSeeTag = !rfidReader.PICC_IsNewCardPresent(); 1106 | 1107 | if (canNotSeeTag && couldNotSeeTag) { 1108 | consecutiveCountsOfNotSeeTag++; 1109 | } 1110 | 1111 | couldNotSeeTag = canNotSeeTag; 1112 | 1113 | if (consecutiveCountsOfNotSeeTag > 2) { 1114 | if (updateRequested) { 1115 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[lastRfidTag + OFFSET_BUTTON_3]); 1116 | sentKeyboardEvent = true; 1117 | } 1118 | if (currentScreenMode == SCREEN_MAIN) { 1119 | sprintf(buttonsStatus2, "RFID Tag:None"); 1120 | } 1121 | 1122 | xSemaphoreTake(mutex, portMAX_DELAY); 1123 | buttonValuesForReporting[lastRfidTag + OFFSET_BUTTON_3] = 0; 1124 | xSemaphoreGive(mutex); 1125 | 1126 | lastRfidTag = -1; 1127 | 1128 | delay(100); 1129 | rfidReader.PICC_HaltA(); 1130 | rfidReader.PCD_StopCrypto1(); 1131 | tagPresents = false; 1132 | } 1133 | } 1134 | } 1135 | 1136 | String getRfidTagUidString() { 1137 | String rfidTagUidString = ""; 1138 | 1139 | for (int i = 0; i < 4; i++) { 1140 | rfidTagUidString += rfidReader.uid.uidByte[i] < 0x10 ? "0" : ""; 1141 | rfidTagUidString += String(rfidReader.uid.uidByte[i], HEX); 1142 | if (i < 3) { 1143 | rfidTagUidString += ":"; 1144 | } 1145 | } 1146 | 1147 | return rfidTagUidString; 1148 | } 1149 | 1150 | void putRfidTagUidString(int rfidTagIdx, const String &rfidTagUid) { 1151 | String rfidTagUidKey = "rfidTagUid["; 1152 | rfidTagUidKey += String(rfidTagIdx, DEC); 1153 | rfidTagUidKey += "]"; 1154 | preferences.putString(rfidTagUidKey.c_str(), rfidTagUid.c_str()); 1155 | } 1156 | 1157 | void handleTouchSensor(bool updateRequested) { 1158 | static unsigned int lastTouched = 0; 1159 | 1160 | // Get the currently touched pads 1161 | unsigned int currentlyTouched = touchSensor.touched(); 1162 | sprintf(buttonsStatus2, "CH0:%d CH1:%d CH2:%d CH3:%d", 1163 | bitRead(currentlyTouched, 0), bitRead(currentlyTouched, 1), 1164 | bitRead(currentlyTouched, 2), bitRead(currentlyTouched, 3)); 1165 | 1166 | for (int i = 0; i < 4; i++) { 1167 | bool wasPadTouched = bitRead(lastTouched, i) == 1; 1168 | bool isPadTouched = bitRead(currentlyTouched, i) == 1; 1169 | 1170 | if (updateRequested) { 1171 | if (!wasPadTouched && isPadTouched) { 1172 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[i + OFFSET_BUTTON_3]); 1173 | sentKeyboardEvent = true; 1174 | } else if (wasPadTouched && !isPadTouched) { 1175 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[i + OFFSET_BUTTON_3]); 1176 | sentKeyboardEvent = true; 1177 | } 1178 | } 1179 | 1180 | xSemaphoreTake(mutex, portMAX_DELAY); 1181 | buttonValuesForReporting[i + OFFSET_BUTTON_3] = isPadTouched; 1182 | xSemaphoreGive(mutex); 1183 | } 1184 | 1185 | lastTouched = currentlyTouched; 1186 | } 1187 | 1188 | void handleGestureSensor(bool updateRequested) { 1189 | static unsigned long lastUpdate = 0; 1190 | static bool wasLastGestureNone = false; 1191 | 1192 | DFRobot_PAJ7620U2::eGesture_t gesture = gestureSensor.getGesture(); 1193 | 1194 | unsigned long now = millis(); 1195 | switch (gesture) { 1196 | // Supported gestures 1197 | case gestureSensor.eGestureRight: 1198 | case gestureSensor.eGestureLeft: 1199 | case gestureSensor.eGestureUp: 1200 | case gestureSensor.eGestureDown: 1201 | case gestureSensor.eGestureForward: 1202 | case gestureSensor.eGestureBackward: 1203 | case gestureSensor.eGestureClockwise: 1204 | case gestureSensor.eGestureAntiClockwise: 1205 | case gestureSensor.eGestureWave: 1206 | if (updateRequested) { 1207 | switch (gesture) { 1208 | case gestureSensor.eGestureRight: 1209 | bleKeyboard.write(KEY_JOYSTICK_RIGHT); 1210 | sentKeyboardEvent = true; 1211 | break; 1212 | case gestureSensor.eGestureLeft: 1213 | bleKeyboard.write(KEY_JOYSTICK_LEFT); 1214 | sentKeyboardEvent = true; 1215 | break; 1216 | case gestureSensor.eGestureUp: 1217 | bleKeyboard.write(KEY_JOYSTICK_CENTER_UP); 1218 | sentKeyboardEvent = true; 1219 | break; 1220 | case gestureSensor.eGestureDown: 1221 | bleKeyboard.write(KEY_JOYSTICK_CENTER_DOWN); 1222 | sentKeyboardEvent = true; 1223 | break; 1224 | case gestureSensor.eGestureForward: 1225 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[0]); 1226 | sentKeyboardEvent = true; 1227 | break; 1228 | case gestureSensor.eGestureBackward: 1229 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[1]); 1230 | sentKeyboardEvent = true; 1231 | break; 1232 | case gestureSensor.eGestureClockwise: 1233 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[2]); 1234 | sentKeyboardEvent = true; 1235 | break; 1236 | case gestureSensor.eGestureAntiClockwise: 1237 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[3]); 1238 | sentKeyboardEvent = true; 1239 | break; 1240 | case gestureSensor.eGestureWave: 1241 | bleKeyboard.press(KEYS_FOR_BUTTON_CH[4]); 1242 | sentKeyboardEvent = true; 1243 | break; 1244 | 1245 | default: 1246 | break; 1247 | } 1248 | } 1249 | 1250 | wasLastGestureNone = false; 1251 | lastUpdate = now; 1252 | sprintf(joystickStatus, "GESTURE: %-14s", 1253 | gestureSensor.gestureDescription(gesture).c_str()); 1254 | 1255 | xSemaphoreTake(mutex, portMAX_DELAY); 1256 | sprintf((char *)joystickValueForReporting, 1257 | gestureSensor.gestureDescription(gesture).c_str()); 1258 | xSemaphoreGive(mutex); 1259 | break; 1260 | 1261 | // Not supported gestures and None 1262 | default: 1263 | if (!wasLastGestureNone && ((now - lastUpdate) > 500)) { 1264 | sprintf(joystickStatus, "GESTURE: "); 1265 | if (updateRequested) { 1266 | bleKeyboard.write(KEY_JOYSTICK_CENTER); 1267 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[0]); 1268 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[1]); 1269 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[2]); 1270 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[3]); 1271 | bleKeyboard.release(KEYS_FOR_BUTTON_CH[4]); 1272 | sentKeyboardEvent = true; 1273 | } 1274 | wasLastGestureNone = true; 1275 | 1276 | xSemaphoreTake(mutex, portMAX_DELAY); 1277 | sprintf((char *)joystickValueForReporting, "None"); 1278 | xSemaphoreGive(mutex); 1279 | } 1280 | break; 1281 | } 1282 | } 1283 | 1284 | void drawButtons(int currentScreenMode) { 1285 | const int LAYOUT_BTN_A_CENTER = 64; 1286 | const int LAYOUT_BTN_B_CENTER = 160; 1287 | const int LAYOUT_BTN_C_CENTER = 256; 1288 | 1289 | switch (currentScreenMode) { 1290 | case SCREEN_MAIN: 1291 | if (!isSendingKeyboardEvents) { 1292 | drawButton(LAYOUT_BTN_A_CENTER, "Setup"); 1293 | drawButton(LAYOUT_BTN_B_CENTER, ""); 1294 | drawButton(LAYOUT_BTN_C_CENTER, "Send"); 1295 | } else { 1296 | drawButton(LAYOUT_BTN_A_CENTER, "Setup"); 1297 | drawButton(LAYOUT_BTN_B_CENTER, ""); 1298 | drawButton(LAYOUT_BTN_C_CENTER, "Stop"); 1299 | } 1300 | break; 1301 | case SCREEN_PREFS_SELECT: 1302 | drawButton(LAYOUT_BTN_A_CENTER, "Exit"); 1303 | drawButton(LAYOUT_BTN_B_CENTER, "Go"); 1304 | drawButton(LAYOUT_BTN_C_CENTER, "Next"); 1305 | break; 1306 | case SCREEN_PREFS_EDIT: 1307 | drawButton(LAYOUT_BTN_A_CENTER, "-"); 1308 | drawButton(LAYOUT_BTN_B_CENTER, "Done"); 1309 | drawButton(LAYOUT_BTN_C_CENTER, "+"); 1310 | break; 1311 | case SCREEN_PREFS_RFID: 1312 | drawButton(LAYOUT_BTN_A_CENTER, ""); 1313 | drawButton(LAYOUT_BTN_B_CENTER, "Done"); 1314 | drawButton(LAYOUT_BTN_C_CENTER, "Reset"); 1315 | break; 1316 | default: 1317 | break; 1318 | } 1319 | } 1320 | 1321 | void drawButton(int centerX, const String &title) { 1322 | const int BUTTON_WIDTH = 72; 1323 | const int BUTTON_HEIGHT = 24; 1324 | 1325 | M5.Display.setTextSize(2); 1326 | 1327 | int fontHeight = M5.Display.fontHeight(); 1328 | int rectLeft = centerX - BUTTON_WIDTH / 2; 1329 | int rectTop = M5.Display.height() - BUTTON_HEIGHT; 1330 | int rectWidth = BUTTON_WIDTH; 1331 | int rectHeight = BUTTON_HEIGHT; 1332 | int coordinateY = rectTop + (rectHeight - fontHeight) / 2; 1333 | 1334 | M5.Display.fillRect(rectLeft, rectTop, rectWidth, rectHeight, TFT_BLACK); 1335 | M5.Display.drawRect(rectLeft, rectTop, rectWidth, rectHeight, TFT_GREEN); 1336 | M5.Display.drawCenterString(title, centerX, coordinateY); 1337 | } 1338 | -------------------------------------------------------------------------------- /IOFrameworkForXR/MFRC522_I2C.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * MFRC522.cpp - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS I2C BY AROZCAN 3 | * MFRC522.cpp - Based on ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI Library BY COOQROBOT. 4 | * NOTE: Please also check the comments in MFRC522.h - they provide useful hints and background information. 5 | * Released into the public domain. 6 | * Author: arozcan @ https://github.com/arozcan/MFRC522-I2C-Library 7 | */ 8 | 9 | #include 10 | #include "MFRC522_I2C.h" 11 | #include 12 | 13 | ///////////////////////////////////////////////////////////////////////////////////// 14 | // Functions for setting up the Arduino 15 | ///////////////////////////////////////////////////////////////////////////////////// 16 | 17 | /** 18 | * Constructor. 19 | * Prepares the output pins. 20 | */ 21 | MFRC522::MFRC522( byte chipAddress 22 | //byte resetPowerDownPin ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low) 23 | ) { 24 | _chipAddress = chipAddress; 25 | // _resetPowerDownPin = resetPowerDownPin; 26 | } // End constructor 27 | 28 | 29 | ///////////////////////////////////////////////////////////////////////////////////// 30 | // Basic interface functions for communicating with the MFRC522 31 | ///////////////////////////////////////////////////////////////////////////////////// 32 | 33 | /** 34 | * Writes a byte to the specified register in the MFRC522 chip. 35 | * The interface is described in the datasheet section 8.1.2. 36 | */ 37 | void MFRC522::PCD_WriteRegister( byte reg, ///< The register to write to. One of the PCD_Register enums. 38 | byte value ///< The value to write. 39 | ) { 40 | Wire.beginTransmission(_chipAddress); 41 | Wire.write(reg); 42 | Wire.write(value); 43 | Wire.endTransmission(); 44 | } // End PCD_WriteRegister() 45 | 46 | /** 47 | * Writes a number of bytes to the specified register in the MFRC522 chip. 48 | * The interface is described in the datasheet section 8.1.2. 49 | */ 50 | void MFRC522::PCD_WriteRegister( byte reg, ///< The register to write to. One of the PCD_Register enums. 51 | byte count, ///< The number of bytes to write to the register 52 | byte *values ///< The values to write. Byte array. 53 | ) { 54 | Wire.beginTransmission(_chipAddress); 55 | Wire.write(reg); 56 | for (byte index = 0; index < count; index++) { 57 | Wire.write(values[index]); 58 | } 59 | Wire.endTransmission(); 60 | } // End PCD_WriteRegister() 61 | 62 | /** 63 | * Reads a byte from the specified register in the MFRC522 chip. 64 | * The interface is described in the datasheet section 8.1.2. 65 | */ 66 | byte MFRC522::PCD_ReadRegister( byte reg ///< The register to read from. One of the PCD_Register enums. 67 | ) { 68 | byte value; 69 | //digitalWrite(_chipSelectPin, LOW); // Select slave 70 | Wire.beginTransmission(_chipAddress); 71 | Wire.write(reg); 72 | Wire.endTransmission(); 73 | 74 | Wire.requestFrom(_chipAddress, 1); 75 | value = Wire.read(); 76 | return value; 77 | } // End PCD_ReadRegister() 78 | 79 | /** 80 | * Reads a number of bytes from the specified register in the MFRC522 chip. 81 | * The interface is described in the datasheet section 8.1.2. 82 | */ 83 | void MFRC522::PCD_ReadRegister( byte reg, ///< The register to read from. One of the PCD_Register enums. 84 | byte count, ///< The number of bytes to read 85 | byte *values, ///< Byte array to store the values in. 86 | byte rxAlign ///< Only bit positions rxAlign..7 in values[0] are updated. 87 | ) { 88 | if (count == 0) { 89 | return; 90 | } 91 | byte address = reg; 92 | byte index = 0; // Index in values array. 93 | Wire.beginTransmission(_chipAddress); 94 | Wire.write(address); 95 | Wire.endTransmission(); 96 | Wire.requestFrom(_chipAddress, count); 97 | while (Wire.available()) { 98 | if (index == 0 && rxAlign) { // Only update bit positions rxAlign..7 in values[0] 99 | // Create bit mask for bit positions rxAlign..7 100 | byte mask = 0; 101 | for (byte i = rxAlign; i <= 7; i++) { 102 | mask |= (1 << i); 103 | } 104 | // Read value and tell that we want to read the same address again. 105 | byte value = Wire.read(); 106 | // Apply mask to both current value of values[0] and the new data in value. 107 | values[0] = (values[index] & ~mask) | (value & mask); 108 | } 109 | else { // Normal case 110 | values[index] = Wire.read(); 111 | } 112 | index++; 113 | } 114 | } // End PCD_ReadRegister() 115 | 116 | /** 117 | * Sets the bits given in mask in register reg. 118 | */ 119 | void MFRC522::PCD_SetRegisterBitMask( byte reg, ///< The register to update. One of the PCD_Register enums. 120 | byte mask ///< The bits to set. 121 | ) { 122 | byte tmp; 123 | tmp = PCD_ReadRegister(reg); 124 | PCD_WriteRegister(reg, tmp | mask); // set bit mask 125 | } // End PCD_SetRegisterBitMask() 126 | 127 | /** 128 | * Clears the bits given in mask from register reg. 129 | */ 130 | void MFRC522::PCD_ClearRegisterBitMask( byte reg, ///< The register to update. One of the PCD_Register enums. 131 | byte mask ///< The bits to clear. 132 | ) { 133 | byte tmp; 134 | tmp = PCD_ReadRegister(reg); 135 | PCD_WriteRegister(reg, tmp & (~mask)); // clear bit mask 136 | } // End PCD_ClearRegisterBitMask() 137 | 138 | 139 | /** 140 | * Use the CRC coprocessor in the MFRC522 to calculate a CRC_A. 141 | * 142 | * @return STATUS_OK on success, STATUS_??? otherwise. 143 | */ 144 | byte MFRC522::PCD_CalculateCRC( byte *data, ///< In: Pointer to the data to transfer to the FIFO for CRC calculation. 145 | byte length, ///< In: The number of bytes to transfer. 146 | byte *result ///< Out: Pointer to result buffer. Result is written to result[0..1], low byte first. 147 | ) { 148 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command. 149 | PCD_WriteRegister(DivIrqReg, 0x04); // Clear the CRCIRq interrupt request bit 150 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization 151 | PCD_WriteRegister(FIFODataReg, length, data); // Write data to the FIFO 152 | PCD_WriteRegister(CommandReg, PCD_CalcCRC); // Start the calculation 153 | 154 | // Wait for the CRC calculation to complete. Each iteration of the while-loop takes 17.73�s. 155 | word i = 5000; 156 | byte n; 157 | while (1) { 158 | n = PCD_ReadRegister(DivIrqReg); // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved 159 | if (n & 0x04) { // CRCIRq bit set - calculation done 160 | break; 161 | } 162 | if (--i == 0) { // The emergency break. We will eventually terminate on this one after 89ms. Communication with the MFRC522 might be down. 163 | return STATUS_TIMEOUT; 164 | } 165 | } 166 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO. 167 | 168 | // Transfer the result from the registers to the result buffer 169 | result[0] = PCD_ReadRegister(CRCResultRegL); 170 | result[1] = PCD_ReadRegister(CRCResultRegH); 171 | return STATUS_OK; 172 | } // End PCD_CalculateCRC() 173 | 174 | 175 | ///////////////////////////////////////////////////////////////////////////////////// 176 | // Functions for manipulating the MFRC522 177 | ///////////////////////////////////////////////////////////////////////////////////// 178 | 179 | /** 180 | * Initializes the MFRC522 chip. 181 | */ 182 | void MFRC522::PCD_Init() { 183 | // Set the chipSelectPin as digital output, do not select the slave yet 184 | 185 | // Set the resetPowerDownPin as digital output, do not reset or power down. 186 | // pinMode(_resetPowerDownPin, OUTPUT); 187 | 188 | 189 | // if (digitalRead(_resetPowerDownPin) == LOW) { //The MFRC522 chip is in power down mode. 190 | // digitalWrite(_resetPowerDownPin, HIGH); // Exit power down mode. This triggers a hard reset. 191 | // // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms. 192 | // delay(50); 193 | // } 194 | // else { // Perform a soft reset 195 | PCD_Reset(); 196 | // } 197 | 198 | // When communicating with a PICC we need a timeout if something goes wrong. 199 | // f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo]. 200 | // TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg. 201 | PCD_WriteRegister(TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds 202 | PCD_WriteRegister(TPrescalerReg, 0xA9); // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25�s. 203 | PCD_WriteRegister(TReloadRegH, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout. 204 | PCD_WriteRegister(TReloadRegL, 0xE8); 205 | 206 | PCD_WriteRegister(TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting 207 | PCD_WriteRegister(ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4) 208 | PCD_AntennaOn(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset) 209 | } // End PCD_Init() 210 | 211 | /** 212 | * Performs a soft reset on the MFRC522 chip and waits for it to be ready again. 213 | */ 214 | void MFRC522::PCD_Reset() { 215 | PCD_WriteRegister(CommandReg, PCD_SoftReset); // Issue the SoftReset command. 216 | // The datasheet does not mention how long the SoftRest command takes to complete. 217 | // But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg) 218 | // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms. 219 | delay(50); 220 | // Wait for the PowerDown bit in CommandReg to be cleared 221 | while (PCD_ReadRegister(CommandReg) & (1<<4)) { 222 | // PCD still restarting - unlikely after waiting 50ms, but better safe than sorry. 223 | } 224 | } // End PCD_Reset() 225 | 226 | /** 227 | * Turns the antenna on by enabling pins TX1 and TX2. 228 | * After a reset these pins are disabled. 229 | */ 230 | void MFRC522::PCD_AntennaOn() { 231 | byte value = PCD_ReadRegister(TxControlReg); 232 | if ((value & 0x03) != 0x03) { 233 | PCD_WriteRegister(TxControlReg, value | 0x03); 234 | } 235 | } // End PCD_AntennaOn() 236 | 237 | /** 238 | * Turns the antenna off by disabling pins TX1 and TX2. 239 | */ 240 | void MFRC522::PCD_AntennaOff() { 241 | PCD_ClearRegisterBitMask(TxControlReg, 0x03); 242 | } // End PCD_AntennaOff() 243 | 244 | /** 245 | * Get the current MFRC522 Receiver Gain (RxGain[2:0]) value. 246 | * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 247 | * NOTE: Return value scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits. 248 | * 249 | * @return Value of the RxGain, scrubbed to the 3 bits used. 250 | */ 251 | byte MFRC522::PCD_GetAntennaGain() { 252 | return PCD_ReadRegister(RFCfgReg) & (0x07<<4); 253 | } // End PCD_GetAntennaGain() 254 | 255 | /** 256 | * Set the MFRC522 Receiver Gain (RxGain) to value specified by given mask. 257 | * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 258 | * NOTE: Given mask is scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits. 259 | */ 260 | void MFRC522::PCD_SetAntennaGain(byte mask) { 261 | if (PCD_GetAntennaGain() != mask) { // only bother if there is a change 262 | PCD_ClearRegisterBitMask(RFCfgReg, (0x07<<4)); // clear needed to allow 000 pattern 263 | PCD_SetRegisterBitMask(RFCfgReg, mask & (0x07<<4)); // only set RxGain[2:0] bits 264 | } 265 | } // End PCD_SetAntennaGain() 266 | 267 | /** 268 | * Performs a self-test of the MFRC522 269 | * See 16.1.1 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 270 | * 271 | * @return Whether or not the test passed. 272 | */ 273 | bool MFRC522::PCD_PerformSelfTest() { 274 | // This follows directly the steps outlined in 16.1.1 275 | // 1. Perform a soft reset. 276 | PCD_Reset(); 277 | 278 | // 2. Clear the internal buffer by writing 25 bytes of 00h 279 | byte ZEROES[25] = {0x00}; 280 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // flush the FIFO buffer 281 | PCD_WriteRegister(FIFODataReg, 25, ZEROES); // write 25 bytes of 00h to FIFO 282 | PCD_WriteRegister(CommandReg, PCD_Mem); // transfer to internal buffer 283 | 284 | // 3. Enable self-test 285 | PCD_WriteRegister(AutoTestReg, 0x09); 286 | 287 | // 4. Write 00h to FIFO buffer 288 | PCD_WriteRegister(FIFODataReg, 0x00); 289 | 290 | // 5. Start self-test by issuing the CalcCRC command 291 | PCD_WriteRegister(CommandReg, PCD_CalcCRC); 292 | 293 | // 6. Wait for self-test to complete 294 | word i; 295 | byte n; 296 | for (i = 0; i < 0xFF; i++) { 297 | n = PCD_ReadRegister(DivIrqReg); // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved 298 | if (n & 0x04) { // CRCIRq bit set - calculation done 299 | break; 300 | } 301 | } 302 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO. 303 | 304 | // 7. Read out resulting 64 bytes from the FIFO buffer. 305 | byte result[64]; 306 | PCD_ReadRegister(FIFODataReg, 64, result, 0); 307 | 308 | // Auto self-test done 309 | // Reset AutoTestReg register to be 0 again. Required for normal operation. 310 | PCD_WriteRegister(AutoTestReg, 0x00); 311 | 312 | // Determine firmware version (see section 9.3.4.8 in spec) 313 | byte version = PCD_ReadRegister(VersionReg); 314 | 315 | // Pick the appropriate reference values 316 | const byte *reference; 317 | switch (version) { 318 | case 0x88: // Fudan Semiconductor FM17522 clone 319 | reference = FM17522_firmware_reference; 320 | break; 321 | case 0x90: // Version 0.0 322 | reference = MFRC522_firmware_referenceV0_0; 323 | break; 324 | case 0x91: // Version 1.0 325 | reference = MFRC522_firmware_referenceV1_0; 326 | break; 327 | case 0x92: // Version 2.0 328 | reference = MFRC522_firmware_referenceV2_0; 329 | break; 330 | default: // Unknown version 331 | return false; 332 | } 333 | 334 | // Verify that the results match up to our expectations 335 | for (i = 0; i < 64; i++) { 336 | if (result[i] != pgm_read_byte(&(reference[i]))) { 337 | return false; 338 | } 339 | } 340 | 341 | // Test passed; all is good. 342 | return true; 343 | } // End PCD_PerformSelfTest() 344 | 345 | ///////////////////////////////////////////////////////////////////////////////////// 346 | // Functions for communicating with PICCs 347 | ///////////////////////////////////////////////////////////////////////////////////// 348 | 349 | /** 350 | * Executes the Transceive command. 351 | * CRC validation can only be done if backData and backLen are specified. 352 | * 353 | * @return STATUS_OK on success, STATUS_??? otherwise. 354 | */ 355 | byte MFRC522::PCD_TransceiveData( byte *sendData, ///< Pointer to the data to transfer to the FIFO. 356 | byte sendLen, ///< Number of bytes to transfer to the FIFO. 357 | byte *backData, ///< NULL or pointer to buffer if data should be read back after executing the command. 358 | byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned. 359 | byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. Default NULL. 360 | byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0. 361 | bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 362 | ) { 363 | byte waitIRq = 0x30; // RxIRq and IdleIRq 364 | return PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, sendData, sendLen, backData, backLen, validBits, rxAlign, checkCRC); 365 | } // End PCD_TransceiveData() 366 | 367 | /** 368 | * Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back from the FIFO. 369 | * CRC validation can only be done if backData and backLen are specified. 370 | * 371 | * @return STATUS_OK on success, STATUS_??? otherwise. 372 | */ 373 | byte MFRC522::PCD_CommunicateWithPICC( byte command, ///< The command to execute. One of the PCD_Command enums. 374 | byte waitIRq, ///< The bits in the ComIrqReg register that signals successful completion of the command. 375 | byte *sendData, ///< Pointer to the data to transfer to the FIFO. 376 | byte sendLen, ///< Number of bytes to transfer to the FIFO. 377 | byte *backData, ///< NULL or pointer to buffer if data should be read back after executing the command. 378 | byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned. 379 | byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. 380 | byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0. 381 | bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 382 | ) { 383 | byte n, _validBits; 384 | unsigned int i; 385 | 386 | // Prepare values for BitFramingReg 387 | byte txLastBits = validBits ? *validBits : 0; 388 | byte bitFraming = (rxAlign << 4) + txLastBits; // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0] 389 | 390 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command. 391 | PCD_WriteRegister(ComIrqReg, 0x7F); // Clear all seven interrupt request bits 392 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization 393 | PCD_WriteRegister(FIFODataReg, sendLen, sendData); // Write sendData to the FIFO 394 | PCD_WriteRegister(BitFramingReg, bitFraming); // Bit adjustments 395 | PCD_WriteRegister(CommandReg, command); // Execute the command 396 | if (command == PCD_Transceive) { 397 | PCD_SetRegisterBitMask(BitFramingReg, 0x80); // StartSend=1, transmission of data starts 398 | } 399 | 400 | // Wait for the command to complete. 401 | // In PCD_Init() we set the TAuto flag in TModeReg. This means the timer automatically starts when the PCD stops transmitting. 402 | // Each iteration of the do-while-loop takes 17.86�s. 403 | i = 2000; 404 | while (1) { 405 | n = PCD_ReadRegister(ComIrqReg); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq 406 | if (n & waitIRq) { // One of the interrupts that signal success has been set. 407 | break; 408 | } 409 | if (n & 0x01) { // Timer interrupt - nothing received in 25ms 410 | return STATUS_TIMEOUT; 411 | } 412 | if (--i == 0) { // The emergency break. If all other condions fail we will eventually terminate on this one after 35.7ms. Communication with the MFRC522 might be down. 413 | return STATUS_TIMEOUT; 414 | } 415 | } 416 | 417 | // Stop now if any errors except collisions were detected. 418 | byte errorRegValue = PCD_ReadRegister(ErrorReg); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr 419 | if (errorRegValue & 0x13) { // BufferOvfl ParityErr ProtocolErr 420 | return STATUS_ERROR; 421 | } 422 | 423 | // If the caller wants data back, get it from the MFRC522. 424 | if (backData && backLen) { 425 | n = PCD_ReadRegister(FIFOLevelReg); // Number of bytes in the FIFO 426 | if (n > *backLen) { 427 | return STATUS_NO_ROOM; 428 | } 429 | *backLen = n; // Number of bytes returned 430 | PCD_ReadRegister(FIFODataReg, n, backData, rxAlign); // Get received data from FIFO 431 | _validBits = PCD_ReadRegister(ControlReg) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last received byte. If this value is 000b, the whole byte is valid. 432 | if (validBits) { 433 | *validBits = _validBits; 434 | } 435 | } 436 | 437 | // Tell about collisions 438 | if (errorRegValue & 0x08) { // CollErr 439 | return STATUS_COLLISION; 440 | } 441 | 442 | // Perform CRC_A validation if requested. 443 | if (backData && backLen && checkCRC) { 444 | // In this case a MIFARE Classic NAK is not OK. 445 | if (*backLen == 1 && _validBits == 4) { 446 | return STATUS_MIFARE_NACK; 447 | } 448 | // We need at least the CRC_A value and all 8 bits of the last byte must be received. 449 | if (*backLen < 2 || _validBits != 0) { 450 | return STATUS_CRC_WRONG; 451 | } 452 | // Verify CRC_A - do our own calculation and store the control in controlBuffer. 453 | byte controlBuffer[2]; 454 | n = PCD_CalculateCRC(&backData[0], *backLen - 2, &controlBuffer[0]); 455 | if (n != STATUS_OK) { 456 | return n; 457 | } 458 | if ((backData[*backLen - 2] != controlBuffer[0]) || (backData[*backLen - 1] != controlBuffer[1])) { 459 | return STATUS_CRC_WRONG; 460 | } 461 | } 462 | 463 | return STATUS_OK; 464 | } // End PCD_CommunicateWithPICC() 465 | 466 | /** 467 | * Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame. 468 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 469 | * 470 | * @return STATUS_OK on success, STATUS_??? otherwise. 471 | */ 472 | byte MFRC522::PICC_RequestA(byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 473 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 474 | ) { 475 | return PICC_REQA_or_WUPA(PICC_CMD_REQA, bufferATQA, bufferSize); 476 | } // End PICC_RequestA() 477 | 478 | /** 479 | * Transmits a Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame. 480 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 481 | * 482 | * @return STATUS_OK on success, STATUS_??? otherwise. 483 | */ 484 | byte MFRC522::PICC_WakeupA( byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 485 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 486 | ) { 487 | return PICC_REQA_or_WUPA(PICC_CMD_WUPA, bufferATQA, bufferSize); 488 | } // End PICC_WakeupA() 489 | 490 | /** 491 | * Transmits REQA or WUPA commands. 492 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 493 | * 494 | * @return STATUS_OK on success, STATUS_??? otherwise. 495 | */ 496 | byte MFRC522::PICC_REQA_or_WUPA( byte command, ///< The command to send - PICC_CMD_REQA or PICC_CMD_WUPA 497 | byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 498 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 499 | ) { 500 | byte validBits; 501 | byte status; 502 | 503 | if (bufferATQA == NULL || *bufferSize < 2) { // The ATQA response is 2 bytes long. 504 | return STATUS_NO_ROOM; 505 | } 506 | PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared. 507 | validBits = 7; // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only) byte. TxLastBits = BitFramingReg[2..0] 508 | status = PCD_TransceiveData(&command, 1, bufferATQA, bufferSize, &validBits); 509 | if (status != STATUS_OK) { 510 | return status; 511 | } 512 | if (*bufferSize != 2 || validBits != 0) { // ATQA must be exactly 16 bits. 513 | return STATUS_ERROR; 514 | } 515 | return STATUS_OK; 516 | } // End PICC_REQA_or_WUPA() 517 | 518 | /** 519 | * Transmits SELECT/ANTICOLLISION commands to select a single PICC. 520 | * Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA(). 521 | * On success: 522 | * - The chosen PICC is in state ACTIVE(*) and all other PICCs have returned to state IDLE/HALT. (Figure 7 of the ISO/IEC 14443-3 draft.) 523 | * - The UID size and value of the chosen PICC is returned in *uid along with the SAK. 524 | * 525 | * A PICC UID consists of 4, 7 or 10 bytes. 526 | * Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used: 527 | * UID size Number of UID bytes Cascade levels Example of PICC 528 | * ======== =================== ============== =============== 529 | * single 4 1 MIFARE Classic 530 | * double 7 2 MIFARE Ultralight 531 | * triple 10 3 Not currently in use? 532 | * 533 | * @return STATUS_OK on success, STATUS_??? otherwise. 534 | */ 535 | byte MFRC522::PICC_Select( Uid *uid, ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID. 536 | byte validBits ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size. 537 | ) { 538 | bool uidComplete; 539 | bool selectDone; 540 | bool useCascadeTag; 541 | byte cascadeLevel = 1; 542 | byte result; 543 | byte count; 544 | byte index; 545 | byte uidIndex; // The first index in uid->uidByte[] that is used in the current Cascade Level. 546 | int8_t currentLevelKnownBits; // The number of known UID bits in the current Cascade Level. 547 | byte buffer[9]; // The SELECT/ANTICOLLISION commands uses a 7 byte standard frame + 2 bytes CRC_A 548 | byte bufferUsed; // The number of bytes used in the buffer, ie the number of bytes to transfer to the FIFO. 549 | byte rxAlign; // Used in BitFramingReg. Defines the bit position for the first bit received. 550 | byte txLastBits; // Used in BitFramingReg. The number of valid bits in the last transmitted byte. 551 | byte *responseBuffer; 552 | byte responseLength; 553 | 554 | // Description of buffer structure: 555 | // Byte 0: SEL Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3 556 | // Byte 1: NVB Number of Valid Bits (in complete command, not just the UID): High nibble: complete bytes, Low nibble: Extra bits. 557 | // Byte 2: UID-data or CT See explanation below. CT means Cascade Tag. 558 | // Byte 3: UID-data 559 | // Byte 4: UID-data 560 | // Byte 5: UID-data 561 | // Byte 6: BCC Block Check Character - XOR of bytes 2-5 562 | // Byte 7: CRC_A 563 | // Byte 8: CRC_A 564 | // The BCC and CRC_A is only transmitted if we know all the UID bits of the current Cascade Level. 565 | // 566 | // Description of bytes 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels) 567 | // UID size Cascade level Byte2 Byte3 Byte4 Byte5 568 | // ======== ============= ===== ===== ===== ===== 569 | // 4 bytes 1 uid0 uid1 uid2 uid3 570 | // 7 bytes 1 CT uid0 uid1 uid2 571 | // 2 uid3 uid4 uid5 uid6 572 | // 10 bytes 1 CT uid0 uid1 uid2 573 | // 2 CT uid3 uid4 uid5 574 | // 3 uid6 uid7 uid8 uid9 575 | 576 | // Sanity checks 577 | if (validBits > 80) { 578 | return STATUS_INVALID; 579 | } 580 | 581 | // Prepare MFRC522 582 | PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared. 583 | 584 | // Repeat Cascade Level loop until we have a complete UID. 585 | uidComplete = false; 586 | while (!uidComplete) { 587 | // Set the Cascade Level in the SEL byte, find out if we need to use the Cascade Tag in byte 2. 588 | switch (cascadeLevel) { 589 | case 1: 590 | buffer[0] = PICC_CMD_SEL_CL1; 591 | uidIndex = 0; 592 | useCascadeTag = validBits && uid->size > 4; // When we know that the UID has more than 4 bytes 593 | break; 594 | 595 | case 2: 596 | buffer[0] = PICC_CMD_SEL_CL2; 597 | uidIndex = 3; 598 | useCascadeTag = validBits && uid->size > 7; // When we know that the UID has more than 7 bytes 599 | break; 600 | 601 | case 3: 602 | buffer[0] = PICC_CMD_SEL_CL3; 603 | uidIndex = 6; 604 | useCascadeTag = false; // Never used in CL3. 605 | break; 606 | 607 | default: 608 | return STATUS_INTERNAL_ERROR; 609 | break; 610 | } 611 | 612 | // How many UID bits are known in this Cascade Level? 613 | currentLevelKnownBits = validBits - (8 * uidIndex); 614 | if (currentLevelKnownBits < 0) { 615 | currentLevelKnownBits = 0; 616 | } 617 | // Copy the known bits from uid->uidByte[] to buffer[] 618 | index = 2; // destination index in buffer[] 619 | if (useCascadeTag) { 620 | buffer[index++] = PICC_CMD_CT; 621 | } 622 | byte bytesToCopy = currentLevelKnownBits / 8 + (currentLevelKnownBits % 8 ? 1 : 0); // The number of bytes needed to represent the known bits for this level. 623 | if (bytesToCopy) { 624 | byte maxBytes = useCascadeTag ? 3 : 4; // Max 4 bytes in each Cascade Level. Only 3 left if we use the Cascade Tag 625 | if (bytesToCopy > maxBytes) { 626 | bytesToCopy = maxBytes; 627 | } 628 | for (count = 0; count < bytesToCopy; count++) { 629 | buffer[index++] = uid->uidByte[uidIndex + count]; 630 | } 631 | } 632 | // Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits 633 | if (useCascadeTag) { 634 | currentLevelKnownBits += 8; 635 | } 636 | 637 | // Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations. 638 | selectDone = false; 639 | while (!selectDone) { 640 | // Find out how many bits and bytes to send and receive. 641 | if (currentLevelKnownBits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT. 642 | //Serial.print(F("SELECT: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC); 643 | buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole bytes 644 | // Calculate BCC - Block Check Character 645 | buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5]; 646 | // Calculate CRC_A 647 | result = PCD_CalculateCRC(buffer, 7, &buffer[7]); 648 | if (result != STATUS_OK) { 649 | return result; 650 | } 651 | txLastBits = 0; // 0 => All 8 bits are valid. 652 | bufferUsed = 9; 653 | // Store response in the last 3 bytes of buffer (BCC and CRC_A - not needed after tx) 654 | responseBuffer = &buffer[6]; 655 | responseLength = 3; 656 | } 657 | else { // This is an ANTICOLLISION. 658 | //Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC); 659 | txLastBits = currentLevelKnownBits % 8; 660 | count = currentLevelKnownBits / 8; // Number of whole bytes in the UID part. 661 | index = 2 + count; // Number of whole bytes: SEL + NVB + UIDs 662 | buffer[1] = (index << 4) + txLastBits; // NVB - Number of Valid Bits 663 | bufferUsed = index + (txLastBits ? 1 : 0); 664 | // Store response in the unused part of buffer 665 | responseBuffer = &buffer[index]; 666 | responseLength = sizeof(buffer) - index; 667 | } 668 | 669 | // Set bit adjustments 670 | rxAlign = txLastBits; // Having a seperate variable is overkill. But it makes the next line easier to read. 671 | PCD_WriteRegister(BitFramingReg, (rxAlign << 4) + txLastBits); // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0] 672 | 673 | // Transmit the buffer and receive the response. 674 | result = PCD_TransceiveData(buffer, bufferUsed, responseBuffer, &responseLength, &txLastBits, rxAlign); 675 | if (result == STATUS_COLLISION) { // More than one PICC in the field => collision. 676 | result = PCD_ReadRegister(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0] 677 | if (result & 0x20) { // CollPosNotValid 678 | return STATUS_COLLISION; // Without a valid collision position we cannot continue 679 | } 680 | byte collisionPos = result & 0x1F; // Values 0-31, 0 means bit 32. 681 | if (collisionPos == 0) { 682 | collisionPos = 32; 683 | } 684 | if (collisionPos <= currentLevelKnownBits) { // No progress - should not happen 685 | return STATUS_INTERNAL_ERROR; 686 | } 687 | // Choose the PICC with the bit set. 688 | currentLevelKnownBits = collisionPos; 689 | count = (currentLevelKnownBits - 1) % 8; // The bit to modify 690 | index = 1 + (currentLevelKnownBits / 8) + (count ? 1 : 0); // First byte is index 0. 691 | buffer[index] |= (1 << count); 692 | } 693 | else if (result != STATUS_OK) { 694 | return result; 695 | } 696 | else { // STATUS_OK 697 | if (currentLevelKnownBits >= 32) { // This was a SELECT. 698 | selectDone = true; // No more anticollision 699 | // We continue below outside the while. 700 | } 701 | else { // This was an ANTICOLLISION. 702 | // We now have all 32 bits of the UID in this Cascade Level 703 | currentLevelKnownBits = 32; 704 | // Run loop again to do the SELECT. 705 | } 706 | } 707 | } // End of while (!selectDone) 708 | 709 | // We do not check the CBB - it was constructed by us above. 710 | 711 | // Copy the found UID bytes from buffer[] to uid->uidByte[] 712 | index = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[] 713 | bytesToCopy = (buffer[2] == PICC_CMD_CT) ? 3 : 4; 714 | for (count = 0; count < bytesToCopy; count++) { 715 | uid->uidByte[uidIndex + count] = buffer[index++]; 716 | } 717 | 718 | // Check response SAK (Select Acknowledge) 719 | if (responseLength != 3 || txLastBits != 0) { // SAK must be exactly 24 bits (1 byte + CRC_A). 720 | return STATUS_ERROR; 721 | } 722 | // Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those bytes are not needed anymore. 723 | result = PCD_CalculateCRC(responseBuffer, 1, &buffer[2]); 724 | if (result != STATUS_OK) { 725 | return result; 726 | } 727 | if ((buffer[2] != responseBuffer[1]) || (buffer[3] != responseBuffer[2])) { 728 | return STATUS_CRC_WRONG; 729 | } 730 | if (responseBuffer[0] & 0x04) { // Cascade bit set - UID not complete yes 731 | cascadeLevel++; 732 | } 733 | else { 734 | uidComplete = true; 735 | uid->sak = responseBuffer[0]; 736 | } 737 | } // End of while (!uidComplete) 738 | 739 | // Set correct uid->size 740 | uid->size = 3 * cascadeLevel + 1; 741 | 742 | return STATUS_OK; 743 | } // End PICC_Select() 744 | 745 | /** 746 | * Instructs a PICC in state ACTIVE(*) to go to state HALT. 747 | * 748 | * @return STATUS_OK on success, STATUS_??? otherwise. 749 | */ 750 | byte MFRC522::PICC_HaltA() { 751 | byte result; 752 | byte buffer[4]; 753 | 754 | // Build command buffer 755 | buffer[0] = PICC_CMD_HLTA; 756 | buffer[1] = 0; 757 | // Calculate CRC_A 758 | result = PCD_CalculateCRC(buffer, 2, &buffer[2]); 759 | if (result != STATUS_OK) { 760 | return result; 761 | } 762 | 763 | // Send the command. 764 | // The standard says: 765 | // If the PICC responds with any modulation during a period of 1 ms after the end of the frame containing the 766 | // HLTA command, this response shall be interpreted as 'not acknowledge'. 767 | // We interpret that this way: Only STATUS_TIMEOUT is an success. 768 | result = PCD_TransceiveData(buffer, sizeof(buffer), NULL, 0); 769 | if (result == STATUS_TIMEOUT) { 770 | return STATUS_OK; 771 | } 772 | if (result == STATUS_OK) { // That is ironically NOT ok in this case ;-) 773 | return STATUS_ERROR; 774 | } 775 | return result; 776 | } // End PICC_HaltA() 777 | 778 | 779 | ///////////////////////////////////////////////////////////////////////////////////// 780 | // Functions for communicating with MIFARE PICCs 781 | ///////////////////////////////////////////////////////////////////////////////////// 782 | 783 | /** 784 | * Executes the MFRC522 MFAuthent command. 785 | * This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card. 786 | * The authentication is described in the MFRC522 datasheet section 10.3.1.9 and http://www.nxp.com/documents/data_sheet/MF1S503x.pdf section 10.1. 787 | * For use with MIFARE Classic PICCs. 788 | * The PICC must be selected - ie in state ACTIVE(*) - before calling this function. 789 | * Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start. 790 | * 791 | * All keys are set to FFFFFFFFFFFFh at chip delivery. 792 | * 793 | * @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key. 794 | */ 795 | byte MFRC522::PCD_Authenticate(byte command, ///< PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B 796 | byte blockAddr, ///< The block number. See numbering in the comments in the .h file. 797 | MIFARE_Key *key, ///< Pointer to the Crypteo1 key to use (6 bytes) 798 | Uid *uid ///< Pointer to Uid struct. The first 4 bytes of the UID is used. 799 | ) { 800 | byte waitIRq = 0x10; // IdleIRq 801 | 802 | // Build command buffer 803 | byte sendData[12]; 804 | sendData[0] = command; 805 | sendData[1] = blockAddr; 806 | for (byte i = 0; i < MF_KEY_SIZE; i++) { // 6 key bytes 807 | sendData[2+i] = key->keyByte[i]; 808 | } 809 | for (byte i = 0; i < 4; i++) { // The first 4 bytes of the UID 810 | sendData[8+i] = uid->uidByte[i]; 811 | } 812 | 813 | // Start the authentication. 814 | return PCD_CommunicateWithPICC(PCD_MFAuthent, waitIRq, &sendData[0], sizeof(sendData)); 815 | } // End PCD_Authenticate() 816 | 817 | /** 818 | * Used to exit the PCD from its authenticated state. 819 | * Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start. 820 | */ 821 | void MFRC522::PCD_StopCrypto1() { 822 | // Clear MFCrypto1On bit 823 | PCD_ClearRegisterBitMask(Status2Reg, 0x08); // Status2Reg[7..0] bits are: TempSensClear I2CForceHS reserved reserved MFCrypto1On ModemState[2:0] 824 | } // End PCD_StopCrypto1() 825 | 826 | /** 827 | * Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC. 828 | * 829 | * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 830 | * 831 | * For MIFARE Ultralight only addresses 00h to 0Fh are decoded. 832 | * The MF0ICU1 returns a NAK for higher addresses. 833 | * The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument. 834 | * For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned. 835 | * A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned. 836 | * 837 | * The buffer must be at least 18 bytes because a CRC_A is also returned. 838 | * Checks the CRC_A before returning STATUS_OK. 839 | * 840 | * @return STATUS_OK on success, STATUS_??? otherwise. 841 | */ 842 | byte MFRC522::MIFARE_Read( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from. 843 | byte *buffer, ///< The buffer to store the data in 844 | byte *bufferSize ///< Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK. 845 | ) { 846 | byte result; 847 | 848 | // Sanity check 849 | if (buffer == NULL || *bufferSize < 18) { 850 | return STATUS_NO_ROOM; 851 | } 852 | 853 | // Build command buffer 854 | buffer[0] = PICC_CMD_MF_READ; 855 | buffer[1] = blockAddr; 856 | // Calculate CRC_A 857 | result = PCD_CalculateCRC(buffer, 2, &buffer[2]); 858 | if (result != STATUS_OK) { 859 | return result; 860 | } 861 | 862 | // Transmit the buffer and receive the response, validate CRC_A. 863 | return PCD_TransceiveData(buffer, 4, buffer, bufferSize, NULL, 0, true); 864 | } // End MIFARE_Read() 865 | 866 | /** 867 | * Writes 16 bytes to the active PICC. 868 | * 869 | * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 870 | * 871 | * For MIFARE Ultralight the operation is called "COMPATIBILITY WRITE". 872 | * Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3) 873 | * are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0. 874 | * * 875 | * @return STATUS_OK on success, STATUS_??? otherwise. 876 | */ 877 | byte MFRC522::MIFARE_Write( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to. 878 | byte *buffer, ///< The 16 bytes to write to the PICC 879 | byte bufferSize ///< Buffer size, must be at least 16 bytes. Exactly 16 bytes are written. 880 | ) { 881 | byte result; 882 | 883 | // Sanity check 884 | if (buffer == NULL || bufferSize < 16) { 885 | return STATUS_INVALID; 886 | } 887 | 888 | // Mifare Classic protocol requires two communications to perform a write. 889 | // Step 1: Tell the PICC we want to write to block blockAddr. 890 | byte cmdBuffer[2]; 891 | cmdBuffer[0] = PICC_CMD_MF_WRITE; 892 | cmdBuffer[1] = blockAddr; 893 | result = PCD_MIFARE_Transceive(cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 894 | if (result != STATUS_OK) { 895 | return result; 896 | } 897 | 898 | // Step 2: Transfer the data 899 | result = PCD_MIFARE_Transceive(buffer, bufferSize); // Adds CRC_A and checks that the response is MF_ACK. 900 | if (result != STATUS_OK) { 901 | return result; 902 | } 903 | 904 | return STATUS_OK; 905 | } // End MIFARE_Write() 906 | 907 | /** 908 | * Writes a 4 byte page to the active MIFARE Ultralight PICC. 909 | * 910 | * @return STATUS_OK on success, STATUS_??? otherwise. 911 | */ 912 | byte MFRC522::MIFARE_Ultralight_Write( byte page, ///< The page (2-15) to write to. 913 | byte *buffer, ///< The 4 bytes to write to the PICC 914 | byte bufferSize ///< Buffer size, must be at least 4 bytes. Exactly 4 bytes are written. 915 | ) { 916 | byte result; 917 | 918 | // Sanity check 919 | if (buffer == NULL || bufferSize < 4) { 920 | return STATUS_INVALID; 921 | } 922 | 923 | // Build commmand buffer 924 | byte cmdBuffer[6]; 925 | cmdBuffer[0] = PICC_CMD_UL_WRITE; 926 | cmdBuffer[1] = page; 927 | memcpy(&cmdBuffer[2], buffer, 4); 928 | 929 | // Perform the write 930 | result = PCD_MIFARE_Transceive(cmdBuffer, 6); // Adds CRC_A and checks that the response is MF_ACK. 931 | if (result != STATUS_OK) { 932 | return result; 933 | } 934 | return STATUS_OK; 935 | } // End MIFARE_Ultralight_Write() 936 | 937 | /** 938 | * MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory. 939 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 940 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 941 | * Use MIFARE_Transfer() to store the result in a block. 942 | * 943 | * @return STATUS_OK on success, STATUS_??? otherwise. 944 | */ 945 | byte MFRC522::MIFARE_Decrement( byte blockAddr, ///< The block (0-0xff) number. 946 | long delta ///< This number is subtracted from the value of block blockAddr. 947 | ) { 948 | return MIFARE_TwoStepHelper(PICC_CMD_MF_DECREMENT, blockAddr, delta); 949 | } // End MIFARE_Decrement() 950 | 951 | /** 952 | * MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory. 953 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 954 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 955 | * Use MIFARE_Transfer() to store the result in a block. 956 | * 957 | * @return STATUS_OK on success, STATUS_??? otherwise. 958 | */ 959 | byte MFRC522::MIFARE_Increment( byte blockAddr, ///< The block (0-0xff) number. 960 | long delta ///< This number is added to the value of block blockAddr. 961 | ) { 962 | return MIFARE_TwoStepHelper(PICC_CMD_MF_INCREMENT, blockAddr, delta); 963 | } // End MIFARE_Increment() 964 | 965 | /** 966 | * MIFARE Restore copies the value of the addressed block into a volatile memory. 967 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 968 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 969 | * Use MIFARE_Transfer() to store the result in a block. 970 | * 971 | * @return STATUS_OK on success, STATUS_??? otherwise. 972 | */ 973 | byte MFRC522::MIFARE_Restore( byte blockAddr ///< The block (0-0xff) number. 974 | ) { 975 | // The datasheet describes Restore as a two step operation, but does not explain what data to transfer in step 2. 976 | // Doing only a single step does not work, so I chose to transfer 0L in step two. 977 | return MIFARE_TwoStepHelper(PICC_CMD_MF_RESTORE, blockAddr, 0L); 978 | } // End MIFARE_Restore() 979 | 980 | /** 981 | * Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore. 982 | * 983 | * @return STATUS_OK on success, STATUS_??? otherwise. 984 | */ 985 | byte MFRC522::MIFARE_TwoStepHelper( byte command, ///< The command to use 986 | byte blockAddr, ///< The block (0-0xff) number. 987 | long data ///< The data to transfer in step 2 988 | ) { 989 | byte result; 990 | byte cmdBuffer[2]; // We only need room for 2 bytes. 991 | 992 | // Step 1: Tell the PICC the command and block address 993 | cmdBuffer[0] = command; 994 | cmdBuffer[1] = blockAddr; 995 | result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 996 | if (result != STATUS_OK) { 997 | return result; 998 | } 999 | 1000 | // Step 2: Transfer the data 1001 | result = PCD_MIFARE_Transceive( (byte *)&data, 4, true); // Adds CRC_A and accept timeout as success. 1002 | if (result != STATUS_OK) { 1003 | return result; 1004 | } 1005 | 1006 | return STATUS_OK; 1007 | } // End MIFARE_TwoStepHelper() 1008 | 1009 | /** 1010 | * MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block. 1011 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 1012 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 1013 | * 1014 | * @return STATUS_OK on success, STATUS_??? otherwise. 1015 | */ 1016 | byte MFRC522::MIFARE_Transfer( byte blockAddr ///< The block (0-0xff) number. 1017 | ) { 1018 | byte result; 1019 | byte cmdBuffer[2]; // We only need room for 2 bytes. 1020 | 1021 | // Tell the PICC we want to transfer the result into block blockAddr. 1022 | cmdBuffer[0] = PICC_CMD_MF_TRANSFER; 1023 | cmdBuffer[1] = blockAddr; 1024 | result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 1025 | if (result != STATUS_OK) { 1026 | return result; 1027 | } 1028 | return STATUS_OK; 1029 | } // End MIFARE_Transfer() 1030 | 1031 | /** 1032 | * Helper routine to read the current value from a Value Block. 1033 | * 1034 | * Only for MIFARE Classic and only for blocks in "value block" mode, that 1035 | * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing 1036 | * the block must be authenticated before calling this function. 1037 | * 1038 | * @param[in] blockAddr The block (0x00-0xff) number. 1039 | * @param[out] value Current value of the Value Block. 1040 | * @return STATUS_OK on success, STATUS_??? otherwise. 1041 | */ 1042 | byte MFRC522::MIFARE_GetValue(byte blockAddr, long *value) { 1043 | byte status; 1044 | byte buffer[18]; 1045 | byte size = sizeof(buffer); 1046 | 1047 | // Read the block 1048 | status = MIFARE_Read(blockAddr, buffer, &size); 1049 | if (status == STATUS_OK) { 1050 | // Extract the value 1051 | *value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]); 1052 | } 1053 | return status; 1054 | } // End MIFARE_GetValue() 1055 | 1056 | /** 1057 | * Helper routine to write a specific value into a Value Block. 1058 | * 1059 | * Only for MIFARE Classic and only for blocks in "value block" mode, that 1060 | * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing 1061 | * the block must be authenticated before calling this function. 1062 | * 1063 | * @param[in] blockAddr The block (0x00-0xff) number. 1064 | * @param[in] value New value of the Value Block. 1065 | * @return STATUS_OK on success, STATUS_??? otherwise. 1066 | */ 1067 | byte MFRC522::MIFARE_SetValue(byte blockAddr, long value) { 1068 | byte buffer[18]; 1069 | 1070 | // Translate the long into 4 bytes; repeated 2x in value block 1071 | buffer[0] = buffer[ 8] = (value & 0xFF); 1072 | buffer[1] = buffer[ 9] = (value & 0xFF00) >> 8; 1073 | buffer[2] = buffer[10] = (value & 0xFF0000) >> 16; 1074 | buffer[3] = buffer[11] = (value & 0xFF000000) >> 24; 1075 | // Inverse 4 bytes also found in value block 1076 | buffer[4] = ~buffer[0]; 1077 | buffer[5] = ~buffer[1]; 1078 | buffer[6] = ~buffer[2]; 1079 | buffer[7] = ~buffer[3]; 1080 | // Address 2x with inverse address 2x 1081 | buffer[12] = buffer[14] = blockAddr; 1082 | buffer[13] = buffer[15] = ~blockAddr; 1083 | 1084 | // Write the whole data block 1085 | return MIFARE_Write(blockAddr, buffer, 16); 1086 | } // End MIFARE_SetValue() 1087 | 1088 | ///////////////////////////////////////////////////////////////////////////////////// 1089 | // Support functions 1090 | ///////////////////////////////////////////////////////////////////////////////////// 1091 | 1092 | /** 1093 | * Wrapper for MIFARE protocol communication. 1094 | * Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout. 1095 | * 1096 | * @return STATUS_OK on success, STATUS_??? otherwise. 1097 | */ 1098 | byte MFRC522::PCD_MIFARE_Transceive( byte *sendData, ///< Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A. 1099 | byte sendLen, ///< Number of bytes in sendData. 1100 | bool acceptTimeout ///< True => A timeout is also success 1101 | ) { 1102 | byte result; 1103 | byte cmdBuffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A. 1104 | 1105 | // Sanity check 1106 | if (sendData == NULL || sendLen > 16) { 1107 | return STATUS_INVALID; 1108 | } 1109 | 1110 | // Copy sendData[] to cmdBuffer[] and add CRC_A 1111 | memcpy(cmdBuffer, sendData, sendLen); 1112 | result = PCD_CalculateCRC(cmdBuffer, sendLen, &cmdBuffer[sendLen]); 1113 | if (result != STATUS_OK) { 1114 | return result; 1115 | } 1116 | sendLen += 2; 1117 | 1118 | // Transceive the data, store the reply in cmdBuffer[] 1119 | byte waitIRq = 0x30; // RxIRq and IdleIRq 1120 | byte cmdBufferSize = sizeof(cmdBuffer); 1121 | byte validBits = 0; 1122 | result = PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, sendLen, cmdBuffer, &cmdBufferSize, &validBits); 1123 | if (acceptTimeout && result == STATUS_TIMEOUT) { 1124 | return STATUS_OK; 1125 | } 1126 | if (result != STATUS_OK) { 1127 | return result; 1128 | } 1129 | // The PICC must reply with a 4 bit ACK 1130 | if (cmdBufferSize != 1 || validBits != 4) { 1131 | return STATUS_ERROR; 1132 | } 1133 | if (cmdBuffer[0] != MF_ACK) { 1134 | return STATUS_MIFARE_NACK; 1135 | } 1136 | return STATUS_OK; 1137 | } // End PCD_MIFARE_Transceive() 1138 | 1139 | /** 1140 | * Returns a __FlashStringHelper pointer to a status code name. 1141 | * 1142 | * @return const __FlashStringHelper * 1143 | */ 1144 | const __FlashStringHelper *MFRC522::GetStatusCodeName(byte code ///< One of the StatusCode enums. 1145 | ) { 1146 | switch (code) { 1147 | case STATUS_OK: return F("Success."); break; 1148 | case STATUS_ERROR: return F("Error in communication."); break; 1149 | case STATUS_COLLISION: return F("Collission detected."); break; 1150 | case STATUS_TIMEOUT: return F("Timeout in communication."); break; 1151 | case STATUS_NO_ROOM: return F("A buffer is not big enough."); break; 1152 | case STATUS_INTERNAL_ERROR: return F("Internal error in the code. Should not happen."); break; 1153 | case STATUS_INVALID: return F("Invalid argument."); break; 1154 | case STATUS_CRC_WRONG: return F("The CRC_A does not match."); break; 1155 | case STATUS_MIFARE_NACK: return F("A MIFARE PICC responded with NAK."); break; 1156 | default: return F("Unknown error"); break; 1157 | } 1158 | } // End GetStatusCodeName() 1159 | 1160 | /** 1161 | * Translates the SAK (Select Acknowledge) to a PICC type. 1162 | * 1163 | * @return PICC_Type 1164 | */ 1165 | byte MFRC522::PICC_GetType(byte sak ///< The SAK byte returned from PICC_Select(). 1166 | ) { 1167 | if (sak & 0x04) { // UID not complete 1168 | return PICC_TYPE_NOT_COMPLETE; 1169 | } 1170 | 1171 | switch (sak) { 1172 | case 0x09: return PICC_TYPE_MIFARE_MINI; break; 1173 | case 0x08: return PICC_TYPE_MIFARE_1K; break; 1174 | case 0x18: return PICC_TYPE_MIFARE_4K; break; 1175 | case 0x00: return PICC_TYPE_MIFARE_UL; break; 1176 | case 0x10: 1177 | case 0x11: return PICC_TYPE_MIFARE_PLUS; break; 1178 | case 0x01: return PICC_TYPE_TNP3XXX; break; 1179 | default: break; 1180 | } 1181 | 1182 | if (sak & 0x20) { 1183 | return PICC_TYPE_ISO_14443_4; 1184 | } 1185 | 1186 | if (sak & 0x40) { 1187 | return PICC_TYPE_ISO_18092; 1188 | } 1189 | 1190 | return PICC_TYPE_UNKNOWN; 1191 | } // End PICC_GetType() 1192 | 1193 | /** 1194 | * Returns a __FlashStringHelper pointer to the PICC type name. 1195 | * 1196 | * @return const __FlashStringHelper * 1197 | */ 1198 | const __FlashStringHelper *MFRC522::PICC_GetTypeName(byte piccType ///< One of the PICC_Type enums. 1199 | ) { 1200 | switch (piccType) { 1201 | case PICC_TYPE_ISO_14443_4: return F("PICC compliant with ISO/IEC 14443-4"); break; 1202 | case PICC_TYPE_ISO_18092: return F("PICC compliant with ISO/IEC 18092 (NFC)");break; 1203 | case PICC_TYPE_MIFARE_MINI: return F("MIFARE Mini, 320 bytes"); break; 1204 | case PICC_TYPE_MIFARE_1K: return F("MIFARE 1KB"); break; 1205 | case PICC_TYPE_MIFARE_4K: return F("MIFARE 4KB"); break; 1206 | case PICC_TYPE_MIFARE_UL: return F("MIFARE Ultralight or Ultralight C"); break; 1207 | case PICC_TYPE_MIFARE_PLUS: return F("MIFARE Plus"); break; 1208 | case PICC_TYPE_TNP3XXX: return F("MIFARE TNP3XXX"); break; 1209 | case PICC_TYPE_NOT_COMPLETE: return F("SAK indicates UID is not complete."); break; 1210 | case PICC_TYPE_UNKNOWN: 1211 | default: return F("Unknown type"); break; 1212 | } 1213 | } // End PICC_GetTypeName() 1214 | 1215 | /** 1216 | * Dumps debug info about the selected PICC to Serial. 1217 | * On success the PICC is halted after dumping the data. 1218 | * For MIFARE Classic the factory default key of 0xFFFFFFFFFFFF is tried. 1219 | */ 1220 | void MFRC522::PICC_DumpToSerial(Uid *uid ///< Pointer to Uid struct returned from a successful PICC_Select(). 1221 | ) { 1222 | MIFARE_Key key; 1223 | 1224 | // UID 1225 | Serial.print(F("Card UID:")); 1226 | for (byte i = 0; i < uid->size; i++) { 1227 | if(uid->uidByte[i] < 0x10) 1228 | Serial.print(F(" 0")); 1229 | else 1230 | Serial.print(F(" ")); 1231 | Serial.print(uid->uidByte[i], HEX); 1232 | } 1233 | Serial.println(); 1234 | 1235 | // PICC type 1236 | byte piccType = PICC_GetType(uid->sak); 1237 | Serial.print(F("PICC type: ")); 1238 | Serial.println(PICC_GetTypeName(piccType)); 1239 | 1240 | // Dump contents 1241 | switch (piccType) { 1242 | case PICC_TYPE_MIFARE_MINI: 1243 | case PICC_TYPE_MIFARE_1K: 1244 | case PICC_TYPE_MIFARE_4K: 1245 | // All keys are set to FFFFFFFFFFFFh at chip delivery from the factory. 1246 | for (byte i = 0; i < 6; i++) { 1247 | key.keyByte[i] = 0xFF; 1248 | } 1249 | PICC_DumpMifareClassicToSerial(uid, piccType, &key); 1250 | break; 1251 | 1252 | case PICC_TYPE_MIFARE_UL: 1253 | PICC_DumpMifareUltralightToSerial(); 1254 | break; 1255 | 1256 | case PICC_TYPE_ISO_14443_4: 1257 | case PICC_TYPE_ISO_18092: 1258 | case PICC_TYPE_MIFARE_PLUS: 1259 | case PICC_TYPE_TNP3XXX: 1260 | Serial.println(F("Dumping memory contents not implemented for that PICC type.")); 1261 | break; 1262 | 1263 | case PICC_TYPE_UNKNOWN: 1264 | case PICC_TYPE_NOT_COMPLETE: 1265 | default: 1266 | break; // No memory dump here 1267 | } 1268 | 1269 | Serial.println(); 1270 | PICC_HaltA(); // Already done if it was a MIFARE Classic PICC. 1271 | } // End PICC_DumpToSerial() 1272 | 1273 | /** 1274 | * Dumps memory contents of a MIFARE Classic PICC. 1275 | * On success the PICC is halted after dumping the data. 1276 | */ 1277 | void MFRC522::PICC_DumpMifareClassicToSerial( Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select(). 1278 | byte piccType, ///< One of the PICC_Type enums. 1279 | MIFARE_Key *key ///< Key A used for all sectors. 1280 | ) { 1281 | byte no_of_sectors = 0; 1282 | switch (piccType) { 1283 | case PICC_TYPE_MIFARE_MINI: 1284 | // Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes. 1285 | no_of_sectors = 5; 1286 | break; 1287 | 1288 | case PICC_TYPE_MIFARE_1K: 1289 | // Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes. 1290 | no_of_sectors = 16; 1291 | break; 1292 | 1293 | case PICC_TYPE_MIFARE_4K: 1294 | // Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes. 1295 | no_of_sectors = 40; 1296 | break; 1297 | 1298 | default: // Should not happen. Ignore. 1299 | break; 1300 | } 1301 | 1302 | // Dump sectors, highest address first. 1303 | if (no_of_sectors) { 1304 | Serial.println(F("Sector Block 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 AccessBits")); 1305 | for (int8_t i = no_of_sectors - 1; i >= 0; i--) { 1306 | PICC_DumpMifareClassicSectorToSerial(uid, key, i); 1307 | } 1308 | } 1309 | PICC_HaltA(); // Halt the PICC before stopping the encrypted session. 1310 | PCD_StopCrypto1(); 1311 | } // End PICC_DumpMifareClassicToSerial() 1312 | 1313 | /** 1314 | * Dumps memory contents of a sector of a MIFARE Classic PICC. 1315 | * Uses PCD_Authenticate(), MIFARE_Read() and PCD_StopCrypto1. 1316 | * Always uses PICC_CMD_MF_AUTH_KEY_A because only Key A can always read the sector trailer access bits. 1317 | */ 1318 | void MFRC522::PICC_DumpMifareClassicSectorToSerial(Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select(). 1319 | MIFARE_Key *key, ///< Key A for the sector. 1320 | byte sector ///< The sector to dump, 0..39. 1321 | ) { 1322 | byte status; 1323 | byte firstBlock; // Address of lowest address to dump actually last block dumped) 1324 | byte no_of_blocks; // Number of blocks in sector 1325 | bool isSectorTrailer; // Set to true while handling the "last" (ie highest address) in the sector. 1326 | 1327 | // The access bits are stored in a peculiar fashion. 1328 | // There are four groups: 1329 | // g[3] Access bits for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39) 1330 | // g[2] Access bits for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39) 1331 | // g[1] Access bits for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39) 1332 | // g[0] Access bits for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39) 1333 | // Each group has access bits [C1 C2 C3]. In this code C1 is MSB and C3 is LSB. 1334 | // The four CX bits are stored together in a nible cx and an inverted nible cx_. 1335 | byte c1, c2, c3; // Nibbles 1336 | byte c1_, c2_, c3_; // Inverted nibbles 1337 | bool invertedError; // True if one of the inverted nibbles did not match 1338 | byte g[4]; // Access bits for each of the four groups. 1339 | byte group; // 0-3 - active group for access bits 1340 | bool firstInGroup; // True for the first block dumped in the group 1341 | 1342 | // Determine position and size of sector. 1343 | if (sector < 32) { // Sectors 0..31 has 4 blocks each 1344 | no_of_blocks = 4; 1345 | firstBlock = sector * no_of_blocks; 1346 | } 1347 | else if (sector < 40) { // Sectors 32-39 has 16 blocks each 1348 | no_of_blocks = 16; 1349 | firstBlock = 128 + (sector - 32) * no_of_blocks; 1350 | } 1351 | else { // Illegal input, no MIFARE Classic PICC has more than 40 sectors. 1352 | return; 1353 | } 1354 | 1355 | // Dump blocks, highest address first. 1356 | byte byteCount; 1357 | byte buffer[18]; 1358 | byte blockAddr; 1359 | isSectorTrailer = true; 1360 | for (int8_t blockOffset = no_of_blocks - 1; blockOffset >= 0; blockOffset--) { 1361 | blockAddr = firstBlock + blockOffset; 1362 | // Sector number - only on first line 1363 | if (isSectorTrailer) { 1364 | if(sector < 10) 1365 | Serial.print(F(" ")); // Pad with spaces 1366 | else 1367 | Serial.print(F(" ")); // Pad with spaces 1368 | Serial.print(sector); 1369 | Serial.print(F(" ")); 1370 | } 1371 | else { 1372 | Serial.print(F(" ")); 1373 | } 1374 | // Block number 1375 | if(blockAddr < 10) 1376 | Serial.print(F(" ")); // Pad with spaces 1377 | else { 1378 | if(blockAddr < 100) 1379 | Serial.print(F(" ")); // Pad with spaces 1380 | else 1381 | Serial.print(F(" ")); // Pad with spaces 1382 | } 1383 | Serial.print(blockAddr); 1384 | Serial.print(F(" ")); 1385 | // Establish encrypted communications before reading the first block 1386 | if (isSectorTrailer) { 1387 | status = PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, firstBlock, key, uid); 1388 | if (status != STATUS_OK) { 1389 | Serial.print(F("PCD_Authenticate() failed: ")); 1390 | Serial.println(GetStatusCodeName(status)); 1391 | return; 1392 | } 1393 | } 1394 | // Read block 1395 | byteCount = sizeof(buffer); 1396 | status = MIFARE_Read(blockAddr, buffer, &byteCount); 1397 | if (status != STATUS_OK) { 1398 | Serial.print(F("MIFARE_Read() failed: ")); 1399 | Serial.println(GetStatusCodeName(status)); 1400 | continue; 1401 | } 1402 | // Dump data 1403 | for (byte index = 0; index < 16; index++) { 1404 | if(buffer[index] < 0x10) 1405 | Serial.print(F(" 0")); 1406 | else 1407 | Serial.print(F(" ")); 1408 | Serial.print(buffer[index], HEX); 1409 | if ((index % 4) == 3) { 1410 | Serial.print(F(" ")); 1411 | } 1412 | } 1413 | // Parse sector trailer data 1414 | if (isSectorTrailer) { 1415 | c1 = buffer[7] >> 4; 1416 | c2 = buffer[8] & 0xF; 1417 | c3 = buffer[8] >> 4; 1418 | c1_ = buffer[6] & 0xF; 1419 | c2_ = buffer[6] >> 4; 1420 | c3_ = buffer[7] & 0xF; 1421 | invertedError = (c1 != (~c1_ & 0xF)) || (c2 != (~c2_ & 0xF)) || (c3 != (~c3_ & 0xF)); 1422 | g[0] = ((c1 & 1) << 2) | ((c2 & 1) << 1) | ((c3 & 1) << 0); 1423 | g[1] = ((c1 & 2) << 1) | ((c2 & 2) << 0) | ((c3 & 2) >> 1); 1424 | g[2] = ((c1 & 4) << 0) | ((c2 & 4) >> 1) | ((c3 & 4) >> 2); 1425 | g[3] = ((c1 & 8) >> 1) | ((c2 & 8) >> 2) | ((c3 & 8) >> 3); 1426 | isSectorTrailer = false; 1427 | } 1428 | 1429 | // Which access group is this block in? 1430 | if (no_of_blocks == 4) { 1431 | group = blockOffset; 1432 | firstInGroup = true; 1433 | } 1434 | else { 1435 | group = blockOffset / 5; 1436 | firstInGroup = (group == 3) || (group != (blockOffset + 1) / 5); 1437 | } 1438 | 1439 | if (firstInGroup) { 1440 | // Print access bits 1441 | Serial.print(F(" [ ")); 1442 | Serial.print((g[group] >> 2) & 1, DEC); Serial.print(F(" ")); 1443 | Serial.print((g[group] >> 1) & 1, DEC); Serial.print(F(" ")); 1444 | Serial.print((g[group] >> 0) & 1, DEC); 1445 | Serial.print(F(" ] ")); 1446 | if (invertedError) { 1447 | Serial.print(F(" Inverted access bits did not match! ")); 1448 | } 1449 | } 1450 | 1451 | if (group != 3 && (g[group] == 1 || g[group] == 6)) { // Not a sector trailer, a value block 1452 | long value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]); 1453 | Serial.print(F(" Value=0x")); Serial.print(value, HEX); 1454 | Serial.print(F(" Adr=0x")); Serial.print(buffer[12], HEX); 1455 | } 1456 | Serial.println(); 1457 | } 1458 | 1459 | return; 1460 | } // End PICC_DumpMifareClassicSectorToSerial() 1461 | 1462 | /** 1463 | * Dumps memory contents of a MIFARE Ultralight PICC. 1464 | */ 1465 | void MFRC522::PICC_DumpMifareUltralightToSerial() { 1466 | byte status; 1467 | byte byteCount; 1468 | byte buffer[18]; 1469 | byte i; 1470 | 1471 | Serial.println(F("Page 0 1 2 3")); 1472 | // Try the mpages of the original Ultralight. Ultralight C has more pages. 1473 | for (byte page = 0; page < 16; page +=4) { // Read returns data for 4 pages at a time. 1474 | // Read pages 1475 | byteCount = sizeof(buffer); 1476 | status = MIFARE_Read(page, buffer, &byteCount); 1477 | if (status != STATUS_OK) { 1478 | Serial.print(F("MIFARE_Read() failed: ")); 1479 | Serial.println(GetStatusCodeName(status)); 1480 | break; 1481 | } 1482 | // Dump data 1483 | for (byte offset = 0; offset < 4; offset++) { 1484 | i = page + offset; 1485 | if(i < 10) 1486 | Serial.print(F(" ")); // Pad with spaces 1487 | else 1488 | Serial.print(F(" ")); // Pad with spaces 1489 | Serial.print(i); 1490 | Serial.print(F(" ")); 1491 | for (byte index = 0; index < 4; index++) { 1492 | i = 4 * offset + index; 1493 | if(buffer[i] < 0x10) 1494 | Serial.print(F(" 0")); 1495 | else 1496 | Serial.print(F(" ")); 1497 | Serial.print(buffer[i], HEX); 1498 | } 1499 | Serial.println(); 1500 | } 1501 | } 1502 | } // End PICC_DumpMifareUltralightToSerial() 1503 | 1504 | /** 1505 | * Calculates the bit pattern needed for the specified access bits. In the [C1 C2 C3] tupples C1 is MSB (=4) and C3 is LSB (=1). 1506 | */ 1507 | void MFRC522::MIFARE_SetAccessBits( byte *accessBitBuffer, ///< Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set. 1508 | byte g0, ///< Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39) 1509 | byte g1, ///< Access bits C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39) 1510 | byte g2, ///< Access bits C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39) 1511 | byte g3 ///< Access bits C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39) 1512 | ) { 1513 | byte c1 = ((g3 & 4) << 1) | ((g2 & 4) << 0) | ((g1 & 4) >> 1) | ((g0 & 4) >> 2); 1514 | byte c2 = ((g3 & 2) << 2) | ((g2 & 2) << 1) | ((g1 & 2) << 0) | ((g0 & 2) >> 1); 1515 | byte c3 = ((g3 & 1) << 3) | ((g2 & 1) << 2) | ((g1 & 1) << 1) | ((g0 & 1) << 0); 1516 | 1517 | accessBitBuffer[0] = (~c2 & 0xF) << 4 | (~c1 & 0xF); 1518 | accessBitBuffer[1] = c1 << 4 | (~c3 & 0xF); 1519 | accessBitBuffer[2] = c3 << 4 | c2; 1520 | } // End MIFARE_SetAccessBits() 1521 | 1522 | 1523 | /** 1524 | * Performs the "magic sequence" needed to get Chinese UID changeable 1525 | * Mifare cards to allow writing to sector 0, where the card UID is stored. 1526 | * 1527 | * Note that you do not need to have selected the card through REQA or WUPA, 1528 | * this sequence works immediately when the card is in the reader vicinity. 1529 | * This means you can use this method even on "bricked" cards that your reader does 1530 | * not recognise anymore (see MFRC522::MIFARE_UnbrickUidSector). 1531 | * 1532 | * Of course with non-bricked devices, you're free to select them before calling this function. 1533 | */ 1534 | bool MFRC522::MIFARE_OpenUidBackdoor(bool logErrors) { 1535 | // Magic sequence: 1536 | // > 50 00 57 CD (HALT + CRC) 1537 | // > 40 (7 bits only) 1538 | // < A (4 bits only) 1539 | // > 43 1540 | // < A (4 bits only) 1541 | // Then you can write to sector 0 without authenticating 1542 | 1543 | PICC_HaltA(); // 50 00 57 CD 1544 | 1545 | byte cmd = 0x40; 1546 | byte validBits = 7; /* Our command is only 7 bits. After receiving card response, 1547 | this will contain amount of valid response bits. */ 1548 | byte response[32]; // Card's response is written here 1549 | byte received; 1550 | byte status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 40 1551 | if(status != STATUS_OK) { 1552 | if(logErrors) { 1553 | Serial.println(F("Card did not respond to 0x40 after HALT command. Are you sure it is a UID changeable one?")); 1554 | Serial.print(F("Error name: ")); 1555 | Serial.println(GetStatusCodeName(status)); 1556 | } 1557 | return false; 1558 | } 1559 | if (received != 1 || response[0] != 0x0A) { 1560 | if (logErrors) { 1561 | Serial.print(F("Got bad response on backdoor 0x40 command: ")); 1562 | Serial.print(response[0], HEX); 1563 | Serial.print(F(" (")); 1564 | Serial.print(validBits); 1565 | Serial.print(F(" valid bits)\r\n")); 1566 | } 1567 | return false; 1568 | } 1569 | 1570 | cmd = 0x43; 1571 | validBits = 8; 1572 | status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 43 1573 | if(status != STATUS_OK) { 1574 | if(logErrors) { 1575 | Serial.println(F("Error in communication at command 0x43, after successfully executing 0x40")); 1576 | Serial.print(F("Error name: ")); 1577 | Serial.println(GetStatusCodeName(status)); 1578 | } 1579 | return false; 1580 | } 1581 | if (received != 1 || response[0] != 0x0A) { 1582 | if (logErrors) { 1583 | Serial.print(F("Got bad response on backdoor 0x43 command: ")); 1584 | Serial.print(response[0], HEX); 1585 | Serial.print(F(" (")); 1586 | Serial.print(validBits); 1587 | Serial.print(F(" valid bits)\r\n")); 1588 | } 1589 | return false; 1590 | } 1591 | 1592 | // You can now write to sector 0 without authenticating! 1593 | return true; 1594 | } // End MIFARE_OpenUidBackdoor() 1595 | 1596 | /** 1597 | * Reads entire block 0, including all manufacturer data, and overwrites 1598 | * that block with the new UID, a freshly calculated BCC, and the original 1599 | * manufacturer data. 1600 | * 1601 | * It assumes a default KEY A of 0xFFFFFFFFFFFF. 1602 | * Make sure to have selected the card before this function is called. 1603 | */ 1604 | bool MFRC522::MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors) { 1605 | 1606 | // UID + BCC byte can not be larger than 16 together 1607 | if (!newUid || !uidSize || uidSize > 15) { 1608 | if (logErrors) { 1609 | Serial.println(F("New UID buffer empty, size 0, or size > 15 given")); 1610 | } 1611 | return false; 1612 | } 1613 | 1614 | // Authenticate for reading 1615 | MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 1616 | byte status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid); 1617 | if (status != STATUS_OK) { 1618 | 1619 | if (status == STATUS_TIMEOUT) { 1620 | // We get a read timeout if no card is selected yet, so let's select one 1621 | 1622 | // Wake the card up again if sleeping 1623 | // byte atqa_answer[2]; 1624 | // byte atqa_size = 2; 1625 | // PICC_WakeupA(atqa_answer, &atqa_size); 1626 | 1627 | if (!PICC_IsNewCardPresent() || !PICC_ReadCardSerial()) { 1628 | Serial.println(F("No card was previously selected, and none are available. Failed to set UID.")); 1629 | return false; 1630 | } 1631 | 1632 | status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid); 1633 | if (status != STATUS_OK) { 1634 | // We tried, time to give up 1635 | if (logErrors) { 1636 | Serial.println(F("Failed to authenticate to card for reading, could not set UID: ")); 1637 | Serial.println(GetStatusCodeName(status)); 1638 | } 1639 | return false; 1640 | } 1641 | } 1642 | else { 1643 | if (logErrors) { 1644 | Serial.print(F("PCD_Authenticate() failed: ")); 1645 | Serial.println(GetStatusCodeName(status)); 1646 | } 1647 | return false; 1648 | } 1649 | } 1650 | 1651 | // Read block 0 1652 | byte block0_buffer[18]; 1653 | byte byteCount = sizeof(block0_buffer); 1654 | status = MIFARE_Read((byte)0, block0_buffer, &byteCount); 1655 | if (status != STATUS_OK) { 1656 | if (logErrors) { 1657 | Serial.print(F("MIFARE_Read() failed: ")); 1658 | Serial.println(GetStatusCodeName(status)); 1659 | Serial.println(F("Are you sure your KEY A for sector 0 is 0xFFFFFFFFFFFF?")); 1660 | } 1661 | return false; 1662 | } 1663 | 1664 | // Write new UID to the data we just read, and calculate BCC byte 1665 | byte bcc = 0; 1666 | for (int i = 0; i < uidSize; i++) { 1667 | block0_buffer[i] = newUid[i]; 1668 | bcc ^= newUid[i]; 1669 | } 1670 | 1671 | // Write BCC byte to buffer 1672 | block0_buffer[uidSize] = bcc; 1673 | 1674 | // Stop encrypted traffic so we can send raw bytes 1675 | PCD_StopCrypto1(); 1676 | 1677 | // Activate UID backdoor 1678 | if (!MIFARE_OpenUidBackdoor(logErrors)) { 1679 | if (logErrors) { 1680 | Serial.println(F("Activating the UID backdoor failed.")); 1681 | } 1682 | return false; 1683 | } 1684 | 1685 | // Write modified block 0 back to card 1686 | status = MIFARE_Write((byte)0, block0_buffer, (byte)16); 1687 | if (status != STATUS_OK) { 1688 | if (logErrors) { 1689 | Serial.print(F("MIFARE_Write() failed: ")); 1690 | Serial.println(GetStatusCodeName(status)); 1691 | } 1692 | return false; 1693 | } 1694 | 1695 | // Wake the card up again 1696 | byte atqa_answer[2]; 1697 | byte atqa_size = 2; 1698 | PICC_WakeupA(atqa_answer, &atqa_size); 1699 | 1700 | return true; 1701 | } 1702 | 1703 | /** 1704 | * Resets entire sector 0 to zeroes, so the card can be read again by readers. 1705 | */ 1706 | bool MFRC522::MIFARE_UnbrickUidSector(bool logErrors) { 1707 | MIFARE_OpenUidBackdoor(logErrors); 1708 | 1709 | byte block0_buffer[] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 1710 | 1711 | // Write modified block 0 back to card 1712 | byte status = MIFARE_Write((byte)0, block0_buffer, (byte)16); 1713 | if (status != STATUS_OK) { 1714 | if (logErrors) { 1715 | Serial.print(F("MIFARE_Write() failed: ")); 1716 | Serial.println(GetStatusCodeName(status)); 1717 | } 1718 | return false; 1719 | } 1720 | return true; 1721 | } 1722 | 1723 | ///////////////////////////////////////////////////////////////////////////////////// 1724 | // Convenience functions - does not add extra functionality 1725 | ///////////////////////////////////////////////////////////////////////////////////// 1726 | 1727 | /** 1728 | * Returns true if a PICC responds to PICC_CMD_REQA. 1729 | * Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored. 1730 | * 1731 | * @return bool 1732 | */ 1733 | bool MFRC522::PICC_IsNewCardPresent() { 1734 | byte bufferATQA[2]; 1735 | byte bufferSize = sizeof(bufferATQA); 1736 | byte result = PICC_RequestA(bufferATQA, &bufferSize); 1737 | return (result == STATUS_OK || result == STATUS_COLLISION); 1738 | } // End PICC_IsNewCardPresent() 1739 | 1740 | /** 1741 | * Simple wrapper around PICC_Select. 1742 | * Returns true if a UID could be read. 1743 | * Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first. 1744 | * The read UID is available in the class variable uid. 1745 | * 1746 | * @return bool 1747 | */ 1748 | bool MFRC522::PICC_ReadCardSerial() { 1749 | byte result = PICC_Select(&uid); 1750 | return (result == STATUS_OK); 1751 | } // End PICC_ReadCardSerial() 1752 | -------------------------------------------------------------------------------- /IOFrameworkForXR/MFRC522_I2C.h: -------------------------------------------------------------------------------- 1 | /** 2 | * MFRC522_I2C.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS I2C BY AROZCAN 3 | * MFRC522_I2C.h - Based on ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI Library BY COOQROBOT. 4 | * Based on code Dr.Leong ( WWW.B2CQSHOP.COM ) 5 | * Created by Miguel Balboa (circuitito.com), Jan, 2012. 6 | * Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013 (Translation to English, refactored, comments, anti collision, cascade levels.) 7 | * Extended by Tom Clement with functionality to write to sector 0 of UID changeable Mifare cards. 8 | * Extended by Ahmet Remzi Ozcan with I2C functionality. 9 | * Author: arozcan @ https://github.com/arozcan/MFRC522-I2C-Library 10 | * Released into the public domain. 11 | * 12 | * Please read this file for an overview and then MFRC522.cpp for comments on the specific functions. 13 | * Search for "mf-rc522" on ebay.com to purchase the MF-RC522 board. 14 | * 15 | * There are three hardware components involved: 16 | * 1) The micro controller: An Arduino 17 | * 2) The PCD (short for Proximity Coupling Device): NXP MFRC522 Contactless Reader IC 18 | * 3) The PICC (short for Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203. 19 | * 20 | * The microcontroller and card reader uses I2C for communication. 21 | * The protocol is described in the MFRC522 datasheet: http://www.nxp.com/documents/data_sheet/MFRC522.pdf 22 | * 23 | * The card reader and the tags communicate using a 13.56MHz electromagnetic field. 24 | * The protocol is defined in ISO/IEC 14443-3 Identification cards -- Contactless integrated circuit cards -- Proximity cards -- Part 3: Initialization and anticollision". 25 | * A free version of the final draft can be found at http://wg8.de/wg8n1496_17n3613_Ballot_FCD14443-3.pdf 26 | * Details are found in chapter 6, Type A – Initialization and anticollision. 27 | * 28 | * If only the PICC UID is wanted, the above documents has all the needed information. 29 | * To read and write from MIFARE PICCs, the MIFARE protocol is used after the PICC has been selected. 30 | * The MIFARE Classic chips and protocol is described in the datasheets: 31 | * 1K: http://www.nxp.com/documents/data_sheet/MF1S503x.pdf 32 | * 4K: http://www.nxp.com/documents/data_sheet/MF1S703x.pdf 33 | * Mini: http://www.idcardmarket.com/download/mifare_S20_datasheet.pdf 34 | * The MIFARE Ultralight chip and protocol is described in the datasheets: 35 | * Ultralight: http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf 36 | * Ultralight C: http://www.nxp.com/documents/short_data_sheet/MF0ICU2_SDS.pdf 37 | * 38 | * MIFARE Classic 1K (MF1S503x): 39 | * Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes. 40 | * The blocks are numbered 0-63. 41 | * Block 3 in each sector is the Sector Trailer. See http://www.nxp.com/documents/data_sheet/MF1S503x.pdf sections 8.6 and 8.7: 42 | * Bytes 0-5: Key A 43 | * Bytes 6-8: Access Bits 44 | * Bytes 9: User data 45 | * Bytes 10-15: Key B (or user data) 46 | * Block 0 is read-only manufacturer data. 47 | * To access a block, an authentication using a key from the block's sector must be performed first. 48 | * Example: To read from block 10, first authenticate using a key from sector 3 (blocks 8-11). 49 | * All keys are set to FFFFFFFFFFFFh at chip delivery. 50 | * Warning: Please read section 8.7 "Memory Access". It includes this text: if the PICC detects a format violation the whole sector is irreversibly blocked. 51 | * To use a block in "value block" mode (for Increment/Decrement operations) you need to change the sector trailer. Use PICC_SetAccessBits() to calculate the bit patterns. 52 | * MIFARE Classic 4K (MF1S703x): 53 | * Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes. 54 | * The blocks are numbered 0-255. 55 | * The last block in each sector is the Sector Trailer like above. 56 | * MIFARE Classic Mini (MF1 IC S20): 57 | * Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes. 58 | * The blocks are numbered 0-19. 59 | * The last block in each sector is the Sector Trailer like above. 60 | * 61 | * MIFARE Ultralight (MF0ICU1): 62 | * Has 16 pages of 4 bytes = 64 bytes. 63 | * Pages 0 + 1 is used for the 7-byte UID. 64 | * Page 2 contains the last check digit for the UID, one byte manufacturer internal data, and the lock bytes (see http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf section 8.5.2) 65 | * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. 66 | * Pages 4-15 are read/write unless blocked by the lock bytes in page 2. 67 | * MIFARE Ultralight C (MF0ICU2): 68 | * Has 48 pages of 4 bytes = 192 bytes. 69 | * Pages 0 + 1 is used for the 7-byte UID. 70 | * Page 2 contains the last check digit for the UID, one byte manufacturer internal data, and the lock bytes (see http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf section 8.5.2) 71 | * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. 72 | * Pages 4-39 are read/write unless blocked by the lock bytes in page 2. 73 | * Page 40 Lock bytes 74 | * Page 41 16 bit one way counter 75 | * Pages 42-43 Authentication configuration 76 | * Pages 44-47 Authentication key 77 | */ 78 | #ifndef MFRC522_h 79 | #define MFRC522_h 80 | 81 | #include 82 | #include 83 | 84 | // Firmware data for self-test 85 | // Reference values based on firmware version 86 | // Hint: if needed, you can remove unused self-test data to save flash memory 87 | // 88 | // Version 0.0 (0x90) 89 | // Philips Semiconductors; Preliminary Specification Revision 2.0 - 01 August 2005; 16.1 Sefttest 90 | const byte MFRC522_firmware_referenceV0_0[] PROGMEM = { 91 | 0x00, 0x87, 0x98, 0x0f, 0x49, 0xFF, 0x07, 0x19, 92 | 0xBF, 0x22, 0x30, 0x49, 0x59, 0x63, 0xAD, 0xCA, 93 | 0x7F, 0xE3, 0x4E, 0x03, 0x5C, 0x4E, 0x49, 0x50, 94 | 0x47, 0x9A, 0x37, 0x61, 0xE7, 0xE2, 0xC6, 0x2E, 95 | 0x75, 0x5A, 0xED, 0x04, 0x3D, 0x02, 0x4B, 0x78, 96 | 0x32, 0xFF, 0x58, 0x3B, 0x7C, 0xE9, 0x00, 0x94, 97 | 0xB4, 0x4A, 0x59, 0x5B, 0xFD, 0xC9, 0x29, 0xDF, 98 | 0x35, 0x96, 0x98, 0x9E, 0x4F, 0x30, 0x32, 0x8D 99 | }; 100 | // Version 1.0 (0x91) 101 | // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 Self test 102 | const byte MFRC522_firmware_referenceV1_0[] PROGMEM = { 103 | 0x00, 0xC6, 0x37, 0xD5, 0x32, 0xB7, 0x57, 0x5C, 104 | 0xC2, 0xD8, 0x7C, 0x4D, 0xD9, 0x70, 0xC7, 0x73, 105 | 0x10, 0xE6, 0xD2, 0xAA, 0x5E, 0xA1, 0x3E, 0x5A, 106 | 0x14, 0xAF, 0x30, 0x61, 0xC9, 0x70, 0xDB, 0x2E, 107 | 0x64, 0x22, 0x72, 0xB5, 0xBD, 0x65, 0xF4, 0xEC, 108 | 0x22, 0xBC, 0xD3, 0x72, 0x35, 0xCD, 0xAA, 0x41, 109 | 0x1F, 0xA7, 0xF3, 0x53, 0x14, 0xDE, 0x7E, 0x02, 110 | 0xD9, 0x0F, 0xB5, 0x5E, 0x25, 0x1D, 0x29, 0x79 111 | }; 112 | // Version 2.0 (0x92) 113 | // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 Self test 114 | const byte MFRC522_firmware_referenceV2_0[] PROGMEM = { 115 | 0x00, 0xEB, 0x66, 0xBA, 0x57, 0xBF, 0x23, 0x95, 116 | 0xD0, 0xE3, 0x0D, 0x3D, 0x27, 0x89, 0x5C, 0xDE, 117 | 0x9D, 0x3B, 0xA7, 0x00, 0x21, 0x5B, 0x89, 0x82, 118 | 0x51, 0x3A, 0xEB, 0x02, 0x0C, 0xA5, 0x00, 0x49, 119 | 0x7C, 0x84, 0x4D, 0xB3, 0xCC, 0xD2, 0x1B, 0x81, 120 | 0x5D, 0x48, 0x76, 0xD5, 0x71, 0x61, 0x21, 0xA9, 121 | 0x86, 0x96, 0x83, 0x38, 0xCF, 0x9D, 0x5B, 0x6D, 122 | 0xDC, 0x15, 0xBA, 0x3E, 0x7D, 0x95, 0x3B, 0x2F 123 | }; 124 | // Clone 125 | // Fudan Semiconductor FM17522 (0x88) 126 | const byte FM17522_firmware_reference[] PROGMEM = { 127 | 0x00, 0xD6, 0x78, 0x8C, 0xE2, 0xAA, 0x0C, 0x18, 128 | 0x2A, 0xB8, 0x7A, 0x7F, 0xD3, 0x6A, 0xCF, 0x0B, 129 | 0xB1, 0x37, 0x63, 0x4B, 0x69, 0xAE, 0x91, 0xC7, 130 | 0xC3, 0x97, 0xAE, 0x77, 0xF4, 0x37, 0xD7, 0x9B, 131 | 0x7C, 0xF5, 0x3C, 0x11, 0x8F, 0x15, 0xC3, 0xD7, 132 | 0xC1, 0x5B, 0x00, 0x2A, 0xD0, 0x75, 0xDE, 0x9E, 133 | 0x51, 0x64, 0xAB, 0x3E, 0xE9, 0x15, 0xB5, 0xAB, 134 | 0x56, 0x9A, 0x98, 0x82, 0x26, 0xEA, 0x2A, 0x62 135 | }; 136 | 137 | class MFRC522 { 138 | public: 139 | // MFRC522 registers. Described in chapter 9 of the datasheet. 140 | enum PCD_Register { 141 | // Page 0: Command and status 142 | // 0x00 // reserved for future use 143 | CommandReg = 0x01 , // starts and stops command execution 144 | ComIEnReg = 0x02 , // enable and disable interrupt request control bits 145 | DivIEnReg = 0x03 , // enable and disable interrupt request control bits 146 | ComIrqReg = 0x04 , // interrupt request bits 147 | DivIrqReg = 0x05 , // interrupt request bits 148 | ErrorReg = 0x06 , // error bits showing the error status of the last command executed 149 | Status1Reg = 0x07 , // communication status bits 150 | Status2Reg = 0x08 , // receiver and transmitter status bits 151 | FIFODataReg = 0x09 , // input and output of 64 byte FIFO buffer 152 | FIFOLevelReg = 0x0A , // number of bytes stored in the FIFO buffer 153 | WaterLevelReg = 0x0B , // level for FIFO underflow and overflow warning 154 | ControlReg = 0x0C , // miscellaneous control registers 155 | BitFramingReg = 0x0D , // adjustments for bit-oriented frames 156 | CollReg = 0x0E , // bit position of the first bit-collision detected on the RF interface 157 | // 0x0F // reserved for future use 158 | 159 | // Page 1: Command 160 | // 0x10 // reserved for future use 161 | ModeReg = 0x11 , // defines general modes for transmitting and receiving 162 | TxModeReg = 0x12 , // defines transmission data rate and framing 163 | RxModeReg = 0x13 , // defines reception data rate and framing 164 | TxControlReg = 0x14 , // controls the logical behavior of the antenna driver pins TX1 and TX2 165 | TxASKReg = 0x15 , // controls the setting of the transmission modulation 166 | TxSelReg = 0x16 , // selects the internal sources for the antenna driver 167 | RxSelReg = 0x17 , // selects internal receiver settings 168 | RxThresholdReg = 0x18 , // selects thresholds for the bit decoder 169 | DemodReg = 0x19 , // defines demodulator settings 170 | // 0x1A // reserved for future use 171 | // 0x1B // reserved for future use 172 | MfTxReg = 0x1C , // controls some MIFARE communication transmit parameters 173 | MfRxReg = 0x1D , // controls some MIFARE communication receive parameters 174 | // 0x1E // reserved for future use 175 | SerialSpeedReg = 0x1F , // selects the speed of the serial UART interface 176 | 177 | // Page 2: Configuration 178 | // 0x20 // reserved for future use 179 | CRCResultRegH = 0x21 , // shows the MSB and LSB values of the CRC calculation 180 | CRCResultRegL = 0x22 , 181 | // 0x23 // reserved for future use 182 | ModWidthReg = 0x24 , // controls the ModWidth setting? 183 | // 0x25 // reserved for future use 184 | RFCfgReg = 0x26 , // configures the receiver gain 185 | GsNReg = 0x27 , // selects the conductance of the antenna driver pins TX1 and TX2 for modulation 186 | CWGsPReg = 0x28 , // defines the conductance of the p-driver output during periods of no modulation 187 | ModGsPReg = 0x29 , // defines the conductance of the p-driver output during periods of modulation 188 | TModeReg = 0x2A , // defines settings for the internal timer 189 | TPrescalerReg = 0x2B , // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg. 190 | TReloadRegH = 0x2C , // defines the 16-bit timer reload value 191 | TReloadRegL = 0x2D , 192 | TCounterValueRegH = 0x2E , // shows the 16-bit timer value 193 | TCounterValueRegL = 0x2F , 194 | 195 | // Page 3: Test Registers 196 | // 0x30 // reserved for future use 197 | TestSel1Reg = 0x31 , // general test signal configuration 198 | TestSel2Reg = 0x32 , // general test signal configuration 199 | TestPinEnReg = 0x33 , // enables pin output driver on pins D1 to D7 200 | TestPinValueReg = 0x34 , // defines the values for D1 to D7 when it is used as an I/O bus 201 | TestBusReg = 0x35 , // shows the status of the internal test bus 202 | AutoTestReg = 0x36 , // controls the digital self test 203 | VersionReg = 0x37 , // shows the software version 204 | AnalogTestReg = 0x38 , // controls the pins AUX1 and AUX2 205 | TestDAC1Reg = 0x39 , // defines the test value for TestDAC1 206 | TestDAC2Reg = 0x3A , // defines the test value for TestDAC2 207 | TestADCReg = 0x3B // shows the value of ADC I and Q channels 208 | // 0x3C // reserved for production tests 209 | // 0x3D // reserved for production tests 210 | // 0x3E // reserved for production tests 211 | // 0x3F // reserved for production tests 212 | }; 213 | 214 | // MFRC522 commands. Described in chapter 10 of the datasheet. 215 | enum PCD_Command { 216 | PCD_Idle = 0x00, // no action, cancels current command execution 217 | PCD_Mem = 0x01, // stores 25 bytes into the internal buffer 218 | PCD_GenerateRandomID = 0x02, // generates a 10-byte random ID number 219 | PCD_CalcCRC = 0x03, // activates the CRC coprocessor or performs a self test 220 | PCD_Transmit = 0x04, // transmits data from the FIFO buffer 221 | PCD_NoCmdChange = 0x07, // no command change, can be used to modify the CommandReg register bits without affecting the command, for example, the PowerDown bit 222 | PCD_Receive = 0x08, // activates the receiver circuits 223 | PCD_Transceive = 0x0C, // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission 224 | PCD_MFAuthent = 0x0E, // performs the MIFARE standard authentication as a reader 225 | PCD_SoftReset = 0x0F // resets the MFRC522 226 | }; 227 | 228 | // MFRC522 RxGain[2:0] masks, defines the receiver's signal voltage gain factor (on the PCD). 229 | // Described in 9.3.3.6 / table 98 of the datasheet at http://www.nxp.com/documents/data_sheet/MFRC522.pdf 230 | enum PCD_RxGain { 231 | RxGain_18dB = 0x00 << 4, // 000b - 18 dB, minimum 232 | RxGain_23dB = 0x01 << 4, // 001b - 23 dB 233 | RxGain_18dB_2 = 0x02 << 4, // 010b - 18 dB, it seems 010b is a duplicate for 000b 234 | RxGain_23dB_2 = 0x03 << 4, // 011b - 23 dB, it seems 011b is a duplicate for 001b 235 | RxGain_33dB = 0x04 << 4, // 100b - 33 dB, average, and typical default 236 | RxGain_38dB = 0x05 << 4, // 101b - 38 dB 237 | RxGain_43dB = 0x06 << 4, // 110b - 43 dB 238 | RxGain_48dB = 0x07 << 4, // 111b - 48 dB, maximum 239 | RxGain_min = 0x00 << 4, // 000b - 18 dB, minimum, convenience for RxGain_18dB 240 | RxGain_avg = 0x04 << 4, // 100b - 33 dB, average, convenience for RxGain_33dB 241 | RxGain_max = 0x07 << 4 // 111b - 48 dB, maximum, convenience for RxGain_48dB 242 | }; 243 | 244 | // Commands sent to the PICC. 245 | enum PICC_Command { 246 | // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4) 247 | PICC_CMD_REQA = 0x26, // REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame. 248 | PICC_CMD_WUPA = 0x52, // Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame. 249 | PICC_CMD_CT = 0x88, // Cascade Tag. Not really a command, but used during anti collision. 250 | PICC_CMD_SEL_CL1 = 0x93, // Anti collision/Select, Cascade Level 1 251 | PICC_CMD_SEL_CL2 = 0x95, // Anti collision/Select, Cascade Level 2 252 | PICC_CMD_SEL_CL3 = 0x97, // Anti collision/Select, Cascade Level 3 253 | PICC_CMD_HLTA = 0x50, // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT. 254 | // The commands used for MIFARE Classic (from http://www.nxp.com/documents/data_sheet/MF1S503x.pdf, Section 9) 255 | // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on the sector. 256 | // The read/write commands can also be used for MIFARE Ultralight. 257 | PICC_CMD_MF_AUTH_KEY_A = 0x60, // Perform authentication with Key A 258 | PICC_CMD_MF_AUTH_KEY_B = 0x61, // Perform authentication with Key B 259 | PICC_CMD_MF_READ = 0x30, // Reads one 16 byte block from the authenticated sector of the PICC. Also used for MIFARE Ultralight. 260 | PICC_CMD_MF_WRITE = 0xA0, // Writes one 16 byte block to the authenticated sector of the PICC. Called "COMPATIBILITY WRITE" for MIFARE Ultralight. 261 | PICC_CMD_MF_DECREMENT = 0xC0, // Decrements the contents of a block and stores the result in the internal data register. 262 | PICC_CMD_MF_INCREMENT = 0xC1, // Increments the contents of a block and stores the result in the internal data register. 263 | PICC_CMD_MF_RESTORE = 0xC2, // Reads the contents of a block into the internal data register. 264 | PICC_CMD_MF_TRANSFER = 0xB0, // Writes the contents of the internal data register to a block. 265 | // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6) 266 | // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight. 267 | PICC_CMD_UL_WRITE = 0xA2 // Writes one 4 byte page to the PICC. 268 | }; 269 | 270 | // MIFARE constants that does not fit anywhere else 271 | enum MIFARE_Misc { 272 | MF_ACK = 0xA, // The MIFARE Classic uses a 4 bit ACK/NAK. Any other value than 0xA is NAK. 273 | MF_KEY_SIZE = 6 // A Mifare Crypto1 key is 6 bytes. 274 | }; 275 | 276 | // PICC types we can detect. Remember to update PICC_GetTypeName() if you add more. 277 | enum PICC_Type { 278 | PICC_TYPE_UNKNOWN = 0, 279 | PICC_TYPE_ISO_14443_4 = 1, // PICC compliant with ISO/IEC 14443-4 280 | PICC_TYPE_ISO_18092 = 2, // PICC compliant with ISO/IEC 18092 (NFC) 281 | PICC_TYPE_MIFARE_MINI = 3, // MIFARE Classic protocol, 320 bytes 282 | PICC_TYPE_MIFARE_1K = 4, // MIFARE Classic protocol, 1KB 283 | PICC_TYPE_MIFARE_4K = 5, // MIFARE Classic protocol, 4KB 284 | PICC_TYPE_MIFARE_UL = 6, // MIFARE Ultralight or Ultralight C 285 | PICC_TYPE_MIFARE_PLUS = 7, // MIFARE Plus 286 | PICC_TYPE_TNP3XXX = 8, // Only mentioned in NXP AN 10833 MIFARE Type Identification Procedure 287 | PICC_TYPE_NOT_COMPLETE = 255 // SAK indicates UID is not complete. 288 | }; 289 | 290 | // Return codes from the functions in this class. Remember to update GetStatusCodeName() if you add more. 291 | enum StatusCode { 292 | STATUS_OK = 1, // Success 293 | STATUS_ERROR = 2, // Error in communication 294 | STATUS_COLLISION = 3, // Collission detected 295 | STATUS_TIMEOUT = 4, // Timeout in communication. 296 | STATUS_NO_ROOM = 5, // A buffer is not big enough. 297 | STATUS_INTERNAL_ERROR = 6, // Internal error in the code. Should not happen ;-) 298 | STATUS_INVALID = 7, // Invalid argument. 299 | STATUS_CRC_WRONG = 8, // The CRC_A does not match 300 | STATUS_MIFARE_NACK = 9 // A MIFARE PICC responded with NAK. 301 | }; 302 | 303 | // A struct used for passing the UID of a PICC. 304 | typedef struct { 305 | byte size; // Number of bytes in the UID. 4, 7 or 10. 306 | byte uidByte[10]; 307 | byte sak; // The SAK (Select acknowledge) byte returned from the PICC after successful selection. 308 | } Uid; 309 | 310 | // A struct used for passing a MIFARE Crypto1 key 311 | typedef struct { 312 | byte keyByte[MF_KEY_SIZE]; 313 | } MIFARE_Key; 314 | 315 | // Member variables 316 | Uid uid; // Used by PICC_ReadCardSerial(). 317 | 318 | // Size of the MFRC522 FIFO 319 | static const byte FIFO_SIZE = 64; // The FIFO is 64 bytes. 320 | 321 | ///////////////////////////////////////////////////////////////////////////////////// 322 | // Functions for setting up the Arduino 323 | ///////////////////////////////////////////////////////////////////////////////////// 324 | MFRC522(byte chipAddress); 325 | 326 | ///////////////////////////////////////////////////////////////////////////////////// 327 | // Basic interface functions for communicating with the MFRC522 328 | ///////////////////////////////////////////////////////////////////////////////////// 329 | void PCD_WriteRegister(byte reg, byte value); 330 | void PCD_WriteRegister(byte reg, byte count, byte *values); 331 | byte PCD_ReadRegister(byte reg); 332 | void PCD_ReadRegister(byte reg, byte count, byte *values, byte rxAlign = 0); 333 | void setBitMask(unsigned char reg, unsigned char mask); 334 | void PCD_SetRegisterBitMask(byte reg, byte mask); 335 | void PCD_ClearRegisterBitMask(byte reg, byte mask); 336 | byte PCD_CalculateCRC(byte *data, byte length, byte *result); 337 | 338 | ///////////////////////////////////////////////////////////////////////////////////// 339 | // Functions for manipulating the MFRC522 340 | ///////////////////////////////////////////////////////////////////////////////////// 341 | void PCD_Init(); 342 | void PCD_Reset(); 343 | void PCD_AntennaOn(); 344 | void PCD_AntennaOff(); 345 | byte PCD_GetAntennaGain(); 346 | void PCD_SetAntennaGain(byte mask); 347 | bool PCD_PerformSelfTest(); 348 | 349 | ///////////////////////////////////////////////////////////////////////////////////// 350 | // Functions for communicating with PICCs 351 | ///////////////////////////////////////////////////////////////////////////////////// 352 | byte PCD_TransceiveData(byte *sendData, byte sendLen, byte *backData, byte *backLen, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); 353 | byte PCD_CommunicateWithPICC(byte command, byte waitIRq, byte *sendData, byte sendLen, byte *backData = NULL, byte *backLen = NULL, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); 354 | byte PICC_RequestA(byte *bufferATQA, byte *bufferSize); 355 | byte PICC_WakeupA(byte *bufferATQA, byte *bufferSize); 356 | byte PICC_REQA_or_WUPA(byte command, byte *bufferATQA, byte *bufferSize); 357 | byte PICC_Select(Uid *uid, byte validBits = 0); 358 | byte PICC_HaltA(); 359 | 360 | ///////////////////////////////////////////////////////////////////////////////////// 361 | // Functions for communicating with MIFARE PICCs 362 | ///////////////////////////////////////////////////////////////////////////////////// 363 | byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid); 364 | void PCD_StopCrypto1(); 365 | byte MIFARE_Read(byte blockAddr, byte *buffer, byte *bufferSize); 366 | byte MIFARE_Write(byte blockAddr, byte *buffer, byte bufferSize); 367 | byte MIFARE_Decrement(byte blockAddr, long delta); 368 | byte MIFARE_Increment(byte blockAddr, long delta); 369 | byte MIFARE_Restore(byte blockAddr); 370 | byte MIFARE_Transfer(byte blockAddr); 371 | byte MIFARE_Ultralight_Write(byte page, byte *buffer, byte bufferSize); 372 | byte MIFARE_GetValue(byte blockAddr, long *value); 373 | byte MIFARE_SetValue(byte blockAddr, long value); 374 | 375 | ///////////////////////////////////////////////////////////////////////////////////// 376 | // Support functions 377 | ///////////////////////////////////////////////////////////////////////////////////// 378 | byte PCD_MIFARE_Transceive(byte *sendData, byte sendLen, bool acceptTimeout = false); 379 | // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory 380 | //const char *GetStatusCodeName(byte code); 381 | const __FlashStringHelper *GetStatusCodeName(byte code); 382 | byte PICC_GetType(byte sak); 383 | // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory 384 | //const char *PICC_GetTypeName(byte type); 385 | const __FlashStringHelper *PICC_GetTypeName(byte type); 386 | void PICC_DumpToSerial(Uid *uid); 387 | void PICC_DumpMifareClassicToSerial(Uid *uid, byte piccType, MIFARE_Key *key); 388 | void PICC_DumpMifareClassicSectorToSerial(Uid *uid, MIFARE_Key *key, byte sector); 389 | void PICC_DumpMifareUltralightToSerial(); 390 | void MIFARE_SetAccessBits(byte *accessBitBuffer, byte g0, byte g1, byte g2, byte g3); 391 | bool MIFARE_OpenUidBackdoor(bool logErrors); 392 | bool MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors); 393 | bool MIFARE_UnbrickUidSector(bool logErrors); 394 | 395 | ///////////////////////////////////////////////////////////////////////////////////// 396 | // Convenience functions - does not add extra functionality 397 | ///////////////////////////////////////////////////////////////////////////////////// 398 | bool PICC_IsNewCardPresent(); 399 | bool PICC_ReadCardSerial(); 400 | 401 | private: 402 | byte _chipAddress; 403 | byte _resetPowerDownPin; // Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low) 404 | byte MIFARE_TwoStepHelper(byte command, byte blockAddr, long data); 405 | }; 406 | 407 | #endif 408 | -------------------------------------------------------------------------------- /IOFrameworkForXR/firmware.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/IOFrameworkForXR/firmware.bin -------------------------------------------------------------------------------- /IOFrameworkSDK.unitypackage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/IOFrameworkSDK.unitypackage -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # I/O Framework for xR 2 | 3 | This project is a framework for xR creators to extend inputs and outputs easily beyond the capabilities of conventional devices. 4 | 5 | The framework consists of firmware for M5Stack and an SDK for Unity with the STYLY plugin. The M5Stack toolkit allows you to easily create IoT projects by connecting various sensors and actuators without soldering. The controller functions as a Bluetooth keyboard and a Wi-Fi server, sending keyboard events to a device such as a smartphone in response to input from sensors. Moreover, you can control actuators by sending HTTP requests to the controller. 6 | 7 | With this framework, you may be able to expand your imagination of the concept of xR and realize your ideas as works. 8 | 9 | --- 10 | 11 | 本プロジェクトは、xRクリエーターが、従来のデバイスの能力を超える入出力を簡単に拡張するためのフレームワークです。 12 | 13 | フレームワークは、M5Stack用のファームウェアと、STYLYプラグインを組み込んだUnity用のSDKで構成されています。M5Stackは、各種センサーやアクチュエーターをハンダづけなしで接続し、IoTプロジェクトを簡単に作成できるツールキットです。コントローラは、BluetoothキーボードおよびWi-Fiサーバーとして機能し、センサーからの入力に応じてキーボードイベントをスマートフォンなどのデバイスに送信します。さらに、コントローラにHTTPリクエストを送ることで、アクチュエータを制御できます。 14 | 15 | このフレームワークを使うことにより、xRの概念に対する想像力を膨らませ、アイデアを作品として実現できるかもしれません。 16 | 17 | ## Status 18 | 19 | :construction: Heavily work in progress; therefore, only for experimental purposes :construction: 20 | 21 | ### Supported Units 22 | 23 | #### Sensors 24 | 25 | - [Mini Dual Button Unit](https://shop.m5stack.com/collections/m5-unit/products/mini-dual-button-unit) 26 | - [Light Sensor Unit](https://shop.m5stack.com/collections/m5-unit/products/light-sensor-unit) 27 | - [Mini Angle Unit](https://shop.m5stack.com/products/angle-unit) 28 | - [I2C Joystick Unit V1.1](https://shop.m5stack.com/collections/m5-sensor/products/i2c-joystick-unit-v1-1-mega8a) 29 | - [Distance Ranging Sensor Unit](https://shop.m5stack.com/products/tof-sensor-unit) 30 | - [TVOC/eCO2 Gas Sensor Unit](https://shop.m5stack.com/products/tvoc-eco2-gas-unit-sgp30) 31 | - [RFID 2 Unit](https://shop.m5stack.com/collections/m5-sensor/products/rfid-unit-2-ws1850s) 32 | - [Gesture recognition sensor](https://shop.m5stack.com/products/unit-gesture-recognition-sensor-paj7620u2) 33 | - [12 Key Capacitive I2C Touch Sensor V3](https://www.seeedstudio.com/Grove-12-Key-Capacitive-I2C-Touch-Sensor-V3-MPR121-p-4694.html) by Seeed Studio 34 | 35 | #### Actuators 36 | 37 | - [Servo Kit 180° Brick-compatible](https://shop.m5stack.com/collections/m5-accessories/products/servo-kit-180) 38 | - [Vibration Motor Unit](https://shop.m5stack.com/products/vibration-motor-unit) 39 | 40 | ### Supported platforms 41 | 42 | :warning: **Not thoroughly tested yet.** 43 | 44 | - iOS/iPadOS - [STYLY](https://itunes.apple.com/jp/app/id1477168256?mt=8) app 45 | - Android - [STYLY](https://play.google.com/store/apps/details?id=com.psychicvrlab.stylymr) app 46 | - Oculus Quest 2 - [STYLY](https://www.oculus.com/experiences/quest/3982198145147898/) app (from App Lab) 47 | - Windows - [STYLY VR](https://store.steampowered.com/app/693990/STYLYVR_PLATFORM_FOR_ULTRA_EXPERIENCE/) app 48 | - Windows - Chrome 49 | - macOS - Chrome 50 | 51 | ### Supported combinations (maximum) 52 | 53 | The connected Unit(s) input is transmitted on three different channels: analog, joystick, and buttons. The analog and joystick channels can handle up to one sensor Unit input for each at once, and the buttons channel can handle up to six button inputs simultaneously. 54 | 55 | | Pattern \ Unit | Gesture | Joystick | Touch | RFID | Gas | Ranging | Dual Button | Analog In | Servo/Vibrator | 56 | | :------------- | :------ | :------- | :----- | :----- | :----- | :------ | :---------- | :-------- | :------------- | 57 | | A | :bulb: | | | | :bulb: | | | | :bulb: | 58 | | B | :bulb: | | | | | :bulb: | | | :bulb: | 59 | | C | :bulb: | | | | | | | :bulb: | | 60 | | D | | :bulb: | :bulb: | | :bulb: | | :bulb: | | | 61 | | E | | :bulb: | :bulb: | | | :bulb: | :bulb: | | | 62 | | F | | :bulb: | | :bulb: | :bulb: | | :bulb: | | | 63 | | G | | :bulb: | | :bulb: | | :bulb: | :bulb: | | | 64 | | H | | :bulb: | :bulb: | | :bulb: | | | | :bulb: | 65 | | I | | :bulb: | :bulb: | | | :bulb: | | | :bulb: | 66 | | J | | :bulb: | :bulb: | | | | | :bulb: | | 67 | | K | | :bulb: | | :bulb: | :bulb: | | | | :bulb: | 68 | | L | | :bulb: | | :bulb: | | :bulb: | | | :bulb: | 69 | | M | | :bulb: | | :bulb: | | | | :bulb: | | 70 | | `Port` | `A` | `A` | `A` | `A` | `A` | `A` | `B` | `B` | `B` | 71 | 72 | #### Notes 73 | 74 | - If you want to connect multiple Units to port A, please connect via a [1 to 3 HUB Expansion Unit](https://shop.m5stack.com/collections/m5-unit/products/mini-hub-module). 75 | - When a Ranging Sensor Unit is connected, you can't use a Joystick Unit nor Gas Sensor Unit. 76 | - To change the connection, make sure to turn off the power (i.e., M5Stack Fire: double-clicking the power button, M5Stack Core 2: pressing the power button for 6 seconds). You cannot turn it off while your controller is connected to a USB port. 77 | 78 | ## How to try 79 | 80 | ### Download 81 | 82 | 1. Download M5Burner v3.0 for your platform from [the official website](https://docs.m5stack.com/en/download) 83 | 2. Extract and launch the M5Burner (move to your Applications folder before launching on macOS) 84 | 3. Choose "I/O Framework for xR" from the projects 85 | 4. Click on the `Download` button of the project 86 | 5. Once finished downloading, the `Download` button becomes the `Burn` button 87 | 6. Click on the `Burn` button 88 | 7. Choose the serial port in the `COM` field and click on the `Start` button to burn the firmware 89 | 90 | ### Setup Wi-Fi 91 | 92 | 1. Install EspTouch for [iOS](https://apps.apple.com/app/espressif-esptouch/id1071176700) or [Android](https://github.com/EspressifApp/EsptouchForAndroid/releases/tag/v2.0.0/esptouch-v2.0.0.apk) (choose the `esptouch-v2.0.0.apk`) to your smartphone 93 | 2. Connect your smartphone to the Wi-Fi router 94 | 3. Open your EspTouch app and tap on the EspTouch item (not EspTouch V2) 95 | 4. Input the router’s password on the EspTouch app 96 | 5. Power on (or reboot) your M5Stack and press the `A` button within three seconds[^MAC] 97 | 6. Tap the `Confirm` button on the EspTouch app and wait for a while 98 | 7. You will see an IP address on the screen of the M5Stack 99 | 100 | [^MAC]: If you need to submit the MAC address to the administrator to connect to the network, please take a picture of the string on the startup screen below the version number and read it. 101 | 102 | ### Test 103 | 104 | 1. Choose a pattern from the table above and connect Unit(s) to your M5Stack controller (e.g., M5Stack FIRE) 105 | 2. Power on your M5Stack controller 106 | 3. If you want to use a Unit to be connected to Port B, please refer to the "How to setup" section and setup (Units to be connected to Port A will be recognized automatically) 107 | 4. Connect the controller as a Bluetooth device to your device (please follow standard instruction for the device) 108 | 5. Open the [IOFrameworkWidget (BLE and Wi-Fi)](https://gallery.styly.cc/scene/dd6b5c48-bb91-46e6-ab01-0f964d96de24) scene in a browser and bring the browser frontmost 109 | 6. Press the `Send` (`C`) button to start sending 110 | 7. Control the joystick, sensor, etc. 111 | 8. Once confirmed, press the `Stop` (`C`) button again to stop sending 112 | 113 | [![STYLY_marker](images/STYLY_marker.png)](https://gallery.styly.cc/scene/dd6b5c48-bb91-46e6-ab01-0f964d96de24) 114 | 115 | ### Setup 116 | 117 | #### PORT B 118 | 119 | 1. Press the `Setup` (`A`) button to enter the preferences screen 120 | 2. Press the `Next` (`C`) button (if needed) to choose the `PORT B: NONE` line 121 | 3. Press the `Go` (`B`) button 122 | 4. Press the `-` (`A`) or `+` (`C`) button to be matched to the device connected to the Port B (i.e., `DUAL BUTTON`, `ANALOG IN`[^ANALOG_IN], `SERVO` or `VIBRATOR`) 123 | 5. Press the `Done` (`B`) button 124 | 6. Press the `Exit` (`A`) button to back to the main screen 125 | 126 | [^ANALOG_IN]: If you want to connect Units to be connected to Port B and use `A.OUT` such as LIGHT, ANGLE etc., please choose this option. 127 | 128 | #### RFID Tags 129 | 130 | 1. Press the `Setup` (`A`) button to enter the preferences screen 131 | 2. Press the `Next` (`C`) button (if needed) to choose the `RFID 1: **:**:**:**` line 132 | 3. Press the `Go` (`B`) button 133 | 4. Press the `Reset` (`C`) button 134 | 5. Put an RFID Tag on the RFID Unit, then remove the Tag 135 | 6. Press the `Next` (`C`) button to choose the next line 136 | 7. Repeat from step 3 for 3 times to register the remaining 3 RFID Tags 137 | 8. Press the `Exit` (`A`) button to back to the main screen 138 | 139 | ### Troubleshooting 140 | 141 | - "IO Framework M5" is shown as connected but no input to the STYLY scene. → Please try to unpair the controller in the Bluetooth preference and pair it again. 142 | - Bluetooth connection status on my controller keeps switching between `Connected` and `Disconnected` when not connected. → The controller might have been paired with an old host (i.e., a PC or smartphone). If you no longer use the controller with the host, please remove the device from the host. 143 | 144 | ## I/O Framework SDK for Unity 145 | 146 | The SDK consists of components as follows. 147 | 148 | - `IOFrameworkManager` is a manager for the I/O Framework 149 | - `IOFrameworkTestUI` is a UI to test the framework 150 | - `IOFrameworkAnalogHandler` is a handler for events in the analog channel 151 | - `IOFrameworkJoystickHandler` is a handler for events in the joystick channel 152 | - `IOFrameworkButtonsHandler` is a handler for events in the buttons channel 153 | - `IOFrameworkGestureHandler` is a handler for events from a Gesture sensor (in both joystick and buttons channel) 154 | - `IOFrameworkOutputHandler` is a handler for events in the output channel via Wi-Fi 155 | 156 | ![IOFrameworkTestUI](images/IOFrameworkTestUI.png) 157 | IOFrameworkTestUI 158 | 159 | ![IOFrameworkAnalogHandler](images/IOFrameworkAnalogHandler.png) 160 | IOFrameworkAnalogHandler 161 | 162 | ![IOFrameworkJoystickHandler](images/IOFrameworkJoystickHandler.png) 163 | IOFrameworkJoystickHandler 164 | 165 | ![IOFrameworkButtonsHandler](images/IOFrameworkButtonsHandler.png) 166 | IOFrameworkButtonsHandler 167 | 168 | ![IOFrameworkGestureHandler](images/IOFrameworkGestureHandler.png) 169 | IOFrameworkGestureHandler 170 | 171 | ![IOFrameworkOutputHandler](images/IOFrameworkOutputHandler.png) 172 | IOFrameworkOutputHandler 173 | 174 | ### Dependencies 175 | 176 | - [ ] [PlayMaker](https://hutonggames.com/) 177 | - [ ] [STYLY Plugin for Unity](https://styly.cc/download/) 178 | 179 | ### Usage 180 | 181 | 1. Import the `IOFrameworkSDK.unitypackage` file to your Unity project 182 | 2. Instantiate an `IOFrameworkManager` 183 | 3. Instantiate an `IOFrameworkTestUI` as a Child of the `IOFrameworkManager` object if necessary 184 | 4. Instantiate a handler from handlers in the SDK (e.g., `IOFrameworkAnalogHandler`) as a Child of the `IOFrameworkManager` object 185 | 5. Unpack the handler 186 | 6. Navigate PlayMaker editor to the FSM of the handler and edit for your scene 187 | 188 | ![How to layout SDK components in Unity](images/how-to-layout-sdk-components-in-unity.png) 189 | How to layout the SDK components in Unity 190 | 191 | ### Input 192 | 193 | IOFrameworkManager broadcasts events to all Children of the IOFrameworkManager. 194 | 195 | - `ANALOG VALUE CHANGED` Int: analog value 196 | - `JOYSTICK VALUE CHANGED` String: joystick value 197 | - `BUTTON 1 DOWN` 198 | - `BUTTON 1 UP` 199 | - `BUTTON 2 DOWN` 200 | - `BUTTON 2 UP` 201 | - `BUTTON 3 DOWN` 202 | - `BUTTON 3 UP` 203 | - `BUTTON 4 DOWN` 204 | - `BUTTON 4 UP` 205 | - `BUTTON 5 DOWN` 206 | - `BUTTON 5 UP` 207 | - `BUTTON 6 DOWN` 208 | - `BUTTON 6 UP` 209 | 210 | ### Output 211 | 212 | Send events to `IOFrameworkManager: Event Handlers FSM`. 213 | 214 | - `SET OUTPUT VALUE REQUEST` String: output value 215 | 216 | ### Wi-Fi 217 | 218 | IOFrameworkManager broadcasts events to all FSMs. 219 | 220 | - `HTTP RESPONSE` String: HTTP response 221 | 222 | Send events to `IOFrameworkManager: Event Handlers FSM`. 223 | 224 | - `SET IP ADDRESS` String: IP address 225 | 226 | Send events to `IOFrameworkManager: HTTP Request Loop FSM`. 227 | 228 | - `START LISTENING` 229 | - `STOP LISTENING` 230 | - `LISTEN ONCE` 231 | 232 | ## Bluetooth keyboard protocol 233 | 234 | ```mermaid 235 | sequenceDiagram 236 | participant S as STYLY app 237 | participant M as M5Stack 238 | M-->>S: keyboard events over BLE 239 | ``` 240 | 241 | ![keyboard-layout](images/keyboard-layout.png) 242 | The keys used for the protocol 243 | 244 | - Keys in green: used in STYLY Web Player 245 | - Keys in yellow: used for the Analog channel 246 | - Keys in orange: used for the Joystick channel 247 | - Keys in red: used for the Buttons channel 248 | 249 | ### Analog channel 250 | 251 | | Analog value | Key | 252 | | :----------- | :------ | 253 | | 0 | `` ` `` | 254 | | 1 | `1` | 255 | | 2 | `2` | 256 | | 3 | `3` | 257 | | 4 | `4` | 258 | | 5 | `5` | 259 | | 6 | `6` | 260 | | 7 | `7` | 261 | | 8 | `8` | 262 | | 9 | `9` | 263 | | 10 | `0` | 264 | 265 | ### Joystick channel 266 | 267 | | Joystick | Key | 268 | | :--------- | :-- | 269 | | Left-Up | `y` | 270 | | Up | `u` | 271 | | Right-Up | `i` | 272 | | Left | `h` | 273 | | Center | `j` | 274 | | Right | `k` | 275 | | Left-Down | `n` | 276 | | Down | `m` | 277 | | Right-Down | `,` | 278 | 279 | ### Buttons channel 280 | 281 | | No. | Name | Key | Assigned input | 282 | | :-- | :---- | :-- | :----------------- | 283 | | 1 | Fire1 | `v` | Dual Button - Red | 284 | | 2 | Fire2 | `b` | Dual Button - Blue | 285 | | 3 | Fire3 | `f` | Touch Sensor - CH0 | 286 | | 4 | Jump | `g` | Touch Sensor - CH1 | 287 | | 5 | | `r` | Touch Sensor - CH2 | 288 | | 6 | | `t` | Touch Sensor - CH3 | 289 | 290 | ### Joystick and Buttons channel (for Gesture sensor only) 291 | 292 | | Joystick | Key | 293 | | :------- | :-- | 294 | | Up | `u` | 295 | | Left | `h` | 296 | | Right | `k` | 297 | | Down | `m` | 298 | 299 | | No. | Name | Key | Assigned input | 300 | | :-- | :---- | :-- | :---------------------- | 301 | | 1 | Fire1 | `v` | Gesture - Forward | 302 | | 2 | Fire2 | `b` | Gesture - Backward | 303 | | 3 | Fire3 | `f` | Gesture - Clockwise | 304 | | 4 | Jump | `g` | Gesture - AntiClockwise | 305 | | 5 | | `r` | Gesture - Wave | 306 | 307 | ## Wi-Fi protocol 308 | 309 | ```mermaid 310 | sequenceDiagram 311 | participant S as STYLY app 312 | participant M as M5Stack 313 | S-->>M: GET HTTP Requests over Wi-Fi 314 | M-->>S: HTTP Responses over Wi-Fi 315 | ``` 316 | 317 | ### Get input values 318 | 319 | `GET` `http://{ip_address}/input` 320 | 321 | `{analog value},{joystick value},{button 1 value},{button 2 value},{button 3 value},{button 4 value},{button 5 value},{button 6 value},` 322 | 323 | Example: 324 | 325 | `9,Left,0,1,0,0,0,0` 326 | 327 | ### Set output value 328 | 329 | `GET` `http://{ip_address}/output?val={value}` 330 | 331 | - `SERVO`: `{value}` is servo angle in degree, between 0 and 180 332 | - `VIBRATOR`: `{value}` is on duration in ms, between 0 and 100 333 | 334 | Example: 335 | 336 | `GET` `http://192.168.0.10/output?val=123` 337 | 338 | ![Control output without SDK: step 1](images/control-output-without-sdk.png) 339 | An example of controlling output without SDK in PlayMaker: build an URL (this part can be parameterized) and issue an HTTP request (you need to add states to handle errors properly) 340 | 341 | ## For firmware developers 342 | 343 | ### Preparing the development environment 344 | 345 | - English: [Arduino IDE environment - M5Core](https://docs.m5stack.com/en/quick_start/m5core/arduino) 346 | - Chinese (simplified): [Arduino IDE 环境搭建 - M5Core](https://docs.m5stack.com/zh_CN/quick_start/m5core/arduino) 347 | 348 | ### Libraries 349 | 350 | - [M5Unified](https://github.com/m5stack/M5Unified) v0.0.7 by M5Stack 351 | - [M5GFX](https://github.com/m5stack/M5GFX) v0.0.20 by M5Stack 352 | - [ESP32 BLE Keyboard library](https://github.com/T-vK/ESP32-BLE-Keyboard/) v0.3.0 by T-vK 353 | - [VL53L0X library for Arduino](https://github.com/pololu/vl53l0x-arduino) v1.3.1 by Pololu[^VL53L0X] 354 | - [Adafruit SGP30 Gas / Air Quality I2C sensor](https://github.com/adafruit/Adafruit_SGP30) v2.0.0 by Adafruit 355 | - [Adafruit MPR121 Library](https://github.com/adafruit/Adafruit_MPR121) v1.1.1 by Adafruit 356 | - [ESP32Servo](https://www.arduinolibraries.info/libraries/esp32-servo) v0.11.0 by Kevin Harrington and John K. Bennett 357 | - [ServoEasing](https://github.com/ArminJo/ServoEasing) v3.0.0 by Armin Joachimsmeyer 358 | - [DFRobot_PAJ7620](https://github.com/DFRobot/DFRobot_PAJ7620U2) v1.0.1 by DFRobot 359 | 360 | [^VL53L0X]: Make sure to install the one by Pololu, not by Adafruit. 361 | 362 | ### How to install 363 | 364 | #### The ESP32 BLE Keyboard library 365 | 366 | 1. Download the ZIP file at the [ESP32-BLE-Keyboard v0.3.0](https://github.com/T-vK/ESP32-BLE-Keyboard/releases/tag/0.3.0) page (you don’t have to extract it after downloading) 367 | 2. In the Arduino IDE, navigate to Sketch → Include Library → Add .ZIP Library... 368 | 3. Select the file you just downloaded 369 | 370 | #### Other libraries 371 | 372 | 1. In the Arduino IDE, navigate to Tools → Manage Libraries... 373 | 2. Type in a part of each library (e.g., `VL53L0X`, `Adafruit SGP30` etc.) in the text field in the top right corner, choose the right library and press the install button 374 | 3. Repeat the second step for all required libraries 375 | 376 | ## Credits 377 | 378 | - The included MFRC522 I2C Library is from the [RFID_RC522 example](https://github.com/m5stack/M5Stack/tree/master/examples/Unit/RFID_RC522) in the public domain, originally developed by [arozcan](https://github.com/arozcan/MFRC522-I2C-Library) based on the findings of the pioneers and modified by M5Stack. 379 | - The technique for detecting that an RFID tag has been removed was implemented by referring to [the example proposed by uluzox](https://github.com/miguelbalboa/rfid/issues/188#issuecomment-495395401) and modified for cooperative multitasking 380 | -------------------------------------------------------------------------------- /images/IOFrameworkAnalogHandler.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/IOFrameworkAnalogHandler.png -------------------------------------------------------------------------------- /images/IOFrameworkButtonsHandler.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/IOFrameworkButtonsHandler.png -------------------------------------------------------------------------------- /images/IOFrameworkGestureHandler.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/IOFrameworkGestureHandler.png -------------------------------------------------------------------------------- /images/IOFrameworkJoystickHandler.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/IOFrameworkJoystickHandler.png -------------------------------------------------------------------------------- /images/IOFrameworkOutputHandler.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/IOFrameworkOutputHandler.png -------------------------------------------------------------------------------- /images/IOFrameworkTestUI.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/IOFrameworkTestUI.png -------------------------------------------------------------------------------- /images/STYLY_marker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/STYLY_marker.png -------------------------------------------------------------------------------- /images/control-output-without-sdk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/control-output-without-sdk.png -------------------------------------------------------------------------------- /images/how-to-layout-sdk-components-in-unity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/how-to-layout-sdk-components-in-unity.png -------------------------------------------------------------------------------- /images/keyboard-layout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kotobuki/IO-Framework-for-xR/f62b575f191329c5533532c5d088c1d72dbb754b/images/keyboard-layout.png --------------------------------------------------------------------------------