次の自家製ライブラリを使用して、Serial3 の RN42 と通信します。::begin() 中に安定するように 50 ミリ秒の遅延があることに注意してください。この後は、単に Serial3.Print または Read を使用します。必要に応じてシリアル番号とピンを変更します。
#define DEFAULT_FLUSH_TIMEOUT 50 // ms
#define BT_RX 14 // PJ1 Output, USART3_TX
#define BT_TX 15 // PJ0 Input, USART3_RX
#define BT_CTS 27 // PA5 Output, Active Low, Enable Device Transmission
#define BT_RTS 26 // PA4 Input , Active Low, Requesting Data
#define BT_RST 23 // PA1 Output, Active Low, Resets BlueTooth Transciever
void RN42::begin() {
digitalWrite(BT_RST, BT_RST_Enabled); //Take Radio out of Reset
digitalWrite(BT_CTS, BT_CTS_Enabled); //Enable Transmitter
delay(750); // need to wait for the radio to stablize.
Serial.print("$$$ = ");
Serial.print (command("$$$", '\n', DEFAULT_FLUSH_TIMEOUT));
Serial.println();
delay(100); // delay as it avoids problems, with flush.
read_version = command("v\n", '\n', DEFAULT_FLUSH_TIMEOUT);
read_serial = command("GB\n", '\n', DEFAULT_FLUSH_TIMEOUT);
read_connection = command("GK\n", '\n', DEFAULT_FLUSH_TIMEOUT);
Serial.print("Online = ");
Serial.print(command("---\n", '\n', DEFAULT_FLUSH_TIMEOUT));
Serial.println();
Serial.print("version1 = ");
Serial.println(read_version);
Serial.print("Serial = ");
Serial.print(read_serial);
Serial.println();
Serial.print("Connection = ");
Serial.print(read_connection);
Serial.println();
}
void RN42::end() {
//turn radio of and put into reset.
digitalWrite(BT_RST, BT_RST_Disabled);
digitalWrite(BT_CTS, BT_CTS_Disabled);
}
void RN42::TxOff() {
// turn Transmitter off to save power
digitalWrite(BT_CTS, BT_CTS_Disabled);
}
void RN42::TxOn() {
// turn Transmitter on, more power
digitalWrite(BT_CTS, BT_CTS_Enabled);
}
void RN42::flush(long timeout) {
long start_time = millis();
int state = 1;
char c;
while (state)
{
int i = Serial3.available();
for (int thischar = 0; thischar < i; thischar++) {
c = Serial3.read();
}
if ( (millis() - start_time) > timeout )
{
state = 0;
}
}
}
String RN42::command (String sCommand, char cTerminator, long timeout)
{
String inData="";
long start_time = millis();
int state = 0;
Serial3.print(sCommand);
while (!state)
{
int len = Serial3.available();
for (int thischar = 0; thischar < len; thischar++) {
char c = (char) Serial3.read();
// Serial.print("0x");
// Serial.println((int) c, HEX);
if ((c == '\n')) {// || (c == '\r')) {
state = 1;
break;
} else {
if (state != 1) {
inData += c;
}
}
}
if ( (millis() - start_time) > timeout )
{
state = 2;
//Serial.println ("TimedOut");
}
}
inData.trim();
if ((state = 1)) flush(timeout);
return inData;
}