public static bool PLCStop(PPIReadWritePara para) { if (!serialPort1.IsOpen) { serialPort1.Open(); } PPIAddress ppiAddress = new PPIAddress(); ppiAddress.DAddress = Convert.ToByte(para.PlcAddress); serialPort1.DiscardInBuffer(); serialPort1.DiscardOutBuffer(); serialPort1.Write(ppiAddress.StopBytesyte, 0, ppiAddress.StopBytesyte.Length); //Thread.Sleep(10); string str = ByteHelper.ByteToString(ppiAddress.StopBytesyte); if (serialPort1.ReadByte() == 0xE5) { return(true); } else { return(false); } }
/// <summary> /// Функция посылает запрос в порт, потом отсчитывает время readTimeout и проверяет буфер порта на чтение. /// Таким образом обеспечивается одинаковый промежуток времени между запросами в порт. /// </summary> public async Task <byte[]> RequestAndRespawnConstPeriodAsync(byte[] writeBuffer, int nBytesRead, int readTimeout, CancellationToken ct) { if (!_port.IsOpen) { return(await Task <byte[]> .Factory.StartNew(() => null, ct)); } //очистили буферы порта _port.DiscardInBuffer(); _port.DiscardOutBuffer(); //отправили данные в порт _port.WriteTimeout = 500; _port.Write(writeBuffer, 0, writeBuffer.Length); //ждем ответа.... await Task.Delay(readTimeout, ct); //проверяем ответ var buffer = new byte[nBytesRead]; if (_port.BytesToRead >= nBytesRead) { _port.Read(buffer, 0, nBytesRead); return(buffer); } Debug.WriteLine($"Время на ожидание ответа вышло {_port.BytesToRead} >= {nBytesRead}"); throw new TimeoutException("Время на ожидание ответа вышло"); }
//---------------------------------------------------------------------------- /// <summary> /// Устанавливает режим транзакции запрос-ответ /// </summary> private void StartTransaction( Modbus.OSIModel.Transaction.TransactionType type) { if (_transaction == TransactionType.Undefined) { if ((_MaskOfMessageLog & TypeOfMessageLog.Information) == TypeOfMessageLog.Information) { Trace.TraceInformation("{0}: Поток ID: {1} : Старт транзакции", DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId); } //_incomingBuffer.Clear(); _serialPort.DiscardInBuffer(); _serialPort.DiscardOutBuffer(); _transaction = type; _error = RequestError.NoError; } else { if ((_MaskOfMessageLog & TypeOfMessageLog.Information) == TypeOfMessageLog.Information) { Trace.TraceError("{0}: Поток ID: {1} : Попытка начать новую транзакцию во время текущей транзакции", DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId); } throw new Exception("Попытка начать новую транзакцию во время текущей транзакции"); } return; }
public bool Close() { if (sp != null && sp.IsOpen) { lock (SyncLock) { sp.DiscardInBuffer(); sp.DiscardOutBuffer(); sp.Close(); } } return(sp.IsOpen); }
private void SendToESP(String s) { // Check connected or disconnected if (serialPort == null) { return; } if (serialPort.IsOpen == false) { return; } // Get text from textbox String data = s + "\n"; try { // Send text serialPort.Write(data); } catch (Exception ex) { MessageBox.Show(ex.Message); } serialPort.DiscardOutBuffer(); }
private void Button_Click(object sender, RoutedEventArgs e)//按钮打开事件 { try { open.IsEnabled = false; stop.IsEnabled = true; control.IsEnabled = true; port = new SerialPort(); port.BaudRate = 115200; port.PortName = COMName.Text; port.DataBits = 8; port.Open(); port.DiscardInBuffer(); port.DiscardOutBuffer(); MessageBox.Show("串口打开成功", "系统提示"); } catch (IOException ex) { MessageBox.Show("串口打开失败" + ex, "系统提示"); return; } _keepReading = true; _readThread = new Thread(ReadPort); _readThread.Start(); }
static public int GetWeight() { try { int W = 0; if (iniFile.ScaleType == 1) { port.DiscardInBuffer(); port.DiscardOutBuffer(); byte[] com = HexStringToByteArray("45"); port.Write(com, 0, 1); int k = (port.Read(com, 0, 1)); BitArray Ba = new BitArray(com); int k2 = (port.Read(com, 0, 1)); BitArray Ba2 = new BitArray(com); BitArray ba3 = new BitArray(16); for (int i = 0; i < 16; i++) { if (i < 8) { ba3.Set(i, Ba[i]); } else { ba3.Set(i, Ba2[i - 8]); } } W = getIntFromBitArray(ba3); } else if (iniFile.ScaleType == 2) { W = ScaleCasAD.GetWeight(); } return(W); } catch (Exception e) { Utils.ToCardLog("[Error] GetWeight " + e.Message); return(-1); } }
public CompanySerialIO(int serialPortNumber) { _semaphore = new Semaphore(1, 1); _serialPort = new SerialPort("COM" + serialPortNumber); _serialPort.ReadTimeout = 1000; _serialPort.Open(); _serialPort.DiscardInBuffer(); // Discard unsynchronized data _serialPort.DiscardOutBuffer(); // Discard unsynchronized data }
/// <summary> /// 向串口发送指令 /// </summary> /// <param name="command"></param> public void SendCommand(String command) { string hexCommand = tool.GetHexString(command); byte[] datat = tool.GetByteData(hexCommand); m_port.DiscardInBuffer(); m_port.DiscardOutBuffer(); m_port.Write(datat, 0, datat.Length); }
public void theLoop() { int listenPort = 11000; UdpClient listener = new UdpClient(listenPort); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); SerialPort portCOM1 = new SerialPort(); try{ portCOM1 = new SerialPort("/dev/ttyS0", 115200, Parity.None, 8, StopBits.One); portCOM1.Open(); } catch(Exception ee) { Console.WriteLine("Not connected to COM1"); Console.WriteLine(ee.Message.ToString()); } string received_data; byte[] received_byte_array; bool done = false; while(!done) { Console.WriteLine("Waiting For Data - press (q) to quit"); received_byte_array = listener.Receive(ref groupEP); received_data = ""; for(int i = 0; i < received_byte_array.Length; i++) { received_data = received_data+received_byte_array[i]+" "; } Console.WriteLine("Recived Data From {0}: {1}", groupEP.ToString(), received_data); try{ portCOM1.Write(received_byte_array,0,received_byte_array.Length); // write what was recived on UDP to com 1 Console.WriteLine("Wrote data to COM1 @ 115200 8N1"); } catch(Exception ee) { Console.WriteLine(ee.Message.ToString()); try{ portCOM1.Close(); portCOM1.DiscardOutBuffer(); portCOM1.DiscardInBuffer(); listener.Close(); listener = new UdpClient(listenPort); groupEP = new IPEndPoint(IPAddress.Any, listenPort); } catch(Exception eee) { Console.WriteLine(eee.Message.ToString()); } } } }
private void singleServoControl(byte lrBody, byte idNum, byte pose) { if (comportCheck()) { byte[] servo = new byte[7]; servo[0] = 255; servo[1] = lrBody; servo[2] = 4; servo[3] = 2; servo[4] = idNum; servo[5] = pose; servo[6] = Convert.ToByte(textBox4.Text); port.DiscardInBuffer(); //buffer clear port.DiscardOutBuffer(); //buffer clear port.Write(servo, 0, servo.Length); } }
/* open serial port */ public void Open(string portName, uint baudRate) { /* initialize serial port */ sp = new SerialPort(portName, (int)baudRate, Parity.Even, 8); /* open serial port */ sp.Open(); /* discard buffers */ sp.DiscardInBuffer(); sp.DiscardOutBuffer(); }
public SerialComm(string port) { serial = new SerialPort(port, 115200, Parity.None, 8, StopBits.One) { Handshake = Handshake.None, //Handshake not needed }; serial.DataReceived += SerialDataReceived; serial.Open(); serial.DiscardOutBuffer(); serial.DiscardInBuffer(); }
public void DiscardOutBuffer() { if (!serialport.IsOpen) { Open(); } if (serialport.IsOpen) { serialport.DiscardOutBuffer(); } }
public static string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage) { port.DiscardOutBuffer(); port.DiscardInBuffer(); receiveNow.Reset(); port.Write(command + "\r"); string input = ReadResponse(port, responseTimeout); if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n")))) throw new ApplicationException("No success message was received."); return input; }
public Modem(SerialPort port) { serialPort = port; //init port EnsurePortOpen(); //we will handle read timeout manually, system implementation is not consistent serialPort.ReadTimeout = 0; serialPort.WriteTimeout = SerialPort.InfiniteTimeout; serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); serialPort.NewLine = "\r"; serialPort.Encoding = Encoding.ASCII; }
public static bool ClearBuffer(SerialPort port) { try { port.DiscardOutBuffer(); port.DiscardInBuffer(); return true; } catch(Exception ex) { FileWorker.WriteEventFile(DateTime.Now, "ASubDriver", "ClearBuffer", ex.Message); return false; } }
public void gainsmessageasync_test() { SerialPort port = new SerialPort("COM7", 250000, Parity.None, 8, StopBits.One); SerialPortInterface portInterface = new SerialPortInterface(port); using (FlightComputerInterface fcInt = new FlightComputerInterface(portInterface)) { fcInt.Open(); port.DiscardInBuffer(); port.DiscardOutBuffer(); FlightComputerTelemetryMessage gains = null; for (int i = 0; i < 1000; i++) { gains = (FlightComputerTelemetryMessage) fcInt.Receive(); Assert.IsTrue(gains.LateralInnerLoopGain == 1.1f); Assert.IsTrue(gains.LongitudeInnerLoopGain == 1.2f); Assert.IsTrue(gains.PitchAngularVelocityGain == 1.3f); Assert.IsTrue(gains.RollAngularVelocityGain == 1.4f); Assert.IsTrue(gains.XAntiWindupGain == 1.5f); Assert.IsTrue(gains.XDerivativeGain == 1.6f); Assert.IsTrue(gains.XIntegralGain == 1.7f); Assert.IsTrue(gains.XProportionalGain == 1.8f); Assert.IsTrue(gains.YAntiWindupGain == 1.9f); Assert.IsTrue(gains.YawAntiWindupGain == 1.0f); Assert.IsTrue(gains.YawDerivativeGain == 1.11f); Assert.IsTrue(gains.YawIntegralGain == 1.12f); Assert.IsTrue(gains.YawProportionalGain == 1.13f); Assert.IsTrue(gains.YDerivativeGain == 1.14f); Assert.IsTrue(gains.YIntegralGain == 1.15f); Assert.IsTrue(gains.YProportionalGain == 1.16f); Assert.IsTrue(gains.ZAntiWindupGain == 1.17f); Assert.IsTrue(gains.ZDerivativeGain == 1.18f); Assert.IsTrue(gains.ZIntegralGain == 1.19f); Assert.IsTrue(gains.ZProportionalGain == i); Debug.WriteLine(i); fcInt.Transmit(gains); } gains = (FlightComputerTelemetryMessage) fcInt.Receive(); Assert.IsTrue(gains.ZProportionalGain == 12); } }
public Link (int BUFSIZE) { // Create a new SerialPort object with default settings. serialPort = new SerialPort("/dev/ttyS1",115200,Parity.None,8,StopBits.One); if(!serialPort.IsOpen) serialPort.Open(); buffer = new byte[(BUFSIZE*2)]; serialPort.ReadTimeout = 500; serialPort.DiscardInBuffer (); serialPort.DiscardOutBuffer (); }
private bool identify(ref Dictionary<string, Arduino> _ArduinoMap, string _potentialArduino) { if (!_ArduinoMap.ContainsKey(_potentialArduino)) { SerialPort temp; try { temp = new SerialPort(_potentialArduino); temp.Open(); string toWrite = Arduino_Codes.IDENTITY_QUERY; temp.DiscardOutBuffer(); temp.DiscardInBuffer(); Thread.Sleep(100); temp.WriteLine(toWrite); Thread.Sleep(200); temp.WriteLine(toWrite); Thread.Sleep(200); string ID = temp.ReadExisting(); if (ID.Contains(Arduino_Codes.ARM_IDENTITY_RESPONSE)) { _ArduinoMap.Add(Arduino_Codes.ARM_IDENTITY, new Arduino(temp, Arduino_Codes.ARM_IDENTITY)); return true; } else if (ID.Contains(Arduino_Codes.HAND_IDENTITY_RESPONSE)) { _ArduinoMap.Add(Arduino_Codes.HAND_IDENTITY, new Arduino(temp, Arduino_Codes.HAND_IDENTITY)); return true; } else if (ID.Contains(Arduino_Codes.DRIVEFRONT_IDENTITY_RESPONSE)) { _ArduinoMap.Add(Arduino_Codes.DRIVEFRONT_IDENTITY, new Arduino(temp, Arduino_Codes.DRIVEFRONT_IDENTITY)); return true; } else if (ID.Contains(Arduino_Codes.DRIVEBACK_IDENTITY_RESPONSE)) { _ArduinoMap.Add(Arduino_Codes.DRIVEBACK_IDENTITY, new Arduino(temp, Arduino_Codes.DRIVEBACK_IDENTITY)); return true; } else if (ID.Contains(Arduino_Codes.PT_IDENTITY_RESPONSE)) { _ArduinoMap.Add(Arduino_Codes.PT_IDENTITY, new Arduino(temp, Arduino_Codes.PT_IDENTITY)); return true; } temp.Dispose(); //Gets rid of safe handle issue! Or at least appears to! } catch { return false; } } return false; }
public Program(string port) { serial = new SerialPort(port, 9600, Parity.None, 8, StopBits.One) { Handshake = Handshake.RequestToSend, NewLine = "\r", }; serial.DataReceived +=(o,e)=> { var num = serial.BytesToRead; if (num == 0) return; var data = new byte[num]; serial.Read(data, 0, num); foreach (var b in data) { switch (phase) { case 0: if (b == 0x0A) phase = 1; else message.Append((char) b); break; case 1: phase = (b == 0x30) ? 2 : 0; break; case 2: phase = (b == 0x30) ? 3 : 0; break; case 3: if (b == 0x0D) { if (message.Length > 0 && verbose) Console.WriteLine(message); lastMessage = message.ToString(); message.Clear(); syncEvent.Set(); } phase = 0; break; } } }; serial.Open(); //serial.RtsEnable = true; serial.DiscardOutBuffer(); serial.DiscardInBuffer(); }
public XmlElement GetTemperature(string port, string baudRate) { try { _serialPort = new SerialPort(port); _serialPort.BaudRate = Convert.ToInt32(baudRate); _serialPort.Parity = Parity.None; _serialPort.StopBits = StopBits.One; _serialPort.DataBits = 8; _serialPort.Handshake = Handshake.None; _serialPort.RtsEnable = true; _serialPort.ReadTimeout = 1000; if (_serialPort.IsOpen) { _serialPort.Close(); _serialPort.Open(); } else { _serialPort.Open(); } Thread.Sleep(1000); count = _serialPort.BytesToRead; if (count < 1) { throw new Exception("No Data to Read..."+count); } else { while (count > 0) { int byteData = _serialPort.ReadByte(); data = data + Convert.ToChar(byteData); count--; } } _serialPort.DiscardOutBuffer(); _serialPort.Close(); _result = GetXML(data.Trim()); } catch (Exception ex) { if (_serialPort.IsOpen) _serialPort.Close(); _result = GetExceptionXML(ex.ToString()); } return _result; }
public static bool ConfigPort(System.IO.Ports.SerialPort _serialPort, SerialPortConfig _serialPortConfig = default(SerialPortConfig)) { Console.WriteLine(" Port: " + _serialPort.PortName); if (_serialPortConfig == null) { _serialPortConfig = new SerialPortConfig(); } bool portOpened = false; try { _serialPort.DataBits = _serialPortConfig.DataBits; _serialPort.StopBits = _serialPortConfig.StopBits; _serialPort.Parity = _serialPortConfig.Parity; _serialPort.Handshake = _serialPortConfig.Handshake; _serialPort.WriteBufferSize = _serialPortConfig.WriteBufferSize; _serialPort.ReadBufferSize = _serialPortConfig.ReadBufferSize; _serialPort.Encoding = System.Text.Encoding.GetEncoding(28591); //Causes an error if it is being used openPort(_serialPort); _serialPort.DiscardInBuffer(); _serialPort.DiscardOutBuffer(); portOpened = true; } catch (Exception ex) { Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message); } if (portOpened) { try { //Causes error in Mono for non-standard baud rate _serialPort.BaudRate = _serialPortConfig.BaudRate; } catch (Exception ex) { Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message); ForceSetBaudRate(_serialPort.PortName, _serialPortConfig.BaudRate); } } return(portOpened); }
//打开端口 public bool OpenPort(SerialPort port) { bool bflag = false; try { port.Open(); port.DiscardInBuffer(); port.DiscardOutBuffer(); bflag = true; } catch (IOException ex) { bflag = false; } return bflag; }
public COMmngr() { //dataReceiveCBs += new DataReceivedCBDeleage(CC2540.DataReceivedCB); com = new SerialPort(); com.BaudRate = 115200; com.PortName = Properties.Settings.Default.COMport; com.Parity = Parity.None; com.Handshake = Handshake.RequestToSend; com.StopBits = StopBits.One; com.DataBits = 8; com.ReadTimeout = 5000; com.WriteTimeout = 5000; com.DataReceived += new SerialDataReceivedEventHandler(COMDataReceivedCB); com.Open(); com.DiscardInBuffer(); com.DiscardOutBuffer(); }
public bool Connect(bool exposeExceptions = false) { try { // Setup read thread readThread = new Thread(ReadResponseBytes); // Create a new SerialPort object with default settings. serialPort = new System.IO.Ports.SerialPort(COMMPort); // Update the Handshake serialPort.Handshake = System.IO.Ports.Handshake.None; // Set the read/write timeouts serialPort.ReadTimeout = 10000; serialPort.WriteTimeout = 10000; // open serial port serialPort.Open(); // monitor port changes PortsChanged += OnPortsChanged; // discard any buffered bytes serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); ResponseBytesHandler += ReadResponses; readThread.Start(); return(connected = true); } catch (Exception) { if (exposeExceptions) { throw; } } return(false); }
private void Button_Click_3(object sender, RoutedEventArgs e) { try { if (serialPort.IsOpen) { serialPort.DiscardOutBuffer(); //清空发送缓存 serialPort.DiscardInBuffer(); //清空接收缓存 } else { return; } } catch (Exception error) { MessageBox.Show(error.ToString()); } }
public Arduino(int compoort) { serialPort = new SerialPort(); serialPort.BaudRate = 9600; string port = "COM" + Convert.ToString(compoort); try { serialPort.PortName = port; serialPort.Open(); if (serialPort.IsOpen) { serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); } } catch { } }
public serial_driver(String port_name, MainPanel panel_form, Profiler probe_profiler_para, stream_source stream_source_para) { main_form = panel_form; data_stream = new SerialPort(port_name, 115200, Parity.None, 8, StopBits.One); data_stream.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); data_stream.ReceivedBytesThreshold = 1; data_stream.Open(); data_stream.DtrEnable = true; data_stream.DtrEnable = false; data_stream.DiscardInBuffer(); data_stream.DiscardOutBuffer(); frame_prop packet_config; packet_config.padding_len = 3; packet_config.padding_byte = new byte[3] { 0xFF, 0x00, 0xAA }; packet_config.pad_EOH = 0xFF; packet_config.pad_EOP = 0xFF; packet_config.header_len = 2; packet_config.crc_len = 2; parser = new Serial_parser(packet_config, main_form, probe_profiler_para, stream_source_para); }
public void ClosePort() { serial.ErrorReceived -= new Ports.SerialErrorReceivedEventHandler(serial_ErrorReceived); serial.DataReceived -= new Ports.SerialDataReceivedEventHandler(serial_DataReceived); serial.DiscardInBuffer(); serial.DiscardOutBuffer(); var stream = serial.BaseStream; stream.Flush(); stream.Close(); stream.Dispose(); serial.Close(); serial.Dispose(); serial = null; stream = null; GC.Collect(); }
//Execute AT Command public string ExecCommand(SerialPort port,string command, int responseTimeout, string errorMessage) { try { // receiveNow = new AutoResetEvent(); port.DiscardOutBuffer(); port.DiscardInBuffer(); receiveNow.Reset(); port.Write(command + "\r"); //Thread.Sleep(3000); //3 seconds string input = ReadResponse(port, responseTimeout); if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n")))) throw new ApplicationException("No success message was received."); return input; } catch (Exception ex) { throw new ApplicationException(errorMessage, ex); } }
protected override bool DoInitialize() { try { _port = new SerialPort(Settings.PortName); _port.BaudRate = 38400; _port.RtsEnable = false; _port.DtrEnable = false; _port.Open(); _port.DiscardOutBuffer(); _port.DiscardInBuffer(); _port.DataReceived += port_DataReceived; } catch (Exception e) { InteractionService.UserIntraction.DisplayPopup("", "Hugin Caller ID Error", e.Message); return false; } return true; }
} // WriteToHands private static int ClearBuffers(String hand) { /*======================================================================================\ | * Clears serial buffers for both hands in try catch blocks. | | * PostConditions: returns 1 for error in L, -1 for R, otherwise 0 | \======================================================================================*/ if (hand == "Left" || hand == "Both") { try { handPortL.DiscardOutBuffer(); handPortL.DiscardInBuffer(); //handPortL.Close(); } catch (Exception e) { UnityEngine.Debug.Log("ClearBuffers() L failed"); return(1); //if one fails they all will fail, should write this seperate -- lazy. } } if (hand == "Right" || hand == "Both") { try { handPortR.DiscardOutBuffer(); handPortR.DiscardInBuffer(); //handPortL.Close(); } catch (Exception e) { UnityEngine.Debug.Log("Error in ClearBuffers() R"); return(-1); } } return(0); } // ClearBuffers
private static void InitCom() { if (iniFile.DisplayBoardType == 1) { port.WriteTimeout = 2000; port.ReadTimeout = 20000; port.BaudRate = iniFile.DisplayBoardPortBaudRate; port.PortName = "com" + iniFile.DisplayBoardPort; port.NewLine = Environment.NewLine; port.DtrEnable = true; port.RtsEnable = true; port.Parity = Parity.None; port.ReadBufferSize = 1024; port.WriteBufferSize = 1024; port.Handshake = Handshake.None; port.Open(); port.DiscardInBuffer(); port.DiscardOutBuffer(); } else if ((iniFile.DisplayBoardType == 2) || (iniFile.DisplayBoardType == 3)) { port.WriteTimeout = -1; port.ReadTimeout = -1; port.BaudRate = iniFile.DisplayBoardPortBaudRate; port.PortName = "com" + iniFile.DisplayBoardPort; port.NewLine = Environment.NewLine; port.DtrEnable = true; port.RtsEnable = true; port.Parity = Parity.None; port.ReadBufferSize = 4096; port.WriteBufferSize = 2048; port.Handshake = Handshake.None; //port.ParityReplace = 20; port.Open(); //port.DiscardInBuffer(); //port.DiscardOutBuffer(); } }
public bool SendReceiveInitData() { bool bret = true; byte[] cmdByteArray = new byte[5]; openPort.DiscardInBuffer(); openPort.DiscardOutBuffer(); // Send byte data cmdByteArray[0] = 0x00; cmdByteArray[1] = 0xFF; cmdByteArray[2] = 0x01; cmdByteArray[3] = 0x01; cmdByteArray[4] = 0x00; openPort.Write(cmdByteArray, 0, 5); strBalanceReturn = ""; if (ptReceiveData != null) { ptReceiveData = null; } while (openPort.BytesToRead == 0 && nCnt < 10) { nCnt++; Thread.Sleep(1000); } byte[] inbyte = new byte[5]; openPort.Read(inbyte, 0, 5); ptReceiveData = inbyte; strBalanceReturn = BitConverter.ToString(inbyte); if (nCnt >= 10) { bret = false; strErrorMsg = "There is impossible to receive any data from microcontroller. Make sure the connection state or Select the correct Comport."; } nCnt = 0; return(bret); }
/// <summary> /// Schreibt ein AT-Command an das Modem /// </summary> /// <param name="command"></param> private void PortComandExe(string command) { System.IO.Ports.SerialPort port = _spManager.SerialPort; //Port bereit? if (port == null) { MessageBox.Show("2003111425 serieller Port ist unbestimmt. Befehl an GSM-Modem wird abgebrochen."); return; } if (!SerialPort.GetPortNames().ToList().Contains(port.PortName)) { MessageBox.Show("2003111551 Der Port >" + port.PortName + " < existiert nicht."); return; } try { if (!port.IsOpen) { MessageBox.Show("2003110953 Port >" + port.PortName + "< ist nicht offen. Versuche zu öffnen"); _spManager.SerialPort.Open(); System.Threading.Thread.Sleep(500); } port.DiscardOutBuffer(); port.DiscardInBuffer(); _spManager.SerialPort.Write(command + "\r"); //MessageBox.Show("PortComandExe(" + command + ")"); } catch (System.IO.IOException ex_io) { MessageBox.Show("2003110956 Konnte Befehl nicht an COM-Port senden.\r\n" + ex_io.Message); return; } }
public void Stop() { try { ThreadRunFlag = false; if (SerialPortMng != null) { SerialPortMng.DiscardOutBuffer(); SerialPortMng.DiscardInBuffer(); SerialPortMng.Close(); SerialPortMng.Dispose(); } SendOrderQueue.Clear(); ReceiveDataQueue.Clear(); ReceiveData.Clear(); } catch (Exception ex) { } }
void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (sender.GetType() != typeof(System.IO.Ports.SerialPort)) { return; } System.IO.Ports.SerialPort comPort = (System.IO.Ports.SerialPort)sender; try { string infoMessage1 = comPort.ReadTo("=>"); infoMessage1 = infoMessage1.Trim().Replace("\0", "").Replace("\n\r", "\r\n"); //实现委托 MyInvoke Invoke1 = new MyInvoke(UpdateForm); this.BeginInvoke(Invoke1, infoMessage1); comPort.DiscardInBuffer(); comPort.DiscardOutBuffer(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public BK2831E(string comPort) { P = new SerialPort(comPort); P.BaudRate = 38400; P.ReadTimeout = 1000; P.Open(); P.DiscardInBuffer(); P.DiscardOutBuffer(); int i = 0; modes = new string[9]; modes[i++] = "VOLTAGE:AC"; modes[i++] = "VOLTAGE:DC"; modes[i++] = "CURRENT:AC"; modes[i++] = "CURRENT:DC"; modes[i++] = "RESISTANCE"; modes[i++] = "FREQUENCY"; modes[i++] = "PERIOD"; modes[i++] = "DIODE"; modes[i++] = "CONTINUITY"; reset(); //test comms with the device try { string instrID = this.instrumentID; if (!instrID.Contains("2831E Multimeter")) throw new Exception("Instrument expected on " + comPort + " is a BK2831E Multimeter, " + instrID + " was found"); } catch (TimeoutException) { throw new Exception("No instrument was found on " + comPort + ", A BK2831E was expected"); } }
protected override bool DoInitialize() { try { _port = new SerialPort(Settings.PortName); _port.Open(); _port.DiscardOutBuffer(); _port.DiscardInBuffer(); _port.RtsEnable = true; var lines = GetInitializationString().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { _port.WriteLine(line + "\r"); } _port.DataReceived += port_DataReceived; } catch (Exception e) { InteractionService.UserIntraction.DisplayPopup("", "Generic Modem Error", e.Message); return false; } return true; }
static void Main(string[] args) { string[] ports = SerialPort.GetPortNames(); foreach (string p in ports) { var port = new SerialPort(p); port.BaudRate = 19200; // 115200; port.Parity = Parity.None; port.StopBits = StopBits.One; port.Handshake = Handshake.RequestToSend; port.DtrEnable = true; port.RtsEnable = true; port.NewLine = System.Environment.NewLine; port.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); try { port.Open(); port.DiscardInBuffer(); port.DiscardOutBuffer(); var command = "AT"; while (!command.Equals("exit")) { port.WriteLine(command); command = Console.ReadLine(); } port.Close(); } catch (Exception e) { Console.WriteLine(e); } } Console.ReadKey(); }
private void doAssay() { Boolean cont = true; int loop = 0; do { DateTime current = DateTime.Now; int endCycle = current.Hour * 60 * 60 + current.Minute * 60 + current.Second; if (duration < endCycle) { cont = false; } SerialPort serialPort = null; // Create a new SerialPort object with default settings. serialPort = new SerialPort(); // Allow the user to set the appropriate properties. serialPort.PortName = port; serialPort.DataBits = 8; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.BaudRate = 9600; // Set the read/write timeouts serialPort.ReadTimeout = 10000; serialPort.WriteTimeout = 500; try { serialPort.Open(); serialPort.DiscardOutBuffer(); serialPort.DiscardInBuffer(); String ReceivedData; //RecievedData = serialPort.ReadLine(); //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler); serialPort.Write("R" + "\r\n"); Boolean conti = true; do { ReceivedData = serialPort.ReadLine(); if (ReceivedData.Contains('$')) { conti = false; } } while (conti); conti = true; serialPort.Write("i" + "\r\n"); String ReceivedData1; do { ReceivedData1 = serialPort.ReadLine(); if (ReceivedData1.Contains('$')) { conti = false; } } while (conti); conti = true; Thread.Sleep(2000); ReceivedData = ReceivedData.Replace("$", ""); ReceivedData1 = ReceivedData1.Replace("$", ""); ReceivedData = ReceivedData.Replace("\r", ""); ReceivedData1 = ReceivedData1.Replace("\r", ""); ReceivedData = ReceivedData.Replace("\n", ""); ReceivedData1 = ReceivedData1.Replace("\n", ""); AppendHeatLabel("Temperature U:" + ReceivedData1.Split(',')[4] + "," + "Temperature M:" + ReceivedData1.Split(',')[5]); AppendData(loop.ToString() + "," + ReceivedData1.Split(',')[4] + "," + ReceivedData1.Split(',')[5] + "," + ReceivedData); string resToAppend = loop.ToString() + ",U,M,"; AppendResult(loop.ToString() + "," + ReceivedData1.Split(',')[4] + "," + ReceivedData1.Split(',')[5] + "," + ReceivedData); Thread.Sleep(2000); serialPort.Close(); } catch (Exception exc) { MessageBox.Show("Serial could not be opened, please check that the device is correct one"); serialPort.Close(); } Boolean timeRunning = true; do { DateTime wait = DateTime.Now; if (endCycle + 120 < wait.Hour * 60 * 60 + wait.Minute * 60 + wait.Second) { timeRunning = false; } Thread.Sleep(100); } while (timeRunning); loop += 1; } while (cont); // Cancel the heat SerialPort serialPortCancel = null; try { // Create a new SerialPort object with default settings. serialPortCancel = new SerialPort(); // Allow the user to set the appropriate properties. serialPortCancel.PortName = port; serialPortCancel.DataBits = 8; serialPortCancel.Parity = Parity.None; serialPortCancel.StopBits = StopBits.One; serialPortCancel.BaudRate = 9600; // Set the read/write timeouts serialPortCancel.ReadTimeout = 500; serialPortCancel.WriteTimeout = 500; serialPortCancel.Open(); serialPortCancel.DiscardOutBuffer(); serialPortCancel.DiscardInBuffer(); String ReceivedData; //RecievedData = serialPort.ReadLine(); //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler); serialPortCancel.Write("C" + "\r\n"); Boolean conti = true; do { ReceivedData = serialPortCancel.ReadLine(); if (ReceivedData.Contains('$')) { conti = false; } } while (conti); ReceivedData = ReceivedData.Replace("$", ""); ReceivedData = ReceivedData.Replace("\r", ""); ReceivedData = ReceivedData.Replace("\n", ""); serialPortCancel.Close(); } catch (Exception exc) { MessageBox.Show("Serial could not be opened, please check that the device is correct one"); serialPortCancel.Close(); } MessageBox.Show("Assay ready"); }
private void AskHeat_Click(object sender, EventArgs e) { SerialPort serialPort = null; // Create a new SerialPort object with default settings. serialPort = new SerialPort(); // Allow the user to set the appropriate properties. serialPort.PortName = COM.Text; serialPort.DataBits = 8; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.BaudRate = 9600; // Set the read/write timeouts serialPort.ReadTimeout = 500; serialPort.WriteTimeout = 500; try { serialPort.Open(); serialPort.DiscardOutBuffer(); serialPort.DiscardInBuffer(); String ReceivedData; //RecievedData = serialPort.ReadLine(); //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler); serialPort.Write("i" + "\r\n"); Boolean conti = true; do { ReceivedData = serialPort.ReadLine(); if (ReceivedData.Contains('$')) { conti = false; } } while (conti); ReceivedData = ReceivedData.Replace("$", ""); ReceivedData = ReceivedData.Replace("\r", ""); ReceivedData = ReceivedData.Replace("\n", ""); AppendHeatLabel("Temperature U:" + ReceivedData.Split(',')[4] + "," + "Temperature M:" + ReceivedData.Split(',')[5]); serialPort.Close(); } catch (Exception exc) { MessageBox.Show("Serial could not be opened, please check that the device is correct one"); serialPort.Close(); } }
private void UploadNowBtn_Click(object sender, EventArgs e) { uploadInProgress = true; // Verify that a valid file path has been entered. If a path is present in the box it is already validated so // there is no need to do any further validation. if (HexFilePathTB.Text.Length == 0) { MessageBox.Show("You must select the path to the desired Hex file in order to perform upload.", "File Path Error"); return; } // Perform the upload... bool uploadSuccess = false; try { this.Cursor = Cursors.WaitCursor; // Initialize ds30 Loader engine { string strBasePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); bool bds30LoaderInitializeResult = false; clsds30Loader.Initialize(strBasePath, ref bds30LoaderInitializeResult); if (bds30LoaderInitializeResult == false) { MessageBox.Show("Failed to initialize ds30 Loader.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Cursor = Cursors.Default; return; } } // Get device object clsDevice objDevice = clsDeviceDb.DeviceGet("PIC24HJ128GP204"); if (objDevice == null) { MessageBox.Show("Unknown device, write aborted.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Cursor = Cursors.Default; return; } // Parse hex file //clsHex18F objHex = new clsHex18F( "serlcd.hex" ); clsHex objHex = (fileIsAutoDownloaded) ? new clsHex(hexFileDestPath) : new clsHex(HexFilePathTB.Text); { bool bParseResult = false; clsParseSettings objParseSettings = new clsParseSettings(); objHex.HexFileValidate += new clsHex.HexFileValidateDelegate(objHex_HexFileValidate); objHex.HexFileParse += new clsHex.HexFileParseDelegate(objHex_HexFileParse); objParseSettings.device = objDevice; objHex.ParseHexFile(objParseSettings, false, 0, ref bParseResult); if (bParseResult == false) { MessageBox.Show("Parse of hex file failed, write process aborted.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Cursor = Cursors.Default; return; } } // Download { bool bDownloadResult = false; myFocuser.Action("ForceHubDisconnect", ""); clsWriteSettings objDownloadSettings = new clsWriteSettings(); objDownloadSettings.portName = myFocuser.Action("GetCOMPortName", ""); objDownloadSettings.writeProgram = true; objDownloadSettings.baudRate = 115200; switch (TimeoutCB.Text) { default: case "10 Sec": objDownloadSettings.timeout = 10000; break; case "30 Sec": objDownloadSettings.timeout = 30000; break; case "60 Sec": objDownloadSettings.timeout = 60000; break; } MessageBox.Show("Press 'OK' and then cycle the power to the FocusLynx device before the timeout period expires.", "Bootloader", MessageBoxButtons.OK, MessageBoxIcon.Information); txtInfo.Text += "Waiting for device power cycle..." + Environment.NewLine; //************************************************************************************************************************ // Before we start the write we have to make sure any garbage that is output form the device at power up is discarded first // using (SerialPort tempPort = new SerialPort(objDownloadSettings.portName, objDownloadSettings.baudRate)) // use same settigs as bootloader { tempPort.Open(); tempPort.DiscardInBuffer(); tempPort.DiscardOutBuffer(); string junk = tempPort.ReadExisting(); DateTime startTime = DateTime.UtcNow; while (DateTime.UtcNow.Subtract(startTime).TotalMilliseconds < (objDownloadSettings.timeout - 2000)) { if (tempPort.BytesToRead > 0) { System.Threading.Thread.Sleep(1000); // Pause while the serial transciever powers up... break; } } EventLogger.LogMessage("Bootloader discarding " + tempPort.BytesToRead + " bytes of junk before bootload", TraceLevel.Info); junk = tempPort.ReadExisting(); tempPort.DiscardInBuffer(); tempPort.Close(); } //************************************************************************************************************************* // Now it is okay to start the download clsds30Loader.Write(objDevice, objHex, objDownloadSettings, 0, ref bDownloadResult); if (bDownloadResult == false) { MessageBox.Show("Write failed", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Cursor = Cursors.Default; uploadSuccess = false; return; } else { uploadSuccess = true; // Delete the autodownloaded file if (fileIsAutoDownloaded) { try { File.Delete(hexFileDestPath); txtInfo.Text += "Temporary hex file removed" + Environment.NewLine; } catch { } } } } } catch (Exception ex) { MessageBox.Show("An error occurred during firmware upload. " + ex.Message, "Error"); } finally { uploadInProgress = false; this.Cursor = Cursors.Default; } if (uploadSuccess) { MessageBox.Show("The device firmware has been successfully upgraded!", "Upload Complete"); // Close the form. //this.Close(); } else { // Leave the form open incase they want to attempt the upload again. } }
public override void DiscardOutBuffer() { _port.DiscardOutBuffer(); }
public void DoWork() { try { string tString = string.Empty; Control_weighing_By_Roman_07032017_0.Controler.info_weight answer = new Control_weighing_By_Roman_07032017_0.Controler.info_weight(); if (myPort.IsOpen == false) { myPort.Open(); } myPort.DiscardInBuffer(); myPort.DiscardOutBuffer(); int i = 0; while (!_shouldStop) { if (myPort.IsOpen != true) { _shouldStop = true; } if (myPort.BytesToRead > 0) { byte[] buffer = new byte[1]; int bytesRead = myPort.Read(buffer, 0, buffer.Length); //i++; //if (i == 10) //{ // i = 0; //} tString += System.Text.Encoding.ASCII.GetString(new[] { buffer[0] }); if (buffer[0] == '>') { if (tString.Length == 10) { showComPortReadData(parcer(tString), taraControl, showWeight); //d(parcer(tString)); tString = string.Empty; } else if (tString.Length < 10) { tString = string.Empty; } } } } } catch (Exception e) { MessageBox.Show(e.Message); } }
/// 丢弃来自串行驱动程序的接收和发送缓冲区的数据 /// </summary> public void DiscardBuffer(SerialPort comm) { comm.DiscardInBuffer(); comm.DiscardOutBuffer(); }
public MFTestResults DataBufferTests() { if (!IsLoopback) return MFTestResults.Skip; result = MFTestResults.Pass; try { using (SerialPort serialPort = new SerialPort(Serial.COM1)) { // set flow control so we can fill both RX/TX buffers serialPort.Handshake = Handshake.RequestToSend; serialPort.WriteTimeout = 1000; serialPort.Open(); // buffer data in RX/TX serialPort.Write(sendbuff, 0, sendbuff.Length); Log.Comment("bytes to send: " + serialPort.BytesToWrite); Log.Comment("bytes to read: " + serialPort.BytesToRead); // clear RX buffer serialPort.DiscardInBuffer(); if (serialPort.BytesToRead != 0) { result = MFTestResults.Fail; Log.Exception(serialPort.BytesToRead + " bytes still in buffer after DiscardInBuffer!"); } // clear TX Buffer serialPort.DiscardOutBuffer(); if (serialPort.BytesToWrite != 0) { // BUGBUG: 21224 result = MFTestResults.Fail; Log.Exception(serialPort.BytesToWrite + " bytes still in buffer after DiscardOutBuffer!"); } serialPort.Close(); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; }
/// <summary> /// Sends a comand frame to the card /// </summary> /// <param name="serialPort">The serial port.</param> /// <param name="commandByte">The command byte.</param> /// <param name="addressByte">The address byte.</param> /// <param name="dataByte">The data byte.</param> /// <returns>A single response command frame</returns> private static Conrad8RelayCardResponseFrame SendCommandToCard(SerialPort serialPort, byte commandByte, byte addressByte, byte dataByte) { lock (serialPort) { serialPort.Open(); // clean up serialPort.DiscardOutBuffer(); /* calculate command frame*/ var commandFrame = CalculateCommandFrame(commandByte, addressByte, dataByte); /* transmit command */ serialPort.Write(commandFrame, 0, 4); /* read and return card response frame */ var result = ReadCardResponseFrame(serialPort); serialPort.Close(); return result; } }
protected override void FlushConnection() { SerialPort.DiscardInBuffer(); SerialPort.DiscardOutBuffer(); }
public void DiscardOutBuffer() { _PortObj.DiscardOutBuffer(); }
public void DiscardOutBuffer() { serialport.DiscardOutBuffer(); }
/// <summary> /// 丢弃来自串行驱动程序的接收和发送缓冲区的数据 /// </summary> public void DiscardBuffer() { serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); }
void Update() { ///string s = ""; string s = ""; if (enableLerpTween) { TweenViewToTarget(); } /// hanfeng /// if (!m) // 如果m 刚开始不是0(因为开始是0 则true) 则 开始调用函数 { Serial_Init(); m = true; } //serialPort.DiscardOutBuffer(); /* * if (serialPort.Read(gest, 0, 8) != 0) // gest 读进来 * { * string s = ""; * //if(sizeof(gest) == 7) * // Debug.Log(gest); * s = System.Text.Encoding.UTF8.GetString(gest, 0, 8); * Debug.Log(s); * serialPort.DiscardOutBuffer(); * * } */ while (s.Length < 7) { char character = (char)serialPort.ReadChar(); /// /// s += character.ToString(); } Debug.Log(s); serialPort.DiscardOutBuffer(); if ((s.Contains("#-3333")) && (GameObject.Find("clone") == null)) // 向左转 { // orderListy.Add(Order.TurnLeft); // SmoothMenuRotationAnimation(true); //Debug.Log(97987978); // 执行OnBtnLeftClick OnBtnRightClick(); // Debug.Log(s); } if (s.Contains("!#-4444")) { // orderListy.Add(Order.TurnRight); // SmoothMenuRotationAnimation(false); OnBtnLeftClick(); } if (GameObject.Find("clone") == null) { if (s.Contains("!#-1111")) { // GameObject.Find("/fuzi"); // if (gameobject.Find == "" // obj.scale +=... // if() // transform.localScale -= new Vector3(1, 1, 0); transform.localScale = new Vector3(0, 0, 0); //背景消失 //Instantiate(GameObject.Find("fuzi"), new Vector3(0, 0, 0), Quaternion.identity); // 这里应该是 curCenterItem // GameObject EnhanceScrollView = Instantiate(GameObject.Find("fuzi"), new Vector3(0, 0, 0), Quaternion.identity) as GameObject; // EnhanceItem curCenterItem // GameObject EnhanceScrollView = Instantiate(EnhanceItem.curCenterItem, new Vector3(0, 0, 0), Quaternion.identity) as GameObject; GameObject Show = Instantiate(instance.curCenterItem.gameObject, new Vector3(0, 0, 0), Quaternion.identity) as GameObject; Show.transform.parent = GameObject.Find("Show").transform; Show.transform.localPosition = new Vector3(-7.0f, 46.0f, 0); // = GameObject.Instantiate(oklable.gameObject.Vector3.zero, Quaternion.identity) as GameObject; Show.name = "clone"; // GameObject.Find("clone").transform.position = new Vector3 (0.021875f, 0.08125f, 0); // (-7, 26, 0); // Gameobject missileCopy = Instantiate<Missile>(missile); // GameObject.Find("fuzi").transform.localScale = new Vector3(0, 0, 0); Show.transform.localScale = new Vector3(1.1f, 1.1f, 1.1f); GameObject.Find("LeftArrow").SetActive(false); GameObject.Find("RightArrow").SetActive(false); GameObject.Find("DoubleArrow").SetActive(false); GameObject.Find("BtnLeft").SetActive(false); GameObject.Find("BtnRight").SetActive(false); GameObject.Find("BtnDoubleTap").SetActive(false); GameObject root7 = GameObject.Find("UI Root"); GameObject map7 = root7.transform.Find("BtnSingle").gameObject; map7.SetActive(true); GameObject root8 = GameObject.Find("UI Root"); GameObject map8 = root8.transform.Find("SingleArrow").gameObject; map8.SetActive(true); } } if ((GameObject.Find("clone") != null) && (s.Contains("!#-2222"))) { // if (s.Contains("!#-2222")) // { transform.localScale += new Vector3(1, 1, 1); // 复原 // for(int i = 0; i < GameObject.Find("Show").transform.childCount; i++) // GameObject go = GameObject.Find("Show").transform.GetChild(i).gameObject; Destroy(GameObject.Find("clone")); GameObject root1 = GameObject.Find("UI Root"); GameObject map1 = root1.transform.Find("LeftArrow").gameObject; map1.SetActive(true); // GameObject.Find ("UI Root/LeftArrow").SetActive (true); GameObject root2 = GameObject.Find("UI Root"); GameObject map2 = root2.transform.Find("RightArrow").gameObject; map2.SetActive(true); GameObject root3 = GameObject.Find("UI Root"); GameObject map3 = root3.transform.Find("DoubleArrow").gameObject; map3.SetActive(true); GameObject root4 = GameObject.Find("UI Root"); GameObject map4 = root4.transform.Find("BtnLeft").gameObject; map4.SetActive(true); GameObject root5 = GameObject.Find("UI Root"); GameObject map5 = root5.transform.Find("BtnRight").gameObject; map5.SetActive(true); GameObject root6 = GameObject.Find("UI Root"); GameObject map6 = root6.transform.Find("BtnDoubleTap").gameObject; map6.SetActive(true); GameObject root9 = GameObject.Find("UI Root"); GameObject map9 = root9.transform.Find("BtnSingle").gameObject; map9.SetActive(false); GameObject root10 = GameObject.Find("UI Root"); GameObject map10 = root10.transform.Find("SingleArrow").gameObject; map10.SetActive(false); } }
void OnProcessExit(object sender, EventArgs e) { // Cancel the heat SerialPort serialPortCancel = null; try { // Create a new SerialPort object with default settings. serialPortCancel = new SerialPort(); // Allow the user to set the appropriate properties. serialPortCancel.PortName = COM.SelectedItem.ToString(); serialPortCancel.DataBits = 8; serialPortCancel.Parity = Parity.None; serialPortCancel.StopBits = StopBits.One; serialPortCancel.BaudRate = 9600; // Set the read/write timeouts serialPortCancel.ReadTimeout = 500; serialPortCancel.WriteTimeout = 500; serialPortCancel.Open(); serialPortCancel.DiscardOutBuffer(); serialPortCancel.DiscardInBuffer(); String ReceivedData; //RecievedData = serialPort.ReadLine(); //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler); serialPortCancel.Write("C" + "\r\n"); Boolean conti = true; do { ReceivedData = serialPortCancel.ReadLine(); if (ReceivedData.Contains('$')) { conti = false; } } while (conti); ReceivedData = ReceivedData.Replace("$", ""); ReceivedData = ReceivedData.Replace("\r", ""); ReceivedData = ReceivedData.Replace("\n", ""); serialPortCancel.Close(); } catch (Exception exc) { MessageBox.Show("Serial could not be opened, please check that the device is correct one. The heat could not be turned off."); serialPortCancel.Close(); } }
//Connect public SerialStatus ConnectSerial(string portName) { h_AhrsSerialPort = new SerialPort(portName,38400,Parity.None,8,StopBits.One); h_AhrsSerialPort.Handshake = Handshake.None; h_AhrsSerialPort.ReadTimeout = SENSOR_TIMEOUT_IN_MSECS; h_AhrsSerialPort.WriteTimeout = SENSOR_TIMEOUT_IN_MSECS; try { h_AhrsSerialPort.Open(); } catch (System.Exception ex) { m_msg = ex.Message; return SerialStatus.CONNECTION_FAILURE; } //Check connection is open if (!h_AhrsSerialPort.IsOpen) { m_msg = "AHRS connection failed to open."; return SerialStatus.CONNECTION_FAILURE; } Thread.Sleep(100); h_AhrsSerialPort.DiscardOutBuffer(); // Changes to polled mode h_AhrsSerialPort.Write(new char[1] { 'P' }, 0, 1); Thread.Sleep(100); if (!pingSerial(5000)) { h_AhrsSerialPort.Close(); return SerialStatus.PING_RESPONSE_FAILURE; } else { m_packetLength = determinePacketLength(); if (m_packetLength < 30) { m_msg = "AHRS packet size too small."; m_receiving = false; return SerialStatus.PACKET_SIZE_MISSMATCH; } m_msg = "AHRS packet size found."; } //Change to Angle (VG) Mode h_AhrsSerialPort.Write(new char[1]{'a'},0,1); m_freqTimer.Start(); //Change to Normal Mode h_AhrsSerialPort.Write(new char[2] {'T', 'C' }, 0, 2); return SerialStatus.SUCCESS; }
public int GetWeight(out double Weight, out bool Stable, out string ErrMess) { Weight = 0; ErrMess = ""; Stable = true; try { Utils.ToLog("GetWeight "); port.DiscardInBuffer(); port.DiscardOutBuffer(); byte[] com = HexStringToByteArray("05"); port.Write(com, 0, 1); Utils.ToLog("GetWeight Send 05"); byte[] com2 = new byte[16]; int k = (port.Read(com2, 0, 2)); if (com2[0] != 6) { Utils.ToLog("GetWeight Неверный ответ на инит запрос Get " + com2[0].ToString()); ErrMess = "Некорректный ответ от весов"; return(-2); //Неверный ответ на инит запрос } com = HexStringToByteArray("11"); port.Write(com, 0, 1); Thread.Sleep(500); Utils.ToLog("GetWeight Send 11"); k = (port.Read(com2, 0, 15)); string Prt = ""; for (int j = 0; j < 15; j++) { Prt += com2[j].ToString() + " "; } Utils.ToLog("Answer " + Prt); if ((com2[0] != 1) || (com2[1] != 2)) { Utils.ToLog("GetWeight Неверный ответ на инит запрос 2 Get " + com2.ToString()); ErrMess = "Некорректный ответ от весов"; return(-3); //Неверный ответ на инит запрос 2 } if (com2[2] != 0x53) { Stable = false; //Utils.ToLog("GetWeight Весы нестабильны " + com2.ToString()); //return -4; //Весы нестабильны } int Plus = 1; if (com2[3] != 0x20) { //Utils.ToLog("GetWeight Вес отрицателен " + com2.ToString()); Plus = -1; //return -5; //Вес отрицателен } string res = ""; for (int i = 0; i < 6; i++) { Utils.ToLog("sc res = " + res); res += Convert.ToChar(com2[i + 4]).ToString(); } Weight = Convert.ToDouble(ReplDemSep(res)) * Plus; return(0); } catch (Exception e) { Utils.ToLog("Error GetWeight " + e.Message); ErrMess = "Ошибка " + e.Message; return(-1); } }