本文整理汇总了C#中System.IO.Ports.SerialPort.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# SerialPort.Dispose方法的具体用法?C# SerialPort.Dispose怎么用?C# SerialPort.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Ports.SerialPort
的用法示例。
在下文中一共展示了SerialPort.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Connect
public void Connect(String comPort)
{
try
{
serialPort = new SerialPort();
serialPort.PortName = comPort;
serialPort.BaudRate = 115200;
serialPort.ReadTimeout = 3000;
serialPort.Open();
}
catch (Exception ex)
{
if (serialPort.IsOpen)
serialPort.Close();
serialPort.Dispose();
serialPort = null;
throw ex;
}
CheckVersion();
serialPort.DataReceived += serialPort_DataReceived;
PrepareSend();
}
示例2: LunaSerial
public LunaSerial(string portName)
: base()
{
try {
port = new SerialPort(portName);
port.BaudRate = 115200;
port.WriteTimeout = 1000;
port.ReadTimeout = 1000;
port.WriteBufferSize = 1024;
port.DataBits = 8;
port.DiscardNull = false;
port.Open();
//SendTurnOn();
} catch {
port.Dispose();
throw;
}
}
示例3: Main
static void Main(string[] args)
{
bool fClose = false;
string aCom = "";
if (args.Count() > 0) aCom = args[0];
Console.WriteLine("Opening com-port: "+aCom+"...");
if (aCom == "") return;
aComP = new SerialPort(aCom, 57600);
aComP.DataReceived += new SerialDataReceivedEventHandler(aComP_DataReceived);
try
{
aComP.Open();
Console.WriteLine("com-port opened.");
string apath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
fLogFile = Path.Combine(apath, "_" + aCom + ".log");
Console.WriteLine("recording to \"" + fLogFile + "\"...");
File.Delete(fLogFile);
try
{
Console.WriteLine("press \"q\" to quit.");
while (Console.ReadKey().KeyChar != 'q')
{
}
fClose = true;
Console.WriteLine("closing comport...");
aComP.Close();
while (aComP.IsOpen)
{
Thread.Sleep(100);
}
Console.WriteLine("comport closed.");
}
finally
{
if (aComP.IsOpen) aComP.Close();
aComP.Dispose();
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
示例4: Discover
private void Discover()
{
EventWaitHandle waithandler = new EventWaitHandle(
false,
EventResetMode.AutoReset,
Guid.NewGuid().ToString());
while (startDiscovering)
{
// possible fix for OSX's toomanyfilesexception
GC.Collect();
string[] ports = SerialPort.GetPortNames();
foreach (string p in ports)
{
foreach (Link l in Links)
{
if (p == l.Address)
{
continue;
}
}
SerialPort sp = new SerialPort(p, baudRate);
if (DetectRoadAt(sp))
{
RoadLink rl = new RoadLink(this, sp);
NewLink(rl);
}
else
{
sp.Close();
sp.Dispose();
}
}
// discover at interval to reduce cpu usage
waithandler.WaitOne(TimeSpan.FromSeconds(discoverInterval));
}
}
示例5: SerialBridge
public SerialBridge(string realRadioPort, string fakeRadioPort, int baud)
{
try
{
m_RealRadio = new SerialPort(realRadioPort);
m_FakeRadio = new SerialPort(fakeRadioPort);
m_RealRadio.BaudRate = m_FakeRadio.BaudRate = baud;
m_RealRadio.Open();
m_FakeRadio.Open();
m_RealRadio.DataReceived += new SerialDataReceivedEventHandler(m_RealRadio_DataReceived);
m_FakeRadio.DataReceived += new SerialDataReceivedEventHandler(m_FakeRadio_DataReceived);
}
catch
{
if (m_RealRadio != null)
m_RealRadio.Dispose();
if (m_FakeRadio != null)
m_FakeRadio.Dispose();
throw;
}
}
示例6: DecompressieKamer
public DecompressieKamer(int maxTries = 3)
{
AreValuesUpToDate = false;
_SerialPort = new SerialPort();
//RP6 default config 38400,8N1
_SerialPort.BaudRate = 38400;
_SerialPort.DataBits = 8;
_SerialPort.Parity = Parity.None;
_SerialPort.StopBits = StopBits.One;
if (!SearchForDecompressionDevice(maxTries))
{
_SerialPort.Dispose();
throw new NoDeviceFoundException();
}
_Message = new Message(_SerialPort);
_LastTimeAlive = DateTime.Now;
_LastUpdateTime = DateTime.Now;
}
示例7: Sender
public Sender(string portName)
{
port = new SerialPort();
port.PortName = portName;
port.WriteTimeout = Settings.Default.SerialPortTimeout;
port.ReadTimeout = Settings.Default.SerialPortTimeout;
try
{
port.Open();
foreach (var item in Settings.Default.CheckBalanceNumberList)
{
SendUSSD(item);
Thread.Sleep(5000);
}
port.Close();
}
catch (Exception)
{
port.Dispose();
return;
}
}
示例8: Connect
public static void Connect()
{
keyboardStateSTM = new STMKeyboardState();
string[] portNames = SerialPort.GetPortNames();
Thread readThread = new Thread(Read);
foreach (string s in portNames)
{
serialPort = new SerialPort();
serialPort.PortName = s;
serialPort.Open();
Thread connectThread = new Thread(Find);
connectThread.Start();
Thread.Sleep(1000);
if (connectThread.ThreadState == ThreadState.Stopped)
break;
else
{
serialPort.Close();
serialPort.Dispose();
connectThread.Abort();
}
}
if (serialPort.IsOpen)
{
isConnected = true;
readThread.Start();
}
else
{
isConnected = false;
}
}
示例9: btnRun_Click
//.........这里部分代码省略.........
string ATcmd="";
try
{
delay=int.Parse(spliString[2].Trim());
boolReadRx=Convert.ToBoolean(spliString[1].Trim());
ATcmd=spliString[0].Trim();
}
catch
{
MessageBox.Show("Error Parsing Data, Please Recheck AT Script File: " + temp,FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop);
return;
}
mySer.DiscardInBuffer();
if(ATcmd.StartsWith("[email protected]")) // if special command
{
txtResult.AppendText("Sending Command: " + ATcmd);
txtResult.AppendText("\r\n");
try
{
string []splitstr=ATcmd.Split(new char[]{'='},StringSplitOptions.RemoveEmptyEntries);
byte ByToSend=Convert.ToByte(splitstr[1],16);
temp=String.Format("Special Command: Sending Hex Data 0x{0:X2}\r\n", ByToSend);
txtResult.AppendText(temp);
mySer.Write(new byte[]{ByToSend},0,1);
}
catch
{
MessageBox.Show("Error Parsing Data, Please Recheck AT Script File: " + temp,FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop);
return;
}
}
else
{
txtResult.AppendText("Sending Command: " + ATcmd);
txtResult.AppendText("\r\n");
try
{
mySer.Write(ATcmd);
mySer.Write(new byte[]{0x0D},0,1);
}
catch
{
MessageBox.Show("Error Sending Data to GSM Modem!",FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop);
return;
}
}
txtResult.AppendText("Delay: " + delay + "msec");
txtResult.AppendText("\r\n");
System.Threading.Thread.Sleep(delay);
if(boolReadRx)
{
string readSer=mySer.ReadExisting();
if(chkBinMode.Checked)
{
char [] readChar= readSer.ToCharArray();
StringBuilder strb=new StringBuilder();
foreach(char mychar in readChar)
{
strb.AppendFormat("<0x{0:X2}>",(int)mychar);
}
readSer=strb.ToString();
}
else if(chkShowEndHex.Checked)
{
for(int ctr=0;ctr<0x20;ctr++)
{
readSer =readSer.Replace(String.Format("{0}",(char)ctr),String.Format("<0x{0:X2}>",ctr));
}
}
txtResult.AppendText("Received Reply:\r\n");
txtResult.AppendText(readSer);
txtResult.AppendText("\r\n");
}
txtResult.AppendText("===========================\r\n");
}
}
finally
{
btnRun.Enabled=true;
mySer.Dispose();
System.GC.Collect();
}
txtResult.AppendText("===========================\r\n");
txtResult.AppendText("===========END===========\r\n");
}
else
{
if(SCRFile==String.Empty)
MessageBox.Show("Choose file first!",FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop);
else
MessageBox.Show("File does not exist!",FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop);
}
}
示例10: DataRcdEvent
public MFTestResults DataRcdEvent()
{
if (!IsLoopback)
return MFTestResults.Skip;
// BUGBUG: 21216
result = MFTestResults.Fail;
try
{
eventCount = 0;
eventSerialPort = new SerialPort(Serial.COM1);
// register before open
eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventserialPort_DataReceived_BeforeOpen);
eventSerialPort.Open();
eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventSerialPort_DataReceived_AfterOpen);
eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventSerialPort_DataReceived_AfterOpen2);
eventSerialPort.Write(sendbuff, 0, sendbuff.Length);
eventSerialPort.Flush();
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
if (eventCount >= 3)
{
result = MFTestResults.Pass;
break;
}
}
Log.Comment(eventCount + " events fired");
eventSerialPort.Close();
}
catch (Exception ex)
{
Log.Exception(ex.Message);
}
finally
{
eventSerialPort.Dispose();
}
return result;
}
示例11: GetPPM
/// <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;
}
示例12: AttemptConnect
private void AttemptConnect()
{
connected = false;
string[] names = SerialPort.GetPortNames();
List<string> Ports = new List<string>();
foreach(string name in names)
{
if(name != "COM1" && name != "COM2" && name != "COM3" && name != "COM4")
Ports.Add( name );
}
// Check status
if(Ports.Count == 0)
{
commStat = CommStatus.NoDevice;
return;
}
commStat = CommStatus.NoElev8;
try
{
bool FoundElev8 = false;
for(int i = 0; i < Ports.Count && FoundElev8 == false; i++)
{
serial = new SerialPort( Ports[i], 115200, Parity.None, 8, StopBits.One );
serial.Open();
txBuffer[0] = (byte)'E';
txBuffer[1] = (byte)'l';
txBuffer[2] = (byte)'v';
txBuffer[3] = (byte)'8';
for(int j = 0; j < 10 && FoundElev8 == false; j++) // Keep pinging until it replies, or we give up
{
serial.Write( txBuffer, 0, 4 );
System.Threading.Thread.Sleep( 50 );
int bytesAvail = serial.BytesToRead;
if(bytesAvail > 0)
{
int TestVal = 0;
while(bytesAvail > 0)
{
int bytesRead = serial.Read( rxBuffer, 0, 1 );
if(bytesRead == 1)
{
TestVal = (TestVal << 8) | rxBuffer[0];
if(TestVal == (int)(('E' << 0) | ('l' << 8) | ('v' << 16) | ('8' << 24)))
{
FoundElev8 = true;
commStat = CommStatus.Connected;
break;
}
}
}
}
}
if(FoundElev8) {
connected = true;
if(ConnectionStarted != null) {
ConnectionStarted();
}
break;
}
else {
serial.Close();
serial.Dispose();
serial = null;
}
}
}
catch(Exception)
{
return;
}
}
示例13: btnRun_Click
private void btnRun_Click(object sender, EventArgs e)
{
string SCRFile = tssStatusScrFile.Text.Trim();
txtResult.Clear();
Application.DoEvents();
if (File.Exists(SCRFile) == true)
{
SerialPort mySer = new SerialPort(cmbSerial.SelectedItem.ToString(), int.Parse(cmbBaud.SelectedItem.ToString()));
mySer.WriteBufferSize = 1000;
mySer.ReadBufferSize = (int)numRXBuffSize.Value;
mySer.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cmbHandShaking.SelectedItem.ToString());
mySer.WriteTimeout = 1000;
try
{
string[] FileAllLines = File.ReadAllLines(SCRFile);
IAtScriptProcessing iAtScriptProc = new AtScriptProcessing();
var ret = iAtScriptProc.ProcessArrayString(FileAllLines);
try
{ mySer.Open(); }
catch
{
MessageBox.Show("Error Opening Serial Port!");
return;
}
btnRun.Enabled = false;
foreach (var x in ret)
{
string temp;
mySer.DiscardInBuffer();
if (x.IsSpecialCommand)
{
temp = String.Format("Special Command: Sending Hex Data 0x{0:X2}\r\n", x.ByteToSend);
txtResult.AppendText(temp);
mySer.Write(new byte[] { x.ByteToSend }, 0, 1);
}
else
{
txtResult.AppendText("Sending Command: " + x.ATCommandToSend);
txtResult.AppendText("\r\n");
try
{
mySer.Write(x.ATCommandToSend);
mySer.Write(new byte[] { 0x0D }, 0, 1);
}
catch
{
MessageBox.Show("Error Sending Data to GSM Modem!", FRM_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
}
txtResult.AppendText("Delay: " + x.Delay + "msec");
txtResult.AppendText("\r\n");
Thread.Sleep(x.Delay);
if (x.ReceiveData)
{
string readSer = mySer.ReadExisting();
if (chkBinMode.Checked)
{
char[] readChar = readSer.ToCharArray();
StringBuilder strb = new StringBuilder();
foreach (char mychar in readChar)
{
strb.AppendFormat("<0x{0:X2}>", (int)mychar);
}
readSer = strb.ToString();
}
else if (chkShowEndHex.Checked)
{
for (int ctr = 0; ctr < 0x20; ctr++)
{
readSer = readSer.Replace(String.Format("{0}", (char)ctr), String.Format("<0x{0:X2}>", ctr));
}
}
txtResult.AppendText("Received Reply:\r\n");
txtResult.AppendText(readSer);
txtResult.AppendText("\r\n");
}
txtResult.AppendText("===========================\r\n");
}
}
finally
{
btnRun.Enabled = true;
mySer.Dispose();
System.GC.Collect();
}
txtResult.AppendText("===========================\r\n");
txtResult.AppendText("===========END===========\r\n");
}
//.........这里部分代码省略.........
示例14: Close
public static void Close(ref SerialPort sp)
{
sp.Close ();
sp.Dispose ();
}
示例15: Open
public bool Open(int baud = 115200)
{
if (_isOpen)
Close();
bool result = false;
try
{
_port = new SerialPort(_portName, baud, Parity.None, 8, StopBits.One);
int openRetries = 5;
bool fDone = false;
do
{
try
{
_port.Open();
_port.DataReceived += _port_DataReceived;
}
catch (System.UnauthorizedAccessException ex)
{
_port.Close();
_port.Dispose();
_port = null;
Debug.WriteLine("SerialPort open failed with exception : " + ex.Message);
Thread.Sleep(1000);
}
catch (System.IO.IOException)
{
// this may be a CDC port - try a serial wrapper - the port parameters don't matter - only the name
_port.Dispose();
_port = null;
Thread.Sleep(300);
_pdpPort = new pdp.SerialPort(_portName, baud, Parity.None, 8, StopBits.One);
_pdpPort.Open();
new Thread(() => { PdpSerialReadLoop(); }).Start();
}
fDone =
(_pdpPort != null && _pdpPort.IsOpen) ||
(_port != null && _port.IsOpen) ||
(--openRetries <= 0);
} while (!fDone);
if ((_port != null && _port.IsOpen) || (_pdpPort != null && _pdpPort.IsOpen))
{
new Thread(() => { ProcessReceivedData(); }).Start();
}
result = (_pdpPort != null && _pdpPort.IsOpen) || (_port != null && _port.IsOpen);
}
catch
{
result = false;
}
_isOpen = result;
return result;
}