使用蓝牙将C#中的ASCII发送到Arduino

时间:2012-06-15 09:30:58

标签: c# bluetooth arduino

我正在尝试将我的笔记本电脑上的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码还是我错过了什么?

1 个答案:

答案 0 :(得分:0)

可能与我回答here时的问题相同。

  

我最近涉足了这个问题。 Arduino会自动重置   从Arduino以外的大多数东西接收串行通信   IDE。这就是您可以从IDE而不是node.js发送的原因。

     

我有一个Uno并在Reset和Ground之间放一个电容。这是一个   页面上有一些关于这个主题的好信息。祝好运。   http://arduino.cc/playground/Main/DisablingAutoResetOnSerialConnection