When programming to Arduino, because there is no debugging tools, often through the use of serial communication to call Serial.print and SERIAL.PRINTLN output Arduino running the relevant information, and then on the computer with the Arduino The IDE's serial monitor to see the print out information. Serial Monitor not only accepts data that Arduino sends to the computer, it can also send data to Arduino for two-way communication. But this way of communication is too primitive, is purely manual way, only suitable for debugging. If you need to interact with the Arduino via a visual interface on your computer, or work with the data that Arduino sends to your computer, you need to program it on your computer. The professional point is that the host computer and the next computer communication. This article describes how to use C # to implement the Arduino and the computer for serial communication.
1, C # serial Programming Foundation in C # there is a serial port class System.IO.Ports.SerialPort, this class instance corresponds to the serial port in the Device Manager. For example SerialPort port = new SerialPort ("COM4") This code defines a string example, corresponding to the USB Serial port (COM4) SerialPort Common methods include open, Close, Read, ReadLine, Write, WriteLine. These methods are easy to understand by name. Specific class information can be referenced msdn:http://msdn.microsoft.com/zh-cn/library/vstudio/system.io.ports.serialport (v=vs.100). aspx 2, Arduino Serial programming base Arduino serial and C # SerialPort usage are similar, there are available, begin, read, Readbytes, write, print, println, also easily understood from the name. For specific usage, refer to the official documentation: Http://arduino.cc/en/Reference/Serial generally we add serial.begin (9600) to the Setup method of the Arduino code, The received data is then read in the Serialevent method. 3, the instance of the scene is: 1, Arduino on a light sensor, through the analog port periodically read the brightness value. 2. After sending a command to the Arduino to start sending data on the computer, light the LED on the 13th digital port on the Arduino, then the Arduino sends the brightness value to the computer via the serial port. 3. After sending a command to the Arduino to stop sending data on the computer, turn off the LED on the 13th digital port on the Arduino, and then the Arduino stops sending the brightness value to the computer via the serial port. This scenario contains two-way communication between the Arduino and the computer. The example uses WinForm and the interface is as follows:
The serial name of the available serial port on the computer is automatically loaded in the port list. Click the "Start reading" button, according to the selected serial port name to instantiate a serial port object, specify the serial port DataReceived event processing method. Then call the Changearduinosendstatus method to send the "serial start" command to the Arduino. Click the "Stop reading" button to send the "serial stop" command to the Arduino, close the serial port and destroy the instance. Click the "Start Send" or "Stop send" button to call the Changearduinosendstatus method to send the "serial start" or "Serial stop" command to the Arduino, Let Arduino start sending data to the computer via the serial port or stop sending data to the computer. The serial port starts to datareceived event after receiving the data, calls the Refreshinfotextbox method in the event processing method, reads the serial port data and appends to the interface text box. Note: The DataReceived event of the serial port is executed by the background thread, to display the read data in the Winfrom interface, you need to use the control's Invoke method to refresh the interface. The C # core code is as follows:
PrivateSerialPort Port =
NULL;
<summary>
Initializing the serial port instance
</summary>
Private
voidInitialserialport ()
{
Try
{
stringPortName =
This. cmbSerials.SelectedItem.ToString ();
Port =
NewSerialPort (PortName, 9600);
Port. Encoding = Encoding.ascii;
Port. DataReceived + = port_datareceived;
Port. Open ();
This. Changearduinosendstatus (
true);
}
Catch(Exception ex)
{
MessageBox.Show ("Initialization of serial port error:" + ex.) message, "hint message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
<summary>
Close and destroy the serial port instance
</summary>
Private
voidDisposeserialport ()
{
if(Port! =
NULL)
{
Try
{
This. Changearduinosendstatus (
false);
if(Port. IsOpen)
{
Port. Close ();
}
Port. Dispose ();
}
Catch(Exception ex)
{
MessageBox.Show ("Turn off serial port error:" + ex.) message, "hint message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
<summary>
Change the transmission status of the Arduino serial port
</summary>
<param name= "Allowsend" > whether to allow data to be sent </param>
Private
voidChangearduinosendstatus (
BOOLAllowsend)
{
if(Port! =
NULL&& Port. IsOpen)
{
if(Allowsend)
{
Port. WriteLine ("serial start");
}
Else
{
Port. WriteLine ("Serial Stop");
}
}
}
<summary>
Read data from the serial port and convert it to a string form
</summary>
<returns></returns>
Private
stringReadserialdata ()
{
stringValue = "";
Try
{
if(Port! =
NULL&& Port. Bytestoread > 0)
{
Value = port. Readexisting ();
}
}
Catch(Exception ex)
{
MessageBox.Show ("Error reading serial port data:" + ex.) message, "hint message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
returnValue
}
<summary>
Refresh text box information when reading to data
</summary>
Private
voidRefreshinfotextbox ()
{
stringValue =
This. Readserialdata ();
action<
string> setvalueaction = Text =
This. txtinfo.text + = Text;
if(
This. txtinfo.invokerequired)
{
This. Txtinfo.invoke (setvalueaction, value);
}
Else
{
Setvalueaction (value);
}
The Arduino code code comment is very detailed and will no longer be interpreted.
intpinled = 13;//Defines the digital port that connects the LEDs, lights the LEDs when the data is allowed to be sent over the serial port, otherwise turns off the LED
Boolean Sendflag =
false;//Indicates whether data is allowed to be sent via serial port Boolean readcompleted =
false;//Indicates whether to complete reading serial data
String serialstring = "";//serial data cache string//author:alex Leo, Email:[email protected], blog:http://conexpress.cnblogs.com/
Reference: Http://arduino.cc/en/Reference/Serial
voidSetup ()
{
Pinmode (Pinled,output);
Serial.begin (9600);
Serialstring.reserve (200);//Initialize string
}
voidLoop ()
{
intLightvalue = Analogread (A0);//Read the value of the light sensor from the A0 port
if(readcompleted)//Determine whether the serial port receives the data and completes the reading
{
Serial.print ("Read value:");
Serial.println (serialstring);//Send the Read information to the computer
if(serialstring = = "Serial start")//when the message read is "serial start", set the Send flag to True
{
Sendflag =
true;
}
Else
if(serialstring = = "Serial Stop")//when the message read is "Serial Stop", set the Send flag to False
{
Sendflag =
false;
}
serialstring = ""; readcompleted =
false;
}
if(Sendflag)//If the serial port is allowed to send data, then light the LED and send data, otherwise turn off the LED {
Digitalwrite (pinled, high);
Serial.print ("Light value:");
Serial.println (Lightvalue);
}
Else
{
Digitalwrite (pinled, low);
}
Delay (1000);//Delay 1000MS
}
voidSerialevent ()//Serial Event processing method, reference: Http://arduino.cc/en/Tutorial/SerialEvent
{
while(Serial.available ())//reference://arduino.cc/en/serial/available
{
CharInchar = (
Char) Serial.read ();
if(Inchar! = ' \ n ')//with a newline character as the read end flag
{
Serialstring + = Inchar;
}
Else
{
readcompleted =
true;
}
}
} Full code Download: Http://files.cnblogs.com/files/conexpress/Arduino%E5%92%8CCSharp%E9%80%9A%E8%AE%AF.rar
"Arduino" uses C # to enable Arduino to communicate with computers serially