Merge branch 'master' of github.com:adafruit/Adafruit_nRF52_Arduino

libraries/Bluefruit52Lib/examples/Peripheral/blemidi_callback/blemidi_callback.ino
This commit is contained in:
hathach committed 2017-03-11 01:03:37 +07:00
commit 221a07223a
10 files changed
+522 -64

No files matched your search

+1
View File
@@ -27,6 +27,7 @@
/tools/nrfutil-0.5.2/dist/
/tools/nrfutil-0.5.2/nrfutil.egg-info/
/tools/.idea/
/tools/midi_tests/node_modules
.DS_Store
*.swp
@@ -14,100 +14,134 @@
#include <bluefruit.h>
#include <MIDI.h>
// To test:
// - Run this sketch and open the Serial Monitor
// - Open the iGrand Piano Free app
// - Open the midimittr app on your phone and under Clients select "Bluefruit52"
// - When you see the 'Connected' label switch to the Routing panel
// - Set the Destination to 'iGrand Piano'
// - Switch to the iGrand Piano Free app and you should see notes playing one by one
BLEDis bledis;
BLEMidi blemidi;
// Create MIDI instance using ble service as physical layer
// Create a new instance of the Arduino MIDI Library,
// and attach BluefruitLE MIDI as the transport.
MIDI_CREATE_BLE_INSTANCE(blemidi);
// Variable that holds the current position in the sequence.
int position = 0;
// Store example melody as an array of note values
byte note_sequence[] = {
74,78,81,86,90,93,98,102,57,61,66,69,73,78,81,85,88,92,97,100,97,92,88,85,81,78,
74,69,66,62,57,62,66,69,74,78,81,86,90,93,97,102,97,93,90,85,81,78,73,68,64,61,
56,61,64,68,74,78,81,86,90,93,98,102
};
// Variable to hold the last time we sent a note
unsigned long previousSend = 0;
void setup()
{
Serial.begin(115200);
Serial.println("Bluefruit52 BLEMIDI Example");
Serial.println("Adafruit Bluefruit52 MIDI over Bluetooth LE Example");
Bluefruit.begin();
Bluefruit.setName("Bluefruit52");
Bluefruit.setName("Bluefruit52 MIDI");
// Setup the BLE LED to be enabled on CONNECT
// Note: This is actually the default behaviour, but provided
// here in case you want to control this manually via PIN 19
Bluefruit.autoConnLed(true);
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
// Setup the on board blue LED to be enabled on CONNECT
Bluefruit.autoConnLed(true);
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
bledis.setModel("Bluefruit Feather52");
bledis.begin();
/* Start BLE MIDI
* Note: Apple requires BLE device must have min connection interval >= 20m
* ( The smaller the connection interval the faster we could send data).
* However for HID and MIDI device, Apple could accept min connection interval
* up to 11.25 ms. Therefore BLEMidi::start() will try to set the min and max
* connection interval to 11.25 ms and 15 ms respectively for best performance.
*/
blemidi.setWriteCallback(midi_write_callback);
blemidi.begin();
// Initialize MIDI, listen to all channels
// Initialize MIDI, and listen to all MIDI channels
MIDI.begin(MIDI_CHANNEL_OMNI);
// Set up Advertising Packet
setupAdv();
// Attach the handleNoteOn function to the MIDI Library. It will
// be called whenever the Bluefruit receives MIDI Note On messages.
MIDI.setHandleNoteOn(handleNoteOn);
// Do the same for MIDI Note Off messages.
MIDI.setHandleNoteOff(handleNoteOff);
// Set General Discoverable Mode flag
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
// Advertise TX Power
Bluefruit.Advertising.addTxPower();
// Advertise BLE MIDI Service
Bluefruit.Advertising.addService(blemidi);
// Advertise device name in the Scan Response
Bluefruit.ScanResponse.addName();
// Start Advertising
Bluefruit.Advertising.start();
}
void setupAdv(void)
void handleNoteOn(byte channel, byte pitch, byte velocity)
{
//Bluefruit.Advertising.addTxPower();
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
// Include bleuart 128-bit uuid
Bluefruit.Advertising.addService(blemidi);
// There is no room for Name in Advertising packet
// Use Scan response for Name
Bluefruit.ScanResponse.addName();
// Log when a note is pressed.
Serial.printf("Note on: channel = %d, pitch = %d, velocity - %d", channel, pitch, velocity);
Serial.println();
}
void midi_write_callback(void)
void handleNoteOff(byte channel, byte pitch, byte velocity)
{
MIDI.read();
// Log when a note is released.
Serial.printf("Note off: channel = %d, pitch = %d, velocity - %d", channel, pitch, velocity);
Serial.println();
}
void loop()
{
if ( Bluefruit.connected() && blemidi.notifyEnabled() )
{
MIDI.sendNoteOn(42, 127, 1); // Send a Note (pitch 42, velo 127 on channel 1)
delay(1000); // Wait for a second
MIDI.sendNoteOff(42, 0, 1); // Stop the note
// Don't continue if we aren't connected.
if (! Bluefruit.connected()) {
return;
}
}
void connect_callback(void)
{
Serial.println("Connected");
}
// Don't continue if the connected device isn't ready to receive messages.
if (! blemidi.notifyEnabled()) {
return;
}
// read any new MIDI messages
MIDI.read();
// Store the current time
unsigned long now = millis();
// Check if enough time has passed since last send
if (now - previousSend < 286) {
return;
}
// Setup variables for the current and previous
// positions in the note sequence.
int current = position;
int previous = position - 1;
// If we currently are at position 0, set the
// previous position to the last note in the sequence.
if (previous < 0) {
previous = sizeof(note_sequence) - 1;
}
// Send Note On for current position at full velocity (127) on channel 1.
MIDI.sendNoteOn(note_sequence[current], 127, 1);
// Send Note Off for previous note.
MIDI.sendNoteOff(note_sequence[previous], 0, 1);
// Increment position
position++;
// If we are at the end of the sequence, start over.
if (position >= sizeof(note_sequence)) {
position = 0;
}
// Log the send time
previousSend = now;
void disconnect_callback(uint8_t reason)
{
(void) reason;
Serial.println("Disconnected");
Serial.println("Bluefruit will auto start advertising (default)");
}
@@ -198,11 +198,18 @@ void BLEMidi::_write_handler(uint8_t* data, uint16_t len)
void BLEMidi::setWriteCallback(midi_write_cb_t fp)
{
_write_cb = fp;
_io.setWriteCallback(blemidi_write_cb);
}
void BLEMidi::begin(int baudrate)
{
(void) baudrate;
begin();
}
err_t BLEMidi::begin(void)
{
_io.setWriteCallback(blemidi_write_cb);
VERIFY_STATUS( this->addToGatt() );
// IO characteristic
@@ -44,7 +44,7 @@
#define MIDI_CREATE_BLE_INSTANCE(midiService) MIDI_CREATE_INSTANCE(BLEMidi, midiService, MIDI)
#define BLE_MIDI_DEFAULT_FIFO_DEPTH 128
#define BLE_MIDI_DEFAULT_FIFO_DEPTH 256
extern const uint8_t BLEMIDI_UUID_SERVICE[];
extern const uint8_t BLEMIDI_UUID_CHR_IO[];
@@ -70,7 +70,7 @@ class BLEMidi: public BLEService, public Stream
virtual err_t begin(void);
// MidiInterface
void begin(int baudrate) { (void) baudrate; }
void begin(int baudrate);
bool notifyEnabled(void);
+98
View File
@@ -0,0 +1,98 @@
# MIDI Tests
This folder contains a small number of tests used to verify BLE MIDI features.
## Setup
First, you will need the current stable version of [Node.js][node] installed.
```console
$ node -v
v7.4.0
```
Next, cd to `tools/midi_tests` and run `npm install`.
```console
$ cd tools/midi_tests
$ npm install
```
## RX Test
This will test receiving MIDI messages on the nRF52 feather.
* Upload the `rx_arduino` example to your nRF52 feather.
* Open the serial monitor, and connect to the feather on OS X using Audio MIDI Setup.
* Once you are connected, navigate to the `tools/midi_tests` folder and run the `rx.js` test.
```console
$ cd tools/midi_tests
$ node rx.js
```
The test will ask how fast you would like to send messages. The default is 100ms. Enter a number and press return.
```
? Send interval (ms) 100
```
Next, the test will ask you to select a MIDI port. Select the Bluefruit52 from the list.
```
? Select port Bluefruit52 Bluetooth
```
The test will begin sending messages at the specified interval. It will send 128 note on and 128 note off messages.
```
note on [===============================================================] 128/128
note off [===============================================================] 128/128
```
Check the Arduino Serial monitor and confirm that you have received all 128 note on and 128 note off messages.
```
note on count: 128
note off count: 128
```
If you have 128 of each, the test passed.
## TX Test
This will test sending MIDI messages from the nRF52 feather.
* Upload the `tx_arduino` example to your nRF52 feather.
* Open the serial monitor, and connect to the feather on OS X using Audio MIDI Setup.
* Once you are connected, navigate to the `tools/midi_tests` folder and run the `tx.js` test.
```console
$ cd tools/midi_tests
$ node tx.js
```
The test will ask you to select a MIDI port. Select the Bluefruit52 from the list.
```
? Select port Bluefruit52 Bluetooth
```
In the Arduino Serial Monitor, you will see a message like the one seen below. Press **space** and then **return** to start the test.
```
Start the node TX test and press a key in the serial monitor to start the test...
```
The nRF52 will now start sending MIDI messages to the test. Check the counters and make sure you receive all 128 note on and 128 note off messages.
```
$ node tx.js
? Select port Bluefruit52 Bluetooth
note on [===============================================================] 128/128
note off [===============================================================] 128/128
```
If you have 128 of each, the test passed.
[node]: https://nodejs.org/
+17
View File
@@ -0,0 +1,17 @@
{
"name": "midi-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"async": "^2.0.0-rc.2",
"inquirer": "^3.0.5",
"midi": "^0.9.4",
"multi-progress": "^2.0.0"
}
}
+69
View File
@@ -0,0 +1,69 @@
var midi = require('midi'),
async = require('async'),
inquirer = require('inquirer'),
progress = require('multi-progress')(process.stdout),
output = new midi.output(),
speed = 100,
portNames = [];
for(var i=0; i < output.getPortCount(); i++) {
portNames.push(output.getPortName(i));
}
if(! portNames.length) {
console.error('no MIDI ports available');
process.exit(1);
}
inquirer.prompt([
{
type: 'input',
name: 'speed',
message: 'Send interval (ms)',
default: speed
},
{
type: 'list',
name: 'port',
message: 'Select port',
choices: portNames
}
]).then(answers => {
output.openPort(portNames.indexOf(answers.port));
speed = parseInt(answers.speed);
startTest();
});
function startTest() {
var on_bar = progress.newBar('note on [:bar] :current/:total', {
incomplete: ' ',
total: 128
});
var off_bar = progress.newBar('note off [:bar] :current/:total', {
incomplete: ' ',
total: 128
});
async.timesSeries(128, function(n, next){
setTimeout(function() {
on_bar.tick();
output.sendMessage([0x90, n, 0x7F]);
next();
}, speed);
}, function() {});
async.timesSeries(128, function(n, next){
setTimeout(function() {
off_bar.tick();
output.sendMessage([0x90, n, 0x00]);
next();
}, speed);
}, function() {});
}
@@ -0,0 +1,79 @@
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
#include <bluefruit.h>
#include <MIDI.h>
BLEMidi blemidi;
// Create a new instance of the Arduino MIDI Library,
// and attach BluefruitLE MIDI as the transport.
MIDI_CREATE_BLE_INSTANCE(blemidi);
int on_count = 0;
int off_count = 0;
void setup()
{
Serial.begin(115200);
Serial.println("Bluefruit52 BLEMIDI RX Test");
Bluefruit.autoConnLed(true);
Bluefruit.begin();
Bluefruit.setName("Bluefruit52");
MIDI.begin(MIDI_CHANNEL_OMNI);
MIDI.setHandleNoteOn(handleNoteOn);
MIDI.setHandleNoteOff(handleNoteOff);
// Set General Discoverable Mode flag
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
// Advertise BLE MIDI Service
Bluefruit.Advertising.addService(blemidi);
// Advertise device name in the Scan Response
Bluefruit.ScanResponse.addName();
// Start Advertising
Bluefruit.Advertising.start();
}
void handleNoteOn(byte channel, byte pitch, byte velocity)
{
on_count++;
Serial.print("note on count: ");
Serial.println(on_count, DEC);
}
void handleNoteOff(byte channel, byte pitch, byte velocity)
{
off_count++;
Serial.print("note off count: ");
Serial.println(off_count, DEC);
}
void loop() {
if(Serial.available()) {
Serial.read();
off_count = 0;
on_count = 0;
Serial.println("Test reset.");
}
MIDI.read();
}
+47
View File
@@ -0,0 +1,47 @@
var midi = require('midi'),
async = require('async'),
inquirer = require('inquirer'),
progress = require('multi-progress'),
input = new midi.input(),
multi = new progress(),
portNames = [];
for(var i=0; i < input.getPortCount(); i++) {
portNames.push(input.getPortName(i));
}
inquirer.prompt([
{
type: 'list',
name: 'port',
message: 'Select port',
choices: portNames
}
]).then((answers) => {
input.openPort(portNames.indexOf(answers.port));
startTest();
});
function startTest() {
var on_bar = multi.newBar('note on [:bar] :current/:total', {
incomplete: ' ',
total: 128
});
var off_bar = multi.newBar('note off [:bar] :current/:total', {
incomplete: ' ',
total: 128,
callback: function() {
input.closePort();
process.exit();
}
});
input.on('message', function(deltaTime, message) {
if(message[0] != 144 && message[0] != 128) return;
if(message[2] == 0) off_bar.tick();
if(message[2] == 100) on_bar.tick();
});
}
+106
View File
@@ -0,0 +1,106 @@
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
#include <bluefruit.h>
#include <MIDI.h>
BLEMidi blemidi;
// Create a new instance of the Arduino MIDI Library,
// and attach BluefruitLE MIDI as the transport.
MIDI_CREATE_BLE_INSTANCE(blemidi);
bool startTest = false;
int on_count = 0;
int off_count = 0;
unsigned long on_interval = 5;
unsigned long off_interval = on_interval;
unsigned long prev_on = millis();
unsigned long prev_off = millis();
void setup()
{
Serial.begin(115200);
Serial.println("Bluefruit52 BLEMIDI TX Test");
Bluefruit.autoConnLed(true);
Bluefruit.begin();
Bluefruit.setName("Bluefruit52");
MIDI.begin(MIDI_CHANNEL_OMNI);
// Set General Discoverable Mode flag
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
// Advertise BLE MIDI Service
Bluefruit.Advertising.addService(blemidi);
// Advertise device name in the Scan Response
Bluefruit.ScanResponse.addName();
// Start Advertising
Bluefruit.Advertising.start();
Serial.println("Waiting for connection...");
}
void loop()
{
// Don't continue if we aren't connected.
if (! Bluefruit.connected()) {
return;
}
// Don't continue if the connected device isn't ready to receive messages.
if (! blemidi.notifyEnabled()) {
return;
}
unsigned long currentMillis = millis();
if(! startTest) {
Serial.println();
Serial.println("Start the node TX test and press a key in the serial monitor to start the test...");
while(Serial.available() == 0) { }
while(Serial.available()) { Serial.read(); }
startTest = true;
prev_on = currentMillis;
prev_off = currentMillis;
Serial.println("Starting test.");
}
if(on_count >= 128 && off_count >= 128) {
Serial.println("Test finished. Resetting.");
startTest = false;
on_count = 0;
off_count = 0;
return;
}
if (currentMillis - prev_on >= on_interval && on_count < 128) {
MIDI.sendNoteOn(on_count, 100, 1);
on_count++;
prev_on = currentMillis;
}
if (currentMillis - prev_off >= off_interval && off_count < 128) {
MIDI.sendNoteOff(off_count, 0, 1);
off_count++;
prev_off = currentMillis;
}
}