当前位置: 首页>>代码示例>>C#>>正文


C# Ports.SerialPort类代码示例

本文整理汇总了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();
        }
开发者ID:magicbug,项目名称:CloudlogCAT,代码行数:30,代码来源:GenericCATRadio.cs

示例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
        }
开发者ID:baminmru,项目名称:vodopad-ip-server,代码行数:35,代码来源:Driver.cs

示例3: NodeConnection

        public NodeConnection(string PortName)
        {
            serialPort = new SerialPort(PortName, 38400);
            serialPort.DataReceived += serialPort_DataReceived;

            currentReceiverMessage = new List<byte>();
        }
开发者ID:caiodossantos,项目名称:wireless-network,代码行数:7,代码来源:NodeConnection.cs

示例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();
        }
开发者ID:njmube,项目名称:ErpBapSoftNet_Producion,代码行数:25,代码来源:Frm_leeCodBar.cs

示例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;
            }
        }
开发者ID:akonkman,项目名称:vixen-modules,代码行数:34,代码来源:SetupDialog.cs

示例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());
        }
开发者ID:willwhitehead94,项目名称:SCIPA,代码行数:32,代码来源:SerialDataHandler.cs

示例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;
        }
开发者ID:ajarrott,项目名称:NewBalance,代码行数:40,代码来源:BalanceReader.cs

示例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();
 }
开发者ID:TomasFilingr,项目名称:WD-offline,代码行数:7,代码来源:LCD43.cs

示例9: ArduiPort

 public ArduiPort(string name, int baud, Logger logger)
 {
     _Logger = logger;
     _port = new SerialPort(name, baud);
     SetName(name);
     SetBaudRate(baud);
 }
开发者ID:hightekjonathan,项目名称:ArduinoCMD,代码行数:7,代码来源:ArduiPort.cs

示例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();
 }
开发者ID:RiekertLeibbrandt,项目名称:marencoLibraries,代码行数:8,代码来源:Class1.cs

示例11: GT730FLSController

        public GT730FLSController(string portName)
        {
            _com = new SerialPort(portName, 38400, Parity.None, 8, StopBits.One);

            _com.ReadTimeout = READ_TIMEOUT;
            _com.Open();
        }
开发者ID:sayrun,项目名称:TestBox,代码行数:7,代码来源:GT730FLSController.cs

示例12: SerialPortService

        public SerialPortService()
        {
            _serialPort = new SerialPort();
            setDefaultValues();

            ComIsOpen = false;
        }
开发者ID:crazymouse0,项目名称:SerialPort-2,代码行数:7,代码来源:SerialPortService.cs

示例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();
            }
        }
开发者ID:bietiekay,项目名称:ffn-switcher,代码行数:29,代码来源:SerialportProcessor.cs

示例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);
                }
            }
        }
开发者ID:rtennys,项目名称:XBee,代码行数:30,代码来源:Program.cs

示例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();
     }
 }
开发者ID:sergiosorias,项目名称:terminalzero,代码行数:34,代码来源:SerialTextOnly.cs


注:本文中的System.IO.Ports.SerialPort类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。