public void Listener() { string str = ""; System.IO.Ports.SerialPort spListner = new System.IO.Ports.SerialPort(); spListner.PortName = "COM5"; spListner.BaudRate = 9600; spListner.Open(); while (spListner.BytesToRead > 0) { str = spListner.ReadLine(); textBox1.AppendText(str); } }
public void SetMode(int TransferMode) { transferMode = TransferMode; if (isConnected) { StopCommunication(); } if (transferMode == Constants.TransferMode.USB) { int test = GetUsbDeviceComport("Ba-Robot"); comport = test; if (comport != 0) { isValidTransferMode = true; serialPort = new System.IO.Ports.SerialPort("COM" + comport.ToString(), baudrate); } } else if (transferMode == Constants.TransferMode.COM) { isValidTransferMode = false; comport = 0; } else { isValidTransferMode = false; transferMode = Constants.TransferMode.COM; comport = -1; serialPort = new System.IO.Ports.SerialPort(); } }
private void TryOpenPort() { if (_port == null) { _port = new System.IO.Ports.SerialPort(); } else if (_port.IsOpen) { return; } _port.PortName = _portName; _port.BaudRate = _portSpeed; _port.ReadTimeout = 1000; _port.ReadBufferSize = 100; try { _port.Open(); } catch (Exception ex) { #region debug debugger.WriteLine(Debugger.DebugLevel.DebugDevice, "TryOpenPort: Cannot open \"{0}\", ex: {1}", _portName, ex.Message); #endregion throw; } }
/// <summary> /// 按照默认波特率打开串口 /// </summary> private void CreateOpenPort(string _baudRate) { int rate = int.Parse(_baudRate); // 默认:9600,无校验, 8数据位,1停止位 if (CompassModulePort == null) { CompassModulePort = new System.IO.Ports.SerialPort(PortName, rate, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); } // 重新创建新的串口 else if (PortName != CompassModulePort.PortName) { CompassModulePort.Close(); CompassModulePort.Dispose(); CompassModulePort = new System.IO.Ports.SerialPort(PortName, rate, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); } // 重新设置波特率 else if (CompassModulePort.BaudRate != rate) { // 需要重新打开。 CompassModulePort.Close(); CompassModulePort.BaudRate = rate; } if (CompassModulePort.IsOpen == false) { CompassModulePort.ReadTimeout = 1000; CompassModulePort.Open(); } }
public GPS(string strPortName, int baudRate) { Data = new GPSData(); Port = new System.IO.Ports.SerialPort(strPortName, baudRate); Port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialDataReceived); }
/// <summary> /// 尝试连接 /// </summary> /// <returns></returns> public bool Connect() { if (connected) { return(true); } serialPort = new System.IO.Ports.SerialPort(portName); try { serialPort.BaudRate = 38400; serialPort.Open(); serialPort.DataReceived += SerialPort_DataReceived; connected = true; LastReciveTransID = 0; LastSendTransID = 0; } catch (Exception ex) { if (serialPort.IsOpen) { serialPort.Close(); } connected = false; throw ex; } return(connected); }
//====================================================================== //函数名称:frm_uart_Load //函数返回:无 //参数说明:无 //功能概要:窗体加载事件,窗体加载时自动调用 //====================================================================== private void frm_uart_Load(object sender, EventArgs e) { //(1)变量申明 string com; //(1)设置允许跨线程操作UI控件 System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; //(2)获得主页面窗体 fmain = (frm_main)this.MdiParent; //(3)更新状态提示信息 fmain.lbl_status.Text = "运行状态:frm_uart_Load函数开始,寻找终端节点..."; //(4)调用pcNode类中的函数,寻找下位机,并更新设备连接状态信息 if (uart != null && uart.IsOpen) { uart.close(); } com = pcNode.findPCNode(); uart = pcNode.PCNode_Uart; fmain.lbl_status.Text = "运行状态:找到" + com; lbl_uart_state.Text = com; //(5)绑定DataReceived事件(即串口接收中断处理函数) if (uart != null) { uartPort = uart.port; uartPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.uartPort_recvData); uart.setReceInt(500); //相当于关闭串口中断 this.btn_autoUpdate.Enabled = true; } //(6)修改其他提示信息 fmain.lbl_protocal.Text = "协议:串口"; fmain.lbl_protocalinfo.Text = "协议信息:端口" + com + ",波特率9600"; }
public void RefreshPorts() { var foundPorts = new List <System.IO.Ports.SerialPort> (); var bauds = new [] { 4800, 9600, 19200, 38400, 57600, 115200, 230400 }; var names = System.IO.Ports.SerialPort.GetPortNames(); foreach (var name in names) { var port = new System.IO.Ports.SerialPort(name); foreach (var rate in bauds) { var expectedString = "AS5048B"; var expectedBuffer = expectedString.ToCharArray(); var actualBuffer = new char[expectedString.Length]; port.BaudRate = rate; var read = port.Read(actualBuffer, 0, buffer.Length); if (read == 7) { try { var actualString = new string (actualBuffer); if (actualString.Equals(expectedString)) { foundPorts.Add(port); } } catch { } } } } }
private void Button_PPMS_Serial_Connect_Click(object sender, RoutedEventArgs e) { try { myparts.myDialog dlg = new myparts.myDialog("シリアルポートに接続します"); if (dlg.ShowDialog() != true) { return; } this.serialport = new System.IO.Ports.SerialPort("COM" + this.TextBox_PPMS_COMPORT.Text, int.Parse(this.TextBox_PPMS_BaudRate.Text), System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); this.serialport.Encoding = Encoding.ASCII; byte[] endsign = { 170, 255 }; this.serialport.NewLine = Encoding.ASCII.GetString(endsign, 0, 1); this.serialport.Open(); this.fps = new FPSAdjuster.FPSAdjuster(); fps.Fps = int.Parse(this.TextBox_PPMS_FPS.Text); fps.Start(); this.CTS = new CancellationTokenSource(); this.maintask = new Task(new Action(this.MainTask_PPMS), this.CTS.Token); this.maintask.Start(); } catch (Exception ex) { myparts.myDialog dlg = new myparts.myDialog(ex.Message); dlg.ShowDialog(); } }
// Serial port event handler for a nice event-driven architecture private void DataReceivedHandler( object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender; Byte[] inData = new Byte[sp.BytesToRead]; // read all available bytes from serial port in one chunk sp.Read(inData, 0, sp.BytesToRead); // DEBUG: display bytes read //ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("<= RX ({0}) [ {1}]", inData.Length, ByteArrayToHexString(inData)) + Environment.NewLine); }); String logText = String.Format("<= RX ({0}) [ {1}]", inData.Length, ByteArrayToHexString(inData)) + Environment.NewLine; if (debug) { SetLogText(logText); } // parse all bytes read through BGLib parser for (int i = 0; i < inData.Length; i++) { bglib.Parse(inData[i]); } }
void connectSerialInterfase() { if (serialInitializeFlag == false) { serialInitializeFlag = true; } else { setDebugPrint("[ INFO ] COM PORT ( " + serialPort.PortName + " ) を切断します."); serialOpenFlag = false; serialPort.Close(); } var selectSerialWindow = new selectSerialPort(); selectSerialWindow.MainWindowPointer = this; selectSerialWindow.Show(); //取り敢えずCOM18に設定 serialPort = new System.IO.Ports.SerialPort("COM18", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); serialPort.NewLine = Environment.NewLine; serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceivedHandler); controlInitBtn.IsEnabled = false; controlUpdateBtn.IsEnabled = false; controlNextBtn.IsEnabled = false; }
private void Form1_Load(object sender, EventArgs e) { watch = Stopwatch.StartNew(); try { /* * System.IO.Ports.SerialPort tempSerial = new System.IO.Ports.SerialPort(); * * // Mostly default settings for the serialport except for the PortName which is whatever the user chose. * tempSerial.BaudRate = 9600; * tempSerial.PortName = Properties.Settings.Default["CurrentCOMPort"].ToString(); * tempSerial.DataBits = 8; * tempSerial.DtrEnable = false; * tempSerial.Handshake = System.IO.Ports.Handshake.None; * tempSerial.Parity = System.IO.Ports.Parity.None; * tempSerial.ParityReplace = 63; * tempSerial.ReadBufferSize = 4096; * tempSerial.ReadTimeout = -1; * tempSerial.ReceivedBytesThreshold = 1; * tempSerial.WriteBufferSize = 2048; * * tempSerial.Open(); * * // Assign the correctly configured serial port to the uninitialized serialport * SerialPort = tempSerial; */ serialPort1.Open(); SerialPort = serialPort1; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Open the requested COM port when the user clicks an item in the "Serial" menu /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void serialToolStripItem_Click(object sender, ToolStripItemClickedEventArgs e) { serial = new System.IO.Ports.SerialPort(e.ClickedItem.Text, 9600); ToolStripMenuItem item = (ToolStripMenuItem)sender; try { serial.Open(); item.CheckOnClick = true; item.Checked = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } // Uncheck all other items in menu foreach (var menuItem in serialToolStripMenuItem.DropDown.Items) { ToolStripMenuItem menuItem2 = (ToolStripMenuItem)menuItem; if (menuItem2 != item) { menuItem2.Checked = false; } } }
/// <summary> /// 获得串口的数据 /// </summary> /// <returns></returns> public static byte[] GetSerialPortRecvData(System.IO.Ports.SerialPort serialPort) { byte[] outData = new byte[0]; try { int iCanReadBytes = 0; int newICanReadBytes = 0; do { iCanReadBytes = serialPort.BytesToRead; //稍等一下,等串口上的数据传输完 System.Threading.Thread.Sleep(delayTime); newICanReadBytes = serialPort.BytesToRead; } while (iCanReadBytes != newICanReadBytes);//判断是否接收完毕 if (iCanReadBytes <= 0) { return(outData); } //接收报文 outData = new byte[iCanReadBytes]; serialPort.Read(outData, 0, outData.Length); return(outData); } catch (System.Exception ex) { throw ex; } }
/** entry point of the application */ public static void Main() { /* temporary array */ byte[] scratch = new byte[1]; /* open the UART, select the com port based on the desired gadgeteer port. * This utilizes the CTRE.IO Library. * The full listing of COM ports on HERO can be viewed in CTRE.IO * */ _uart = new System.IO.Ports.SerialPort(CTRE.HERO.IO.Port1.UART, 115200); _uart.Open(); /* send a message to the terminal for the user to see */ _uart.Write(_helloMsg, 0, _helloMsg.Length); /* loop forever */ while (true) { /* read bytes out of uart */ if (_uart.BytesToRead > 0) { int readCnt = _uart.Read(_rx, 0, CalcRemainingCap() ); for (int i = 0; i < readCnt; ++i) { PushByte(_rx[i]); } } /* if there are bufferd bytes echo them back out */ if (_uart.CanWrite && (_txCnt > 0) ) { scratch[0] = PopByte(); _uart.Write(scratch, 0, 1); } /* wait a bit, keep the main loop time constant, this way you can add to this example (motor control for example). */ System.Threading.Thread.Sleep(10); } }
public SimpleBarReader() { config = FT.Commons.Cache.StaticCacheManager.GetConfig<BarReaderConfig>(); this.serialPort1=new System.IO.Ports.SerialPort(); this.InitByConfig(); this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived); }
public DongleDevice(string ComPort, int baud) { port = new System.IO.Ports.SerialPort(ComPort, baud, System.IO.Ports.Parity.None); try { if (port.IsOpen) { Console.WriteLine("port is opened"); Console.ReadKey(); } // port.DiscardInBuffer(); // port.DiscardOutBuffer(); port.Open(); // port.DtrEnable = true; port.RtsEnable = true; } catch (Exception ex) { Console.WriteLine(ex.Message + "," + ex.StackTrace); Console.ReadKey(); // Environment.Exit(-1); } this.RecriveThread = new System.Threading.Thread(ReceiveTask); RecriveThread.Start(); }
public GrblCore(System.Windows.Forms.Control syncroObject) { syncro = syncroObject; com = new System.IO.Ports.SerialPort(); TX = new Tools.ThreadObject(ThreadTX, 1, true, "Serial TX Thread", null); RX = new Tools.ThreadObject(ThreadRX, 1, true, "Serial RX Thread", null); file = new GrblFile(); file.OnFileLoaded += RiseOnFileLoaded; mMachineStatus = MacStatus.Disconnected; mQueue = new System.Collections.Generic.Queue <GrblCommand>(); mPending = new System.Collections.Generic.Queue <GrblCommand>(); mSent = new System.Collections.Generic.List <IGrblRow>(); mBuffer = 0; mSentPtr = mSent; mQueuePtr = mQueue; mGrblVersion = null; mCurOvFeed = mCurOvRapids = mCurOvSpindle = 100; mTarOvFeed = mTarOvRapids = mTarOvSpindle = 100; }
static void Main() { serial = new System.IO.Ports.SerialPort("COM1", 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); }
public bool openCom(System.IO.Ports.SerialPort newPort) { ComPort = newPort; ComunicationPort.ComPortSet(newPort); ComunicationPort.ComPortOpen(); return true; }
public static IScaleDataInterpreter GetDataInterpreter(Int32 type, System.IO.Ports.SerialPort port) { mSerialPort = port; IScaleDataInterpreter scaleDataInterpreter; switch (type) { case (int)ScaleBrandType.YH: scaleDataInterpreter = new YaoHuanDataInterpreter(); break; case (int)ScaleBrandType.LBKL: scaleDataInterpreter = new LBKLDataInterpreter(); break; case (int)ScaleBrandType.TLD: scaleDataInterpreter = new TLDDataInterpreter(); break; case (int)ScaleBrandType.SDLS: scaleDataInterpreter = new SDLSDataInterpreter(); break; default: scaleDataInterpreter = new NotSuporInterprete(); break; } return(scaleDataInterpreter); }
/// <summary> /// Overload Constructor /// </summary> /// <param name="SerialPortNumber"></param> /// <param name="SerialBaudRate"></param> public clsSLM(int SerialPortNumber, long SerialBaudRate) { m_iCommPortNumber = SerialPortNumber; m_lCommBaudRate = SerialBaudRate; m_serport = new System.IO.Ports.SerialPort(); }
/// ------------------------------------------------------------------------------ /// <summary> /// 功 能:打开串口 /// </summary> /// <param name="portName">串口名</param> /// <param name="baudRate">波特率</param> /// <returns>true:打开成功;false:打开失败</returns> /// ----------------------------------------------------------------------------- private bool open(string portName, int baudRate = 9600) { if (_Uartport != null && _Uartport.IsOpen) { _Uartport.Close(); Thread.Sleep(20); } _Uartport = new System.IO.Ports.SerialPort(); _Uartport.PortName = portName; //设置串口号 _Uartport.BaudRate = baudRate; //设置波特率 _Uartport.Parity = System.IO.Ports.Parity.None; //设置无奇偶校验 _Uartport.DataBits = 8; //设置8比特数据位 _Uartport.StopBits = System.IO.Ports.StopBits.One; //设置1位停止位 _Uartport.ReadBufferSize = ReadBufferSize; //接收缓冲区大小(字节) _Uartport.WriteBufferSize = WriteBufferSize; //发送缓冲区大小(字节) _Uartport.ReceivedBytesThreshold = 1; //设置串口触发条件 try { _Uartport.Open(); } catch (Exception ex) { //MessageBox.Show(ex.Message); return(false); } return(true); }
private bool Serial_Write_String(System.IO.Ports.SerialPort Serial, string myOutput) { int x; if (Serial.IsOpen) { for (x = 0; x < myOutput.Length; x++) { try { Serial.Write(myOutput.Substring(x, 1)); } catch (Exception ex) { //clsGlobals.log.Error("", ex); mstr_error = "Error: Serial Write String" + "\n" + ex.Message; return(false); } //Add the intercharacter Delay DelayMS(m_iIntercharacterDelay); } } else { return(false); } //After the transmission is done, wait a little longer DelayMS(m_iIntercharacterDelay); return(true); }
private void btnLoad_Click(object sender, EventArgs e) { /*string source = item["source"].InnerText; * string subject = item["subject"].InnerText; * string summary = item["summary"].InnerText; * string date = item["date"].InnerText; * * if (item.Name == "RSSEntry") * { * lstPrincipal.Items.Add(new ListViewItem(new[] { source + " - " + subject, summary, date }, 0)); * } * else if (item.Name == "TwitterEntry") * { * lstPrincipal.Items.Add(new ListViewItem(new[] { source + " - " + subject, summary, date }, 1)); * } * else * { * lstPrincipal.Items.Add(new ListViewItem(new[] { source + " - " + subject, summary, date }, 2)); * }*/ string state = "Nsadasdsadsa"; string location = "Kitchenasdadasdasdsadsadasdsadsa"; string val; string val2; serialPort1 = new System.IO.Ports.SerialPort("COM8", 9600); serialPort2 = new System.IO.Ports.SerialPort("COM9", 9600); serialPort2.PortName = "COM9"; serialPort2.BaudRate = 9600; serialPort1.Open(); val = serialPort1.ReadLine(); serialPort1.Close(); /*serialPort2.Open(); * val2 = serialPort2.ReadLine(); * serialPort2.Close();*/ if (Convert.ToInt32(val) == 0) { lstSensors.Items.Add(new ListViewItem(new[] { "No Leak", serialPort1.PortName }, 0)); } else { lstSensors.Items.Add(new ListViewItem(new[] { "Leak!", serialPort1.PortName }, 1)); } /*if (Convert.ToInt32(val2) == 0) * { * lstSensors.Items.Add(new ListViewItem(new[] { "No Leak", serialPort2.PortName }, 0)); * } * else * { * lstSensors.Items.Add(new ListViewItem(new[] { "Leak!", serialPort2.PortName }, 1)); * }*/ lstSensors.Items.Add(new ListViewItem(new[] { state, location }, 1)); }
private bool Serial_Write_Byte(System.IO.Ports.SerialPort Serial, byte myOutput) { byte[] temp = new byte[2]; temp[0] = myOutput; temp[1] = 0; if (Serial.IsOpen) { try { Serial.Write(temp, 0, 1); } catch (Exception ex) { //clsGlobals.log.Error("", ex); mstr_error = "Error: Serial Write Byte" + "\n" + ex.Message; return(false); } //Add the intercharacter Delay DelayMS(m_iIntercharacterDelay); } else { return(false); } //After the transmission is done, wait a little longer DelayMS(m_iIntercharacterDelay); return(true); }
// 打印 //打印文字(端口号 字符) public void PrintString(int Port, string val) { System.IO.Ports.SerialPort sp = new System.IO.Ports.SerialPort(); sp.PortName = "COM" + Port.ToString(); try { sp.Open(); } catch { throw new AppException("端口被占用"); } List <byte> data = new List <byte>(); string[] lines = val.Split('\n'); for (int i = 0; i < lines.Length; i++) { byte[] content = System.Text.Encoding.Default.GetBytes(lines[i].Replace("\r", "")); byte[] wapbt = { 0x0a }; data.AddRange(content); data.AddRange(wapbt); } byte[] cutbt = { 0x1d, 0x56, 0x42, 0x11 }; data.AddRange(cutbt); byte[] databt = data.ToArray(); sp.Write(databt, 0, databt.Length); sp.Close(); }
private bool Serial_Wait_For_ACK(System.IO.Ports.SerialPort Serial, double TimeoutmSeconds) { System.DateTime myTime = new DateTime(); int myRead; myTime = System.DateTime.Now.AddMilliseconds(TimeoutmSeconds); while (myTime > System.DateTime.Now) { //Only read if there is something in the buffer if (Serial.IsOpen && Serial.BytesToRead > 0) { myRead = Serial.ReadByte(); if (myRead == 6) //ACK { return(true); } else if (myRead == 21) //NAK { return(false); } } } return(false); }
public static void UploadData(string comPort, int baudRate) { System.IO.Ports.SerialPort Com = new System.IO.Ports.SerialPort(comPort, baudRate, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.Two); byte[] Data = GetBytesFromCurrentImage(); // Get image data for sending Com.Open(); //Open port for transfering data //Setting timeout for writing and reading for 5 seconds Com.ReadTimeout = 5000; Com.WriteTimeout = 5000; //Handshaking Com.Write("A"); //Acknowledge from the microcontroller Com.ReadByte(); int offset = 0; //Sending data to the com port while (offset < 32 * 360) { //Sending 4 column at a time Com.Write(Data, offset, 32 * 4); //Waiting for ackknowledge Com.ReadByte(); offset += 32 * 4; } Com.Close(); //Close port }
private bool Serial_Wait_For_String(System.IO.Ports.SerialPort Serial, string MyString, double TimeoutmSeconds) { System.DateTime myTime = new DateTime(); int myRead; string temp = ""; myTime = System.DateTime.Now.AddMilliseconds(TimeoutmSeconds); while (myTime > System.DateTime.Now) { //Only read if there is something in the buffer if (Serial.IsOpen && Serial.BytesToRead > 0) { myRead = Serial.ReadByte(); temp = temp + (char)myRead; if (temp.Contains(MyString)) { return(true); } } } return(false); }
private void load_window(object sender, RoutedEventArgs e) { //Esto es opcional pero ayuda a colocar el dispositivo Kinect a un cierto angulo de inclinacion, desde -27 a 27 ArduinoPort = new System.IO.Ports.SerialPort(); ArduinoPort.PortName = "COM3"; //sustituir por vuestro ArduinoPort.BaudRate = 9600; ArduinoPort.Open(); this.isGrip = false; //miKinect.Stop(); this.miKinect = KinectSensor.KinectSensors[0]; //this.sensorChooser.sensor.Kinect;// miKinect.SkeletonStream.Enable(); miKinect.ColorStream.Enable(); this.miKinect.Start(); miKinect.ElevationAngle = 15; this.miKinect.Stop(); sensorChooser = new KinectChooser(this.kinectRegion, this.sensorChooserUi); // miKinect.ColorFrameReady += miKinect_ColorFrameReady; // miKinect.SkeletonFrameReady += miKinect_SkeletonFrameReady; // AsyncCallback callBack = new AsyncCallback(OnQuery); // KinectRegion.AddQueryInteractionStatusHandler(this.kinectRegion, OnQuery); miKinect.ColorFrameReady += miKinect_ColorFrameReady; Task t1 = Task.Run(() => KinectRegion.AddQueryInteractionStatusHandler(this.kinectRegion, OnQuery)); Task t2 = Task.Run(() => miKinect.SkeletonFrameReady += miKinect_SkeletonFrameReady); // Task t3 = Task.Run(() =>this.dist.Text = ArduinoPort.ReadByte().ToString()); }
private int Data_RemainingBytes; // remaining bytes yet to be received for the message being currently received #endregion Fields #region Constructors // constructor #1 (commport identified with its number) public IMUCommsDevice(int CommPortID) { // 1. Initializing Commport CommPort = new System.IO.Ports.SerialPort("COM" + Convert.ToString(CommPortID)); //CommPort.BaudRate = Serial_BaudRate_Standard; CommPort.BaudRate = Serial_BaudRate_Standard; CommPort.WriteBufferSize = 10000; //CommPort.ReadBufferSize = Serial_MaxNumMsgInBuffer * IMUMessage.c_MessageLength; CommPort.Parity = System.IO.Ports.Parity.None; CommPort.Handshake = System.IO.Ports.Handshake.RequestToSend; CommPort.StopBits = System.IO.Ports.StopBits.Two; CommPort.ReadBufferSize = 10000; CommPort.ReceivedBytesThreshold = 20; // 2. Initializing state to St_Idle //State = St_Idle; // 3. The device is disabled Flag_CommsActive = false; // 4. Creating an empty Message queue // MessageQueue = new IMUMessageQueue(); // setting last nknown readings to zero Last_Acc1 = Last_Acc2 = Last_Acc3 = Last_Angvel1 = Last_Angvel2 = Last_Angvel3 = 0; // create the queue semaphore //MsgQueueSemaphore = new Semaphore(1, 1); }
public ValuesController() { Arduino = new System.IO.Ports.SerialPort(); Arduino.PortName = "COM4"; Arduino.BaudRate = 9600; Arduino.Open(); }
public MeterBusStream(SettingsSerial settings) { System.IO.Ports.SerialPort serialPort = new System.IO.Ports.SerialPort(settings.PortName, settings.BaudRate, settings.Parity, settings.DataBits, settings.StopBits); objectsToDispose.Add(serialPort); serialPort.Open(); this.stream = serialPort.BaseStream; }
//发送短信 private void SendMessage(String target, String content) { System.IO.Ports.SerialPort serial = new System.IO.Ports.SerialPort(); serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = System.IO.Ports.Parity.None; serial.PortName = "COM4"; serial.StopBits = System.IO.Ports.StopBits.One; if (!serial.IsOpen) { serial.Open(); } serial.DiscardInBuffer(); PDU sms = new PDU(); sms.setCenter("+8613800571500"); sms.setTarget(target); sms.setMessage(content); System.Threading.Thread.Sleep(200); serial.Write("AT\r\n"); System.Threading.Thread.Sleep(200); serial.WriteLine("AT+CMGF=0\r\n"); System.Threading.Thread.Sleep(200); serial.WriteLine("AT+CMGS=" + sms.getPureLength().ToString() + "\r\n"); System.Threading.Thread.Sleep(200); serial.WriteLine(sms.getPDUCode() + Encoding.ASCII.GetString(new byte[] { (byte)26 })); System.Threading.Thread.Sleep(2000); serial.Close(); }
public static bool SerialPortAvailable() { try { //Debug.Log("Trying to open serial port"); var sp = new System.IO.Ports.SerialPort(); sp.BaudRate = 57600; sp.PortName = "/dev/null"; sp.Open(); sp.Close(); //Debug.Log("Succeeded...sp support ok"); return true; } catch (Exception e) { //Debug.Log(e.GetType().FullName); if ( e.GetType().FullName.Contains("DllNotFoundException") // libary not present || e.GetType().FullName.Contains("NotInstalledException")) // proxy not removed { Debug.Log(e.GetType().FullName); //Debug.Log("DllNotFoundException caught..."); Debug.Log(e.Message + "\n" + e.StackTrace); Debug.LogWarning("SerialPort support not found. Uniduino will not function until you use the Install button in the Uniduino Setup utility under Window/Uniduino"); return false; } } return true; }
//Criar uma instância de um portSerial com as características default //definidas em MipUsbComConstants private void createDefaultComPort() { if (serialPort != null) { return; } //criar uma instancia da classe portSerial serialPort = new System.IO.Ports.SerialPort(); //ajustar propriedades default do port serialPort.PortName = TeensyUsbComConstants.PortName; serialPort.BaudRate = TeensyUsbComConstants.BaudRate; serialPort.DataBits = TeensyUsbComConstants.DataBits; serialPort.StopBits = TeensyUsbComConstants.StopBits; serialPort.DtrEnable = TeensyUsbComConstants.DtrEnable; serialPort.RtsEnable = TeensyUsbComConstants.RtsEnable; serialPort.Handshake = TeensyUsbComConstants.Handshake; serialPort.Parity = TeensyUsbComConstants.Parity; serialPort.ParityReplace = TeensyUsbComConstants.ParityReplace; serialPort.ReadBufferSize = TeensyUsbComConstants.ReadBufferSize; serialPort.ReadTimeout = TeensyUsbComConstants.ReadTimeOut; serialPort.ReceivedBytesThreshold = TeensyUsbComConstants.ReceivedBytesThreshold; serialPort.WriteBufferSize = TeensyUsbComConstants.WriteBufferSize; serialPort.WriteTimeout = TeensyUsbComConstants.WriteTimeout; serialPort.Encoding = Encoding.GetEncoding(TeensyUsbComConstants.Encoding); serialPort.NewLine = TeensyUsbComConstants.StringEndMsg; }
public SerialPort() { m_port = new System.IO.Ports.SerialPort(); m_port.ErrorReceived += this.Port_ErrorReceived; m_port.DataReceived += this.Port_DataReceived; m_port.Encoding = new ASCIIEncoding(); }
//====================================================================== //函数名称:btn_uartcheck_Click //函数返回:无 //参数说明:无 //功能概要:“重新连接”按钮点击事件,实现上位机与终端的重新连接操作 //====================================================================== private void btn_uartcheck_Click(object sender, EventArgs e) { //(1)变量申明 string com; //(2)更新状态提示信息 fmain.lbl_status.Text = "运行状态:单机“重新连接”按钮..."; //(3)重新遍历串口,寻找下位机 if (uart != null && uart.IsOpen) { uart.close(); } com = pcNode.findPCNode(); uart = pcNode.PCNode_Uart; fmain.lbl_status.Text = "运行状态:找到" + com; lbl_uart_state.Text = com; //(4)重新绑定DataReceived事件(即串口接收中断处理函数) if (uart != null) { uartPort = uart.port; uartPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.uartPort_recvData); //先移除委托函数,防止多次触发 uartPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.uartPort_recvData); uart.setReceInt(500); //相当于关闭串口中断 this.btn_autoUpdate.Enabled = true; //使能连接终端操作 } else { this.btn_autoUpdate.Enabled = false; //使能连接终端操作 } //(5)修改其他提示信息 fmain.lbl_protocal.Text = "协议:串口"; fmain.lbl_protocalinfo.Text = "协议信息:端口" + com + ",波特率9600"; }
// O evento é gerado quando a serial receber PELO MENOS a quantidade de // bytes definida na propriedade ReceivedBytesThreshold do port. // Nesta aplicação aquele limiar é setado para a mínima quantidade de bytes // que deve ser enviada em cada transação. // DataReceived event is also raised if an Eof character // is received, regardless of the number of bytes in the internal input // buffer and the value of the ReceivedBytesThreshold property. // // Os dados recebidos serão armazenados num buffer circular do objeto // teensyDataObj para tratamento futuro. // //NOTA: The DataReceived event is raised on a secondary thread when data is //received from the SerialPort object. private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { int bytesRead; byte[] dataSerial; //Garantir que este evento foi gerado pelo port do Teensy que estamos usando. System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender; if (sp.PortName != serialPort.PortName) { return; } //o buffer temporário deve ser capaz de armazenar todos os byter no receiving buffer da serial dataSerial = new byte[serialPort.ReadBufferSize]; //buffer para conter dados sendo recebidos pela USB até a chegada completa do pacote. bytesRead = sp.Read(dataSerial, 0, sp.BytesToRead); //transferir todos os bytes recebidos para o buffer circular de teensyDataObj for (int i = 0; i < bytesRead; i++) { teensyDataObj.serialDataBC.write(dataSerial[i]); } }
public void Close() { if (port != null) { port.Close(); port = null; } }
//The Constructor: public SerialUtilities() { spIOPort = new System.IO.Ports.SerialPort(); SerialOut = new Queue<String>(); //Define Events + Link Handlers: spIOPort.DataReceived += spIOPort_DataReceived; spIOPort.ErrorReceived += spIOPort_ErrorReceived; }
public FormMain() { InitializeComponent(); // // serialPort // this.serialPort = new System.IO.Ports.SerialPort(); this.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived); }
public static void Main() { port = new System.IO.Ports.SerialPort("Com3", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); port.Close(); port.Open(); while (true) { OutputWeather(ConvertWeatherInput(port.ReadLine())); } }
public Sim900Modem(int port, GTM.Display_HD44780 display) { this.display = display; socket = GT.Socket.GetSocket(port, true, null, null); powerPin = new GTI.DigitalOutput(socket, GT.Socket.Pin.Three, false, null); serial = new System.IO.Ports.SerialPort("COM2", 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); serial.ReadTimeout = 1000; serial.Open(); bufferd = new byte[32]; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //定义串口 System.IO.Ports.SerialPort comm = new System.IO.Ports.SerialPort(); Application.Run(new Start(comm)); }
public void Connect(string portName, int baudRate) { Close(); port = new System.IO.Ports.SerialPort(); port.PortName = portName; port.BaudRate = baudRate; port.Open(); // initialize mavlink. port.Write("sh /etc/init.d/rc.usb\n"); }
private void Init_Classes() { this.serialport = new System.IO.Ports.SerialPort("COM10", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); this.serialport.Encoding = Encoding.ASCII; this.serialport.Open(); this.CTS = new CancellationTokenSource(); this.maintask = new Task( new Action(MainTask),this.CTS.Token); this.maintask.Start(); }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.robotPort = new System.IO.Ports.SerialPort(this.components); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(12, 12); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "Test"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(93, 12); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(97, 23); this.button2.TabIndex = 1; this.button2.Text = "Walk in square"; this.button2.UseVisualStyleBackColor = true; this.button2.Visible = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // robotPort // this.robotPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.robotPort_DataReceived); // // richTextBox1 // this.richTextBox1.Location = new System.Drawing.Point(12, 40); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size(314, 96); this.richTextBox1.TabIndex = 2; this.richTextBox1.Text = ""; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(338, 148); this.Controls.Add(this.richTextBox1); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "PDACmd"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); }
public ActionResult TurnOn() { var components = new System.ComponentModel.Container(); var arduinoPort = new System.IO.Ports.SerialPort(components) {PortName = "COM7"}; arduinoPort.Open(); string on = "H"; arduinoPort.WriteLine(on); arduinoPort.Close(); return new HttpStatusCodeResult(HttpStatusCode.OK); }
/// <summary> /// Initialized the GUI /// Attempts to open COM 9 by default /// </summary> /// <param name="frmChoose">The parent chooser form</param> public frmTeslaGui(frmChoose frmChoose) { InitializeComponent(); this.chooserForm = frmChoose; updateGUI = new UpdateGUI(this.UpdateGUIFunction); //add the serial port selection to the menu string[] serialPorts = System.IO.Ports.SerialPort.GetPortNames(); foreach (string portName in serialPorts) { COMPortToolStripMenuItem.DropDownItems.Add(portName, null, (object sender, EventArgs e) => { serialPort.PortName = portName; UncheckAllComs(); ((ToolStripMenuItem)sender).Checked = true; }); if (portName == "COM9") { ((ToolStripMenuItem)COMPortToolStripMenuItem.DropDownItems[COMPortToolStripMenuItem.DropDownItems.Count - 1]).Checked = true; } } //set up serial port serialPort = new System.IO.Ports.SerialPort(); if (serialPorts.Contains("COM9")) { serialPort.PortName = "COM9"; } serialPort.BaudRate = 57600; serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived); //Initialize classes antComm = new ANTCommunication(ref serialPort, this); spBuffer = new BufferedReader(this); tempConv = new TempVal(); //Initialize timers flashTimer = new System.Timers.Timer(50); flashTimer.Elapsed += new System.Timers.ElapsedEventHandler(flashTimer_Elapsed); simTimer = new System.Timers.Timer(500); simTimer.Elapsed += new System.Timers.ElapsedEventHandler(simTimer_Elapsed); pastTemps = new Queue<double>(150); //Clear labels lblError.Text = ""; lblLastMessage.Text = ""; //Set up last received lastRecieved = new Dictionary<DataDecoder.SensorType, int>(3); lastRecieved.Add(DataDecoder.SensorType.Temperature, 100); lastRecieved.Add(DataDecoder.SensorType.Accelerometer, 100); lastRecieved.Add(DataDecoder.SensorType.Button, 100); }
public static void Main() { //access weatherboard serial port, com number must be set manually port = new System.IO.Ports.SerialPort(comPort, 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); //port.Close(); //while (port.IsOpen) { }//loop until port is actually closed port.Open(); //set up output file StreamWriter writer = new StreamWriter("C:\\WeatherData.csv", true); writer.WriteLine("Data Start at " + System.DateTime.Now); foreach (string s in WEATHER_BOARD_FIELDS) { writer.Write(s + ","); } writer.WriteLine(); //output data to screen and file string input; string output; double[] data; while (!System.Console.KeyAvailable)//exit loop if any key is pressed { input = port.ReadLine(); data = ConvertWeatherInput(input); //output comma separated values //foreach (double d in data) //{ // writer.Write(d + ","); //} ////add dew point and newline //writer.WriteLine(RSMath.TemperatureMath.getDewPoint(input[2], input[0])); ////flush writer to ensure data is written in case of crash //writer.Flush(); //write output to console window //OutputWeather(data); //wait a half second between logged events System.Threading.Thread.Sleep(2000); } //clean up output file //writer.WriteLine("End of data - file closed normally"); //writer.Close(); //indicate normal close System.Console.WriteLine("Process ended succesfully. Press Return to exit."); System.Console.ReadLine();//empty console input }
public void SetComport(int Port) { if (Port > 0 && Port < 21 && transferMode == Constants.TransferMode.COM) { comport = Port; isValidTransferMode = true; serialPort = new System.IO.Ports.SerialPort("COM" + comport.ToString(), baudrate); } else { comport = -1; } }
public SerialPort([NotNull] string portName) : base(portName) { if (portName == null) throw new ArgumentNullException("portName"); internalPort = new System.IO.Ports.SerialPort(portName) { ReadTimeout = 200, WriteTimeout = 200, Encoding = Encoding, NewLine = LineBreak }; internalPort.Disposed += (s, e) => Dispose(false); internalPort.Open(); }
internal CSharpSerialPortWrapper(string serialPortName) { if (FrostedSerialPortFactory.GetAppropriateFactory("RepRap").IsWindows) { try { SerialPortFixer.Execute(serialPortName); } catch (Exception) { } } port = new System.IO.Ports.SerialPort(serialPortName); }
public SerialService(string namePort) { try { _Port = new System.IO.Ports.SerialPort(namePort); init(); } catch (Exception e) { ErrorMessage = e.Message; Status = false; } Status = true; }
public SerialService(string namePort, int baudRate, System.IO.Ports.Parity parity) { try { _Port = new System.IO.Ports.SerialPort(namePort, baudRate, parity); init(); } catch (Exception e) { ErrorMessage = e.Message; Status = false; } Status = true; }
public XModem(System.IO.Ports.SerialPort port) { //if (sp != null) { try { this.sp = port; if (!sp.IsOpen) sp.Open(); sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(sp_DataReceived); bOpen = true; } catch { } } }
public CtlPacket(System.IO.Ports.SerialPort tPort, ushort addr, UInt16 ctlWord, byte tcnt) { serial = tPort; buffer = new byte[9]; buffer[0] = 0xfe; buffer[1] = 0x09; buffer[2] = 0x05; buffer[3] = (byte)(addr >> 8); //高8位 buffer[4] = (byte)(addr & 0x00FF);//低8位 buffer[5] = (byte)(ctlWord >> 8); ;//高8位 buffer[6] = (byte)(ctlWord & 0x00FF);//低8位 buffer[7] = tcnt; buffer[8] = 0xfb; cnt = tcnt; }
const string VideoFile = @"tohou.mp4"; // Bad apple!! original video (03:39 length) #endregion Fields #region Methods static void Main(string[] args) { var files = Directory.EnumerateFiles(ImagePath).ToList(); var images = files.Select(File.ReadAllBytes).ToArray(); WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer(); player.settings.autoStart = false; player.settings.playCount = 1000; player.URL = VideoFile; Thread.Sleep(1000); // let wmp to finish all the loading shit var com = new System.IO.Ports.SerialPort(PortName, 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); com.Open(); int currentImage = 0; bool isPlaying = false; while (currentImage < images.Length) { com.ReadByte(); if (!isPlaying) { player.controls.play(); isPlaying = true; } var currentPosition = player.controls.currentPosition; currentImage = (int)(FPS * currentPosition); com.Write(images[Math.Min(currentImage, images.Length - 1)], 0, 504); } com.Close(); }