nRF51822_OBS + mocro:bit_ADV

Dependencies:   mbed BLE_API Adafruit_GFX nRF51822

Тесты по созданию связи между micro:bit и nRF51822 & BLE400 эта часть под nRF51822

main.cpp

Committer:
mamont090671
Date:
2019-12-17
Revision:
15:23ce464fa0b5
Parent:
14:985bfbee997b

File content as of revision 15:23ce464fa0b5:

/* mbed Microcontroller Library
 * Copyright (c) 2006-2015 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mbed.h"
#include "BLE.h"
#include "Adafruit_SSD1306.h"
//Задаем пины для i2c шины
#define SDA P0_0
#define SCL P0_1

#define APP_SPECIFIC_ID_TEST 0x0059 //0xFEFE

#pragma pack(1)
/* Advertising data  */
struct AdvertisingData_t {
    uint8_t length; /* doesn't include itself */
    GapAdvertisingData::DataType dataType;
    uint8_t data[1];
};

struct ApplicationData_t {
    uint16_t applicationSpecificId;             /* An ID used to identify temperature value
                                                   in the manufacture specific AD data field */
    uint8_t ExtT_Value; /* User defined application data */
//    uint8_t btnA_Value;
//    uint8_t btnB_Value;
};
#pragma pack()

//Функции обработки событий кнопок
void triggerfall_1();   //Button1 falling interrupt function
void triggerrise_1();   //Button1 rising interrupt function
void triggerfall_2();   //Button2 falling interrupt function
void triggerrise_2();   //Button2 rising interrupt function
//Задаем кнопки
DigitalIn  sw1(BUTTON1);
DigitalIn  sw2(BUTTON2);

//Initiate input interrupts
InterruptIn sw1Press(BUTTON1);
InterruptIn sw2Press(BUTTON2);
int flag_button;

class I2C2 : public I2C
{
public:
    I2C2(PinName sda, PinName scl) : I2C(sda, scl)
    {
        frequency(400000);
        start();
    };
};

I2C2 gI2C(SDA,SCL);
Adafruit_SSD1306_I2c gOled2(gI2C, NC, 0x78, 64, 128);
//Используем BLE
BLE        ble;
//Задаем светодиод
DigitalOut led1(LED1);
//Задаем интерфейс rs232
Serial pc(USBTX, USBRX);
//Функция вызываемая по таймеру
void periodicCallback(void)
{
    led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */
}
//Функция вызывается при обнаружении ADV пакета
void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params)
{
    AdvertisingData_t *pAdvData = NULL;
    uint8_t len = 0;

    /* Search for the manufacturer data */
    while(len < params->advertisingDataLen) {
        pAdvData = (AdvertisingData_t *)&params->advertisingData[len];
        if(pAdvData->dataType == GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA) {
            ApplicationData_t *pAppData = (ApplicationData_t *)pAdvData->data;
            if(pAppData->applicationSpecificId == APP_SPECIFIC_ID_TEST) {
//                pc.printf("From [%02x %02x %02x %02x %02x %02x], ", params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0]);
//Если MAC заканчивается на 0х38 то ....
                if(params->peerAddr[0] == 0x38 && flag_button == 1) {
                    pc.printf("Temp is %.02f\r", (float)pAppData->ExtT_Value);
//                    gOled2.clearDisplay();
//Выводим двойную рамку для веха экрана
                    gOled2.drawRoundRect(0, 0, 127, 15, 3, 1);
                    gOled2.drawRoundRect(1, 1, 125, 13, 2, 1);
//Выводим двойную рамку для низа экрана
                    gOled2.drawRoundRect(0, 16, 127, 47, 3, 1);
                    gOled2.drawRoundRect(1, 17, 125, 45, 2, 1);
//    gOled2.drawRect(0, 0, 127, 63, 1);
//    gOled2.drawRect(1, 1, 125, 61, 1);
//Показываем на экране
                    gOled2.display();
//Устанавливаем курсор
                    gOled2.setTextCursor(4, 4);
//Задаем размер шрифта
                    gOled2.setTextSize(1);
                    gOled2.printf("Observer Init \r");
//Показываем на экране
                    gOled2.display();

                    gOled2.setTextCursor(4, 22);
                    gOled2.setTextSize(2);
//Выводим показания внешнего датчика температуры на экран
                    gOled2.printf("ExtT: %.01f", (float)pAppData->ExtT_Value);
                    gOled2.display();
//Иначе, если MAC другой, то ...
                } else if (params->peerAddr[0] != 0x38 && flag_button == 2) {
//Выводим показания другого датчика на экран
                    pc.printf("XZ is %.02f\r", (float)pAppData->ExtT_Value);
                    gOled2.setTextCursor(4, 22);
                    gOled2.setTextSize(2);
                    gOled2.printf("IntT: 0x%02x", pAppData->ExtT_Value);
                    gOled2.display();
                }
//                pc.printf(" ButtonAB is %02x", pAppData->btnA_Value);
//                pc.printf("%02x\r", pAppData->btnB_Value);
                break;
            }
        }
        len += (pAdvData->length + 1);
    }
}

int main(void)
{
//Set falling and rising edge to apppropriate interrup function
    sw1Press.fall(&triggerfall_1);
    sw1Press.rise(&triggerrise_1);
    sw2Press.fall(&triggerfall_2);
    sw2Press.rise(&triggerrise_2);
    flag_button = 0;

    led1 = 1;
//Объявляем таймер
    Ticker ticker;
//Назначаем таймеру функцию и интервал
    ticker.attach(periodicCallback, 1);

//инициализируем BLE
    ble.init();
//Задаем параметры сканирования
    ble.gap().setScanParams(1800 /* scan interval */, 1500 /* scan window */);
//Запускаем сканирование
    ble.gap().startScan(advertisementCallback);

//Задаем параметры порта rs232
    pc.baud(9600);
    pc.printf("Observer Init \r\n");

//Очищаем экран
    gOled2.clearDisplay();
    gOled2.display();

    while (true) {
        ble.waitForEvent();
    }
}

//Button1 falling interrupt function
void triggerfall_1()
{
    flag_button = flag_button++;
    pc.printf("\r\nflag: %d\r\n", flag_button);
    if (flag_button == 3) {
        flag_button = 0;
        gOled2.clearDisplay();
        gOled2.display();
    }
}
//Button1 rising interrupt function
void triggerrise_1()
{
}

//Button1 falling interrupt function
void triggerfall_2()
{
}
//Button1 rising interrupt function
void triggerrise_2()
{
}