Android connect Netduino by Bluetooth

在龍年的尾聲,寫了一個for Netduino平台以Bluetooth connection的經典"Hello World"程式,算是送走龍年給自己的一個交代吧。

public class Program {

// for Bluetooth
public static SerialPort serial;
private static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
private static OutputPort redled = new OutputPort(Pins.GPIO_PIN_D13, false);

public static void Main() {
string greeting = "Everything you type in this window will be echoed\n\r";
byte[] greetingBytes = System.Text.Encoding.UTF8.GetBytes(greeting);
// initialize the serial port for COM2 (using D2 & D3)
serial = new SerialPort(SerialPorts.COM2, 9600, Parity.None, 8, StopBits.One);
// open the serial-port, so we can send & receive data
serial.Open();
// add an event-handler for handling incoming data
serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);

// Wait a little bet to let the bluetooth connection setup
// -- ok this magic worked so I'm keeping it!
Thread.Sleep(250);
serial.Write(greetingBytes, 0, greetingBytes.Length);

// we can toggle the LED including Sleep() because we use a multi threaded event handler
// OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

while (true) {
// // // led.Write(true);
redled.Write(true);
Thread.Sleep(500);
redled.Write(false);
// // // led.Write(false);
Thread.Sleep(500);
}

// original example code said wait forever...
// Thread.Sleep(Timeout.Infinite);
}

public static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e) {
// create a single byte array
byte[] bytes = new byte[1];

// as long as there is data waiting to be read
led.Write(true);
Thread.Sleep(250);
while (serial.BytesToRead > 0) {
// read a single byte
serial.Read(bytes, 0, bytes.Length);
// send the same byte back
serial.Write(bytes, 0, bytes.Length);
}
led.Write(false);
}
}

廣告

About fenjj

Perfect !!??...
本篇發表於 Uncategorized。將永久鏈結加入書籤。

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s