Có nhiều cách để gửi lệnh từ máy tính đến Arduino. Sandeep Bansil cung cấp một ví dụ tốt về kết nối và đọc một cổng nối tiếp.
Dưới đây là ví dụ làm việc về cách ghi vào cổng nối tiếp dựa trên trạng thái hộp kiểm trên biểu mẫu cửa sổ amd cách xử lý yêu cầu từ máy tính trên Arduino.
Đây là ví dụ tiết, có các giải pháp rõ ràng hơn nhưng điều này rõ ràng hơn.
Trong ví dụ, arduino đợi hoặc là 'a' hoặc 'b' từ máy tính. máy tính sẽ gửi 'a' khi hộp kiểm được chọn và gửi 'b' khi hộp kiểm không được chọn. Ví dụ giả sử pin kỹ thuật số 4 trên Arduino.
Arduino đang
#define DIGI_PIN_SOMETHING 4
unit8_t commandIn;
void setup()
{
//create a serial connection at 57500 baud
Serial.begin(57600);
}
void loop()
{
//if we have some incomming serial data then..
if (Serial.available() > 0)
{
//read 1 byte from the data sent by the pc
commandIn = serial.read();
//test if the pc sent an 'a' or 'b'
switch (commandIn)
{
case 'a':
{
//we got an 'a' from the pc so turn on the digital pin
digitalWrite(DIGI_PIN_SOMETHING,HIGH);
break;
}
case 'b':
{
//we got an 'b' from the pc so turn off the digital pin
digitalWrite(DIGI_PIN_SOMETHING,LOW);
break;
}
}
}
}
Windows C#
Mã này sẽ nằm trong file mẫu của bạn cs. Ví dụ giả định rằng bạn đã đính kèm các sự kiện biểu mẫu cho OnOpenForm, OnCloseForm và sự kiện OnClick vào hộp kiểm. Từ mỗi sự kiện bạn có thể gọi các phương pháp tương ứng bên dưới ....
using System;
using System.IO.Ports;
class fooForm and normal stuff
{
SerialPort port;
private myFormClose()
{
if (port != null)
port.close();
}
private myFormOpen()
{
port = new SerialPort("COM4", 57600);
try
{
//un-comment this line to cause the arduino to re-boot when the serial connects
//port.DtrEnabled = true;
port.Open();
}
catch (Exception ex)
{
//alert the user that we could not connect to the serial port
}
}
private void myCheckboxClicked()
{
if (myCheckbox.checked)
{
port.Write("a");
}
else
{
port.Write("b");
}
}
}
Mẹo:
Nếu bạn muốn đọc một tin nhắn từ Arduino sau đó thêm một bộ đếm thời gian để hình của bạn với một khoảng thời gian 50
hoặc 100
mili giây.
Trong trường hợp OnTick
của Timer bạn nên kiểm tra dữ liệu bằng cách sử dụng đoạn mã sau:
//this test is used to see if the arduino has sent any data
if (port.BytesToRead > 0)
//On the arduino you can send data like this
Serial.println("Hellow World")
//Then in C# you can use
String myVar = port.ReadLine();
Kết quả của readLine()
sẽ là myVar
chứa Hello World
.
Nguồn
2012-08-27 22:00:31
đối với một số lý do, tôi không bao giờ tìm kiếm đã cho tôi trang đó. cảm ơn. – ikathegreat