BluetoothのSPP接続を行うためのサンプルコードです。

サンプル
#include <stdio.h>
#include <string.h>
#include "lib.h"
int BluetoothConnect(int port, char *bdAddress, char *pincode);

void main( void )
{
    char ch;
    printf("[Bluetooth sample]\r\n");
    while (1)
    {
        // Connect Bluetooth SPP master mode.
        while (BluetoothConnect(COM3, "00126afedcba", "0000") != OK)    Idle();
        PutString("Message from OPH-5000i.");
        Cursor(AUTOWRAP);
        printf("Waiting receive host:");
        while (1)
        {
            if (comloc() > 0 )
            {
                if ((ch=GetCom(0)) != -1)
                {
                    putchar(ch);
                }
            }
            if (GetConnectionStatus(COM3) != COM_STATE_CONNECT)
            {
                printf("Disconnected\r\n");
                Cursor(NOWRAP);
                ComClose(COM3);
                break;
            }
        }
    }
}

int BluetoothConnect(int port, char *bdAddress, char *pincode)
{
    int status;
    int prevStatus = -1;
    setconfig_comapi spp_cfg;
    if(GetConnectionStatus(port) == COM_STATE_CLOSE)
    {
        GetConfig(port, (void *)&spp_cfg);
        if (port == COM3 && bdAddress != NULL)    // BD address if SPP master mode
        {
            strncpy((char *)spp_cfg.blt.address, bdAddress, BLT_BD_ADDR_LEN);
        }
        if (pincode != NULL)
        {
            spp_cfg.blt.dynamicPIN = FALSE;
            strncpy((char *)spp_cfg.blt.pincode, pincode, BLT_MAX_PINCODE_LEN);
        }
        SetConfig(port, (void *)&spp_cfg);
        if (ComOpen(port) != OK)
        {
            ComClose(port);
            return ERROR;
        }
    }
    BltWaitAcceptStart();
    while (1)
    {
        status = GetConnectionStatus(port);
        if (status != prevStatus)
        {
            printf("connect status:%d\r\n", status);
            prevStatus = status;
        }
        if (status == COM_STATE_CONNECT)
        {
            BltWaitAcceptEnd(TRUE);
            break;
        }
        else if (status == COM_STATE_CLOSE)
        {
            BltWaitAcceptEnd(TRUE);
            ComClose(port);
            return ERROR;
        }
        Idle();
    }
    return OK;
}

最終更新日:2021/03/17