public static void Main() { SerialPort serialPort = new SerialPort("COM1", 115200, Parity.None); serialPort.ReadTimeout = 5000; // milliseconds serialPort.Open(); byte[] outBuffer = Encoding.UTF8.GetBytes("All right?\r\n"); byte[] inBuffer = new byte[2]; while (true) { Debug.Print("Request data"); serialPort.Write(outBuffer, 0, outBuffer.Length); int count = serialPort.Read(inBuffer, 0, 2); if (count == 2) { Debug.Print("Received expected two bytes!"); } else { if (count == 0) Debug.Print("No response!"); if (count == 1) Debug.Print("Not enough bytes received!"); } Debug.Print(string.Empty); } }
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(); }
private void buttonSend_Click(object sender, EventArgs e) { string number = textBoxNumber.Text; string message = textBoxMessage.Text; _serialPort = new SerialPort("COM7", 115200); //Replace "COM7" with corresponding port name Thread.Sleep(1000); _serialPort.Open(); Thread.Sleep(1000); _serialPort.Write("AT+CMGF=1\r"); Thread.Sleep(1000); _serialPort.Write("AT+CMGS=\"" + number + "\"\r\n"); Thread.Sleep(1000); _serialPort.Write(message + "\x1A"); Thread.Sleep(1000); labelStatus.Text = "Status: Message sent"; _serialPort.Close(); }
public static AsyncSerial SearchPort(string write, char search, int baud=9600) { foreach (string port in SerialPort.GetPortNames()) { SerialPort temp; try { temp = new SerialPort(port, baud); try { temp.Open(); temp.ReadTimeout = 2500; temp.Write(write); var v = temp.ReadChar(); MainForm.Instance.logControl.Add(v.ToString(), LogEntryType.Error); if (v == search) { temp.Close(); return new AsyncSerial(port); } } catch (Exception ex) {} finally { temp.Close(); } } catch (Exception ex) {} } throw new Exception("Port not found."); }
void do_Send(string vMsg) { if (string.IsNullOrEmpty(vMsg)) { return; } if (ckASCII_out.Checked) { byte[] sndBuffer = ASCIIEncoding.Default.GetBytes(vMsg); _client.Write(sndBuffer, 0, sndBuffer.Length); } else { string[] _arr = vMsg.Split(' '); List <byte> _lst = new List <byte>(); if (!F_Parse.IsNumeric(_arr[0])) { byte[] sndBuffer = ASCIIEncoding.Default.GetBytes(vMsg); _client.Write(sndBuffer, 0, sndBuffer.Length); } else { for (int i = 0; i < _arr.Length; i++) { _lst.Add((byte)Convert.ToInt32(_arr[i], 16)); } if (_lst.Count > 0) { _client.Write(_lst.ToArray(), 0, _lst.Count); } } } }
/// <summary> /// 开始检测 /// </summary> /// <returns>string</returns> public bool Start() { ReadData(); int i = 0; byte[] Content = new byte[] { 0x02, 0x01, 0xa6, 0x57 }; ComPort_1.Write(Content, 0, 4); //发送开始测量命令 Thread.Sleep(50); while (ComPort_1.BytesToRead < 4) //等待仪器返回 { i++; Thread.Sleep(10); if (i == 100) { return(false); } } ReadData(); if (Read_Buffer[0] == 0x06) { return(true); } else { return(false); } }
private void TrySerial() { /* to understand if the keyboard is serial or ps/2 */ if (serialPort.BytesToRead > 0) { serialPort.ReadExisting(); } if (PosConfiguration.IntegrationMode != IntegrationMode.S60D_KEYBOARD) { //below bytes creates bytes to read if keyboard is serial HY_Write(new byte[] { 0xBA, 0x03, 0x98, 0x02, 0x00 }, 0, 5); //clear keyboard immediately, because if keyboar is not serial, unwanted characters occurs on the display serialPort.Write(initializeDisplay, 0, 3); System.Threading.Thread.Sleep(150); //if (serialPort.BytesToRead == 0) // throw new NotSerialException(); } else { Write(initLCD, 0, initLCD.Length); } /* if serial read bytes to read */ serialPort.ReadExisting(); }
/// <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("Время на ожидание ответа вышло"); }
private void Wyslij(string numer, string wiadomosc) { //inicjalizacja zmiennej port z domyślnymi wartościami port = new SerialPort(); //ustawienie timeoutów aby program się nie wieszał port.ReadTimeout = 500; port.WriteTimeout = 500; sPortName = textBox3.Text; string sBaud = "9600"; string sData = "8"; string sParity = "None"; string sStop = "One"; port.PortName = sPortName; port.BaudRate = Int32.Parse(sBaud); port.DataBits = Int32.Parse(sData); port.Parity = (Parity)Enum.Parse(typeof(Parity), sParity); port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), sStop); port.Open(); Pauza(); port.Write("at" + (char)13); // TODO: przy pierwszej komendzie ATodem zwraca "ERROR" zamiast "OK" ? Pauza(); port.Write("at+cmgf=1" + (char)13); Pauza(); port.Write("at+cmgs=" + (char)34 + numer + (char)34 + (char)13); Pauza(); port.WriteLine(wiadomosc + (char)26 + (char)13); Pauza(); port.Close(); }
// private static System.IO.Ports.SerialPort serialPort1 = new System.IO.Ports.SerialPort(); public static void display(string Line1, string Line2, string Line3, string Line4) { System.IO.Ports.SerialPort serialPort1 = new System.IO.Ports.SerialPort(); try { serialPort1.PortName = PortName; serialPort1.BaudRate = Convert.ToInt32(BaudRate); serialPort1.DataBits = Convert.ToInt32(DataBits); serialPort1.Parity = Parity.None; serialPort1.StopBits = StopBits.One; serialPort1.DtrEnable = true; serialPort1.RtsEnable = true; serialPort1.Open(); serialPort1.Write(new byte[] { 0x0C }, 0, 1); // byte[] data = Encoding.ASCII.GetBytes(Line1 + space1 + Line2); // your byte data; serialPort1.Write(Line1 + Line2); //Goto Bottem Line //serialPort1.Write(new byte[] { 0x0A, 0x0D }, 0, 2); //byte[] data1 = Encoding.ASCII.GetBytes(Line3 + space2 + Line4); // your byte data; serialPort1.Write(Line3 + Line4); serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; } catch (Exception) { serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; //MessageBox.Show(ex.ToString() + "----"+ PortName+"----"+ BaudRate.ToString()+"----"+ DataBits.ToString()); } }
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); } }
public HYDisplay() { try { String portName = PosConfiguration.Get("DisplayComPort"); serialPort = new SerialPort(portName); if (!serialPort.IsOpen) { serialPort.ReadTimeout = 2048; serialPort.Open(); Write(ledsOff, 0, 6); Write(initializeDisplay, 0, 3); serialPort.Write(horizontalScrollMode, 0, horizontalScrollMode.Length); System.Threading.Thread.Sleep(100); serialPort.Write(normalMode, 0, normalMode.Length); } } catch (UnauthorizedAccessException ex) { throw ex; } catch { Display.Log.Fatal("HYDisplay:HyDisplay - Exception {0} is {1}", serialPort.PortName, serialPort.IsOpen ? "Open" : "Closed"); } }
private void Tick_Elapsed(object sender, ElapsedEventArgs e) { if (TimeOut != 0) { if (--TimeOut == 0) { if (ReSendCount != 0) { ReSendCount--; ResendPack(); return; } if (RecvFlag != 0) { RecvFlag = 0; if (CallBackList[tcmd] != null && COM.IsOpen) { CallBackList[tcmd](PacketStats.RecvTimeOut, recvbuff); } } if (DataPipe.Count != 0 && COM.IsOpen) { COM.Write(DataPipe[0], 0, DataPipe[0].Length); DataPipe.RemoveAt(0); } } } if (RecvTimeout != 0) { if (--RecvTimeout == 0) { RecvMode = 0; } } }
private void sendBtn_Click(object sender, EventArgs e) { if (port.IsOpen) { port.Write(sendText.Text); } }
public static void WritePage(byte[] pageData, int pageNumber, int pageSize, SerialPort port) { port.Write(new byte[1]{Convert.ToByte(pageNumber)},0,1); port.Write(pageData,pageNumber*pageSize,pageSize); if(port.ReadChar()!='A') throw new Exception("No acknowledge from target!"); }
private bool sendSMS(string port, string phoneno, string msg) { bool status = false; try { System.IO.Ports.SerialPort sport = new System.IO.Ports.SerialPort(); sport.PortName = port; sport.BaudRate = 9600; sport.DataBits = 8; sport.StopBits = StopBits.One; sport.Parity = Parity.None; sport.Open(); sport.Write(@"AT+CMGF=1" + (char)(13)); sport.Write(@"AT+CMGS=" + (char)(34) + phoneno + (char)(34) + (char)(13)); sport.Write(@msg + (char)(13) + (char)(26)); sport.Close(); status = true; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } return(status); }
private void bSend_Click(object sender, EventArgs e) { DateTime dt = DateTime.Now; String dtn = dt.ToShortTimeString(); cmd_send_last = cmd_send; cmd_send = tbTx.Text; pBar.Maximum = Import.Length; pBar.Step = 1; tbEX.Clear(); sport.Write(cmd_send); tbRX.AppendText("\n---------------------------------------------\n\n"); tbRX.AppendText("[" + dtn + "]" + " Sent: " + cmd_send + "\n\n"); // Import new data on board if (cmd_send == "3" && IsImport) { for (int i = 0; i < Import.Length; i++) { sport.Write(Import[i]); System.Threading.Thread.Sleep(10); // Debug transimiting error sport.Write("\n"); System.Threading.Thread.Sleep(5); pBar.PerformStep(); } sport.Write("\r"); tbRX.AppendText("[" + dtn + "]" + " Import done.\n"); } }
public static void OpenDrawer() { System.IO.Ports.SerialPort serialPort1 = new System.IO.Ports.SerialPort(); serialPort1.PortName = CashDrawPortName; serialPort1.Encoding = Encoding.ASCII; serialPort1.BaudRate = Convert.ToInt32(CashDrawBaudRate); serialPort1.Parity = System.IO.Ports.Parity.None; serialPort1.DataBits = Convert.ToInt32(CashDrawDataBits); serialPort1.StopBits = System.IO.Ports.StopBits.One; serialPort1.DtrEnable = true; try { serialPort1.Open(); serialPort1.Write(Char.ConvertFromUtf32(27) + char.ConvertFromUtf32(64)); serialPort1.Write(char.ConvertFromUtf32(27) + char.ConvertFromUtf32(112) + char.ConvertFromUtf32(0) + char.ConvertFromUtf32(5) + char.ConvertFromUtf32(5)); serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; } catch (Exception) { serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; // MessageBox.Show(ex.ToString() + "----" + CashDrawPortName + "----" + CashDrawBaudRate.ToString() + "----" + CashDrawDataBits.ToString()); } }
private bool SendReadCommand(byte devID, UInt16 address, UInt16 length) { UInt16 CRC; byte[] command = new byte[9]; command[0] = devID; command[1] = (byte)COMMAND.READ; command[2] = (byte)(address / 256); command[3] = (byte)(address % 256); command[4] = (byte)(length / 256); command[5] = (byte)(length % 256); CRC = MakeCRC(command, 6); command[6] = (byte)(CRC / 256); command[7] = (byte)(CRC % 256); command[8] = (byte)ASCII.EOT; try { m_SerialPort.Write(command, 0, command.Length); } catch { return(false); } return(true); }
public void Write(System.IO.Ports.SerialPort comPort) { //comPort = new System.IO.Ports.SerialPort("Com2", 115200, System.IO.Ports.Parity.None, 8, StopBits.One); comPort.DtrEnable = true; comPort.Write("ATZ" + System.Convert.ToChar(13).ToString()); //Switch to Voice Mode comPort.Write("AT+FCLASS=8" + System.Convert.ToChar(13).ToString()); comPort.Write("AT+VSM=128,8000" + System.Convert.ToChar(13).ToString()); //start calling string m_phoneNumber = ""; comPort.Write("ATDT" + m_phoneNumber + System.Convert.ToChar(13).ToString()); System.Threading.Thread.Sleep(17000); //to enable voice-transmission mode @ send audio file comPort.Write("AT+VTX" + System.Convert.ToChar(13).ToString()); //Call Number comPort.Write("ATDT1231234" + System.Convert.ToChar(13).ToString()); //Enter Voice-Transmission Mode comPort.Write("AT+VTX" + System.Convert.ToChar(13).ToString()); bool MSwitch = false; byte[] buffer = new byte[500000]; FileStream strm = new FileStream(@"C:\HelpSound.wav", System.IO.FileMode.Open); MemoryStream ms = new MemoryStream(); int count = ms.Read(buffer, 44, buffer.Length - 44); BinaryReader rdr = new BinaryReader(strm); while (!MSwitch) { byte[] bt = new byte[1024]; bt = rdr.ReadBytes(1024); if (bt.Length == 0) { MSwitch = true; break; } comPort.Write(bt, 0, bt.Length); } strm.Close(); strm.Dispose(); comPort.Close(); //we terminate the connection by: sending 0x10 0x03 to the modem to switch off the sending mode byte[] terminator = new byte[2]; terminator[0] = 0x10; terminator[1] = 0x03; comPort.Write(terminator, 0, 2); //and then hang up the phone by sending “ATH”. comPort.Write("ATH" + System.Convert.ToChar(13).ToString()); }
private void btnMove_Click(object sender, EventArgs e) { string err = "Error: Please Enter valid Hex-Code!"; string pos = comPositions.Text; byte[] bit = new byte[6]; if (pos == "Position 1") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x1, 0x0, 0xBA }; } else if (pos == "Position 2") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x2, 0x0, 0xBB }; } else if (pos == "Position 3") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x3, 0x0, 0xBC }; } else if (pos == "Position 4") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x4, 0x0, 0xBD }; } else if (pos == "Position 5") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x5, 0x0, 0xBE }; } else if (pos == "Position 6") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x6, 0x0, 0xBF }; } else if (pos == "Position 7") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x7, 0x0, 0xC0 }; } else if (pos == "Position 8") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x8, 0x0, 0xC1 }; } else if (pos == "Position 9") { bit = new byte[] { 0xA5, 0x3, 0x11, 0x9, 0x0, 0xC2 }; } else if (pos == "Position 10") { bit = new byte[] { 0xA5, 0x3, 0x11, 0xA, 0x0, 0xC3 }; } else { txtError.Text = err; } sport.Write(bit, 0, 6); Thread.Sleep(200); byte[] move = new byte[sport.BytesToRead]; sport.Read(move, 0, sport.BytesToRead); }
public bool SendData(byte[] data) { try { serial.Write(data, 0, data.Length); return(true); } catch { return(false); } }
public void Send(SerialPort SP) { SP.Write(new byte[] { Command }, 0, 1); SP.Write(new byte[] { (byte)(PageNumber >> 8), (byte)(PageNumber & 0xFF) }, 0, 2); SP.Write(new byte[] { Part }, 0, 1); SP.Write(new byte[] { (byte)(CRC16 >> 8), (byte)(CRC16 & 0xFF) }, 0, 2); SP.Write(Payload, 0, Payload.Length); // should be 32 bytes in length }
void sendAck() { print("Sending ACK..."); if (arduinoSerialPort != null && arduinoSerialPort.IsOpen) { arduinoSerialPort.Write(ARDUINO_ACK); arduinoSerialPort.BaseStream.Flush(); } }
public void SetColor(int r, int g, int b) { SerialPort sp = new SerialPort("COM7", 9600); sp.Open(); sp.Write(new Byte[] {0xFF },0,1); sp.Write(new Byte[] { (Byte)(r) }, 0, 1); sp.Write(new Byte[] { (Byte)(g) }, 0, 1); sp.Write(new Byte[] { (Byte)(b) }, 0, 1); sp.Close(); }
// Gets the uart->spi bridge's signature (MSP430 etc) public static string GetBridgeSignature(SerialPort sp) { //sp.Write("{g00}"); sp.Write("{"); sp.Write("g"); sp.Write("0"); sp.Write("0"); sp.Write("}"); return sp.ReadLine(); }
static void Write(SerialPort port, string data, bool sleep) { foreach (char c in data) { port.Write(new string(c, 1)); if (sleep) Thread.Sleep(50); } port.Write("\r"); }
static private void Send(System.IO.Ports.SerialPort serialPort1, byte[] data) { if (serialPort1 == null || !serialPort1.IsOpen) { return; } if (!serialPort1.IsOpen) { return; } if (data.Length <= 64) { try { serialPort1.Write(data, 0, data.Length); while (serialPort1.BytesToWrite > 0) { ; } } catch { } } else { byte offset = 0; int len = data.Length; while (len > 0) { try { serialPort1.Write(data, offset, len > 64 ? 64 : len); while (serialPort1.BytesToWrite > 0) { ; } } catch { } len -= 64; offset += 64; } } while (serialPort1.BytesToWrite > 0) { ; } }
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"); }
public void Write(string data) { if (!serialport.IsOpen) { Open(); } if (serialport.IsOpen) { serialport.Write(data); } }
public void ByteCommand(byte[] cmd) { if (myPort.IsOpen) { try { myPort.Write(cmd, 0, cmd.Length); } catch { } } }
public void SendMultipleLeds(LedStrip ledStrip) { if (SerialMaster != null && SerialMaster.IsOpen && !WaitingForResponse) { byte[] command = { 0, 0, Convert.ToByte(ledStrip.NumberOfLeds), COMMAND_SET_MULTIPLE_LEDS }; byte[] data = ledStrip.ToByteArray(); SerialMaster.Write(command, 0, command.Count()); SerialMaster.Write(data, 0, data.Count()); } LedColorChanged?.Invoke(this, ledStrip.Leds); }
public Boolean openSerial(String port, String arduinoVer) { if (SP != null && SP.IsOpen) SP.Close(); if (port == "") return false; console("Opening Serial Port on: " + port); SP = new SerialPort(port, 9600, Parity.None, 8); SP.Open(); open = true; //handshake SP.ReadTimeout = 5000; SP.Write("1"); String s = ""; int t = 0; while (s.Length < 4 && t < 500) { System.Threading.Thread.Sleep(10); s = SP.ReadExisting(); if (!s.Contains(".")) s = ""; else s = s.Split('.')[1]; SP.Write("1"); t += 1; } String av = arduinoVer.Replace(@".", string.Empty); if (av.Length < 4) { av = av[0] + "" + av[1] + "0" + av[2]; } if (s == "") console("No Responce from Arduino, going ahead with connection but errors may occour"); else { s = s.Substring(s.Length - 4, 4); if (Convert.ToInt16(s) < Convert.ToInt16(av)) { console("Arduino Code Outdated(v" + s[0] + "." + s[1] + "." + s[2] + s[3] + "). Please Update Arduino to at least v" + arduinoVer + " and then Retry"); return false; } console("Handshake Sucsessful, Connected to Arduino Running: v" + s[0] + "." + s[1] + "." + s[2] + s[3]); } return true; }
private void Nullbtn_Click(object sender, RoutedEventArgs e) { try { this.elecsport = Properties.Settings.Default.elecserobj; elecsport.Write(elecstartcmd + "\r\n"); elecsport.ReadExisting(); Thread.Sleep(20000); elecsport.Write(elecnullcmd + "\r\n"); elecsport.ReadExisting(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); } }
/// <summary> /// Writes the message to the port. /// </summary> /// <param name='aMessage'> /// A message. /// </param> /// <returns>The number of bytes written</returns> public int Write(string aMessage) { int numWritten = -1; try { m_serial.Write(aMessage); numWritten = aMessage.Length; } catch (System.Exception e) { m_error = e.Message; } return(numWritten); }
public void Actuate() { using (var serial = new SerialPort(Settings.ComPort)) { if (!serial.IsOpen) serial.Open(); if (!serial.IsOpen) return; serial.Write(new byte[] {0xFF, 0x01, 0x01}, 0, 3); Thread.Sleep(Settings.ActuateTime); serial.Write(new byte[] {0xFF, 0x01, 0x00}, 0, 3); serial.Close(); } }
public void SendData() { if (serialPort.IsOpen) { if (IsWrite) { serialPort.Write(ScreenText); } else { serialPort.WriteLine(ScreenText); } } }
public static void Main() { // A program to set the baud rate on a new HC-06 to // 115200 // SerialPort blueComms = new SerialPort(SerialPorts.COM1, 9600, Parity.None, 8, StopBits.One); blueComms.Open(); // // Rename the device // byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes("AT+NAMEHC_A"); blueComms.Write(outBuffer, 0, outBuffer.Length); Thread.Sleep(2000); while (blueComms.BytesToRead > 0) { byte[] a = new byte[1] { 0 }; blueComms.Read(a, 0, 1); char[] cc = System.Text.Encoding.UTF8.GetChars(a, 0, a.Length); Debug.Print(cc.ToString()); Thread.Sleep(10); } // // Set the baud rate. // outBuffer = System.Text.Encoding.UTF8.GetBytes("AT+BAUD8"); blueComms.Write(outBuffer, 0, outBuffer.Length); Thread.Sleep(2000); blueComms.Close(); SerialPort blueFast = new SerialPort(SerialPorts.COM1, 115200, Parity.None, 8, StopBits.One); blueFast.Open(); outBuffer = System.Text.Encoding.UTF8.GetBytes("AT"); blueComms.Write(outBuffer, 0, outBuffer.Length); Debug.Print("After Baud rate set"); while (blueComms.BytesToRead > 0) { byte[] a = new byte[1] { 0 }; blueComms.Read(a, 0, 1); char[] cc = System.Text.Encoding.UTF8.GetChars(a, 0, a.Length); Debug.Print(cc.ToString()); Thread.Sleep(10); } }
public void WriteControlSystem(byte[] inputstring) { //if (Conn.State == ConnectionState.Closed) // Conn.Open(); if (!ComPort.IsOpen) { try { ComPort.Open(); } catch {//COM口初始化失败 return; } } byte[] bytes = inputstring;// Encoding.UTF8.GetBytes(inputstring);//inputstring.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray(); byte[] SHOW = bytes; byte crc = CRC_Compute(bytes, bytes.Length); byte[] AddSHOW = new byte[SHOW.Length + 1]; for (int i = 0; i < SHOW.Length; i++) { AddSHOW[i] = SHOW[i]; } //AddSHOW[AddSHOW.Length - 2] = crc[0]; AddSHOW[AddSHOW.Length - 1] = crc; ComPort.Write(AddSHOW, 0, AddSHOW.Length); Thread.Sleep(AddSHOW.Length / 10 + 1); //Thread.Sleep(200); //byte[] recivedata = new byte[ComPort.BytesToRead]; //if (ComPort.BytesToRead >= 5) //{ // bytes = new byte[ComPort.BytesToRead]; // ComPort.Read(recivedata, 0, recivedata.Length); // byte temp = CRC_Compute(recivedata,recivedata.Length); // if (temp == recivedata[recivedata.Length - 1] )//注意高低位调换 // { // ReadFrameList.Insert(ResponseBytesPoint,recivedata) ; // ResponseBytesPoint++; // //Console.ReadLine(); // } // else // { // //Console.WriteLine("接收数据错误"); // } //} }
static void Main(string[] args) { SerialPort mySerialPort = new SerialPort("COM3"); mySerialPort.BaudRate = 9600; mySerialPort.Open(); while (running) { //string myData = mySerialPort.ReadLine(); //Console.WriteLine(myData); mySerialPort.Write("p"); System.Threading.Thread.Sleep(1000); mySerialPort.Write("n"); System.Threading.Thread.Sleep(1000); } }
public static void Main() { // Instantiate the communications // port with some basic settings SerialPort port = new SerialPort( "COM1", 9600, Parity.None, 8, StopBits.One); // Open the port for communications port.Open(); OutputPort ledPort = new OutputPort(Pins.ONBOARD_LED, false); byte[] buffer = new byte[message.Length]; buffer = System.Text.Encoding.UTF8.GetBytes(message); try { while (true) { ledPort.Write(true); Thread.Sleep(200); port.Write(buffer, 0, buffer.Length); ledPort.Write(false); Thread.Sleep(5000); } } finally { port.Close(); } }
//点击发送按钮事件的响应 private void buttonfs_Click(object sender, EventArgs e) { //ASCII规则 comm.Write(this.textBoxfs.Text); //如果写错了一些,我们允许的,只用正则得到有效的十六进制数 /*MatchCollection mc = Regex.Matches(textBoxfs.Text, @"(?i)[\da-f]{2}"); * //填充到这个临时列表中 * List<byte> buf = new List<byte>(); * //依次添加到列表中 * foreach (Match m in mc) * { * buf.Add(byte.Parse(m.Value, System.Globalization.NumberStyles.HexNumber)); * } */ //转换列表为数组后发送 try { if (!comm.IsOpen) { comm.Open(); } } //打开失败,抛出异常 catch (Exception ex) { //捕获到异常信息,创建一个新的comm对象,之前的不能用了。 comm = new SerialPort(); } comm.Write("211"); }
static void Main(string[] args) { SerialPort MyCOMPort = new SerialPort(); // Create a new SerialPort Object String COM_PortName; String TX_data = "A"; Console.WriteLine("\t+------------------------------------------+"); Console.WriteLine("\t| Writing to Serial Port using C# |"); Console.WriteLine("\t+------------------------------------------+"); Console.WriteLine("\t| (c) www.xanthium.in |"); Console.WriteLine("\t+------------------------------------------+"); Console.Write("\n\t Enter the COM port [eg COM32] -> "); COM_PortName = Console.ReadLine(); COM_PortName = COM_PortName.Trim(); // Remove any extra spaces COM_PortName = COM_PortName.ToUpper(); // convert the string to upper case //COM port settings to 8N1 mode MyCOMPort.PortName = COM_PortName; // Name of your COM port MyCOMPort.BaudRate = 9600; // Baudrate = 9600bps MyCOMPort.Parity = Parity.None; // Parity bits = none MyCOMPort.DataBits = 8; // No of Data bits = 8 MyCOMPort.StopBits = StopBits.One; // No of Stop bits = 1 MyCOMPort.Open(); // Open the port MyCOMPort.Write(TX_data); // Write an ascii "A" Console.WriteLine("\n\t {0} written to {1}", TX_data, COM_PortName); MyCOMPort.Close(); // Close port Console.WriteLine("\t+------------------------------------------+"); Console.ReadLine(); }
public static void Main() { int count = 0; SerialPort SPort = new SerialPort(SerialPorts.COM2, 9600, Parity.None,8,StopBits.One); SPort.ReadTimeout = 1000; SPort.WriteTimeout = 1000; byte[] buf = new byte[5]; string CardId = ""; SPort.Open(); byte[] readCommand = { 0x21, 0x52, 0x57, 0x01, 0x03 }; int numCodes = 0; while (true) { //SPort.Write(new byte[] { 0xFF, 0xFF, 0X39, 0x44 }, 0, 4); SPort.Write(readCommand, 0, 5); SPort.Flush(); int readcnt = SPort.Read(buf, 0, SPort.BytesToRead); SPort.Flush(); string s = ""; if (buf[0] == 0x01 && numCodes < 10) { foreach (byte b in buf) { s = s + b.ToString() + ","; } if (s[0] == '1') { count++; Debug.Print(count.ToString() + ":" + s + "\n"); numCodes++; } } } }
static void Main(string[] args) { Console.WriteLine("Numer portu: (COM3/4/...?)"); string com = Console.ReadLine(); SerialPort port = new SerialPort(com, 56000, Parity.None, 8, StopBits.One); port.Open(); Listen LISTEN = new Listen(port); Thread oThread = new Thread(new ThreadStart(LISTEN.Listening)); oThread.Start(); while (true) { string line = Console.ReadLine(); if (line == "bb") break; else if (line == "power") { Console.WriteLine("Podaj moc: "); line = Console.ReadLine(); port.Write(new byte[] { 0x43, 0x78, 0x1E, 0x09, Convert.ToByte(line) }, 0, 5); } else if (line == "czulosc") { Console.WriteLine("Podaj czul: "); line = Console.ReadLine(); port.Write(new byte[] { 0x43, 0x78, 0x1E, 0x10, Convert.ToByte(line) }, 0, 5); } SendSampleData(port, line); line = ""; } }
/// <summary> /// 发送数据 /// </summary> /// <param name="Content">内容</param> public void SendData(byte[] Content) { try { byte[] Cmd_Temp = Content; int Sum = 0; foreach (byte b in Cmd_Temp) { Sum += b; } Sum = Sum % 256; byte[] Cmd = new byte[Cmd_Temp.Length + 2]; for (int i = 0; i < Cmd_Temp.Length; i++) { Cmd[i] = Cmd_Temp[i]; } Cmd[Cmd_Temp.Length] = Convert.ToByte(Sum); Cmd[Cmd_Temp.Length + 1] = 0x43; Send_Buffer = Cmd; //string sss = Encoding.Default.GetString(Send_Buffer); ComPort_2.Write(Send_Buffer, 0, Send_Buffer.Length); } catch (Exception) { //throw; } }
static void Main(string[] args) { System.IO.Ports.SerialPort wixel = new System.IO.Ports.SerialPort("COM20", 57600); wixel.Open(); wixel.Write("hello"); wixel.Close(); }
static private void SendSampleData(SerialPort port, string l) { port.Write(l + "&"); //port.Write(new byte[] { 0x0A, 0xE2, 0xFF }, 0, 3); }
public static void Main() { SerialPort UART = new SerialPort("COM1", 9600); SPI.Configuration config = new SPI.Configuration((Cpu.Pin)FEZ_Pin.Digital.Di10, false, 0, 0, true, true, 250, SPI.SPI_module.SPI1); SPI Spi = new SPI(config); UART.Open(); string Datoreaded = ""; byte[] datain = new byte[1]; byte[] dataout = new byte[1]; while (true) { // Sleep for 500 milliseconds Thread.Sleep(500); dataout[0] = (byte)0x55; datain[0] = (byte)0; Spi.WriteRead(dataout, datain); Datoreaded = datain[0].ToString(); Datoreaded += "\n\r"; byte[] buffer = Encoding.UTF8.GetBytes(Datoreaded); UART.Write(buffer, 0, buffer.Length); } }
public SPICommunicator() { port = new SerialPort() { BaudRate = 115200, DataBits = 8, StopBits = StopBits.One, Parity = Parity.None, PortName = "COM3", Handshake = Handshake.None }; if (!port.IsOpen) { port.Open(); } string line = "TEST"; int i = 0; do { port.Write(line); string inLine = port.ReadLine(); i++; } while (i < 3); port.Close(); }
private void button1_Click(object sender, EventArgs e) { if (colorDialog1.ShowDialog() == DialogResult.OK) { Color selectedColor = colorDialog1.Color; Console.WriteLine("New color: #" + selectedColor.R + selectedColor.G + selectedColor.B); string serialPortName = (string)cbSerialPort.SelectedItem; SerialPort serialPort = new SerialPort(serialPortName, 9600); serialPort.WriteTimeout = 5000; Console.WriteLine("Connecting to " + serialPortName); serialPort.Open(); Console.WriteLine("Connected"); byte[] message = new byte[3]; message[0] = selectedColor.R; message[1] = selectedColor.G; message[2] = selectedColor.B; try { serialPort.Write(message, 0, 3); Console.Write("Sent "); for (int i = 0; i < 3; i++) Console.Write(message[i]) ; Console.WriteLine(); } catch (TimeoutException) { Console.WriteLine("Timeout while sending..."); } serialPort.Close(); Console.WriteLine("Connection closed"); BackColor = selectedColor; } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); // ArduinoControllerMain arduino = new ArduinoControllerMain(); SerialPort _Port = new SerialPort("COM7", 9600); _Port.Open(); while (true) { string currentTime = DateTime.Now.ToString(); byte[] buffer = new byte[8]; buffer[0] = Convert.ToByte(currentTime[0]); buffer[1] = Convert.ToByte(currentTime[1]); buffer[2] = Convert.ToByte(currentTime[3]); buffer[3] = Convert.ToByte(currentTime[4]); buffer[4] = Convert.ToByte(currentTime[6]); buffer[5] = Convert.ToByte(currentTime[7]); buffer[6] = Convert.ToByte(currentTime[9]); buffer[7] = Convert.ToByte(currentTime[10]); _Port.Write(buffer, 0, 8); Thread.Sleep(2000); } }
internal static void QueryDevice(string port) { try { tP = new SerialPort(port, 115200, Parity.None, 8, StopBits.One); tP.DataReceived += new SerialDataReceivedEventHandler(tP_DataReceived); tP.ErrorReceived += new SerialErrorReceivedEventHandler(tP_ErrorReceived); tP.Handshake = Handshake.RequestToSend; tP.DtrEnable = true; tP.RtsEnable = true; tP.NewLine = Environment.NewLine; tP.ReadTimeout = 2000; tP.WriteTimeout = 2000; tP.Open(); Thread.Sleep(200); tP.Write("AT+GMM" + (char)13); Thread.Sleep(500); tP.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (tP.IsOpen) tP.Close(); } }
private void _output() { if (!_ser_out.IsOpen) { try { _ser_out.Open(); _ser_out.DtrEnable = _horn; _ser_out.RtsEnable = _shotclock_horn; } catch { } } while (true) { do { StringBuilder stringBuilder = new StringBuilder(); }while (!_sending_active); try { foreach (string key in _fields.Keys) { _ser_out.Write(2.ToString() + key.ToString() + "=" + _fields[key].ToString() + (object)'\x0003'); Thread.Sleep(_refresh_interval); } } catch { } } }
public static string getComPort() { try { string[] str = SerialPort.GetPortNames(); string recieved = ""; string com = ""; serialPort = new SerialPort(); foreach (string value in str) { Console.WriteLine(value); serialPort.PortName = value; serialPort.BaudRate = 9600; serialPort.Parity = 0; serialPort.DataBits = 8; serialPort.ReadTimeout = 5000; serialPort.WriteTimeout = 500; serialPort.Open(); serialPort.Write(comTest, 0, comTest.Length); Thread.Sleep(100); recieved = serialPort.ReadExisting(); if (recieved.Equals("\u001by")) { Console.WriteLine(value); com = value; } serialPort.Close(); } return com; } catch(Exception e) { Console.WriteLine(e); return ""; } }
private bool DetectSerialCom() { foreach (var portName in SerialPort.GetPortNames()) { _serialPort = new SerialPort(portName, 38400, Parity.None, 8, StopBits.One) { ReadTimeout = 10 }; try { _serialPort.Open(); } catch (IOException) { continue; } try { _serialPort.Write("T"); int read = _serialPort.ReadChar(); if ((char)read == 'T') return true; } catch (Exception) { continue; } } return false; }
private static void Main(string[] args) { PacketStorage = new PacketStorage(); var inPort = new SerialPort("COM1"); inPort.Open(); var outPort = new SerialPort("COM1"); outPort.Open(); inPort.DataReceived += InPortOnDataReceived; PacketStorage.MessageReceived += PacketStorageOnMessageReceived; while (true) { var m = Console.ReadLine(); if (m.ToLower() == "exit") break; var msg = Encoding.Default.GetBytes(m); //split to packets int pieceCount = (msg.Length + PacketSize - 1) / PacketSize; for (int i = 0; i < pieceCount; i++) { var buffer = new byte[PacketSize + 2]; buffer[0] = (byte)i; buffer[1] = (byte)pieceCount; var l = msg.Length - PacketSize * i; if (l > PacketSize) l = PacketSize; Array.Copy(msg, i * PacketSize, buffer, 2, l); outPort.Write(buffer, 0, buffer.Length); } } }
public void SendSetMessage(byte destNodeId, byte sensorId, string payload) { try { var strMessage = BaseMessage.BuildMessageString(destNodeId, sensorId, MessageType.SET, 1, (byte)SensorDataType.V_LIGHT, payload); if (!string.IsNullOrEmpty(strMessage)) { _serialPort.Write(strMessage); } } catch (Exception ex) { Console.WriteLine("Error sending message to {0} Type {1} SubType {2}", destNodeId, MessageType.SET, SensorDataType.V_LIGHT); } }
private static List<CommandResponse> ExecuteCommand(Pc900Command command, SerialPort myPort) { List <CommandResponse> responses = new List<CommandResponse>(); try { foreach (var buffer in command.CommandsList.Select(byteList => byteList.ToArray())) { myPort.Write(buffer, 0, buffer.Length); Console.WriteLine("Sent:" + string.Join(", ", buffer)); var readBuffer = ReadBuffer(myPort, command.ExpectedResponseBytes); responses.Add(command.ResponseDelegate(readBuffer.ToList())); } return responses; } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); throw; } finally { myPort.Close(); } }