Advertisement
andrewb

Arduino.cs

Apr 30th, 2014
615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using System;
  2. using System.IO.Ports;
  3. using System.Text;
  4.  
  5. namespace ScanAndBlink
  6. {
  7.     class Arduino
  8.     {
  9.         private string _comPort = "";
  10.         private int _baudRate = 9600;
  11.         private int _timeOut = 500;
  12.         private string _test = "";
  13.         private string _confirmation = "";
  14.  
  15.         public string Comport { get { return _comPort; } set { _comPort = value; } }
  16.         public int Baudrate { get { return _baudRate; } set { _baudRate = value; } }
  17.         public int Timeout { get { return _timeOut; } set { _timeOut = value; } }
  18.         public string Test { get { return _test; } set { _test = value; } }
  19.         public string Confirmation { get { return _confirmation; } set { _confirmation = value; } }
  20.  
  21.         public SerialPort New()
  22.         {
  23.             if (CheckForArduino() == true)
  24.             {
  25.                 return new SerialPort(_comPort, _baudRate, Parity.None, 8, StopBits.One);
  26.             }
  27.             else
  28.             {
  29.                 throw new Exception("No Arduino plugged in.");
  30.             }
  31.         }
  32.  
  33.         public bool CheckForArduino()
  34.         {
  35.             string[] sp = SerialPort.GetPortNames();
  36.             foreach (string s in sp)
  37.             {
  38.                 string readback = "";
  39.  
  40.                 SerialPort temp = new SerialPort(s, _baudRate, Parity.None, 8, StopBits.One);
  41.                 temp.ReadTimeout = _timeOut;
  42.                 temp.Open();
  43.                 temp.Write(_test);
  44.                 readback = temp.ReadLine();
  45.                 temp.Close();
  46.                 temp.Dispose();
  47.  
  48.                 if (readback.Substring(0, _confirmation.Length) == _confirmation)
  49.                 {
  50.                     _comPort = s;
  51.                     return true;
  52.                 }
  53.             }
  54.             return false;
  55.         }
  56.  
  57.         public Arduino() { }
  58.         public Arduino(string t, string c) { _test = t; _confirmation = c; }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement