本文整理汇总了C#中System.IO.Ports.SerialPort类的典型用法代码示例。如果您正苦于以下问题:C# SerialPort类的具体用法?C# SerialPort怎么用?C# SerialPort使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SerialPort类属于System.IO.Ports命名空间,在下文中一共展示了SerialPort类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenericCATRadio
public GenericCATRadio(RadioConnectionSettings connectionSettings)
{
ConnectionSettings = connectionSettings;
m_SerialPort = new SerialPort { PortName = connectionSettings.Port, BaudRate = connectionSettings.BaudRate, DtrEnable = connectionSettings.UseDTR, RtsEnable = connectionSettings.UseRTS };
switch (connectionSettings.FlowControl)
{
case FlowControl.None:
m_SerialPort.Handshake = Handshake.None;
break;
case FlowControl.DsrDtr:
case FlowControl.RtsCts:
m_SerialPort.Handshake = Handshake.RequestToSend;
break;
case FlowControl.XonXoff:
m_SerialPort.Handshake = Handshake.XOnXOff;
break;
}
m_SerialPort.Open();
string logsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Cloudlog\\Logs");
if (!Directory.Exists(logsFolder))
Directory.CreateDirectory(logsFolder);
string logPath = Path.Combine(logsFolder, "CloudlogCAT-" + DateTime.Now.ToString("yyyy-MM-dd-hhmmss") + ".txt");
m_LogWriter = new StreamWriter(logPath);
m_LogWriter.AutoFlush = true;
m_PollThread = new Thread(PollMethod);
m_PollThread.IsBackground = true;
m_PollThread.Start();
}
示例2: ModbusSerialAsciiMasterReadRegisters
/// <summary>
/// Simple Modbus serial ASCII master read holding registers example.
/// </summary>
public static void ModbusSerialAsciiMasterReadRegisters()
{
using (SerialPort port = new SerialPort("COM1"))
{
// configure serial port
port.BaudRate = 9600;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.Open();
// create modbus master
IModbusSerialMaster master = ModbusSerialMaster.CreateAscii(port);
byte slaveId = 1;
ushort startAddress = 1;
ushort numRegisters = 5;
// read five registers
ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);
for (int i = 0; i < numRegisters; i++)
Console.WriteLine("Register {0}={1}", startAddress + i, registers[i]);
}
// output:
// Register 1=0
// Register 2=0
// Register 3=0
// Register 4=0
// Register 5=0
}
示例3: NodeConnection
public NodeConnection(string PortName)
{
serialPort = new SerialPort(PortName, 38400);
serialPort.DataReceived += serialPort_DataReceived;
currentReceiverMessage = new List<byte>();
}
示例4: btniniciar_Click
private void btniniciar_Click(object sender, EventArgs e)
{
MSComm = new SerialPort();
try
{
MSComm.PortName = cmbpuerto.Text.ToString();
MSComm.BaudRate = Convert.ToInt32(cmbbaudios.Text.Trim());
MSComm.Parity = System.IO.Ports.Parity.None;
MSComm.DataBits = 8;
MSComm.StopBits = System.IO.Ports.StopBits.One;
MSComm.Handshake = System.IO.Ports.Handshake.None;
MSComm.ReceivedBytesThreshold = 1;
MSComm.DataReceived += serialPort_DataReceived;
MSComm.Open();
btniniciar.Enabled = false;
btndetener.Enabled = true;
Cambiar_Estado(false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
CODBAR.Focus();
}
示例5: SetupDialog
public SetupDialog(Data data)
{
InitializeComponent();
_data = data;
tbHeader.Enabled = false;
tbFooter.Enabled = false;
if (!string.IsNullOrEmpty(data.Header))
{
cbHeader.Checked = true;
tbHeader.Enabled = true;
tbHeader.Text = data.Header;
}
if (!string.IsNullOrEmpty(data.Footer))
{
cbFooter.Checked = true;
tbFooter.Enabled = true;
tbFooter.Text = data.Footer;
}
if (!string.IsNullOrEmpty(data.PortName))
{
_serialPort = new SerialPort(data.PortName, data.BaudRate, data.Parity, data.DataBits, data.StopBits);
updateSettingLabel();
btnOkay.Enabled = true;
}
else
{
lblSettings.Text = "Not Set";
btnOkay.Enabled = false;
}
}
示例6: SerialDataHandler
/// <summary>
/// Constructor taking a SerialCommunicator object so as to allow COM settings to be
/// implemented.
/// </summary>
/// <param name="communicator"></param>
public SerialDataHandler(SerialCommunicator communicator, Rule rule, Value value)
{
//Create temp variable to read the required values.
var comm = (SerialCommunicator) communicator;
//Initialise the COM Port settings.
_sPort = new SerialPort(comm.ComPort)
{
BaudRate = comm.BaudRate,
Parity = Parity.None,
StopBits = StopBits.One,
DataBits = comm.DataBits,
Handshake = Handshake.None,
DtrEnable=comm.IsDTR,
RtsEnable = comm.IsRTS
};
//Make the Value available.
_value = value;
//Output the data required - any instance of [val] is replaced with the actual value
StringBuilder builder = new StringBuilder(rule.Action.OutputValue);
builder.Replace("[val]", _value.StringValue);
//Output the string
OutputValue(builder.ToString());
}
示例7: BalanceReader
/*
* public string ComPort = String.Empty;
public int BaudRate = 110;
public StopBits StopBits = StopBits.None;
public int DataBits = 7;
public Parity Parity = Parity.None;
* */
public BalanceReader(string comPort = "COM1", int baudRate = 9600, StopBits stopBits = StopBits.One,
int dataBits = 7, Parity parity = Parity.Even, string sicsCommand = "SI", bool rts = false)
{
_sicsCommand = sicsCommand;
if (comPort == String.Empty) comPort = "COM1";
_port = new SerialPort
{
PortName = comPort,
BaudRate = baudRate,
StopBits = stopBits,
DataBits = 7,
Parity = Parity.Even,
RtsEnable = rts
};
// from Page 39 of NewClassic Balances METTLER TOLEDO manual for MS-S / MS-L Models
//_port.Handshake = Handshake.XOnXOff;
if (_port.IsOpen == false)
{
try
{
_port.Open();
}
catch (Exception)
{
// port will not be open, therefore will become null
}
}
_port.DataReceived += _port_DataReceived;
}
示例8: LCD43
public LCD43()
{
comLcdPri = new SerialPort(SerialPorts.COM1, 115200, Parity.None, 8, StopBits.One);
comLcdPri.DataReceived += new SerialDataReceivedEventHandler(Lcd_DataReceived);
comLcdPri.ReadTimeout = 100;
comLcdPri.Open();
}
示例9: ArduiPort
public ArduiPort(string name, int baud, Logger logger)
{
_Logger = logger;
_port = new SerialPort(name, baud);
SetName(name);
SetBaudRate(baud);
}
示例10: Serial2Matlab
// public Serial2Matlab(string port, int baudRate = 115200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
public Serial2Matlab()
{
serialPort = new SerialPort("COM43", 115200, Parity.None, 8, StopBits.One);
serialPort.ReadTimeout = 2;
serialPort.Open();
serialPort.DiscardInBuffer();
}
示例11: GT730FLSController
public GT730FLSController(string portName)
{
_com = new SerialPort(portName, 38400, Parity.None, 8, StopBits.One);
_com.ReadTimeout = READ_TIMEOUT;
_com.Open();
}
示例12: SerialPortService
public SerialPortService()
{
_serialPort = new SerialPort();
setDefaultValues();
ComIsOpen = false;
}
示例13: Init
public void Init()
{
try
{
try
{
if (Port != null)
{
ConsoleOutputLogger.WriteLine("[COM] COM-Port soll reinitialisiert werden - schliesse alten COM-Port.");
Port.Close();
}
}
catch (Exception e)
{
ConsoleOutputLogger.WriteLine("[[email protected]] Beim Versuch den COM-Port zu schliessen ist ein Fehler aufgetreten.");
ConsoleOutputLogger.WriteLine("[[email protected]] "+e.Message);
}
Port = new SerialPort("COM"+Convert.ToInt32(FFN_Switcher.Properties.Settings.Default.Comport));
Port.Open();
ConsoleOutputLogger.WriteLine("[COM] COM-Port " + Convert.ToInt32(FFN_Switcher.Properties.Settings.Default.Comport) + " geöffnet und bereit.");
}
catch (Exception e)
{
ConsoleOutputLogger.WriteLine("[[email protected]] " + e.Message);
ConsoleOutputLogger.WriteLine("[COM] Kann COM-Port nicht öffnen - bitte Konfiguration überprüfen.");
Pause();
}
}
示例14: Main
private static void Main()
{
using (var port = new SerialPort("COM3", 9600))
{
_xbee = new XBeeReader(port);
CreatePipeListener();
while (true)
{
if (Console.KeyAvailable)
{
var c = char.ToUpper(Console.ReadKey(true).KeyChar);
if (c == 'X') break;
if (c == ' ') TriggerGarageDoor(_xbee);
}
else if (_xbee.FrameAvailable)
{
var frame = _xbee.ReadFrame();
if (frame.FrameType == XBeeFrameType.RXIOReceived)
ProcessTemperatureReading(new XBeeIOFrame(frame));
else
Console.WriteLine(frame);
}
Thread.Sleep(500);
}
}
}
示例15: SerialTextOnly
/// <summary>Constructor con parámetros de puerto serie
/// </summary>
/// <param name="portName">nombre del port (generalmente "com1")
/// se pueden obtener los nombres disponibles usando System.IO.Ports.SerialPort.GetPortNames()</param>
/// <param name="bauds">velocidad (generalmente 9600)</param>
/// <param name="parity">tipo de paridad (generalmente None)</param>
/// <param name="dataBits">bits de datos (generalmente 8)</param>
/// <param name="stopBits">bits de parada (generalmente One)</param>
/// <param name="info"></param>
public SerialTextOnly(PrinterInfo info)
: base(info)
{
try
{
commPort = new SerialPort(Name, int.Parse(info.Parameters[kBouds]), Parity.None, int.Parse(info.Parameters[kDatabits]), StopBits.One);
IsOnLine = true;
LastError = null;
PaperCut = CutMode.Partial;
PaperCutJump = 32;
UseCrLf = false;
}
catch (IOException ex)
{
IsOnLine = false;
LastErrorDesc = "Configuración de puerto no válida";
LastError = ex.ToString();
}
catch (Exception ex)
{
IsOnLine = false;
LastErrorDesc = "Error no contemplado";
LastError = ex.ToString();
}
}