Modulino Media Deck: Bluetooth® music remote for iPhone
An UNO R4 WiFi and six Modulino nodes become a no-app media controller that shows the song title and the volume level.
Devices & Components
1
Modulino™ Joystick
1
Modulino™ Vibro
1
Arduino Plug and Make Kit
Software & Tools
Arduino IDE
Project description
Code
Modulino Media Deck sketch
cpp
Sketch for the UNO R4 WiFi and six Modulino nodes.
1/* 2 Modulino Media Deck: Bluetooth music remote for iPhone 3 ------------------------------------------------------- 4 Board: Arduino UNO R4 WiFi. 5 Modulino nodes (Qwiic chain): Knob, Joystick, Buttons, Pixels, Vibro and Buzzer. 6 7 The board shows up on the iPhone as a Bluetooth LE HID device (the same 8 profile a keyboard or a headset with buttons uses) and sends it media keys: 9 play/pause, next, previous, volume and mute. 10 11 Controls 12 Knob turn = volume · press = play/pause 13 Joystick flick right/left = next/previous song 14 hold right/left = fast-forward/rewind inside the song 15 up/down = volume · press = mute 16 Buttons A = previous · B = play/pause · C = next 17 Pixels volume level of the iPhone (8 LEDs) and link state; 18 while music plays they bounce like a VU meter, never above the volume 19 Matrix title of the song, scrolling (the LED matrix of the board) 20 Vibro on volume changes, stronger the higher the volume; on song changes 21 Buzzer chime on connect, on disconnect and when there is no iPhone 22 23 The volume and the song title come from the iPhone itself, through its 24 "Apple Media Service" (AMS), which the board reads once the link is up. 25 26 Pairing: Settings > Bluetooth > "Control Modulino" > Pair. 27 Forgetting the stored iPhone: power the board with button B pressed 28 (and on the iPhone, "Forget This Device"). 29 30 ArduinoBLE has no HID profile and does not store pairing keys: the HID 31 service is built by hand here and the keys are kept in the EEPROM. 32*/ 33 34// ArduinoGraphics goes before the matrix so that the matrix can draw text 35#include <ArduinoGraphics.h> 36#include <Arduino_LED_Matrix.h> 37#include <ArduinoBLE.h> 38// Only to be able to restart the radio module if it does not start; WiFi is not used 39#include <WiFiS3.h> 40#include <utility/ATT.h> 41#include <local/BLELocalCharacteristic.h> 42#include <Arduino_Modulino.h> 43#include <EEPROM.h> 44 45// --------------------------------------------------------------------------- 46// Settings 47// --------------------------------------------------------------------------- 48 49const char DEVICE_NAME[] = "Control Modulino"; 50 51// Orientation of the joystick as mounted. This one is rotated a quarter turn: 52// what the node calls "y" is right/left here, and its "x" is up/down. 53// If a direction comes out reversed, change the sign of that axis. 54const bool SWAP_AXES = true; 55const int SIGN_X = 1; 56const int SIGN_Y = -1; 57 58// Tilt from which the joystick counts as an action, and the rest threshold 59const int JOY_ACTIVE = 80; 60const int JOY_RELEASED = 35; 61 62// How often the volume repeats while the joystick stays tilted 63const unsigned long VOLUME_REPEAT_MS = 220; 64 65// Time tilted to one side after which it is no longer "change song" but 66// fast-forward or rewind inside it 67const unsigned long HOLD_MS = 450; 68 69// A knob step against the previous one, sooner than this, is contact bounce 70const unsigned long KNOB_BOUNCE_MS = 150; 71 72// After a volume change the LEDs show the level still for this long, and 73// then go back to bouncing if music is playing 74const unsigned long LEVEL_STILL_MS = 1500; 75 76// How often the song title advances one dot on the matrix 77const unsigned long TITLE_STEP_MS = 75; 78 79// --------------------------------------------------------------------------- 80// Types (kept at the top: Arduino declares the functions before reading the rest) 81// --------------------------------------------------------------------------- 82 83enum LinkState { SEARCHING, PAIRING, READY }; 84 85struct Note { uint16_t frequency; uint16_t duration; }; 86 87struct Pixel { uint8_t r, g, b, brightness; }; 88 89// --------------------------------------------------------------------------- 90// Media keys (HID "Consumer" usage page) 91// --------------------------------------------------------------------------- 92 93enum Action { PLAY, NEXT, PREVIOUS, VOL_UP, VOL_DOWN, MUTE, ACTION_COUNT }; 94 95const uint16_t KEYS[ACTION_COUNT] = { 0x00CD, 0x00B5, 0x00B6, 0x00E9, 0x00EA, 0x00E2 }; 96 97const char* const ACTION_NAMES[ACTION_COUNT] = { 98 "play/pause", "next", "previous", "volume +", "volume -", "mute" 99}; 100 101// These two stay pressed for as long as the joystick is tilted 102const uint16_t KEY_FAST_FORWARD = 0x00B3; 103const uint16_t KEY_REWIND = 0x00B4; 104 105// HID descriptor: a single 16-bit report (ID 1) holding the pressed key 106const uint8_t HID_REPORT_MAP[] = { 107 // Usage page: Consumer 108 0x05, 0x0C, 109 // Usage: Consumer Control 110 0x09, 0x01, 111 // Collection: application 112 0xA1, 0x01, 113 // Report ID: 1 114 0x85, 0x01, 115 // Logical minimum: 0 116 0x15, 0x00, 117 // Logical maximum: 0x03FF 118 0x26, 0xFF, 0x03, 119 // Usage minimum: 0 120 0x19, 0x00, 121 // Usage maximum: 0x03FF 122 0x2A, 0xFF, 0x03, 123 // Size: 16 bits 124 0x75, 0x10, 125 // Count: 1 126 0x95, 0x01, 127 // Input: data, array, absolute 128 0x81, 0x00, 129 // End of collection 130 0xC0 131}; 132 133// HID 1.11, no country code, normally connectable 134const uint8_t HID_INFO[] = { 0x11, 0x01, 0x00, 0x02 }; 135 136// Report 1, input 137const uint8_t REPORT_REFERENCE[] = { 0x01, 0x01 }; 138 139// Vendor ID source USB (0x02), Arduino (0x2341), UNO R4 WiFi (0x1002), version 1.0 140const uint8_t PNP_ID[] = { 0x02, 0x41, 0x23, 0x02, 0x10, 0x00, 0x01 }; 141 142// --------------------------------------------------------------------------- 143// Bluetooth services 144// --------------------------------------------------------------------------- 145 146BLEService hidService("1812"); 147BLECharacteristic hidInfo("2A4A", BLERead, sizeof(HID_INFO), true); 148BLECharacteristic hidReportMap("2A4B", BLERead | BLEEncryption, sizeof(HID_REPORT_MAP), true); 149BLECharacteristic hidControlPoint("2A4C", BLEWriteWithoutResponse, 1, true); 150BLECharacteristic hidProtocolMode("2A4E", BLERead | BLEWriteWithoutResponse, 1, true); 151BLECharacteristic hidReport("2A4D", BLERead | BLENotify | BLEEncryption, 2, true); 152BLEDescriptor reportReference("2908", REPORT_REFERENCE, sizeof(REPORT_REFERENCE)); 153 154BLEService infoService("180A"); 155BLECharacteristic manufacturer("2A29", BLERead, "Arduino"); 156BLECharacteristic modelNumber("2A24", BLERead, "UNO R4 WiFi"); 157BLECharacteristic pnpId("2A50", BLERead, sizeof(PNP_ID), true); 158 159BLEService batteryService("180F"); 160BLEUnsignedCharCharacteristic batteryLevel("2A19", BLERead | BLENotify); 161 162// ArduinoBLE does not expose the value handle of a characteristic; these two 163// structs only open those protected methods so the sketch can notify directly. 164struct OpenCharacteristic : BLECharacteristic { using BLECharacteristic::local; }; 165struct OpenLocal : BLELocalCharacteristic { using BLELocalCharacteristic::valueHandle; }; 166 167uint16_t reportHandle = 0; 168 169// --------------------------------------------------------------------------- 170// Stored bond (a single iPhone) 171// --------------------------------------------------------------------------- 172 173const uint32_t BOND_MAGIC = 0x434D4431; 174 175struct Bond { 176 uint32_t magic; 177 uint8_t hasIRK; 178 uint8_t hasLTK; 179 uint8_t address[6]; 180 uint8_t irk[16]; 181 uint8_t ltk[16]; 182}; 183 184Bond bond; 185bool savePending = false; 186unsigned long saveSince = 0; 187 188void loadBond() { 189 EEPROM.get(0, bond); 190 if (bond.magic != BOND_MAGIC) { 191 memset(&bond, 0, sizeof(bond)); 192 } 193} 194 195void eraseBond() { 196 memset(&bond, 0, sizeof(bond)); 197 EEPROM.put(0, bond); 198} 199 200// The library hands over the identity of the iPhone when pairing ends 201int onStoreIRK(uint8_t* address, uint8_t* irk) { 202 memcpy(bond.address, address, 6); 203 memcpy(bond.irk, irk, 16); 204 bond.hasIRK = 1; 205 bond.hasLTK = 0; 206 return 1; 207} 208 209// ...and right after, the key the link is encrypted with 210int onStoreLTK(uint8_t* address, uint8_t* ltk) { 211 memcpy(bond.address, address, 6); 212 memcpy(bond.ltk, ltk, 16); 213 bond.hasLTK = 1; 214 // The EEPROM is written later, from loop(), so pairing is not slowed down 215 savePending = true; 216 saveSince = millis(); 217 Serial.println("Bond: the keys of the iPhone arrived"); 218 return 1; 219} 220 221// On reconnection the library asks for the key of the phone it recognized 222int onGetLTK(uint8_t* address, uint8_t* ltk) { 223 if (!bond.hasLTK) { 224 Serial.println("Bond: a key was requested and none is stored"); 225 return 0; 226 } 227 if (memcmp(address, bond.address, 6) != 0) { 228 Serial.println("Bond: the address does not match; trying the stored key"); 229 } 230 memcpy(ltk, bond.ltk, 16); 231 return 1; 232} 233 234// The iPhone changes its address every so often; with this identity the 235// library knows it is the same phone. Memory is allocated the way the library frees it. 236int onGetIRKs(uint8_t* count, uint8_t** types, uint8_t*** addresses, uint8_t*** irks) { 237 uint8_t n = bond.hasIRK ? 1 : 0; 238 *count = n; 239 *addresses = new uint8_t*[n]; 240 *irks = new uint8_t*[n]; 241 *types = new uint8_t[n]; 242 if (n == 1) { 243 (*types)[0] = 0; 244 (*addresses)[0] = new uint8_t[6]; 245 (*irks)[0] = new uint8_t[16]; 246 memcpy((*addresses)[0], bond.address, 6); 247 memcpy((*irks)[0], bond.irk, 16); 248 } 249 return 1; 250} 251 252// --------------------------------------------------------------------------- 253// What the iPhone reports: volume, song and player state (AMS) 254// --------------------------------------------------------------------------- 255 256const char AMS_SERVICE_UUID[] = "89d3502b-0f36-433a-8ef4-c502ad55f8dc"; 257const char AMS_ENTITY_UPDATE_UUID[] = "2f7cabce-808d-411f-9a0c-bb92ba96c102"; 258 259// AMS entities and attributes the sketch asks for 260const uint8_t AMS_PLAYER = 0; 261const uint8_t AMS_TRACK = 2; 262const uint8_t AMS_PLAYER_PLAYBACK_INFO = 1; 263const uint8_t AMS_PLAYER_VOLUME = 2; 264const uint8_t AMS_TRACK_TITLE = 2; 265 266// Volume of the iPhone from 0 to 1; negative while unknown 267float volume = -1; 268// Last time the volume changed or a change was requested 269unsigned long volumeMovedAt = 0; 270// Song title already converted to plain letters, which is what the matrix draws 271char title[100] = ""; 272bool titleChanged = false; 273// 0 paused, 1 playing, 2 rewinding, 3 fast-forwarding; -1 unknown 274int playerState = -1; 275 276bool amsReady = false; 277uint8_t amsAttempts = 0; 278unsigned long amsNextTry = 0; 279 280// The matrix font only has unaccented letters: "canción" becomes "cancion" 281void toPlainLetters(const uint8_t* source, int length, char* target, int capacity) { 282 // Letters from U+00C0 to U+00FF without their accent 283 static const char LATIN[] = "AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTsaaaaaaaceeeeiiiidnooooo/ouuuuyty"; 284 int n = 0; 285 int i = 0; 286 while (i < length && n < capacity - 1) { 287 uint8_t c = source[i]; 288 if (c < 0x80) { 289 if (c >= 0x20) target[n++] = (char)c; 290 i += 1; 291 } else if (c == 0xC3 && i + 1 < length) { 292 uint8_t d = source[i + 1]; 293 if (d >= 0x80 && d <= 0xBF) target[n++] = LATIN[d - 0x80]; 294 i += 2; 295 } else if (c == 0xC2 && i + 1 < length) { 296 // Spanish opening question and exclamation marks 297 if (source[i + 1] == 0xBF) target[n++] = '?'; 298 if (source[i + 1] == 0xA1) target[n++] = '!'; 299 i += 2; 300 } else if (c == 0xE2 && i + 2 < length && source[i + 1] == 0x80) { 301 // Typographic quotes and dashes 302 uint8_t d = source[i + 2]; 303 if (d == 0x98 || d == 0x99) target[n++] = '\''; 304 if (d == 0x9C || d == 0x9D) target[n++] = '"'; 305 if (d == 0x93 || d == 0x94) target[n++] = '-'; 306 i += 3; 307 } else if (c >= 0xF0) { 308 i += 4; 309 } else if (c >= 0xE0) { 310 i += 3; 311 } else { 312 i += 2; 313 } 314 } 315 target[n] = '\0'; 316} 317 318// Every AMS notification carries: entity, attribute, flags and the value as text 319void onAmsUpdate(BLEDevice phone, BLECharacteristic characteristic) { 320 int length = characteristic.valueLength(); 321 const uint8_t* data = characteristic.value(); 322 if (length < 3 || data == nullptr) { 323 return; 324 } 325 char text[24]; 326 int n = min(length - 3, (int)sizeof(text) - 1); 327 memcpy(text, data + 3, n); 328 text[n] = '\0'; 329 330 if (data[0] == AMS_PLAYER && data[1] == AMS_PLAYER_VOLUME) { 331 float reading = constrain(atof(text), 0.0, 1.0); 332 if (reading != volume) { 333 volumeMovedAt = millis(); 334 } 335 volume = reading; 336 Serial.print("iPhone: volume "); 337 Serial.print((int)(volume * 100 + 0.5)); 338 Serial.println(" %"); 339 } else if (data[0] == AMS_PLAYER && data[1] == AMS_PLAYER_PLAYBACK_INFO) { 340 const char* const STATES[] = { "paused", "playing", "rewinding", "fast-forwarding" }; 341 int state = (n > 0 && text[0] >= '0' && text[0] <= '3') ? text[0] - '0' : -1; 342 if (state >= 0) { 343 // The full text is "state,rate,elapsed seconds": it shows whether a seek is moving 344 Serial.print("iPhone: "); 345 Serial.print(STATES[state]); 346 Serial.print(" ("); 347 Serial.print(text); 348 Serial.println(")"); 349 } 350 playerState = state; 351 } else if (data[0] == AMS_TRACK && data[1] == AMS_TRACK_TITLE) { 352 char plain[sizeof(title)]; 353 toPlainLetters(data + 3, length - 3, plain, sizeof(plain)); 354 if (strcmp(plain, title) != 0) { 355 strcpy(title, plain); 356 titleChanged = true; 357 Serial.print("iPhone: song \""); 358 Serial.print(title); 359 Serial.println("\""); 360 } 361 } 362} 363 364// Finds the AMS service inside the iPhone and subscribes to it. It takes a couple 365// of seconds during which the controls do not respond; done once per connection. 366bool connectAms() { 367 BLEDevice phone = BLE.central(); 368 if (!phone || !phone.discoverService(AMS_SERVICE_UUID)) { 369 return false; 370 } 371 BLECharacteristic entityUpdate = phone.characteristic(AMS_ENTITY_UPDATE_UUID); 372 if (!entityUpdate) { 373 return false; 374 } 375 entityUpdate.setEventHandler(BLEUpdated, onAmsUpdate); 376 if (!entityUpdate.subscribe()) { 377 return false; 378 } 379 const uint8_t ASK_PLAYER[] = { AMS_PLAYER, AMS_PLAYER_PLAYBACK_INFO, AMS_PLAYER_VOLUME }; 380 const uint8_t ASK_TRACK[] = { AMS_TRACK, AMS_TRACK_TITLE }; 381 bool a = entityUpdate.writeValue(ASK_PLAYER, sizeof(ASK_PLAYER)); 382 bool b = entityUpdate.writeValue(ASK_TRACK, sizeof(ASK_TRACK)); 383 return a && b; 384} 385 386void resetAms() { 387 amsReady = false; 388 amsAttempts = 0; 389 volume = -1; 390 playerState = -1; 391 title[0] = '\0'; 392 titleChanged = true; 393} 394 395// --------------------------------------------------------------------------- 396// LED matrix of the board: the song title, scrolling 397// --------------------------------------------------------------------------- 398 399ArduinoLEDMatrix matrix; 400 401const int MATRIX_WIDTH = 12; 402const int LETTER_WIDTH = 5; 403 404void serviceMatrix() { 405 static unsigned long last = 0; 406 static int x = MATRIX_WIDTH; 407 static bool blank = false; 408 409 if (millis() - last < TITLE_STEP_MS) { 410 return; 411 } 412 last = millis(); 413 if (titleChanged) { 414 // A new song starts entering from the right 415 titleChanged = false; 416 x = MATRIX_WIDTH; 417 blank = false; 418 } 419 int length = strlen(title); 420 if (length == 0) { 421 if (!blank) { 422 matrix.beginDraw(); 423 matrix.clear(); 424 matrix.endDraw(); 425 blank = true; 426 } 427 return; 428 } 429 // Only the letters that fall inside the matrix are drawn 430 int first = x < 0 ? (-x) / LETTER_WIDTH : 0; 431 char visible[5]; 432 int n = 0; 433 while (n < 4 && first + n < length) { 434 visible[n] = title[first + n]; 435 n++; 436 } 437 visible[n] = '\0'; 438 matrix.beginDraw(); 439 matrix.clear(); 440 matrix.stroke(0xFFFFFF); 441 matrix.textFont(Font_5x7); 442 matrix.text(visible, x + first * LETTER_WIDTH, 1); 443 matrix.endDraw(); 444 445 x--; 446 if (x < -length * LETTER_WIDTH) { 447 x = MATRIX_WIDTH; 448 } 449} 450 451// --------------------------------------------------------------------------- 452// Modulino nodes 453// --------------------------------------------------------------------------- 454 455ModulinoKnob knob; 456ModulinoJoystick joystick; 457ModulinoButtons buttons; 458ModulinoPixels pixels; 459ModulinoVibro vibro; 460ModulinoBuzzer buzzer; 461 462bool hasKnob, hasJoystick, hasButtons, hasPixels, hasVibro, hasBuzzer; 463 464// --------------------------------------------------------------------------- 465// Link state 466// --------------------------------------------------------------------------- 467 468LinkState linkState = SEARCHING; 469 470// --------------------------------------------------------------------------- 471// Sound: short melodies that do not stop the program 472// --------------------------------------------------------------------------- 473 474const Note MELODY_CONNECTED[] = { { 880, 90 }, { 1319, 140 } }; 475const Note MELODY_DISCONNECTED[] = { { 880, 90 }, { 587, 160 } }; 476const Note MELODY_NO_IPHONE[] = { { 220, 120 } }; 477const Note MELODY_FORGOTTEN[] = { { 660, 90 }, { 440, 90 }, { 330, 180 } }; 478 479const Note* melody = nullptr; 480uint8_t notesLeft = 0; 481unsigned long nextNoteAt = 0; 482 483void playMelody(const Note* notes, uint8_t count) { 484 melody = notes; 485 notesLeft = count; 486 nextNoteAt = millis(); 487} 488 489void serviceMelody() { 490 if (notesLeft == 0 || (long)(millis() - nextNoteAt) < 0) { 491 return; 492 } 493 if (hasBuzzer) { 494 buzzer.tone(melody->frequency, melody->duration); 495 } 496 nextNoteAt = millis() + melody->duration + 15; 497 melody++; 498 notesLeft--; 499} 500 501// --------------------------------------------------------------------------- 502// LEDs: background state and a flash per action 503// --------------------------------------------------------------------------- 504 505const uint8_t LED_COUNT = 8; 506const unsigned long FLASH_MS = 360; 507const int FLASH_NO_IPHONE = ACTION_COUNT; 508 509Pixel frame[LED_COUNT]; 510Pixel frameShown[LED_COUNT]; 511int flash = -1; 512unsigned long flashSince = 0; 513 514// Key the joystick is holding down (0 = none) 515uint16_t heldKey = 0; 516bool heldKeySent = false; 517 518void setPixel(uint8_t i, uint8_t r, uint8_t g, uint8_t b, uint8_t brightness) { 519 if (i < LED_COUNT) { 520 frame[i] = { r, g, b, brightness }; 521 } 522} 523 524void startFlash(int which) { 525 flash = which; 526 flashSince = millis(); 527} 528 529void drawFlash(unsigned long elapsed) { 530 // Dot that runs along the strip: used for next and previous 531 uint8_t step = min((unsigned long)(LED_COUNT - 1), elapsed / 40); 532 switch (flash) { 533 case PLAY: 534 for (uint8_t i = 0; i < LED_COUNT; i++) setPixel(i, 0, 255, 0, 12); 535 break; 536 case NEXT: 537 setPixel(step, 160, 0, 255, 20); 538 if (step > 0) setPixel(step - 1, 160, 0, 255, 5); 539 break; 540 case PREVIOUS: 541 setPixel(LED_COUNT - 1 - step, 160, 0, 255, 20); 542 if (step > 0) setPixel(LED_COUNT - step, 160, 0, 255, 5); 543 break; 544 case VOL_UP: 545 for (uint8_t i = 4; i < LED_COUNT; i++) setPixel(i, 0, 200, 255, 12); 546 break; 547 case VOL_DOWN: 548 for (uint8_t i = 0; i < 4; i++) setPixel(i, 0, 200, 255, 12); 549 break; 550 case MUTE: 551 for (uint8_t i = 0; i < LED_COUNT; i++) setPixel(i, 255, 255, 255, 8); 552 break; 553 default: 554 for (uint8_t i = 0; i < LED_COUNT; i++) setPixel(i, 255, 0, 0, 12); 555 break; 556 } 557} 558 559// LED dance while music plays. It is a simulated VU meter: the board cannot 560// hear the audio, so the jumps are random with a beat every half second. 561// It never goes above the volume level, and the LED that marks that level 562// stays dimly lit so the volume can still be read. 563void drawDance(int steps) { 564 static float height = 0; 565 static unsigned long nextJump = 0; 566 static unsigned long nextBeat = 0; 567 unsigned long now = millis(); 568 // LEDs covered by the volume, from 1 to 8 569 int top = (steps + 1) / 2; 570 571 if ((long)(now - nextBeat) >= 0) { 572 nextBeat = now + 500; 573 height = top; 574 } else if ((long)(now - nextJump) >= 0) { 575 nextJump = now + random(90, 170); 576 float jump = top * random(25, 80) / 100.0; 577 if (jump > height) height = jump; 578 } 579 if (height > top) height = top; 580 581 for (int i = 0; i < top; i++) { 582 // How much of this LED is inside the bar: 1 all of it, 0 none 583 float inside = constrain(height - i, 0.0, 1.0); 584 if (i == 0 && inside < 0.3) inside = 0.3; 585 if (inside > 0) { 586 uint8_t brightness = 2 + (uint8_t)(inside * 12); 587 if (i <= 2) { 588 setPixel(i, 0, 255, 0, brightness); 589 } else if (i <= 5) { 590 setPixel(i, 0, 200, 255, brightness); 591 } else { 592 setPixel(i, 160, 0, 255, brightness); 593 } 594 } else if (i == top - 1) { 595 setPixel(i, 0, 255, 0, 2); 596 } 597 } 598 // The bar falls on its own between jumps 599 height -= 0.12 + top * 0.05; 600 if (height < 0) height = 0; 601} 602 603void drawBackground() { 604 unsigned long now = millis(); 605 if (linkState == SEARCHING) { 606 // Blue dot going back and forth: waiting for the iPhone 607 uint8_t phase = (now / 130) % (2 * (LED_COUNT - 1)); 608 uint8_t position = phase < LED_COUNT ? phase : 2 * (LED_COUNT - 1) - phase; 609 setPixel(position, 0, 0, 255, 12); 610 } else if (linkState == PAIRING) { 611 // Alternating halves: connected, waiting for "Pair" to be accepted 612 bool even = (now / 300) % 2 == 0; 613 for (uint8_t i = 0; i < LED_COUNT; i++) { 614 if ((i % 2 == 0) == even) setPixel(i, 255, 180, 0, 10); 615 } 616 } else if (heldKey != 0) { 617 // Dot that keeps running towards where the song is moving 618 uint8_t step = (now / 60) % LED_COUNT; 619 setPixel(heldKey == KEY_FAST_FORWARD ? step : LED_COUNT - 1 - step, 160, 0, 255, 20); 620 } else if (volume < 0) { 621 // Two dim green dots in the middle: ready, volume not read yet 622 setPixel(3, 0, 255, 0, 4); 623 setPixel(4, 0, 255, 0, 4); 624 } else { 625 // Volume level: the iPhone has 16 steps and there are 8 LEDs here, so 626 // each LED is worth two steps (half = dim, full = bright) 627 int steps = (int)(volume * 16 + 0.5); 628 if (playerState == 1 && steps > 0 && now - volumeMovedAt > LEVEL_STILL_MS) { 629 drawDance(steps); 630 return; 631 } 632 for (uint8_t i = 0; i < LED_COUNT; i++) { 633 if (steps >= 2 * (i + 1)) { 634 setPixel(i, 0, 255, 0, 12); 635 } else if (steps == 2 * i + 1) { 636 setPixel(i, 0, 255, 0, 2); 637 } 638 } 639 } 640} 641 642// LEDs of the three buttons: off without an iPhone, on while paused and, 643// with music, a single one that runs through A, B and C 644void serviceButtonLeds() { 645 static uint8_t shown = 0xFF; 646 if (!hasButtons) { 647 return; 648 } 649 uint8_t wanted = 0; 650 if (linkState == READY) { 651 wanted = playerState == 1 ? (1 << ((millis() / 250) % 3)) : 7; 652 } 653 if (wanted == shown) { 654 return; 655 } 656 shown = wanted; 657 buttons.setLeds(wanted & 1, wanted & 2, wanted & 4); 658} 659 660void servicePixels() { 661 static unsigned long last = 0; 662 if (!hasPixels || millis() - last < 40) { 663 return; 664 } 665 last = millis(); 666 memset(frame, 0, sizeof(frame)); 667 if (flash >= 0 && millis() - flashSince < FLASH_MS) { 668 drawFlash(millis() - flashSince); 669 } else { 670 flash = -1; 671 drawBackground(); 672 } 673 // I2C is only written when the drawing changed 674 if (memcmp(frame, frameShown, sizeof(frame)) == 0) { 675 return; 676 } 677 memcpy(frameShown, frame, sizeof(frame)); 678 for (uint8_t i = 0; i < LED_COUNT; i++) { 679 pixels.set(i, frame[i].r, frame[i].g, frame[i].b, frame[i].brightness); 680 } 681 pixels.show(); 682} 683 684// --------------------------------------------------------------------------- 685// Sending keys 686// --------------------------------------------------------------------------- 687 688const uint8_t QUEUE_MAX = 16; 689const unsigned long KEY_STEP_MS = 15; 690 691uint16_t keyQueue[QUEUE_MAX]; 692uint8_t queueStart = 0; 693uint8_t queueCount = 0; 694bool keyDown = false; 695unsigned long nextStepAt = 0; 696 697void sendReport(uint16_t usage) { 698 uint8_t bytes[2] = { lowByte(usage), highByte(usage) }; 699 hidReport.writeValue(bytes, sizeof(bytes)); 700 // On reconnection the iPhone takes for granted the subscription it made when 701 // pairing, and the library forgets it: in that case the sketch notifies directly. 702 if (!hidReport.subscribed()) { 703 ATT.handleNotify(reportHandle, bytes, sizeof(bytes)); 704 } 705} 706 707void serviceQueue() { 708 if ((long)(millis() - nextStepAt) < 0) { 709 return; 710 } 711 if (keyDown) { 712 // Every key is released before the next one is sent 713 sendReport(0); 714 keyDown = false; 715 nextStepAt = millis() + KEY_STEP_MS; 716 return; 717 } 718 if (heldKey != 0) { 719 // While seeking, the key stays down and the keyQueue waits 720 if (!heldKeySent) { 721 sendReport(heldKey); 722 heldKeySent = true; 723 } 724 return; 725 } 726 if (queueCount == 0) { 727 return; 728 } 729 sendReport(keyQueue[queueStart]); 730 queueStart = (queueStart + 1) % QUEUE_MAX; 731 queueCount--; 732 keyDown = true; 733 nextStepAt = millis() + KEY_STEP_MS; 734} 735 736void doAction(Action action) { 737 if (linkState != READY) { 738 Serial.print("No iPhone: not sent: "); 739 Serial.println(ACTION_NAMES[action]); 740 startFlash(FLASH_NO_IPHONE); 741 playMelody(MELODY_NO_IPHONE, 1); 742 return; 743 } 744 if (queueCount >= QUEUE_MAX) { 745 return; 746 } 747 keyQueue[(queueStart + queueCount) % QUEUE_MAX] = KEYS[action]; 748 queueCount++; 749 bool isVolume = action == VOL_UP || action == VOL_DOWN; 750 bool isSongChange = action == NEXT || action == PREVIOUS; 751 if (isVolume) { 752 volumeMovedAt = millis(); 753 } 754 // With the level on screen, volume needs no flash: you can see it rise 755 if (!isVolume || volume < 0) { 756 startFlash(action); 757 } 758 if (hasVibro) { 759 if (isVolume) { 760 // The higher the volume, the stronger and longer the pulse. It starts from a 761 // floor that can already be felt: under 40 ms the motor barely spins up. 762 float level = volume < 0 ? 0.5 : volume + (action == VOL_UP ? 0.0625 : -0.0625); 763 level = constrain(level, 0.0, 1.0); 764 vibro.on(45 + (int)(level * 75), false, 38 + (int)(level * 12)); 765 } else if (isSongChange) { 766 vibro.on(150, MAXIMUM); 767 } else { 768 vibro.on(70, POWERFUL); 769 } 770 } 771 Serial.print("Action: "); 772 Serial.println(ACTION_NAMES[action]); 773} 774 775// Leaves a key pressed until releaseKey() is called 776void holdKey(uint16_t key) { 777 if (linkState != READY) { 778 startFlash(FLASH_NO_IPHONE); 779 playMelody(MELODY_NO_IPHONE, 1); 780 return; 781 } 782 heldKey = key; 783 heldKeySent = false; 784 if (hasVibro) vibro.on(60, INTENSE); 785 Serial.println(key == KEY_FAST_FORWARD ? "Action: fast-forward (held)" : "Action: rewind (held)"); 786} 787 788void releaseKey() { 789 if (heldKey == 0) { 790 return; 791 } 792 // If the key did go out, the next keyQueue step sends the release 793 if (heldKeySent) { 794 keyDown = true; 795 nextStepAt = millis(); 796 } 797 heldKey = 0; 798 heldKeySent = false; 799 Serial.println("Action: release"); 800} 801 802// --------------------------------------------------------------------------- 803// Reading the controls 804// --------------------------------------------------------------------------- 805 806// Counters of what was discarded while reading the knob; printed with "?" 807unsigned long knobFailedReads = 0; 808unsigned long knobJumps = 0; 809unsigned long knobBounces = 0; 810 811void readKnob() { 812 static int16_t lastPosition = 0; 813 static int16_t lastRaw = 0; 814 static bool firstRead = true; 815 static bool pressed = false; 816 static int lastDirection = 0; 817 static unsigned long lastTurnAt = 0; 818 static unsigned long lastClickAt = 0; 819 820 // The node is read directly. With the library's get() a failed read comes 821 // back as position 0, which turned into several "volume -" followed by the 822 // same number of "volume +": the volume went down and up on its own. 823 uint8_t data[3]; 824 if (!knob.read(data, 3)) { 825 knobFailedReads++; 826 return; 827 } 828 int16_t position = (int16_t)(data[0] | (data[1] << 8)); 829 bool pressedNow = data[2] != 0; 830 if (firstRead) { 831 lastPosition = position; 832 lastRaw = position; 833 firstRead = false; 834 } 835 // A reading counts if it is close to the previous one; a lone distant one is noise 836 int16_t distance = position - lastRaw; 837 lastRaw = position; 838 if (distance > 3 || distance < -3) { 839 knobJumps++; 840 return; 841 } 842 int16_t turn = position - lastPosition; 843 lastPosition = position; 844 if (turn > 12 || turn < -12) { 845 knobJumps++; 846 turn = 0; 847 } 848 if (turn != 0) { 849 int direction = turn > 0 ? 1 : -1; 850 if (direction != lastDirection && millis() - lastTurnAt < KNOB_BOUNCE_MS) { 851 // A hand does not change direction that fast: it is the encoder bouncing 852 knobBounces++; 853 turn = 0; 854 } else { 855 lastDirection = direction; 856 lastTurnAt = millis(); 857 } 858 } 859 while (turn > 0) { 860 doAction(VOL_UP); 861 turn--; 862 } 863 while (turn < 0) { 864 doAction(VOL_DOWN); 865 turn++; 866 } 867 if (pressedNow && !pressed && millis() - lastClickAt > 250) { 868 lastClickAt = millis(); 869 doAction(PLAY); 870 } 871 pressed = pressedNow; 872} 873 874int zone(int value, int previous) { 875 if (value > JOY_ACTIVE) return 1; 876 if (value < -JOY_ACTIVE) return -1; 877 if (abs(value) < JOY_RELEASED) return 0; 878 return previous; 879} 880 881// Last joystick reading, from -127 to 128 per axis; printed with "?" 882int joystickX = 0; 883int joystickY = 0; 884bool joystickButton = false; 885unsigned long joystickFailedReads = 0; 886 887void readJoystick() { 888 static uint8_t failuresInARow = 0; 889 static int zoneX = 0; 890 static int zoneY = 0; 891 static bool pressed = false; 892 static bool holding = false; 893 static unsigned long sinceX = 0; 894 static unsigned long lastVolumeAt = 0; 895 static unsigned long lastClickAt = 0; 896 897 // The node is read directly. The library's getX() and getY() return int8_t, 898 // and at full deflection the value 128 becomes -128: with the stick pushed all 899 // the way up it read "volume -", and the volume went up and down on its own. 900 uint8_t data[3]; 901 if (joystick.read(data, 3)) { 902 failuresInARow = 0; 903 joystickX = 128 - (int)data[0]; 904 joystickY = 128 - (int)data[1]; 905 joystickButton = data[2] != 0; 906 } else { 907 joystickFailedReads++; 908 // Without readings it cannot stay "tilted": everything is released 909 if (++failuresInARow >= 5) { 910 failuresInARow = 5; 911 joystickX = 0; 912 joystickY = 0; 913 joystickButton = false; 914 } 915 } 916 int x = (SWAP_AXES ? joystickY : joystickX) * SIGN_X; 917 int y = (SWAP_AXES ? joystickX : joystickY) * SIGN_Y; 918 // The most tilted axis wins, so a diagonal does not send two actions 919 if (abs(x) >= abs(y)) { 920 y = 0; 921 } else { 922 x = 0; 923 } 924 int newX = zone(x, zoneX); 925 int newY = zone(y, zoneY); 926 927 if ((newX != zoneX && newX != 0) || (newY != zoneY && newY != 0)) { 928 Serial.print("Joystick node: x "); 929 Serial.print(joystickX); 930 Serial.print(" | y "); 931 Serial.println(joystickY); 932 } 933 934 // X axis: short flick = change song; hold = fast-forward or rewind. 935 // That is why the action goes out on release, once it is known which it was. 936 if (newX != zoneX) { 937 if (zoneX != 0) { 938 if (holding) { 939 releaseKey(); 940 } else { 941 doAction(zoneX > 0 ? NEXT : PREVIOUS); 942 } 943 } 944 holding = false; 945 sinceX = millis(); 946 } else if (newX != 0 && !holding && millis() - sinceX >= HOLD_MS) { 947 holding = true; 948 holdKey(newX > 0 ? KEY_FAST_FORWARD : KEY_REWIND); 949 } 950 951 // Y axis: volume, repeating while it stays tilted 952 if (newY != 0 && (newY != zoneY || millis() - lastVolumeAt > VOLUME_REPEAT_MS)) { 953 lastVolumeAt = millis(); 954 doAction(newY > 0 ? VOL_UP : VOL_DOWN); 955 } 956 zoneX = newX; 957 zoneY = newY; 958 959 bool pressedNow = joystickButton; 960 if (pressedNow && !pressed && millis() - lastClickAt > 250) { 961 lastClickAt = millis(); 962 doAction(MUTE); 963 } 964 pressed = pressedNow; 965} 966 967void readButtons() { 968 static bool before[3] = { false, false, false }; 969 const Action BUTTON_ACTION[3] = { PREVIOUS, PLAY, NEXT }; 970 971 if (!buttons.update()) { 972 return; 973 } 974 bool now[3]; 975 for (uint8_t i = 0; i < 3; i++) { 976 now[i] = buttons.isPressed(i); 977 if (now[i] && !before[i]) { 978 doAction(BUTTON_ACTION[i]); 979 } 980 before[i] = now[i]; 981 } 982 // With an iPhone, all three lit; the one being pressed goes off for a moment 983 bool ready = linkState == READY; 984 buttons.setLeds(ready && !now[0], ready && !now[1], ready && !now[2]); 985} 986 987// Until this moment the Serial Monitor is ignored (see startBluetooth) 988unsigned long serialIgnoredUntil = 0; 989 990// Commands from the Serial Monitor, to test without touching the Modulino nodes 991void readSerial() { 992 if (!Serial.available()) { 993 return; 994 } 995 char c = Serial.read(); 996 if ((long)(millis() - serialIgnoredUntil) < 0) { 997 return; 998 } 999 switch (c) { 1000 case 'p': doAction(PLAY); break; 1001 case 'n': doAction(NEXT); break; 1002 case 'b': doAction(PREVIOUS); break; 1003 case '+': doAction(VOL_UP); break; 1004 case '-': doAction(VOL_DOWN); break; 1005 case 'm': doAction(MUTE); break; 1006 case '?': printStatus(); break; 1007 // Only vibrates, without sending anything to the iPhone: useful to check 1008 // whether the motor adds noise to the knob readings 1009 case 'v': 1010 if (hasVibro) vibro.on(70, false, 50); 1011 break; 1012 case 'i': printBus(); break; 1013 default: break; 1014 } 1015} 1016 1017void printStatus() { 1018 const char* const TEXT[] = { "searching for iPhone", "connected, not encrypted", "ready" }; 1019 Serial.print("State: "); 1020 Serial.print(TEXT[linkState]); 1021 Serial.print(" | bond stored: "); 1022 Serial.print(bond.hasLTK ? "yes" : "no"); 1023 Serial.print(" | subscribed: "); 1024 Serial.println(hidReport.subscribed() ? "yes" : "no"); 1025 Serial.print("iPhone data (AMS): "); 1026 Serial.print(amsReady ? "yes" : "no"); 1027 Serial.print(" | volume: "); 1028 if (volume < 0) { 1029 Serial.print("unknown"); 1030 } else { 1031 Serial.print((int)(volume * 100 + 0.5)); 1032 Serial.print(" %"); 1033 } 1034 Serial.print(" | song: \""); 1035 Serial.print(title); 1036 Serial.println("\""); 1037 Serial.print("Knob: failed reads "); 1038 Serial.print(knobFailedReads); 1039 Serial.print(" | discarded jumps "); 1040 Serial.print(knobJumps); 1041 Serial.print(" | discarded bounces "); 1042 Serial.println(knobBounces); 1043 Serial.print("Joystick: x "); 1044 Serial.print(joystickX); 1045 Serial.print(" | y "); 1046 Serial.print(joystickY); 1047 Serial.print(" | failed reads "); 1048 Serial.println(joystickFailedReads); 1049 printModulinos(); 1050} 1051 1052// --------------------------------------------------------------------------- 1053// Link state changes 1054// --------------------------------------------------------------------------- 1055 1056void serviceLinkState() { 1057 LinkState newState = SEARCHING; 1058 if (BLE.connected()) { 1059 newState = BLE.paired() ? READY : PAIRING; 1060 } 1061 if (newState == linkState) { 1062 return; 1063 } 1064 if (newState == READY) { 1065 Serial.println("Link encrypted: ready to send actions"); 1066 playMelody(MELODY_CONNECTED, 2); 1067 if (hasVibro) vibro.on(90, INTENSE); 1068 } else if (newState == SEARCHING) { 1069 Serial.println("iPhone disconnected; advertising again"); 1070 if (linkState == READY) playMelody(MELODY_DISCONNECTED, 2); 1071 queueCount = 0; 1072 keyDown = false; 1073 heldKey = 0; 1074 heldKeySent = false; 1075 } else { 1076 Serial.println("iPhone connected; the link is not encrypted yet"); 1077 } 1078 linkState = newState; 1079 // The iPhone data is requested again on every connection, a moment after 1080 // the link is ready so it does not collide with what the phone reads from the board 1081 resetAms(); 1082 amsNextTry = millis() + 2500; 1083 if (hasButtons) { 1084 buttons.setLeds(linkState == READY, linkState == READY, linkState == READY); 1085 } 1086} 1087 1088void serviceAms() { 1089 if (linkState != READY || amsReady || amsAttempts >= 4 || (long)(millis() - amsNextTry) < 0) { 1090 return; 1091 } 1092 amsAttempts++; 1093 unsigned long start = millis(); 1094 amsReady = connectAms(); 1095 Serial.print(amsReady ? "iPhone data (AMS): subscribed in " : "iPhone data (AMS): no answer in "); 1096 Serial.print(millis() - start); 1097 Serial.println(" ms"); 1098 amsNextTry = millis() + 8000; 1099} 1100 1101void serviceBondSave() { 1102 // Half a second after the keys arrive, once pairing has finished 1103 if (!savePending || millis() - saveSince < 500) { 1104 return; 1105 } 1106 savePending = false; 1107 bond.magic = BOND_MAGIC; 1108 EEPROM.put(0, bond); 1109 Serial.println("Bond: saved to the EEPROM"); 1110} 1111 1112// --------------------------------------------------------------------------- 1113// Startup 1114// --------------------------------------------------------------------------- 1115 1116void haltWithError(const char* message) { 1117 while (true) { 1118 Serial.println(message); 1119 if (hasPixels) { 1120 for (uint8_t i = 0; i < LED_COUNT; i++) pixels.set(i, 255, 0, 0, 10); 1121 pixels.show(); 1122 delay(400); 1123 pixels.clear(); 1124 pixels.show(); 1125 } 1126 delay(1600); 1127 } 1128} 1129 1130void printModulinos() { 1131 Serial.print("Modulino nodes: Knob "); 1132 Serial.print(hasKnob ? "yes" : "NO"); 1133 Serial.print(" | Joystick "); 1134 Serial.print(hasJoystick ? "yes" : "NO"); 1135 Serial.print(" | Buttons "); 1136 Serial.print(hasButtons ? "yes" : "NO"); 1137 Serial.print(" | Pixels "); 1138 Serial.print(hasPixels ? "yes" : "NO"); 1139 Serial.print(" | Vibro "); 1140 Serial.print(hasVibro ? "yes" : "NO"); 1141 Serial.print(" | Buzzer "); 1142 Serial.println(hasBuzzer ? "yes" : "NO"); 1143} 1144 1145// Asks every Modulino address 20 times whether it is there; printed with "i". 1146// A healthy node answers 20 out of 20; fewer means a loose cable or not enough power. 1147void printBus() { 1148 const uint8_t ADDRESSES[] = { 0x1E, 0x2C, 0x36, 0x38, 0x3A, 0x3B, 0x3E }; 1149 const char* const WHO[] = { "Buzzer", "Joystick", "Pixels", "Vibro", "Knob", "Knob (alternate)", "Buttons" }; 1150 Serial.println("Qwiic bus, answers out of 20 attempts:"); 1151 for (uint8_t i = 0; i < sizeof(ADDRESSES); i++) { 1152 uint8_t answers = 0; 1153 for (uint8_t attempt = 0; attempt < 20; attempt++) { 1154 Wire1.beginTransmission(ADDRESSES[i]); 1155 if (Wire1.endTransmission() == 0) answers++; 1156 } 1157 Serial.print(" "); 1158 Serial.print(WHO[i]); 1159 Serial.print(": "); 1160 Serial.println(answers); 1161 } 1162} 1163 1164void startModulinos() { 1165 Modulino.begin(); 1166 hasKnob = knob.begin(); 1167 hasJoystick = joystick.begin(); 1168 hasButtons = buttons.begin(); 1169 hasPixels = pixels.begin(); 1170 hasVibro = vibro.begin(); 1171 hasBuzzer = buzzer.begin(); 1172 1173 printModulinos(); 1174 1175 if (hasPixels) { 1176 pixels.clear(); 1177 pixels.show(); 1178 } 1179 if (hasButtons) { 1180 buttons.setLeds(false, false, false); 1181 } 1182} 1183 1184// A Modulino that did not answer at startup is looked for again every 3 seconds 1185void findMissingModulinos() { 1186 static unsigned long last = 0; 1187 if (millis() - last < 3000) { 1188 return; 1189 } 1190 last = millis(); 1191 bool found = false; 1192 if (!hasKnob && knob.begin()) hasKnob = found = true; 1193 if (!hasJoystick && joystick.begin()) hasJoystick = found = true; 1194 if (!hasButtons && buttons.begin()) hasButtons = found = true; 1195 if (!hasVibro && vibro.begin()) hasVibro = found = true; 1196 if (!hasBuzzer && buzzer.begin()) hasBuzzer = found = true; 1197 if (!hasPixels && pixels.begin()) { 1198 hasPixels = found = true; 1199 // Forces every LED to be redrawn 1200 memset(frameShown, 0xFF, sizeof(frameShown)); 1201 } 1202 if (found) { 1203 Serial.print("A Modulino showed up. "); 1204 printModulinos(); 1205 } 1206} 1207 1208void startBluetooth() { 1209 BLE.setGetIRKs(onGetIRKs); 1210 BLE.setGetLTK(onGetLTK); 1211 BLE.setStoreIRK(onStoreIRK); 1212 BLE.setStoreLTK(onStoreLTK); 1213 1214 // Useful to know whether the module should be updated when it freezes 1215 Serial.print("Radio module firmware: "); 1216 Serial.println(WiFi.firmwareVersion()); 1217 1218 // Sometimes the radio module does not answer on the first try after a reset 1219 bool started = false; 1220 for (uint8_t attempt = 1; attempt <= 5 && !started; attempt++) { 1221 started = BLE.begin(); 1222 if (!started) { 1223 Serial.print("Bluetooth did not start, attempt "); 1224 Serial.println(attempt); 1225 BLE.end(); 1226 delay(700); 1227 if (attempt == 2) { 1228 // The radio module (ESP32-S3) is stuck: it is asked to restart. 1229 // The USB port goes through it, so the Serial Monitor drops for a moment. 1230 Serial.println("Restarting the radio module"); 1231 Serial.flush(); 1232 std::string answer; 1233 modem.write(std::string(PROMPT(_RESET)), answer, "%s", CMD(_RESET)); 1234 delay(4000); 1235 // When it comes back, the USB bridge echoes what the board prints and 1236 // that was read as commands: the Serial Monitor is ignored for 20 seconds 1237 serialIgnoredUntil = millis() + 20000; 1238 } 1239 } 1240 } 1241 if (!started) { 1242 haltWithError("Bluetooth did not start: unplug the board and plug it back in; if it persists, check the ESP32-S3 firmware (0.2.0 or newer)"); 1243 } 1244 1245 BLE.setDeviceName(DEVICE_NAME); 1246 BLE.setLocalName(DEVICE_NAME); 1247 // Appearance: generic HID device 1248 BLE.setAppearance(0x03C0); 1249 BLE.setAdvertisedService(hidService); 1250 1251 hidService.addCharacteristic(hidInfo); 1252 hidService.addCharacteristic(hidReportMap); 1253 hidService.addCharacteristic(hidControlPoint); 1254 hidService.addCharacteristic(hidProtocolMode); 1255 hidReport.addDescriptor(reportReference); 1256 hidService.addCharacteristic(hidReport); 1257 BLE.addService(hidService); 1258 1259 infoService.addCharacteristic(manufacturer); 1260 infoService.addCharacteristic(modelNumber); 1261 infoService.addCharacteristic(pnpId); 1262 BLE.addService(infoService); 1263 1264 batteryService.addCharacteristic(batteryLevel); 1265 BLE.addService(batteryService); 1266 1267 const uint8_t NO_KEY[2] = { 0, 0 }; 1268 // Report mode (not boot mode) 1269 const uint8_t REPORT_MODE = 1; 1270 hidInfo.writeValue(HID_INFO, sizeof(HID_INFO)); 1271 hidReportMap.writeValue(HID_REPORT_MAP, sizeof(HID_REPORT_MAP)); 1272 hidProtocolMode.writeValue(&REPORT_MODE, 1); 1273 hidReport.writeValue(NO_KEY, sizeof(NO_KEY)); 1274 manufacturer.writeValue("Arduino"); 1275 modelNumber.writeValue("UNO R4 WiFi"); 1276 pnpId.writeValue(PNP_ID, sizeof(PNP_ID)); 1277 batteryLevel.writeValue(100); 1278 1279 BLELocalCharacteristic* internal = (hidReport.*(&OpenCharacteristic::local))(); 1280 reportHandle = (internal->*(&OpenLocal::valueHandle))(); 1281 1282 // Pairing without a code ("Just Works"): the iPhone only asks "Pair" 1283 BLE.setPairable(Pairable::YES); 1284 1285 if (!BLE.advertise()) { 1286 haltWithError("Bluetooth started but could not advertise"); 1287 } 1288 Serial.print("Bluetooth ready. Board address: "); 1289 Serial.println(BLE.address()); 1290 Serial.print("Advertising as \""); 1291 Serial.print(DEVICE_NAME); 1292 Serial.println("\""); 1293} 1294 1295void setup() { 1296 Serial.begin(115200); 1297 delay(1500); 1298 Serial.println(); 1299 Serial.println("Modulino Media Deck - UNO R4 WiFi + Modulino nodes"); 1300 1301 matrix.begin(); 1302 startModulinos(); 1303 loadBond(); 1304 1305 // Button B pressed at power-up: forget the stored iPhone 1306 if (hasButtons) { 1307 buttons.update(); 1308 if (buttons.isPressed(1)) { 1309 eraseBond(); 1310 Serial.println("Bond: erased (button B at power-up)"); 1311 playMelody(MELODY_FORGOTTEN, 3); 1312 } 1313 } 1314 Serial.print("Bond stored: "); 1315 Serial.println(bond.hasLTK ? "yes" : "no"); 1316 1317 startBluetooth(); 1318} 1319 1320void loop() { 1321 static unsigned long lastReadAt = 0; 1322 1323 BLE.poll(); 1324 serviceLinkState(); 1325 serviceBondSave(); 1326 serviceQueue(); 1327 serviceMelody(); 1328 servicePixels(); 1329 serviceButtonLeds(); 1330 serviceMatrix(); 1331 serviceAms(); 1332 findMissingModulinos(); 1333 readSerial(); 1334 1335 // The controls are read every 10 ms; the rest of the time belongs to Bluetooth 1336 if (millis() - lastReadAt >= 10) { 1337 lastReadAt = millis(); 1338 if (hasKnob) readKnob(); 1339 if (hasJoystick) readJoystick(); 1340 if (hasButtons) readButtons(); 1341 } 1342}
Comments
Only logged in users can leave comments