bool IsPVC(SerialPort port) { string returnMessage = ""; try { if (port.IsOpen) port.Close (); port.Open (); Thread.Sleep (1500); // Fails if this delay is any shorter port.Write ("#"); port.Write (port.NewLine); Thread.Sleep (500); // Fails if this delay is any shorter int count = port.BytesToRead; int intReturnASCII = 0; while (count > 0) { intReturnASCII = port.ReadByte (); returnMessage = returnMessage + Convert.ToChar (intReturnASCII); count--; } } catch { } finally { port.Close (); } if (returnMessage.Contains (Identifier)) { return true; } else { return false; } }
public string Identify(SerialPort port) { string returnMessage = ""; try { if (port.IsOpen) port.Close (); port.Open (); Thread.Sleep (1500); // Fails sometimes if this delay is any shorter port.Write (IdentifyRequest); port.Write (port.NewLine); Thread.Sleep (500); // Fails sometimes if this delay is any shorter int count = port.BytesToRead; int intReturnASCII = 0; while (count > 0) { intReturnASCII = port.ReadByte (); returnMessage = returnMessage + Convert.ToChar (intReturnASCII); count--; } } catch { } finally { port.Close (); } return returnMessage.Trim(); }
public string ReadData() { byte tmpByte; string rxString = ""; try { tmpByte = (byte)mySerial.ReadByte(); //Console.WriteLine("Start ...." + tmpByte); while (tmpByte != 255) { rxString += ((char)tmpByte); tmpByte = (byte)mySerial.ReadByte(); //Console.WriteLine("Get data ...." + tmpByte); } } catch (System.TimeoutException exc) { // ignore timeout, finish read-out } LogHelper.Log(LogLevel.Info, String.Format("Message received:" + rxString.Trim().Replace('\r', '-'))); return(rxString); }
// public Read_Data_From_Com_Port() // { //// to_read_the_data_from_a_port(); // } public void ReadData() { byte tmpByte; string rxString = ""; try { tmpByte = (byte)mySerial.ReadByte(); while ((char)tmpByte != '\r') { if (char.IsDigit(((char)tmpByte))) { rxString += ((char)tmpByte); } tmpByte = (byte)mySerial.ReadByte(); } if (rxString.Length > 0) { //lock (MainStaticClass.Barcode) //{ MainStaticClass.Barcode = rxString; //} } } catch (Exception ex) { //MessageBox.Show(ex.Message); } }
private string ReadByteData() { byte tmpByte; string rxString = ""; try { tmpByte = (byte)_comPort.ReadByte(); //LogHelper.Log(LogLevelTrace, String.Format("Start ...." + tmpByte)); while (tmpByte != 255) { rxString += ((char)tmpByte); tmpByte = (byte)_comPort.ReadByte(); //LogHelper.Log(LogLevel.Trace, String.Format("Get data ...." + tmpByte)); } } catch (System.TimeoutException exc) { // ignore timeout, finish read-out } LogHelper.Log(LogLevel.Debug, "(ReadByteData) Message received:" + rxString.Trim().Replace('\r', '-')); return(rxString); }
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); } }
private void ReadTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (ComPort.BytesToRead > 0) { int counter = ComPort.BytesToRead; for (int i = 0; i < counter; i++) { DataReadBack[DataReadCount] = (byte)ComPort.ReadByte(); DataReadCount++; } } if (DataReadCount > 7) {//满足解析的必要条件 // for (int i = 0; (i + 1) < DataReadCount; i++) { if (DataReadBack[i] == 0x55 && DataReadBack[i + 1] == 0xAA && (DataReadCount - i) >= 7) { FrameCopy(i); ReorgnizeBuf(i); } else if ((DataReadCount - i) < 7) { //未接受完,继续接收等待 } } } }
public XmlElement GetTemperature(string port, string baudRate) { try { _serialPort = new SerialPort(port,Convert.ToInt32(baudRate)); _serialPort.Open(); if (!_serialPort.IsOpen) { throw new Exception("Cannot Open Serial Port..."); } count = _serialPort.BytesToRead; if (count < 1) { throw new Exception("No Data to Read..."); } else { while (count > 0) { int byteData = _serialPort.ReadByte(); data = data + Convert.ToChar(byteData); } } _result = GetXML(data.ToString()); } catch (Exception ex) { _result = GetExceptionXML(ex.ToString()); } return _result; }
public RadioDevice(string comPort, bool IsMaster) { this.comPort = comPort; this.IsMaster=IsMaster; com = new SerialPort(comPort, 9600, Parity.None, 8, StopBits.One); try { com.Open(); } catch (Exception ex) { Console.WriteLine(ex.Message); throw ex; } System.Threading.Thread.Sleep(1000); int cnt = com.BytesToRead; for (int i = 0; i < cnt; i++) { // lock(this) com.ReadByte(); } // long l= com.BaseStream.Length; // for (int i = 0; i < l; i++) // com.ReadByte(); // if(!IsMaster) ReceiverThread = new Thread(ReceiverTask) ; ReceiverThread.Start(); }
public static byte[] ReadBytesFromPort(System.IO.Ports.SerialPort _serialPort, int iMaxBuffer = 512) { byte[] DataIn = null; int index = 0; try { byte[] DatosInBytes = new byte[iMaxBuffer]; while (_serialPort.BytesToRead != 0) { DatosInBytes[index] = (byte)(_serialPort.ReadByte()); index++; if (index >= iMaxBuffer - 1) { break; } } DataIn = new byte[index]; if (index > 0) { Array.Copy(DatosInBytes, DataIn, index); } return(DataIn); } catch (Exception ex) { Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message); DataIn = new byte[0]; return(DataIn); } }
protected override int ReadByte() { if (GetState() != SHIMMER_STATE_NONE) { return(SerialPort.ReadByte()); } throw new InvalidOperationException(); }
static void Main(string[] args) { SerialPort comm; string portName; long portNum; long block; string input; string filename; long page; byte checksum; Console.Write("COM Port ? "); input = Console.ReadLine(); portNum = long.Parse(input); Console.Write("Block ? "); input = Console.ReadLine(); block = long.Parse(input); Console.Write("Filename ? "); filename = Console.ReadLine(); portName = "COM" + portNum.ToString(); block = 0; comm = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One); comm.Open(); BinaryWriter bw = new BinaryWriter(File.Open(filename, FileMode.Create)); byte data; byte[] buf = new byte[1]; buf[0] = (byte) block; comm.Write(buf, 0, 1); checksum = 0; for (page = 0; page < 256; page++) { Console.WriteLine("Reading page " + page.ToString()); for (int i = 0; i < 128; i++) { data = (byte)comm.ReadByte(); bw.Write(data); if (i != 5) checksum += data; } } comm.Close(); Console.WriteLine("Checksum : " + checksum.ToString()); Console.WriteLine("Complete"); }
// Use included loader.bin for the Pi // run this program, put a breakpoint at the end and use the debugger to see what data is returned. // NOTE - this should compile with any C# compiler, but the serial port stuff is Windows specific. // I use an FT232-based USB adapter with the Ground/Tx/Rx pins hooked up to the Pi, and the port set to COM7. // Please feel free to write something easier to use!! static void Main(string[] args) { var sp = new SerialPort("COM7", 115200, Parity.None, 8); sp.Open(); byte[] data; using (var sr = new BinaryReader(new FileStream(PATH, FileMode.Open, FileAccess.Read))) { int length = (int)sr.BaseStream.Length; sr.BaseStream.Position = 0; data = new byte[length + 5]; // 0x7C indicates start of data to send data[0] = 0x7C; // size of data to send, 32-bit, big endian data[4] = (byte)(length & 0xFF); data[3] = (byte)((length >> 8) & 0xFF); data[2] = (byte)((length >> 16) & 0xFF); data[1] = (byte)((length >> 24) & 0xFF); // data to send sr.Read(data, 5, length); } sp.Write(data, 0, data.Length); // size of data to receive, 32-bit, big endian int recvLength = 0; for (int i = 0; i < 4; i++) { recvLength = (recvLength << 8) | (byte)sp.ReadByte(); } // data to receive byte[] recvData = new byte[recvLength]; for (int i = 0; i < recvData.Length; i++) { recvData[i] = (byte)sp.ReadByte(); } // PUT BREAKPOINT HERE }
public void SetupPort(string portName) { if (ports.Contains(portName)) { SerialMaster = new SerialPort(); SerialMaster.PortName = portName; SerialMaster.BaudRate = 115200; SerialMaster.DataBits = 8; SerialMaster.Parity = Parity.None; SerialMaster.StopBits = StopBits.One; SerialMaster.WriteBufferSize = 1000; SerialMaster.ReadTimeout = 2000; SerialMaster.WriteTimeout = 2000; SerialMaster.Open(); SerialMaster.DiscardNull.ToString(); SerialMaster.Encoding.ToString(); while (SerialMaster.BytesToRead > 0) { SerialMaster.ReadByte(); } SerialMaster.DataReceived += (o, e) => { int resp = SerialMaster.ReadByte(); if (resp == COMMAND_RESPONSE_OK) { WaitingForResponse = false; } else { throw new Exception("Invalid Response received"); } }; } else { //throw new SystemException("Port name " + portName + " not existent"); Disconnected?.Invoke(this, null); } Connected?.Invoke(this, null); }
public void ReadAllJunk() { if (!serial.IsOpen) { return; } while (serial.BytesToRead > 0) { serial.ReadByte(); } }
public int ReadByte() { if (port != null) { return(port.ReadByte()); } else { return(-1); } }
static void Main(string[] args) { SerialPort comm; string portName; long portNum; long block; string input; string filename; long pageIndex; byte inData; byte checksum; byte[] buf = new byte[1]; if (args.Length < 1) return; Console.Write("COM Port ? "); input = Console.ReadLine(); portNum = long.Parse(input); portName = "COM" + portNum.ToString(); //filename = args[0]; filename = "C:\\badge\\out.eeprom"; comm = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One); comm.Open(); BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)); byte data; // Send the 100 code to start things off buf[0] = (byte)100; comm.Write(buf, 0, 1); for (pageIndex = 0; pageIndex < 256; pageIndex++) { inData = (byte)comm.ReadByte(); Console.WriteLine("Writing page " + inData.ToString()); for (int i = 0; i < 128; i++) { data = br.ReadByte(); buf[0] = data; comm.Write(buf, 0, 1); } } comm.Close(); Console.WriteLine("Complete"); }
/// <summary> /// 串口读(非阻塞方式读串口,直到串口缓冲区中没有数据 /// </summary> /// <param name="readBuf">串口数据缓冲 </param> /// <param name="bufRoom">串口数据缓冲空间大小 </param> /// <param name="HowTime">设置串口读放弃时间 </param> /// <param name="ByteTime">字节间隔最大时间 </param> /// <returns>串口实际读入数据个数 </returns> public int ReadComm(out Byte[] readBuf, int bufRoom, int HowTime, int ByteTime) { //throw new System.NotImplementedException(); readBuf = new Byte[64]; Array.Clear(readBuf, 0, readBuf.Length); int nReadLen, nBytelen; if (serialPort1.IsOpen == false) { return(-1); } nBytelen = 0; serialPort1.ReadTimeout = HowTime; try { readBuf[nBytelen] = (byte)serialPort1.ReadByte(); byte[] bTmp = new byte[1023]; Array.Clear(bTmp, 0, bTmp.Length); nReadLen = ReadBlock(out bTmp, bufRoom - 1, ByteTime); if (nReadLen > 0) { Array.Copy(bTmp, 0, readBuf, 1, nReadLen); nBytelen = 1 + nReadLen; } else if (nReadLen == 0) { nBytelen = 1; } } catch (Exception ex) { throw new Exception(ex.Message); } return(nBytelen); }
/// <summary> /// Waitforsequence with option for verbosity /// </summary> /// <param name="str">String to look for</param> /// <param name="altStr">String to look for but don't want</param> /// <param name="sp">SerialPort object.</param> /// <param name="verbose">Boolean to indicate verbosity.</param> /// <returns>Boolean to indicate if str or altStr was found.</returns> public static Boolean waitForSequence(String str, String altStr, SerialPort sp, Boolean verbose) { Boolean strFound = false, altStrFound = false; Byte[] input = new Byte[256]; String inputStr; Int32 i; while ((!strFound) && (!altStrFound)) { i = 0; do { input[i++] = (Byte)sp.ReadByte(); //Console.Write(input[i - 1] + " "); } while ( (input[i - 1] != 0) && (i < (input.Length - 1)) && (input[i - 1] != 0x0A) && (input[i - 1] != 0x0D) ); // Convert to string for comparison if ((input[i-1] == 0x0A) || (input[i-1] == 0x0D)) inputStr = (new ASCIIEncoding()).GetString(input, 0, i-1); else inputStr = (new ASCIIEncoding()).GetString(input, 0, i); if (inputStr.Length == 0) { continue; } // Compare Strings to see what came back if (verbose) Console.WriteLine("\tTarget:\t{0}", inputStr); if (inputStr.Contains(altStr)) { altStrFound = true; if (String.Equals(str, altStr)) { strFound = altStrFound; } } else if (inputStr.Contains(str)) { strFound = true; } else { strFound = false; } } return strFound; }
private void Bus_port_DataReceived(object sender, SerialDataReceivedEventArgs e) { int s = bus_port.BytesToRead; while (s-- != 0) { Object temp = bus_port.ReadByte(); if (temp != null) { m_SyncContext.Post(date_chuli, temp); } } }
// Read data from port private void DataReceived(object sender, SerialDataReceivedEventArgs e) { try { // Read all the bytes from the port and send them to the upper layer while ((_SerialPort != null) && (_SerialPort.BytesToRead > 0)) { OnRxDataReceived((byte)_SerialPort.ReadByte()); } } catch (Exception) { } }
public byte ReadByte() { byte readByte = 0; try { readByte = (byte)m_serialPort.ReadByte(); } catch (Exception ex) { Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message); } return(readByte); }
private void si_DataReceived1() { lock (threadLock) { try { int count = Serial.ReadByte(); if (numTextbox == 5) { numTextbox = 0; } int step = 1; int data = 0; for (int i = 0; i < count; i++) { data += Serial.ReadByte() * step; step *= 10; } reserv(data); } catch { } } }
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; }
/// <summary> /// Reads the packet from the com port /// </summary> /// <param name="serialPort"></param> /// <returns></returns> public bool ReadPacket(SerialPort pPort) { bool vShortContent = false; if (pPort.BytesToRead == 0) { return false; } while ((char)pPort.ReadByte() != '$') { } while ((char)pPort.ReadByte() != '*') { } this.mID = (byte)pPort.ReadByte(); this.mType = (byte)pPort.ReadByte(); this.mSubType = (byte)pPort.ReadByte(); this.mExpectAcknowledge = ((byte)pPort.ReadByte() == 0 ? false : true); for (int i = 0; i < CONTENT_LENGTH; ) { this.mContent[i++] = (char)pPort.ReadByte(); if (i < CONTENT_LENGTH - 1 && this.mContent[i-1] == '*') { this.mContent[i++] = (char)pPort.ReadByte(); if (this.mContent[i-1] == '$') { vShortContent = true; break; } } } if (!vShortContent) { while ((char)pPort.ReadByte() != '*') { } while ((char)pPort.ReadByte() != '$') { } } //remove trailing *$ if (this.mContent != null) { for (int i = 0; i < CONTENT_LENGTH-1; i++) { if (this.mContent[i] == '*' && this.mContent[i + 1] == '$') { this.mContent[i] = (char)0; break; } } } return true; }
internal void Init() { comPort = new SerialPort(ApplicationConfig.Port, 9600, Parity.None, 8, StopBits.One); comPort.Handshake = Handshake.None; comPort.Open(); while (!_stop) { while (comPort.BytesToRead != 0) recievedData.Enqueue((byte)comPort.ReadByte()); ProcessReceivedData(); Thread.Sleep(20); } }
private string PSRead(string terminator, Single WaitTimeSeconds) { Int64 lng_WaitTm; string data; Int32 TermL; long tmr; if (terminator == null) { terminator = ""; } if (WaitTimeSeconds == 0) { WaitTimeSeconds = 2; } data = ""; TermL = terminator.Length; lng_WaitTm = Convert.ToInt64(WaitTimeSeconds * System.TimeSpan.TicksPerSecond); tmr = clsUtils.StartTimeInTicks(); while (clsUtils.ElapseTimeInSeconds(tmr) < WaitTimeSeconds) { if (m_ComPort.BytesToRead > 0) { while (m_ComPort.BytesToRead > 0) { data = data + Convert.ToChar(m_ComPort.ReadByte()); } System.Windows.Forms.Application.DoEvents(); if (m_ComPort.BytesToRead == 0) { if (TermL > 0) { if (data.EndsWith(terminator) == true) { break; } } } } System.Windows.Forms.Application.DoEvents(); } return(data); }
public bool ReadRemoveInputByte(out byte data) { if (serialPort == null || serialPort.IsOpen == false) { data = 0; return(false); } if (serialPort.BytesToRead > 0) { data = (byte)serialPort.ReadByte(); return(true); } data = 0; return(false); }
private static string ReadLine(SerialPort port, int timeout) { int i = 0; StringBuilder builder = new StringBuilder(); while (i < timeout) { while (port.BytesToRead > 0) { byte b = (byte)port.ReadByte(); switch (b) { case 0xAA: return ((char)b).ToString(); case 0x0D: return builder.ToString(); default: builder.Append((char)b); break; } } i++; Thread.Sleep(1); } throw new TimeoutException(); }
public static string readSequence(SerialPort sp, Boolean verbose) { Boolean strFound = false, altStrFound = false; Byte[] input = new Byte[256]; String inputStr; Int32 i; sp.ReadTimeout=300000; while ((!strFound) && (!altStrFound)) { i = 0; do { try { input[i++] = (Byte)sp.ReadByte(); } catch { //Console.Write("."); } //Console.Write(input[i - 1] + " "); } while ( (input[i - 1] != 0) && (i < (input.Length - 1)) && (input[i - 1] != 0x0A) && (input[i - 1] != 0x0D) ); // Convert to string for comparison if ((input[i-1] == 0x0A) || (input[i-1] == 0x0D)) inputStr = (new ASCIIEncoding()).GetString(input, 0, i-1); else inputStr = (new ASCIIEncoding()).GetString(input, 0, i); if (inputStr.Length == 0) { continue; } // Compare Strings to see what came back if (verbose) Console.WriteLine("\tTarget:\t{0}", inputStr); return inputStr; } return "FAIL"; }
private void button1_Click(object sender, EventArgs e) { CP1616Packet Rx1616 = new CP1616Packet(100, 1); bool bOK = false; for (int i = 0; i < 3; i++) { try { byte[] deviceID = new byte[2]; deviceID[0] = BytesOP.GetHighByte((ushort)numericUpDown1.Value); deviceID[1] = BytesOP.GetLowByte((ushort)numericUpDown1.Value); byte[] tx = CP1616Packet.MakeCP1616Packet(100, 1, deviceID); try { COMPort1.Write(tx, 0, tx.Length); } catch { continue; } while (true) { try { if (Rx1616.DataPacketed((byte)COMPort1.ReadByte())) { MessageBox.Show("设定成功"); bOK = true; return; } } catch { break; } } if (bOK) { break; } Thread.Sleep(100); } catch { break; } } MessageBox.Show("设定失败"); }
///<summary>读取</summary> private void Read() { try { int temp; do { temp = m_SerialPort.ReadByte(); if (temp >= 0) { m_Handler.Push((byte)temp); } }while (true); } catch { Stop(); } }
//Lectura en el puerto para esperar mensaje del arduino public String read() { using (SerialPort sp = new SerialPort("COM4", 9600)) // Pasarlos por parámetro { try { //Abre el puerto especifico sp.Open(); //Preparamos variables string returnMessage = ""; int intReturnASCII = 0; /* Enciclamos el sp.ReadByte(); para obtener los bytes desde el arduino * cada byte se pega a la linea de caracteres de retorno. * ## Esto deberia ser una tarea asyncrona ·## */ while (true) { //Lee un byte intReturnASCII = sp.ReadByte(); //Cuando lee un byte asigna a la cadena de retorno toda la cadena + el byte returnMessage = returnMessage + Convert.ToChar(intReturnASCII); //La cantidad de caracteres que queremos leer del codigo de la tarjeta if (returnMessage.Length == 26) // Pasarlo por parámetro { sp.Close(); return returnMessage; } } } //Si encuentra un error en el proceso catch(Exception e){ sp.Close(); return ""; } } }
public virtual void Read() { while (!KillThread) { try { switch (RMode) { case tRMode.LINE_MODE: COM_line(ComPort.ReadLine().TrimEnd('\r', '\n')); break; case tRMode.BYTE_MODE: int b = ComPort.ReadByte(); if (b == -1) { KillThread = true; } else { if (recv_buff == null) { recv_buff = new byte[2048]; recv_buff_length = 0; } recv_buff[recv_buff_length++] = (byte)b; if (COM_byte(recv_buff, recv_buff_length)) { recv_buff = null; recv_buff_length = 0; } } break; } } catch (Exception e) { Program.Logger(e.ToString()); KillThread = true; } } }
private static void RunTests() { SerialPort port = new SerialPort("COM6", 9600); port.Open(); const int count = 2; port.ErrorReceived += (s, e) => { Console.WriteLine("Error: " + e.EventType); }; while (true) { Random random = new Random(); byte[] buffer = new byte[count]; buffer[0] = (byte)random.Next(255); buffer[1] = (byte)random.Next(255); port.Write(buffer, 0, count); tx_bytes += 1; byte[] input = new byte[count]; int readed = 0; for (int i = 0; i < count; i++) { input[i] = (byte)port.ReadByte(); rx_bytes++; } rx_bytes += readed; Console.WriteLine("{0} - expected: {1}, received: {2}", rx_bytes, buffer, input); for (int i = 0; i < count; i++) { if (buffer[i] != input[i]) { Console.WriteLine("miss: {0} != {1}", buffer[i], input[i]); } } } }
static void Main(string[] args) { receiverPort = new SerialPort(); receiverPort.BaudRate = 9600; receiverPort.PortName = "COM18"; receiverPort.Open(); senderPort = new SerialPort(); senderPort.BaudRate = 4800; senderPort.PortName = "COM19"; senderPort.Open(); while (true) { int val = senderPort.ReadByte(); byte b = (byte)val; byte[] bytes = new byte[1]; bytes[0] = b; receiverPort.Write(bytes, 0, 1); Console.Write(bytes[0].ToString()); } }
public static byte[] readline(SerialPort comport) { byte[] temp = new byte[101]; int count = 0; int step = 0; while (true) { temp[count] = (byte)comport.ReadByte(); if (temp[0] == 'A' && temp[1] == 'A' && temp[2] == 'A' || step >= 1) // start of data { step++; } if (temp[count] == '\n' && step == 0) // normal line { break; } if (temp[count] == '\n' && step == AAAlength-1) // dont finish until we have all data { break; } count++; if (count == 100) break; } byte[] temp2 = new byte[count+1]; Array.Copy(temp, 0, temp2, 0, count+1); return temp2; }
private void WpiszOdebrane() { bufferData = port.ReadByte(); DodajKolorowy(rtbTerminal, bufferData.ToString() + " ", System.Drawing.Color.Blue); sprawdz(bufferData); }
// TODO постараться вынести инициализацию в метод Read private InitializationData ReadInitialization(SerialPort readport) { while (true) { try { readport.ReadTo("\xAA\x55"); // Считывание данных для создания пакета // Здесь важен строгий порядок считывания байтов, точно как в пакете. byte recipient = (byte)readport.ReadByte(); byte sender = (byte)readport.ReadByte(); ushort dataLenght = BitConverter.ToUInt16( new byte[] { (byte)readport.ReadByte(), (byte)readport.ReadByte() }, 0); byte option1 = (byte)readport.ReadByte(); byte option2 = (byte)readport.ReadByte(); ushort crc = BitConverter.ToUInt16( new byte[] { (byte)readport.ReadByte(), (byte)readport.ReadByte() }, 0); // Счетчик количества итерация цикла while int count = 0; while (readport.BytesToRead < dataLenght) { count++; Thread.Sleep(_sleepTime); if (count > dataLenght) { break; } } byte[] data = new byte[dataLenght]; readport.Read(data, 0, dataLenght); var packet = new Packet.Packet(new Header(recipient, sender, option1, option2), data); // Проверка crc и id клиента, id отправителя и типа пакета if (packet.Header.Crc == crc && packet.Header.Recipient == ClietnId && packet.Header.Sender == 0 && packet.Data.Type == DataType.Initialization) { SendAcknowledge(packet); var initialization = StructConvertor.FromBytes<InitializationData>(packet.Data.Content); return initialization; } } catch (InvalidOperationException) { IsPortAvailable(readport); Thread.Sleep(3000); } catch (TimeoutException exception) { // TODO ограничить количество отправок запроса SendInitializationRequest(); } catch (Exception exception) { LogHelper.GetLogger<CommunicationUnit>().Error("Ошибка при чтение с порта", exception); } } }
//Timer TimerDetectBoard; public bool DetectBoard() { string[] Ports = SerialPort.GetPortNames(); List<string> Found = new List<string>(); Board = null; foreach (string Port in Ports) { try { SerialPort sp = new SerialPort(Port, BaudRateBootloader, Parity.None, 8, StopBits.One); sp.RtsEnable = false; sp.DtrEnable = false; sp.Open(); /*TimerDetectBoard = new Timer(); TimerDetectBoard.Interval = 500; TimerDetectBoard.Start(); TimerDetectBoard.Tick += new EventHandler(t_Detect_Tick);*/ sp.Write(new byte[] { CMD_NOP }, 0, 1); int reply = -1; //while (TimerDetectBoard.Enabled) //reply = sp.ReadByte(); Thread.Sleep(500); if (sp.BytesToRead > 0) reply = sp.ReadByte(); if (reply != -1 && reply == CMD_NOP_REPLY) { Found.Add(Port); } Thread.Sleep(1000); sp.Close(); } catch (Exception) { } } if (Found.Count > 1) MessageBox.Show("Detected more XBoards! Using the first one."); foreach (string Port in Found) MessageBox.Show("Detected XBoard on port " + Port); if (Found.Count > 0) { Comm = new SerialPort(Found[0], BaudRateBootloader, Parity.None, 8, StopBits.One); Comm.RtsEnable = false; Comm.DtrEnable = false; Comm.Open(); Connected = true; LoadBoardInfo(); return true; } return false; }
public void DetectArduino() { if (sp.IsOpen) { sp.DataReceived -= sp_DataReceived; ClosePort(); } else { FillPorts(); foreach (string port in portslist) { //sp = new SerialPort(port, 9600); sp = new SerialPort(port, 38400); int intReturnASCII = 0; char charReturnValue = (Char)intReturnASCII; ClosePort(); sp.Open(); sp.WriteLine("1535 "); Thread.Sleep(500); int count = sp.BytesToRead; string returnMessage = ""; while (count > 0) { intReturnASCII = sp.ReadByte(); returnMessage = returnMessage + Convert.ToChar(intReturnASCII); count--; } Task.Delay(1000); sp.Close(); if (returnMessage.Contains("YES")) { Port = sp.PortName; OpenPort(Port); IsArduinoDetected = true; //Con.Content = "Desconectar"; } } } }
public static void tryConnect(int baud, string recognizeText, int loggedInValue) { try { byte[] buffer = new byte[5]; buffer[0] = Convert.ToByte(16); buffer[1] = Convert.ToByte(connectionCorrect); buffer[2] = Convert.ToByte(0); buffer[3] = Convert.ToByte(loggedInValue); buffer[4] = Convert.ToByte(4); int intReturnASCII = 0; char charReturnValue = (Char)intReturnASCII; string[] ports = SerialPort.GetPortNames(); foreach(string newport in ports) { currentPort = new SerialPort(newport, baud); currentPort.Open(); currentPort.Write(buffer, 0, 5); Thread.Sleep(1000); int count = currentPort.BytesToRead; string returnMessage = ""; while(count > 0) { intReturnASCII = currentPort.ReadByte(); returnMessage = returnMessage + Convert.ToChar(intReturnASCII); count--; }; port = newport; if(returnMessage.Contains(recognizeText)) { connectionCorrect = 127; } } } catch(UnauthorizedAccessException e) { System.Windows.Forms.MessageBox.Show(e.Message); } }
static void Main(string[] args) { try { if (args.Length != 4) { Console.WriteLine("usage: sendjpeg <jpegfile> <com-port> <baud-rate> <chunk-size>"); return; } // open the port Console.WriteLine("Opening port "+args[2]); SerialPort serialPort = new SerialPort(args[1],int.Parse(args[2]),Parity.None,8,StopBits.One); serialPort.Handshake = Handshake.None; serialPort.Open(); // get the size of the file to send FileInfo fi=new FileInfo(args[0]); long size=fi.Length; Console.WriteLine("Writing file size ("+size+") bytes"); // send the file size, LSB first byte[] buffer=new byte[4]; buffer[3]=(byte)((size >> 24) & 0xff); buffer[2]=(byte)((size >> 16) & 0xff); buffer[1]=(byte)((size >> 8) & 0xff); buffer[0]=(byte)(size & 0xff); serialPort.Write(buffer,0,4); // get ready to send the file buffer=new byte[1000]; long remaining=size; int count,value; int chunkAvailable,chunkSize=int.Parse(args[3]); Console.WriteLine("Writing file data"); using(BufferedStream bs=new BufferedStream(new FileStream(args[0],FileMode.Open,FileAccess.Read))) { chunkAvailable=chunkSize; while(remaining>0) { // read either 1000 or what's left count=(int)(remaining<1000 ? remaining : 1000); bs.Read(buffer,0,count); for(int i=0;i<count;i++) { // send a byte serialPort.Write(buffer,i,1); // if we have just sent the last of a chunk, wait for the ack if(--chunkAvailable==0) { value=serialPort.ReadByte(); if(value!=0xaa) throw new Exception("Unexpected chunk acknowledgement"); // new chunk on its way chunkAvailable=chunkSize; } } remaining-=count; Console.Write("."); } } Console.WriteLine("\nDone."); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } }
//---------------------------------------------------------------------------- /// <summary> /// Обработчик события приёма данных из COM-порта /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { int data; // Сбрасываем межкадровый таймер _tmrInterFrameDelay.Stop(); if (_serialPort.BytesToRead == 0) { if ((_MaskOfMessageLog & TypeOfMessageLog.Warning) == TypeOfMessageLog.Warning) { Trace.TraceWarning("{0}: Поток ID: {1} : Принята нулевая посылка", DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId); } // После принятия очердной порции байт ответа // Запускаем межкадровый таймер _tmrInterFrameDelay.Start(); return; } else { StringBuilder sb; // Идёт транзакция запрос-ответ? if (_transaction == TransactionType.UnicastMode) { // Да - Принимаем байты sb = new StringBuilder(); while (_serialPort.BytesToRead != 0) { data = _serialPort.ReadByte(); if (data != -1) { lock (_incomingBuffer) { _incomingBuffer.Add(System.Convert.ToByte(data)); sb.Append(data.ToString("X2")); sb.Append(" "); } } } if ((_MaskOfMessageLog & TypeOfMessageLog.Information) == TypeOfMessageLog.Information) { Trace.TraceInformation("{0}: Поток ID: {1} : Принято байт: {2}", DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId, sb.ToString()); } // После принятия очердной порции байт ответа // Запускаем межкадровый таймер _tmrInterFrameDelay.Start(); } else { // Нет - принят мусор с линии sb = new StringBuilder(); // Вычитываем этот мусор while (_serialPort.BytesToRead != 0) { data = _serialPort.ReadByte(); if (data != -1) { lock (_incomingBuffer) { sb.Append(data.ToString("X2")); sb.Append(" "); } } } if ((_MaskOfMessageLog & TypeOfMessageLog.Warning) == TypeOfMessageLog.Warning) { Trace.TraceWarning("{0}: Поток ID: {1} : Приняты данные, в отсутствии запроса : {2}", DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId, sb.ToString()); } _serialPort.DiscardInBuffer(); } } }
private bool Handshake(SerialPort sp) { try { //The below setting are for the Hello handshake byte[] buffer = new byte[2] { Convert.ToByte(16), Convert.ToByte(128) }; int intReturnASCII = 0; char charReturnValue = (Char)intReturnASCII; if (!sp.IsOpen) sp.Open(); sp.Write(buffer, 0, 2); Thread.Sleep(500); int count = sp.BytesToRead; string returnMessage = ""; while (count > 0) { intReturnASCII = sp.ReadByte(); returnMessage = returnMessage + Convert.ToChar(intReturnASCII); count--; } // ComPort.name = returnMessage; sp.Close(); if (returnMessage.Contains("FOOT")) { numOfButtons.Add(sp.PortName, (int)Char.GetNumericValue(returnMessage[4])); return true; } else { return false; } } catch (Exception) { return false; } }
public int Read() { return(port.ReadByte()); }
private void AsyncReceive(SerialPort com) { if (!com.IsOpen) return; try { int len = com.BytesToRead; if (len < MessageLenth) return; byte c; if (index == 0)//从头读 { for (int pos = 0; pos < len; pos++) { c = (byte)com.ReadByte(); if (c == Head) { myBuffer[index++] = c; break; } } len = com.BytesToRead; } if (index > 0)//已经读到起始符了 { for (int pos = 0; pos < len; pos++) { c = (byte)com.ReadByte(); myBuffer[index++] = c; if (index == 4) { string str = string.Format("{0:X}", myBuffer[1]); System.Array.Clear(myBuffer, 0, BufferSize); index = 0; SerialPort_OnReceive(str); } } } } catch { } }
/// <summary> /// Takes reading from Atlas Scientific ElectricalConductivity Stamp /// </summary> /// <returns></returns> private float GetPPM() { float PPM = 0.0F; SerialPort sp = new SerialPort(Serial.COM2, 38400, Parity.None, 8, StopBits.One); sp.ReadTimeout = 1000; try { string command = ""; string response = ""; char inChar; // Send the temperature reading if available if (m_Temperature > 0) command = m_Temperature.ToString("F") + "\rR\r"; else command = "R\r"; Debug.Print(command); byte[] message = Encoding.UTF8.GetBytes(command); sp.Open(); sp.Write(message, 0, message.Length); sp.Flush(); Debug.Print("sending message"); // Now collect response while ((inChar = (char)sp.ReadByte()) != '\r') { response += inChar; } response = response.Split(',')[1]; // Stamp can return text if reading was not successful, so test before returning double ppmReading; if (Double.TryParse(response, out ppmReading)) PPM = (float)ppmReading; } catch (Exception e) { Debug.Print(e.StackTrace); } finally { sp.Close(); sp.Dispose(); } return PPM; }
/// <summary> /// 从串口输入缓冲区中同步读取一个字节 /// </summary> /// <returns>强制转换为Int32 的字节;或者,如果已读取到流的末尾,则为 -1。</returns> public int ReadByte() { return(COM.ReadByte()); }
public void Work() { while (!_stop) { try { _serialPort = new SerialPort { PortName = _portName, BaudRate = 9600, StopBits = StopBits.One, Parity = Parity.None, DataBits = 8, DtrEnable = false, ReadTimeout = 200 }; _serialPort.Open(); while (!_stop) { for (byte i = 1; i <= 4; ++i) { _serialPort.ReadExisting(); _serialPort.Write(new byte[] { (byte)(i + 48) }, 0, 1); _inputBuffer[0] = (byte)_serialPort.ReadByte(); _inputBuffer[1] = (byte)_serialPort.ReadByte(); _inputBuffer[2] = (byte)_serialPort.ReadByte(); _inputBuffer[3] = (byte)_serialPort.ReadByte(); _inputBuffer[4] = (byte)_serialPort.ReadByte(); _inputBuffer[5] = (byte)_serialPort.ReadByte(); var tmpX = (Int16)((_inputBuffer[0] << 8) | _inputBuffer[1]); var tmpY = (Int16)((_inputBuffer[2] << 8) | _inputBuffer[3]); var tmpZ = (Int16)((_inputBuffer[4] << 8) | _inputBuffer[5]); /*if (_afterTimeout == 6) { var tmpX = (Int16)((_inputBuffer[0] << 8) | _inputBuffer[1]); var tmpY = (Int16)((_inputBuffer[2] << 8) | _inputBuffer[3]); var tmpZ = (Int16)((_inputBuffer[4] << 8) | _inputBuffer[5]); lock (_calibrationLock) { if (_calibrationPhase == 0) { if (Changed != null) Changed(this, new CompassEventArgs(new Point3D(tmpX, tmpY, tmpZ))); } else { if (_calibrationPhase % 2 == 1) { ++_calibrationPhase; if (CalibrationPhaseChanged != null) CalibrationPhaseChanged(this, new CalibrationEventArgs(CalibrationPhase.Rotate, _calibrationPhase == 2)); Thread.Sleep(100); if (CalibrationPhaseChanged != null) CalibrationPhaseChanged(this, new CalibrationEventArgs(CalibrationPhase.Hold, false)); _calibrationMilestone = _stopwatch.ElapsedMilliseconds; continue; } if (_calibrationDataOffset < 128) { _calibrationData[_calibrationDataOffset, 0] = tmpX; _calibrationData[_calibrationDataOffset, 1] = tmpY; _calibrationData[_calibrationDataOffset, 2] = tmpZ / 10d; _calibrationData[_calibrationDataOffset, 3] = 1; ++_calibrationDataOffset; } _calibrationX += tmpX; _calibrationY += tmpY; ++_calibrationMeasurements; if (_stopwatch.ElapsedMilliseconds - _calibrationMilestone > 4000) { if (_calibrationPhase++ == 8) { _calibrationPhase = 0; var tmpMatrixA = (new DenseMatrix(_calibrationData)).Transpose(); var tmpMatrixB = new DenseMatrix(_calibrationData); var tmpMatrixC = (new DenseMatrix(_calibrationData)).Transpose(); var tmpSquares = new double[128, 1]; for (var i = 0; i < 128; ++i) { tmpSquares[i, 0] = Math.Pow(_calibrationData[i, 0], 2) + Math.Pow(_calibrationData[i, 1], 2) + Math.Pow(_calibrationData[i, 2], 2); } var tmpMatrixD = new DenseMatrix(tmpSquares); var tmpBeta = tmpMatrixA.Multiply(tmpMatrixB).Inverse().Multiply(tmpMatrixC).Multiply(tmpMatrixD); _calibrationOffset.X = tmpBeta[0, 0] / 2; _calibrationOffset.Y = tmpBeta[1, 0] / 2; //_calibrationOffset.X = (double) (_calibrationX) / _calibrationMeasurements; //_calibrationOffset.Y = (double) (_calibrationY) / _calibrationMeasurements; if (CalibrationPhaseChanged != null) CalibrationPhaseChanged(this, new CalibrationEventArgs(CalibrationPhase.Calibrated, false)); } } } } } _afterTimeout = 0;*/ } } } catch (Exception) { if (_serialPort != null && _serialPort.IsOpen) _serialPort.Close(); } } if (_serialPort != null && _serialPort.IsOpen) _serialPort.Close(); }
private static bool GetPacket(SerialPort port, ref int length, byte[] buf, ref int cnt, ref bool escChar) { int b; if(port==null || !port.IsOpen) { return false; } while(port.BytesToRead>0) { b=port.ReadByte(); if(b<0) { break; } #if !UART_RAW_MQTTSN if(b==0xC0) { escChar=false; if(cnt>1 && cnt==length) { return true; } else { if(cnt>1) { Log.Warning("r {0}: {1} size mismatch: {2}/{3}", port.PortName, BitConverter.ToString(buf, 0, cnt), cnt, length); } cnt=-1; } continue; } if(b==0xDB) { escChar=true; continue; } if(escChar) { b^=0x20; escChar=false; } if(cnt==0x100) { cnt=-1; continue; } #endif if(cnt>=0) { buf[cnt++]=(byte)b; #if UART_RAW_MQTTSN if(cnt==length) { return true; } #endif } else { #if UART_RAW_MQTTSN if(b<2 && b>MsMessage.MSG_MAX_LENGTH) { if(_verbose.value) { Log.Warning("r 0x{0:X2} wrong length of the packet: {1}", port.PortName, b); } cnt=-1; port.DiscardInBuffer(); return false; } #endif length=b; cnt++; } } return false; }
private void button1_Click(object sender, EventArgs e) { try { port = new SerialPort("COM" + textBox3.Text, 9600); port.Open(); run = 1; //make it run mod = 1; //module 2 } catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } // number of bytes to read int count = port.BytesToRead; int [] inBuf = new int[2]; //initialize a 2 byte array. int temp = 0; while (run==1) { { inBuf[0] = port.ReadByte(); //get 2 bytes first from micor controller inBuf[1] = port.ReadByte(); if ((inBuf[0] + (inBuf[1] * 256)) == 0xDEAD) { //check if equal the start tag 0xDEAD for (int i = 0; i < 3;i++ ) // get x y c acceleroment, each size of them is 2 byte { inBuf[0] = port.ReadByte(); inBuf[1] = port.ReadByte(); temp = 0; if (i == 0) //x { label8.Text = Convert.ToString(inBuf[0] + (inBuf[1] * 256)); // combine 2 byte to 1 temp = temp + (inBuf[0] + (inBuf[1] * 256)); } else if (i == 1) //y { label9.Text = Convert.ToString(inBuf[0] + (inBuf[1] * 256)); temp = temp + (inBuf[0] + (inBuf[1] * 256)); } else if (i == 2) //z { label10.Text = Convert.ToString(inBuf[0] + (inBuf[1] * 256)); temp = temp + (inBuf[0] + (inBuf[1] * 256)); } perfChart1.AddValue(temp/30); //reduce the size of the acceleroment and put it on the graph. Using the perf Chart. Application.DoEvents(); } } else continue; } } }
void begin() { this.Cmd = 'R'; Task.Run(async () => { try { var c = new UdpClient(cPort); for (;;) { var r = await c.ReceiveAsync(); if (r.Buffer.Length > 0) { if (r.Buffer[0] == 'S') this.Cmd = 'S'; else if (r.Buffer[0] == 'R') this.Cmd = 'R'; else this.Cmd = '?'; } } } catch (Exception ex) { Console.WriteLine("UdpClient error. {0}", ex); } }); Task.Run(() => { try { for (;;) { string port = ""; lock (this) { var pp = new List<string>(); for (int p = 0; p < 10; ++p) pp.Add(string.Format("/dev/ttyACM{0}", p)); for (int p = 0; p < 10; ++p) pp.Add(string.Format("/dev/ttyUSB{0}", p)); bool ok = false; do { for (int p = 0; p < pp.Count; ++p) { try { port = pp[p]; _s = new SerialPort(port); //_s.BaudRate = 19200; //_s.BaudRate = 115200; _s.BaudRate = 38400; _s.DataBits = 8; _s.Parity = Parity.None; _s.StopBits = StopBits.One; _s.Handshake = Handshake.None; _s.ReadTimeout = 100; _s.Open(); ok = true; break; } catch (Exception) { } } } while(ok == false); } var cc = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("===> Reading from {0} port <====", port); Console.ForegroundColor = cc; while (this.Cmd == 'R') { try { int b = _s.ReadByte(); char ch = (char)b; Console.Write("{0}", ch); } catch (TimeoutException) { } } if (this.Cmd == 'S') { Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("===> Releasing COM port <===="); Console.ForegroundColor = cc; lock(this) { _s.Close(); _s = null; this.Cmd = '?'; } } while (this.Cmd != 'R') { Thread.Sleep(100); } } } catch (Exception ex) { Console.WriteLine("Task.Run error. {0}", ex); } }); try { for (;;) { var r = Console.ReadKey(); string ss = r.KeyChar.ToString(); lock (this) { if (_s != null) _s.Write(ss); } } } catch (Exception ex) { Console.WriteLine("ReadKey error. {0}", ex); } }
void ReadSerialPort(CancellationToken token) { var header = new byte[] { 0xFF, 0xFE, 0xFF, 0xFE }; var serialPort = new SerialPort("COM3", 115200); serialPort.Open(); try { while (!token.IsCancellationRequested) { var headerIndex = 0; while (headerIndex < header.Length) { WaitForBytesReady(serialPort, 1, token); var value = serialPort.ReadByte(); if (value == header[headerIndex]) { headerIndex++; } else { headerIndex = 0; } } _currentData = ReadBytes(serialPort, token); } } catch (OperationCanceledException) { } finally { serialPort.Close(); } }