simple c# control arduino
Arduino code
ref https://forum.arduino.cc/index.php?topic=6075.0
int ledPin = 7;//Setting Pin for the LED
void setup(){
pinMode(ledPin, OUTPUT);//ledPin as an output
digitalWrite(ledPin,HIGH);
Serial.begin(9600);
}
void loop(){
while(Serial.available() > 0){
char incomingData = Serial.read(); //reading from the serial ( data from C# )
if(incomingData == '7'){//low
digitalWrite(ledPin,LOW);
Serial.println("LOW");
}
else if(incomingData == '8'){//height
digitalWrite(ledPin,HIGH);
Serial.println("HIGH");
}
}
}
C# code
ref https://forum.arduino.cc/index.php?topic=40336.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace controlArduino
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SerialPort serialPort1;
private void button1_Click(object sender, EventArgs e)
{
serialPort1 = new SerialPort();
serialPort1.PortName = "COM9";
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
serialPort1.Open();
serialPort1.DataReceived += serialPort1_DataReceived;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string line = serialPort1.ReadLine(); // with CR or serialPort1.ReadExisting(); if no CR
this.BeginInvoke(new LineReceivedEvent(LineReceived), line);
}
private delegate void LineReceivedEvent(string line);
private void LineReceived(string line)
{
//What to do with the received line here
label1.Text = line;
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.WriteLine("7");
}
private void button3_Click(object sender, EventArgs e)
{
serialPort1.WriteLine("8");
}
}
}
using System;
using System.Threading;
using System.IO.Ports;
public class ArduinoIOUtil
{
DateTime ErrorPinOnTime = DateTime.MaxValue;
public static int PulzsMS = 500;
private static String ArduinoMsg = "";
public static bool WriteStatus = false;
public ArduinoIOUtil()
{
}
private static SerialPort serialPort1;
public static void Inital(string comName)
{
try
{
Close();
serialPort1 = new SerialPort();
serialPort1.PortName = comName;
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
serialPort1.Open();
serialPort1.DataReceived += serialPort1_DataReceived;
WriteStatus = true;
}
catch (Exception ex)
{
FileUtil.Write(ex.ToString());
}
}
private static void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
ArduinoMsg = serialPort1.ReadLine();
}
public static bool Connecting()
{
bool result = false;
try
{
result = WriteStatus && serialPort1.IsOpen;
}
catch (Exception)
{
result = false;
//throw;
}
return result;
}
public static void Close()
{
CloseSerialOnExit();
}
private static void CloseSerialOnExit()
{
if (CheckUtil.OCV_Station == Station.OCV1 || CheckUtil.OCV_Station == Station.OCV2)
{
try
{
serialPort1.DtrEnable = false;
serialPort1.RtsEnable = false;
serialPort1.DiscardInBuffer();
serialPort1.DiscardOutBuffer();
serialPort1.Close();
}
catch (Exception ex) { }
}
}
public static void Pulze(int pulzeMS)
{
if (ArduinoIOUtil.Connecting())
{
Thread t1 = new Thread(delegate()
{
On();
//Set("7");
Thread.Sleep(pulzeMS);
Off();
//Set("8");
});
t1.Start();
}
}
public static void Set(String cmd)
{
try
{
if (ArduinoIOUtil.Connecting())
{
ArduinoMsg = "";
serialPort1.WriteLine(cmd);
Thread oThread = new Thread(delegate()
{
DateTime startTime = DateTime.Now;
while (ArduinoMsg == "")
{
if ((DateTime.Now - startTime).Milliseconds > 200)
{
//timeout
CheckUtil.PiMessage.Enqueue("IO無回應,請確認!");
break;
}
Thread.Sleep(5);
}
if (ArduinoMsg != "")
{
}
});
oThread.Start();
}
}
catch (Exception)
{
WriteStatus = false;
//throw;
}
}
public static void On()
{
Set("7");
}
public static void Off()
{
Set("8");
}
public static void HeartBit()
{
Set("9");
}
}
String arduinoCom = ComUtil.GetDeviceCom("Uno");
ArduinoIOUtil.Inital(arduinoCom);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Collections;
using System.Windows.Forms;
using System.Management;
//加入參考
//專案→加入參考→.Net→System.Management
namespace Utility
{
public delegate void CRLFEventHandler(object sender, CRLFEventArgs e);
public delegate void CheckStringEventHandler(object sender, CheckStringEventArgs e);
public class CheckStringEventArgs : EventArgs
{
public CheckStringEventArgs()
{
}
}
public class CRLFEventArgs : EventArgs
{
public String ComValue;
public ushort Value;
public CRLFEventArgs(String comValue)
{
ComValue = comValue;
}
}
public class ComUtil
{
public SerialPort mySerialPort;
//public string ReceiveString = "";
public bool IsConnected = false;
public bool CheckCRLF = true;
public bool CheckString = false;
public String CheckTargetString = "!";
public byte[] ReceiveByteArray = new byte[0];
public static int BaudRate9600 = 9600;
public static int BaudRate19200 = 19200;
public static int BaudRate38400 = 38400;
public static int BaudRate57600 = 57600;
public static int BaudRate115200 = 115200;
public static int BaudRate230400 = 230400;
Thread ReadThread;
Queue<SendObject> sendQueue = new Queue<SendObject>();
public event CRLFEventHandler CRLFEEvent;
public event CheckStringEventHandler CheckStringEvent;
//connect com if possible
public void ConnectDefaultCom(String deviceName, int targetBaudrate)
{
if (!IsConnected)
{
SetCom(GetDeviceCom(deviceName), targetBaudrate);
}
}
//get com friend name list
public static ArrayList GetDeviceNames()
{
var deviceNameList = new System.Collections.ArrayList();
var check = new System.Text.RegularExpressions.Regex("(COM[1-9][0-9]?[0-9]?)");
ManagementClass mcPnPEntity = new ManagementClass("Win32_PnPEntity");
ManagementObjectCollection manageObjCol = mcPnPEntity.GetInstances();
//全てのPnPデバイスを探索しシリアル通信が行われるデバイスを随時追加する
foreach (ManagementObject manageObj in manageObjCol)
{
//Nameプロパティを取得
var namePropertyValue = manageObj.GetPropertyValue("Name");
if (namePropertyValue == null)
{
continue;
}
//Nameプロパティ文字列の一部が"(COM1)~(COM999)"と一致するときリストに追加"
string name = namePropertyValue.ToString();
if (check.IsMatch(name))
{
deviceNameList.Add(name);
}
}
return deviceNameList;
}
//Get com friend name by com1
public static string GetDeviceName(String com)
{
var deviceNameList = GetDeviceNames();
var check = new System.Text.RegularExpressions.Regex("("+com+")");
String deviceName = "";
//戻り値作成
if (deviceNameList.Count > 0)
{
string[] deviceNames = new string[deviceNameList.Count];
int index = 0;
foreach (var name in deviceNameList)
{
if (check.IsMatch(name.ToString()))
{
deviceName = name.ToString();
break;
}
}
}
return deviceName;
}
//Get com by friend name
public static string GetDeviceCom(String deviceName)
{
var deviceNameList = GetDeviceNames();
var check = new System.Text.RegularExpressions.Regex(deviceName);
String com = "";
//戻り値作成
if (deviceNameList.Count > 0)
{
string[] deviceNames = new string[deviceNameList.Count];
foreach (var name in deviceNameList)
{
if (check.IsMatch(name.ToString()))
{
String deviceFullName = name.ToString();
com = deviceFullName.Substring(deviceFullName.IndexOf("(COM")+1,5);
com = com.Replace(")", "");
break;
}
}
}
return com;
}
public static void ListParity(ComboBox cb)
{
foreach (string parity in Enum.GetNames(typeof(Parity)))
{
cb.Items.Add(parity);
cb.SelectedIndex = 0;
}
}
public static void ListHandshake(ComboBox cb)
{
foreach (string name in Enum.GetNames(typeof(Handshake)))
{
cb.Items.Add(name);
cb.SelectedIndex = 0;
}
}
public static void ListStopBits(ComboBox cb)
{
foreach (string name in Enum.GetNames(typeof(StopBits)))
{
if (name == "None")
continue;
cb.Items.Add(name);
}
cb.SelectedIndex = 1;
}
public static void ListDataBit(ComboBox cb)
{
cb.Items.Add("5");
cb.Items.Add("6");
cb.Items.Add("7");
cb.Items.Add("8");
cb.SelectedIndex = 3;
}
public static void ListBaudRate(ComboBox cb)
{
cb.Items.Add(BaudRate9600.ToString());
cb.Items.Add(BaudRate19200.ToString());
cb.Items.Add(BaudRate38400.ToString());
cb.Items.Add(BaudRate57600.ToString());
cb.Items.Add(BaudRate115200.ToString());
cb.Items.Add(BaudRate230400.ToString());
cb.SelectedIndex = 0;
}
public static void ListCom(ComboBox cb)
{
string[] ports = SerialPort.GetPortNames();
cb.Items.Clear();
for (int i = 0; i < ports.Count(); i++)
{
cb.Items.Add(ports[i]);
cb.SelectedIndex = 0;
}
}
public static int GetDataBitByComboBoxIndex(int index)
{
ComboBox cb = new ComboBox();
ListDataBit(cb);
cb.SelectedIndex = index;
return Int16.Parse(cb.Text);
}
public static int GetBaudRateByComboBoxIndex(int index)
{
ComboBox cb = new ComboBox();
ListBaudRate(cb);
cb.SelectedIndex = index;
return Int32.Parse(cb.Text);
}
public static string GetComByComboBoxIndex(int index)
{
string[] ports = SerialPort.GetPortNames();
return ports[index];
}
public bool IsOpen()
{
bool isOpen = true;
if (mySerialPort == null || !mySerialPort.IsOpen)
{
isOpen = false;
}
return isOpen;
}
public void SetCom(ComboBox comport, ComboBox baudRate)
{
SetCom(comport.Text, Int16.Parse(baudRate.Text));
}
public void SetCom(String comport, int baudRate)
{
//SetCom(comport, baudRate, false, false);
SetCom(comport, baudRate, true, true);
}
public void SetCom(String comport, int baudRate, StopBits stopBits, int dataBits, Parity parity, Handshake handshake, bool rts, bool dtr)
{
IsConnected = false;
try
{
Stop();
if ((comport.Length < 4))
return;
if ((comport.Substring(0, 3) != "COM"))
return;
mySerialPort = new SerialPort(comport);
mySerialPort.BaudRate = baudRate;
mySerialPort.Parity = parity;
mySerialPort.DataBits = dataBits;
mySerialPort.Handshake = handshake;
mySerialPort.RtsEnable = rts;
mySerialPort.DtrEnable = dtr;
//mySerialPort.StopBits = StopBits.One;
mySerialPort.StopBits = stopBits;
mySerialPort.Open();
StartReadThread();
IsConnected = true;
}
catch (Exception ex)
{
FileUtil.Write(ex.ToString());
Stop();
//MessageBox.Show(String.Format("{0} 無法連線!", comport));
}
}
public void SetCom(String comport, int baudRate, bool rts, bool dtr)
{
SetCom(comport, baudRate, StopBits.One, 8 ,Parity.None, Handshake.None, rts, dtr);
}
// This method will be called when the thread is started.
public Byte[] ReadBytes()
{
Byte[] byteArray = new Byte[mySerialPort.BytesToRead];
mySerialPort.Read(byteArray, 0, byteArray.GetLength(0));
ReceiveByteArray = AddByteArray(ReceiveByteArray, byteArray);
return ReceiveByteArray;
}
public byte[] AddByteArray(byte[] one, byte[] two)
{
List<byte> list1 = new List<byte>(one);
List<byte> list2 = new List<byte>(two);
list1.AddRange(list2);
return list1.ToArray();
}
public void StartReadThread()
{
ReadThread = new Thread(ReadForThread);
ReadThread.Start();
}
public void StopReadThread( )
{
if (ReadThread != null)
{
ReadThread.Abort();
}
}
public void ReadForThread()
{
String debugSTR = "";
try
{
byte[] tmpByteArray = new byte[0];
while (true)
{
//ReadBytes();
tmpByteArray = ReadBytes();
//check crlf
string decodeString = System.Text.Encoding.ASCII.GetString(tmpByteArray);
if (tmpByteArray.Length > 0)
{
int i = 0;
}
if (CheckCRLF && decodeString.IndexOf("\r\n") >= 0)
{
ReceiveByteArray = new byte[0];
//觸發事件
CRLFEventArgs sampleEventArgs = new CRLFEventArgs(decodeString);
CRLFEEvent(this, sampleEventArgs);
}
if (CheckTargetString.Length > 0 && decodeString.IndexOf(CheckTargetString) >= 0)
{
ReceiveByteArray = new byte[0];
//觸發事件
CheckStringEventArgs sampleEventArgs = new CheckStringEventArgs();
CheckStringEvent(this, sampleEventArgs);
}
Thread.Sleep(100);
debugSTR = decodeString;
}
}
catch (Exception ex)
{
FileUtil.Write(ex.ToString());
}
}
public String GetReadString()
{
string readString = System.Text.Encoding.Default.GetString(ReceiveByteArray);
ReceiveByteArray = new byte[0];
return readString;
}
public byte[] GetReceiveByteArray()
{
byte[] tmp = ReceiveByteArray;
ReceiveByteArray = new byte[0];
return tmp;
}
public void write(String sendString)
{
//byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(sendString);
byte[] byteArray = Encoding.ASCII.GetBytes(sendString);
// Encoding.ASCII.GetBytes(dataToCalculate)
write(byteArray);
}
public void write(byte sendByte)
{
byte[] byteArray = { sendByte };
write(byteArray);
}
// データ送信を行う
public void write(byte[] buffer)
{
//! シリアルポートをオープンしていない場合、処理を行わない.
if (mySerialPort == null)
{
return;
}
if (mySerialPort.IsOpen == false)
{
return;
}
//! 送信するテキストがない場合、データ送信は行わない.
if (buffer == null || buffer.Length == 0)
{
return;
}
try
{
//! シリアルポートからテキストを送信する.
mySerialPort.Write(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
FileUtil.Write(ex.ToString());
}
}
//將等送字元存入Queue
public void writeToQueue(byte[] buffer)
{
String tmp = BitConverter.ToString(buffer);
sendQueue.Enqueue(new SendObject(buffer, 0));
}
//將等送字元存入Queue
public void writeToQueue(byte[] buffer, int delay)
{
String tmp = BitConverter.ToString(buffer);
sendQueue.Enqueue(new SendObject(buffer, delay));
}
//由Queue順序送出
public void writeQueue()
{
while (sendQueue.Count > 0)
{
SendObject cmdObject = sendQueue.Dequeue();
if (cmdObject == null)
continue;
write(cmdObject.SendBytes);
Thread.Sleep(cmdObject.Delay);
}
}
public void Stop()
{
IsConnected = false;
StopReadThread();
if (mySerialPort != null && mySerialPort.IsOpen)
{
mySerialPort.Close();
}
}
}
/// <summary>
/// 要由傳Com port傳送的Byte
/// </summary>
public class SendObject
{
public byte[] SendBytes;
public int Delay = 0;
public SendObject(byte[] sendBytes, int delay)
{
SendBytes = sendBytes;
Delay = delay;
}
}
//Use sample
// ComUtil.ListCom(comboBoxPlcCom);
// ComUtil.ListBaudRate(comboBoxBauRate);
// private void buttonConnectPLC_Click(object sender, EventArgs e)
//{
// if (IsConnection)
// {
// comUtil.Stop();
// buttonConnectPLC.Text = "連線";
// IsConnection = false;
// ConnectionUIEnable(true);
// }
// else
// {
// comUtil.SetCom(comboBoxPlcCom, comboBoxBauRate);
// buttonConnectPLC.Text = "離線";
// IsConnection = true;
// ConnectionUIEnable(false);
// }
//}
//private void ConnectionUIEnable(bool enable)
//{
// comboBoxPlcCom.Enabled = enable;
// comboBoxBauRate.Enabled = enable;
//}
}
留言
張貼留言