Подключение Arduino Nano 33 IoT к приложению Android через Bluetooth
Я работаю над подключением Arduino nano 33 iot к приложению Android через возможности Bluetooth устройства iot. Я видел много ресурсов, относящихся к использованию модуля Bluetooth, но не видел ресурсов об использовании возможностей nano 33 iot Bluetooth.
Я хочу получать данные от Arduino через соединение Bluetooth и отображать их в приложении для Android. Я разработал приложение, которое может видеть Arduino в списке устройств Bluetooth, но мне не удается подключиться к Arduino из-за того, что он не может быть сопряжен с телефоном.
Спасибо
2 ответа
Вы нашли решение? Я думаю, вам нужно быть уверенным, что вы подключаетесь по Bluetooth Low Energy к плате Nano от Arduino. Способ, описанный в вашем опубликованном учебнике, не является низкоэнергетическим. Из-за этого вы не можете создать пару.
Чтобы подключить Arduino nano 33 IoT через BLE, вы можете использовать демонстрацию Бернардо Джованни в качестве кода шаблона для своего проекта.
*/
// Voltage divider definitions.
// Here I've reported my precise values for R1 (47K) and R2 (33K)
// remember: you cannot apply more than 3.3V on analog input.
// Having a voltage divider with those values (47K and 33K)
// consent to apply on the voltage divider input a maximum of:
// 3.3/VDK = 3.3/0.4125 = 8V
#define R1 46.2F
#define R2 32.86F
#define VDK (R2/(R1+R2))
// since I'm using a 4xAA battery holder and you cannot apply
// less than 5V on Vin pin, I define my "battery full" value as 6V
// and "battery low" value as 5V
#define BAT_FUL 6
#define BAT_LOW 5
// analog pin connected to the voltage divider for battery
// voltage reading
#define AN_BAT A7
#include <ArduinoBLE.h> // Arduino BLE library
#include <Arduino_LSM6DS3.h> // Use Arduino library for the IMU on the Nano 33 IOT
// UUid for Service
const char* UUID_serv = "84582cd0-3df0-4e73-9496-29010d7445dd";
// UUids for accelerometer characteristics (I separated x, y and z values)
const char* UUID_ax = "84582cd1-3df0-4e73-9496-29010d7445dd";
const char* UUID_ay = "84582cd2-3df0-4e73-9496-29010d7445dd";
const char* UUID_az = "84582cd3-3df0-4e73-9496-29010d7445dd";
// UUids for gyroscope characteristics (as above)
const char* UUID_gx = "84582cd4-3df0-4e73-9496-29010d7445dd";
const char* UUID_gy = "84582cd5-3df0-4e73-9496-29010d7445dd";
const char* UUID_gz = "84582cd6-3df0-4e73-9496-29010d7445dd";
// UUid for battery values (bap=percent, ba=voltage)
const char* UUID_bap = "84582cd7-3df0-4e73-9496-29010d7445dd";
const char* UUID_ba = "84582cd8-3df0-4e73-9496-29010d7445dd";
// BLE Service
BLEService myService(UUID_serv);
// BLE Characteristics
BLEFloatCharacteristic chAX(UUID_ax, BLERead|BLENotify);
BLEFloatCharacteristic chAY(UUID_ay, BLERead|BLENotify);
BLEFloatCharacteristic chAZ(UUID_az, BLERead|BLENotify);
BLEFloatCharacteristic chGX(UUID_gx, BLERead|BLENotify);
BLEFloatCharacteristic chGY(UUID_gy, BLERead|BLENotify);
BLEFloatCharacteristic chGZ(UUID_gz, BLERead|BLENotify);
BLEFloatCharacteristic chBAP(UUID_bap, BLERead|BLENotify);
BLEFloatCharacteristic chBA(UUID_ba, BLERead|BLENotify);
void setup()
{
Serial.begin(115200);
uint32_t t=millis();
while (!Serial) // wait 5 seconds for serial connection
{
if ((millis()-t) > 5000) break;
}
bool err=false;
pinMode(LED_BUILTIN, OUTPUT); // onboard led
digitalWrite(LED_BUILTIN, LOW); // led off
// init IMU
if (!IMU.begin())
{
Serial.println("IMU: failed");
err=true;
}
Serial.println("IMU: ok");
// init BLE
if (!BLE.begin())
{
Serial.println("BLE: failed");
err=true;
}
Serial.println("BLE: ok");
// error: flash led forever
if (err)
{
Serial.println("Init error. System halted");
while(1)
{
digitalWrite(LED_BUILTIN, HIGH); // led on
delay(500);
digitalWrite(LED_BUILTIN, LOW); // led off
delay(500);
}
}
// BLE service
// correct sequence:
// set BLE name > advertised service > add characteristics > add service > set initial values > advertise
// Set BLE name
BLE.setLocalName("Settorezero_IMU");
BLE.setDeviceName("Arduino"); // Arduino is the default value on this module
// Set advertised Service
BLE.setAdvertisedService(myService);
// Add characteristics to the Service
myService.addCharacteristic(chAX);
myService.addCharacteristic(chAY);
myService.addCharacteristic(chAZ);
myService.addCharacteristic(chGX);
myService.addCharacteristic(chGY);
myService.addCharacteristic(chGZ);
myService.addCharacteristic(chBAP);
myService.addCharacteristic(chBA);
// add service to BLE
BLE.addService(myService);
// characteristics initial values
chAX.writeValue(0);
chAY.writeValue(0);
chAZ.writeValue(0);
chGX.writeValue(0);
chGY.writeValue(0);
chGZ.writeValue(0);
chBAP.writeValue(0);
chBA.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("Advertising started");
}
void loop()
{
static long preMillis = 0;
// listen for BLE centrals devices
BLEDevice central = BLE.central();
// central device connected?
if (central)
{
digitalWrite(LED_BUILTIN, HIGH); // turn on the onboard led
Serial.print("Connected to central: ");
Serial.println(central.address()); // central device MAC address
// while the central is still connected to peripheral:
while (central.connected())
{
// additional placeholder for writing command from central
// to this device. "myCharacteristic" is a characteristic initialized
// in write mode (BLEwrite) with his own UUid
/*
if (myCharacteristic.written())
{
command = myCharacteristic.value(); // retrieve value sent from central
Serial.print(F("commmand value: "));
Serial.println(command);
}
*/
long curMillis = millis();
if (preMillis>curMillis) preMillis=0; // millis() rollover?
if (curMillis - preMillis >= 10) // check values every 10mS
{
preMillis = curMillis;
updateValues(); // call function for updating value to send to central
}
} // still here while central connected
// central disconnected:
digitalWrite(LED_BUILTIN, LOW);
Serial.print(F("Disconnected from central: "));
Serial.println(central.address());
} // no central
}
void updateValues()
{
uint8_t averages=10; // average on this values count (accelerometer and gyroscope)
uint16_t b_averages=500; // average for battery
// accelerometer averaged values/actual values
static float ax=0;
static float ay=0;
static float az=0;
float ax1, ay1, az1;
// gyroscope averaged values/actual values
static float gx=0;
static float gy=0;
static float gz=0;
float gx1, gy1, gz1;
// battery averaged value/actual value
static float anBa=0;
float anBa1;
static uint8_t i_a=0; // accelerometer readings counter
static uint8_t i_g=0; // gyroscope readings counter
static uint16_t i_b=0; // battery readings counter
// read accelerometer values if available
if (IMU.accelerationAvailable())
{
i_a++;
IMU.readAcceleration(ax1, ay1, az1);
ax+=ax1;
ay+=ay1;
az+=az1;
if (i_a==averages) // send average over BLE
{
ax/=averages;
ay/=averages;
az/=averages;
//Serial.println("Accelerometer: "+String(ax)+","+String(ay)+","+String(az));
chAX.writeValue(ax);
chAY.writeValue(ay);
chAZ.writeValue(az);
ax=0;
ay=0;
az=0;
i_a=0;
}
}
// read gyroscope values if available
if (IMU.gyroscopeAvailable())
{
i_g++;
IMU.readGyroscope(gx1, gy1, gz1);
gx+=gx1;
gy+=gy1;
gz+=gz1;
if (i_g==averages) // send average over BLE
{
gx/=averages;
gy/=averages;
gz/=averages;
//Serial.println("Gyroscope: "+String(gx)+","+String(gy)+","+String(gz));
chGX.writeValue(gx);
chGY.writeValue(gy);
chGZ.writeValue(gz);
gx=0;
gy=0;
gz=0;
i_g=0;
}
}
// read battery value
anBa1=analogRead(AN_BAT);
anBa+=anBa1;
i_b++;
if (i_b==b_averages)
{
anBa/=b_averages; // averaged analog value
float voltage=anBa*(3.3/1023); // voltage on pin (if 3.3V => ADC gives 1023)
voltage=voltage/VDK; // real voltage on the voltage divider input = battery voltage
// send voltage in V to BLE
chBA.writeValue(voltage);
/*
Serial.print("Battery: ");
Serial.print(voltage,2);
Serial.print("V (");
*/
// calculate percentual battery
// we must consider BAT_FUL=100% and BAT_LO=0%
// report voltage to range having 0 as lower limit and (BAT_FUL-BAT_LO) as higher limit
// for having percent value
voltage-=BAT_LOW;
voltage/=(BAT_FUL-BAT_LOW);
anBa=voltage*100;
// keep percent value in the range 0-100
if (anBa<0) anBa=0;
else if (anBa>100) anBa=100;
// send % value to BLE
chBAP.writeValue(anBa); // percent voltage
/*
Serial.print(anBa,1);
Serial.println("%)");
*/
i_b=0;
anBa=0;
}
}
На сайте arduino есть хороший учебник по BLEhttps://docs.arduino.cc/tutorials/nano-33-iot/Bluetooth.