我正在尝试将我的 C# Windows Forms应用程序从我的笔记本电脑连接到 Arduino Duemilanove。蓝牙模块连接到 Arduino 上的 Tx 和 Rx 引脚。我的目标是在我输入字母“a”时点亮板载 LED,但到目前为止还没有成功。我确定蓝牙已与我的笔记本电脑连接,但它没有响应我按下的字母。
C# 代码
public partial class Form1 : Form
{
private Guid service = BluetoothService.SerialPort;
private BluetoothClient bluetoothClient;
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);
}
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'a')
{
Stream peerStream = bluetoothClient.GetStream();
Byte[] buffer = Encoding.ASCII.GetBytes("a");
peerStream.Write(buffer, 0, buffer.Length);
}
}
private void search_Click(object sender, EventArgs e)
{
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
BluetoothRadio myRadio = BluetoothRadio.PrimaryRadio;
bluetoothClient = new BluetoothClient();
Cursor.Current = Cursors.WaitCursor;
BluetoothDeviceInfo[] bluetoothDeviceInfo = { };
bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10);
comboBox1.DataSource = bluetoothDeviceInfo;
comboBox1.DisplayMember = "DeviceName";
comboBox1.ValueMember = "DeviceAddress";
comboBox1.Focus();
Cursor.Current = Cursors.Default;
}
private void Connect_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
try
{
bluetoothClient.Connect(new BluetoothEndPoint((BluetoothAddress)comboBox1.SelectedValue, service));
MessageBox.Show("Connected");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Arduino代码
int incomingByte = 0; // For incoming serial data
void setup()
{
pinMode(13, OUTPUT); // On-board LED as output
Serial.begin(9600); // Opens serial port, sets data rate to 9600 bit/s.
}
void loop()
{
if (Serial.available() > 0)
{
// Read the incoming byte:
incomingByte = Serial.read();
if (incomingByte == 'a')
digitalWrite(13, HIGH);
}
}
我是否错误地发送了 ASCII 码或者我错过了什么?