• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Ports.SerialPort类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.IO.Ports.SerialPort的典型用法代码示例。如果您正苦于以下问题:C# SerialPort类的具体用法?C# SerialPort怎么用?C# SerialPort使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



SerialPort类属于System.IO.Ports命名空间,在下文中一共展示了SerialPort类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: SerialClass

 /// <summary>
 /// 构造函数,可以自定义串口的初始化参数
 /// </summary>
 /// <param name="comPortName">需要操作的COM口名称</param>
 /// <param name="baudRate">COM的速度</param>
 /// <param name="parity">奇偶校验位</param>
 /// <param name="dataBits">数据长度</param>
 /// <param name="stopBits">停止位</param>
 public SerialClass(string comPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
 {
     _serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);
     _serialPort.RtsEnable = true;  //自动请求
     _serialPort.ReadTimeout = 3000;//超时
     setSerialPort();
 }
开发者ID:yaopengchao,项目名称:tcz,代码行数:15,代码来源:CSerialClass.cs


示例17: ComPort

        public ComPort(byte number, int baudrate, byte data_bits, byte parity, byte stop_bits, ushort write_timeout, ushort read_timeout, byte attemts)
        {
            m_name = "COM" + Convert.ToString(number);
            m_baudrate = baudrate;
            m_data_bits = data_bits;
            m_parity = (Parity)parity;
            m_stop_bits = (StopBits)stop_bits;
            m_write_timeout = write_timeout;
            m_read_timeout = read_timeout;
            m_attemts = attemts;

            try
            {
                m_Port = new SerialPort(m_name, m_baudrate, m_parity, m_data_bits, m_stop_bits);

                /*ELF: для работы с elf108*/
                m_Port.DtrEnable = true;
                m_Port.RtsEnable = true;
            }
            catch (Exception ex)
            {
                #if (DEBUG)
                    WriteToLog("Create " + m_name + ": " + ex.Message);
                #endif
            }
        }
开发者ID:Prizmer,项目名称:ps,代码行数:26,代码来源:Ports.cs


示例18: init

 public void init(COMServer tmpcomServer, int j)
 {
     comServer = tmpcomServer;
     while (mRun)
     {
         Console.WriteLine("new SerialPort()", Environment.NewLine);
         portnr = j;
         _serialPort = new SerialPort();
         int i = 0;
         foreach (string s in SerialPort.GetPortNames())
         {
             if (j == i)
             {
                 Console.WriteLine(s);
                 _serialPort.PortName = s;
             }
             i++;
         }
         _serialPort.ReadTimeout = 500;
         _serialPort.WriteTimeout = 500;
         _serialPort.BaudRate = 9600;
         _serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), _serialPort.Parity.ToString());
         _serialPort.DataBits = int.Parse(_serialPort.DataBits.ToString());
         _serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _serialPort.StopBits.ToString());
         _serialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), _serialPort.Handshake.ToString());
         _serialPort.Open();
         _serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
         while (_serialPort.IsOpen == true)
         {
             Thread.Sleep(50);
         }
         Console.WriteLine("closed", Environment.NewLine);
     }
     Console.WriteLine("eind init", Environment.NewLine);
 }
开发者ID:kwakkel1000,项目名称:mix-weeg-service,代码行数:35,代码来源:serial_port.cs


示例19: Reading

        private void Reading()
        {
            var currentPort = new SerialPort(_name, 115200);
            currentPort.Open();
            while (!stop)
            {
                var line = currentPort.ReadLine();
                try
                {
                    var strings = line.Replace("\r", "").Split(',');
                    var x = (int)int.Parse(strings[0]) / 16384.0F;
                    var y = (int)int.Parse(strings[1]) / 16384.0F;
                    var z = (int)int.Parse(strings[2]) / 16384.0F;
                    if (!_valuesInitialized)
                    {
                        _x = x;
                        _y = y;
                        _z = z;
                        _valuesInitialized = true;
                    }

                    _x = (_x*3 + x)/4;
                    _y = (_y*3 + y)/4;
                    _z = (_z*3 + z)/4;
                }
                catch (Exception)
                {

                }

                HasNew = true;
            }
        }
开发者ID:x4m,项目名称:lr17,代码行数:33,代码来源:AccelListener.cs


示例20: Main

        static void Main(string[] args)
        {
            int i = 0;
            SerialPort SP = null;
            Console.WriteLine("Specify which comport you want to connect to:");
            
            foreach (string s in SerialPort.GetPortNames())
            {
                Console.WriteLine($"{i++,2} {s}");
            }
            int PortNo = int.Parse(Console.ReadLine());
            try
            {
                SP = new SerialPort(SerialPort.GetPortNames()[PortNo]);
                SP.Open();
                while(true)
                {
                    Console.Write(SP.ReadExisting());
                }
            }
            finally
            {
                if (SP.IsOpen)
                {
                    SP.Close();
                }
            }

            Console.Read();
        }
开发者ID:svutborg,项目名称:Programming-II,代码行数:30,代码来源:Program.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IdentityModel.DictionaryManager类代码示例发布时间:2022-05-26
下一篇:
C# Ports.SerialErrorReceivedEventArgs类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap