2016年4月27日 星期三

Arduino 端的模擬訊號

為了在 Android 端能接收到不斷變化的數據,加上老師希望我能教學生在 Android 程式經藍芽讀取溫度數據,於是乎編寫了以下隨機傳回 15 至 25 度的數值。務求在 Android 端能模擬到像真的數據。
//------------------------------------------------------------------------------
//  Send Signal from Bluetooth for Android App Test
//------------------------------------------------------------------------------
//  Platform: Arduino UNO + ITEAD Wireless Bluetooth Shield Module Starter Kit
//  Written by Pacess HO
//  Copyright 2016 Pacess Studio.    All rights resvered.
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
#include <SoftwareSerial.h>

//------------------------------------------------------------------------------
SoftwareSerial mySerial(6, 7); // RX, TX

int _bufferIndex = 0;
byte _buffer[64];

int _count = 0;
int _major = 25;
int _minor = 0;

char _printBuffer[16];

//------------------------------------------------------------------------------
void setup()  {
    randomSeed(analogRead(0));

    //  Open serial communications and wait for port to open:
    Serial.begin(38400);

    //  Wait for serial port to connect. Needed for native USB port only
    while (!Serial);

    //  Please change to DAT mode on the shield
    mySerial.begin(9600);

    _count = 0;
    _bufferIndex = 0;
    Serial.println("Signal-BT is ready...");
    Serial.println("Copyright 2016 Pacess Studio.  All rights resvered.");
}

//------------------------------------------------------------------------------
void loop()  {
    if (_count++ > 20000)  {
        _count = 0;

        int value = random(100);
        if (value < 10)  {
            if (_minor > 0)  {_minor--;}
            else if (_major > 15)  {
                _major--;
                _minor = 9;
            }
        }    else if (value < 20)  {
            if (_minor < 9)  {_minor++;}
            else if (_major < 25)  {
                _major++;
                _minor = 0;
            }
        }

        sprintf(_printBuffer, "%d.%d\r\n", _major, _minor);
        Serial.write(_printBuffer);
        mySerial.write(_printBuffer);
    }

    if (mySerial.available())  {
        Serial.write(mySerial.read());
    }

    if (Serial.available())  {
        byte value = Serial.read();
        _buffer[_bufferIndex] = value;
        _bufferIndex++;

        if (value == '.')  {
            _buffer[_bufferIndex-1] = '\n';
            _buffer[_bufferIndex] = '\n';

            for (int i=0; i<=_bufferIndex; i++)  {
                value = _buffer[i];
                Serial.write(value);
                mySerial.write(value);
            }
            Serial.write("#");
            _bufferIndex = 0;
        }
    }
}