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

C# SerialPort类代码示例

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

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



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

示例1: Chronopic

    //-- Constructor
    public Chronopic(SerialPort sp)
    {
        //-- Comprobar si puerto serie ya estaba abierto
        if (sp != null)
            if (sp.IsOpen)
                sp.Close();

        //-- Abrir puerto serie
        sp.Open();

        //-- Configurar timeout por defecto
        //de momento no en windows (hasta que no encontremos por qué falla)
        //OperatingSystem os = Environment.OSVersion;
        //not used, now there's no .NET this was .NET related
        //on mono timeouts work on windows and linux
        //if( ! os.Platform.ToString().ToUpper().StartsWith("WIN"))
            sp.ReadTimeout = DefaultTimeout;

        //-- Guardar el puerto serie
        this.sp = sp;

        //		//-- Vaciar buffer
        //		//done in a separate method
        //		this.flush();
    }
开发者ID:GNOME,项目名称:chronojump,代码行数:26,代码来源:chronopic.cs


示例2: CreateRtu

        /// <summary>
        ///     Modbus RTU slave factory method.
        /// </summary>
        public static ModbusSerialSlave CreateRtu(byte unitId, SerialPort serialPort)
        {
            if (serialPort == null)
                throw new ArgumentNullException("serialPort");

            return CreateRtu(unitId, new SerialPortAdapter(serialPort));
        }
开发者ID:baminmru,项目名称:vodopad-ip-server,代码行数:10,代码来源:ModbusSerialSlave.cs


示例3: Open

	public void Open () {
		// Opens the serial port
		stream = new SerialPort(port, baudrate);
		stream.ReadTimeout = 50;
		stream.Open();
		//this.stream.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
	}
开发者ID:jpmckinney,项目名称:The-Machine-to-be-Another-Unity,代码行数:7,代码来源:arduinoControl.cs


示例4: Start

    // Use this for initialization
    void Start()
    {
        //Screen.showCursor = false;
        isPlaying = false;

        //Health = 100;
        isDead = false;

        Health = 100;
        _curHealth = Health;

        PlArmIdentity = PlayerArm.transform.rotation;

        Instantiate(Spells[0], PlayerArm.transform.GetChild(0).position, Quaternion.identity);
        CastingSpell = GameObject.FindGameObjectWithTag("Spell");

        string[] ports = SerialPort.GetPortNames();

        //		foreach (string port in ports)
        //		{
        //			Console.WriteLine(port);
        //		}

        _serialPort = new SerialPort(ports[1], 9600);
        _serialPort.Open();
        Debug.Log(_serialPort.PortName);
        Debug.Log(_serialPort.BaudRate);
        Debug.Log(_serialPort.IsOpen);
    }
开发者ID:kdittle,项目名称:PhysicalComputing,代码行数:30,代码来源:PlayerScript.cs


示例5: spInit

        private void spInit()
        {
            sp = new SerialPort();
            sp.PortName = "COM40";
            sp.BaudRate = 57600;
            sp.DataBits = 8;
            sp.Parity = Parity.Even;
            try
            {
                sp.Open();
                try
                {
                    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);//事件

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("无法连接串口");
            }
        }
开发者ID:ShallYu,项目名称:mood_massage,代码行数:25,代码来源:SerialData.cs


示例6: Start

    // Use this for initialization
    void Start()
    {
        Debug.Log(SerialPort.GetPortNames().ToString());
        mySerialPort = new SerialPort("\\\\.\\COM18");
        mySerialPort.BaudRate = 9600;
        //mySerialPort.Parity = Parity.None;
        //mySerialPort.StopBits = StopBits.One;
        //mySerialPort.DataBits = 8;
        //mySerialPort.Handshake = Handshake.None;
        //mySerialPort.RtsEnable = true;

        //mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        if ( mySerialPort != null )
        {
            if ( mySerialPort.IsOpen ) // close if already open
            {
                mySerialPort.Close();
                Debug.Log ("Closed stream");
            }
            mySerialPort.Open();
            Debug.Log ("Opened stream");
        }
        else
        {
            Debug.Log ("ERROR: Uninitialized stream");
        }
          myThread = new Thread(new ThreadStart(GetArduino));
          	  myThread.Start();
    }
开发者ID:am-t,项目名称:mount-amanita,代码行数:31,代码来源:ArduinoSerialInterface.cs


示例7: runProgram

    public static void runProgram(SerialPort port)
    {
        //System.IO.Ports.SerialPort serialPort1;
        //System.ComponentModel.IContainer components = new System.ComponentModel.Container();
        //serialPort1 = new System.IO.Ports.SerialPort(components);
        //serialPort1.PortName = "COM4";
        //serialPort1.BaudRate = 9600;
        port.Open();

        // this turns on !
           // serialPort1.DtrEnable = true;
        Console.Write("starting loop");
        while (true)
        {
            //port.Write(new byte[] { 1 }, 0, 1);
            //System.Threading.Thread.Sleep(1000);
            //port.Write(new byte[] { 0 }, 0, 1);
            //System.Threading.Thread.Sleep(1000);
            Transmit(port, 63, 63, 40, 63);

            //wait for received
            while (port.BytesToRead==0)
            {
                System.Threading.Thread.Sleep(10);
            }
            if (port.ReadByte() != 103)
            {
                Console.Write("Bad ack");
                break;
            }
        }
    }
开发者ID:darrenks,项目名称:The-Force,代码行数:32,代码来源:heliserialtest.cs


示例8: Class_FeedbackStage

    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="_sleep">モニタのスリープ時間</param>
    public Class_FeedbackStage(string _stageName="")
    {
        stageName = _stageName + ": ";

        serialPort = new SerialPort();
        serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
    }
开发者ID:hirokinnp,项目名称:Scanner,代码行数:11,代码来源:Class_FeedbackStage.cs


示例9: GetMavStreamFromArgs

    public static Stream GetMavStreamFromArgs(string[] args)
    {
        Stream strm = null;

        if (args.Length == 0)
        {
            strm = Console.OpenStandardInput();
        }
        else if (args.Length == 1)
        {
            Console.WriteLine("Usage (todo)");
            Console.ReadKey();
            Environment.Exit(0);
        }
        else if (args[0] == "-S")
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Usage (todo)");
                Environment.Exit(1);
            }
            var comport = args[1];
            var baud = Convert.ToInt32(args[2]);
            var port = new SerialPort(comport, baud);
            port.Open();
            strm = port.BaseStream;
        }
        else
        {
            strm = File.OpenRead(args[1]);
        }
        return strm;
    }
开发者ID:mandrolic,项目名称:pymavlink,代码行数:33,代码来源:ExampleCommon.cs


示例10: Start

    //int leftPos=500;

    // Start
    void Start()
    {
        //start the serial connection.
        if (gameObject.GetComponent<COMParser>() != null)
            COMPort = gameObject.GetComponent<COMParser>().com;
        else if (gameObject.transform.parent.GetComponent<COMParser>() != null)
            COMPort = gameObject.transform.parent.GetComponent<COMParser>().com;
        else
            COMPort = gameObject.transform.parent.parent.GetComponent<COMParser>().com;

        if (COMPort != "COM0")
        {
            _SerialPort = new SerialPort(COMPort, 9600);

            OpenConnection();
            //check how many outputs and inputs there are.
            for (int pinconfigcounter = 0; pinconfigcounter < pinConfig.Length; pinconfigcounter++)
            {
                if (pinConfig[pinconfigcounter].Equals("o")) outputcount++;
                if (pinConfig[pinconfigcounter].Equals("i")) inputcount++;
                if (pinConfig[pinconfigcounter].Equals("p")) pwmcount++;
            }
            DigitalInputs = new int[inputcount];
            FromJavaToArduino = new char[pinConfig.Length];

        }
    }// Start
开发者ID:thomvandevin,项目名称:thomvandevin_pintsandpunches,代码行数:30,代码来源:GuiArduinoSerialScript.cs


示例11: Main

 public static void Main()
 {
     Debug.Print("BLE Shield");
     var port = SerialPorts.COM1; // using D0 & D1
     //var port = SerialPorts.COM2; // using D2 & D3
     var bleShield = new SerialPort(port, 19200, Parity.None, 8, StopBits.None);
     bleShield.DataReceived += (sender, args) =>
     {
         var receiveBuffer = new byte[16];
         int bytesReceived = bleShield.Read(receiveBuffer, 0, receiveBuffer.Length);
         if (bytesReceived > 0)
         {
             Debug.Print("Bytes received: " + bytesReceived);
             Debug.Print(new String(Encoding.UTF8.GetChars(receiveBuffer)));
         }
     };
     bleShield.Open();
     while (true)
     {
         var random = new Random();
         var sendBuffer = new byte[4];
         random.NextBytes(sendBuffer);
         bleShield.Write(sendBuffer, 0, sendBuffer.Length);
         Thread.Sleep(1000);
     }
 }
开发者ID:thisischris,项目名称:BLE-Shield,代码行数:26,代码来源:Program.cs


示例12: Start

	// Use this for initialization
    void Start()
    {
		nazwaPortu = COM.com;
        // utworzenie obiektu do komunikacji na danym porcie
        stm = new SerialPort(nazwaPortu, 38400, Parity.None, 8, StopBits.One);
        // proba otwarcia portu
        try
        {
            stm.Open();
            if (!stm.IsOpen)
            {
                // jezeli nie udalo sie utworzyc portu to komponent jest likwidowany
                Debug.LogWarning("Nie udalo sie otworzyc polaczenia z portem: " + nazwaPortu);
                Destroy(this);
            }
            else
            {
                Debug.Log("Otwarto polaczenie z portem: " + nazwaPortu);
                // udalo sie utworzyc polaczenie z portem - startuje watek do czytania danych z portu
                stmThread = new Thread(stmOdczyt);
                stmThread.Start();
            }
        }
        catch (Exception e)
        {
            // jezeli nie udalo sie utworzyc portu to komponent jest likwidowany
            Debug.LogWarning("Nie udalo sie otworzyc polaczenia z portem: " + nazwaPortu);
            Destroy(this);
        }
	}
开发者ID:glocklueng,项目名称:STMPong,代码行数:31,代码来源:STMController.cs


示例13: TrainDrukteForm

        public TrainDrukteForm()
        {
            InitializeComponent();
            timer1.Start();

            _serialPort = new SerialPort();
        }
开发者ID:grasmanek94,项目名称:CodeDump,代码行数:7,代码来源:TrainDrukteForm.cs


示例14: Start

	// Use this for initialization
	void Start () {
		serialPort = new SerialPort ("/dev/cu.usbmodem1421", 57600);
		serialPort.Open ();
		serialPort.ReadTimeout = 1;
		
		
	}
开发者ID:JonathanMcCaffrey,项目名称:ArdunioUnityControl,代码行数:8,代码来源:ArdunioControls.cs


示例15: Start

	// Use this for initialization
	void Start () {
        rb = GetComponent<Rigidbody>();

        stream = new SerialPort("COM4", 9600);
        stream.ReadTimeout = 50;
        stream.Open();
    }
开发者ID:singlerider,项目名称:head-tracker,代码行数:8,代码来源:paddle.cs


示例16: Arduino

 /// <summary>
 /// Initializes a new instance of the Arduino.
 /// </summary>
 /// <param name="id">Identifier.</param>
 /// <param name="comPort">COM port.</param>
 public Arduino(int id, string comPort)
 {
     NextStation = new IPEndPoint(1, 1);
     this.ComPort = comPort;
     this.Id = id;
     this._serialPort = new SerialPort(ComPort, 9600);
 }
开发者ID:grasmanek94,项目名称:t22-4,代码行数:12,代码来源:Arduino.cs


示例17: CreateIp

        public static ModbusIpMaster CreateIp(SerialPort serialPort)
        {
            if (serialPort == null)
                throw new ArgumentNullException("serialPort");

            return CreateIp(new SerialPortAdapter(serialPort));
        }
开发者ID:baminmru,项目名称:vodopad-ip-server,代码行数:7,代码来源:ModbusIpMaster.cs


示例18: checkConnection

    // The state object is necessary for a TimerCallback.
    public void checkConnection(object stateObject)
    {
        Process p = new Process();
        Ping pingSender = new Ping ();
        p.StartInfo.FileName = "arp";
        p.StartInfo.Arguments = "-a";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;

        string data = "a";
         byte[] buffer = Encoding.ASCII.GetBytes (data);

        for(int i = 0; i < 25 ; i++){
            pingSender.Send ("10.0.0."+i.ToString(),10,buffer);
        }

        p.Start();

        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        string MAC = "xx-xx-xx-xx-xx-xx";
        if(output.Contains(MAC)){
            SerialPort port = new SerialPort("COM5", 9600);
            port.Open();
            port.Write("u");
            port.Close();
        }
        else{
            SerialPort port = new SerialPort("COM5", 9600);
            port.Open();
            port.Write("l");
            port.Close();
        }
    }
开发者ID:kurtvonehr,项目名称:ARP-Windows-Service,代码行数:36,代码来源:wifi_doorlock_service.cs


示例19: rcvAndEcho

    private bool rcvAndEcho(ref SerialPort mySP)
    {
        byte rcv;
        char tmp;
        bool hasRcvd = false;

        try {
            rcv = (byte)mySP.ReadByte();
            if (rcv != 255) {
                hasRcvd = true;

                tmp = (char)rcv;
                if (tmp != 0x0d && tmp != 0x0a) { // not CRLF
                    accRcvd = accRcvd + tmp.ToString();
                }
                if (tmp == 0x0d) { // CR
                    mySP.WriteLine(accRcvd);
                    rcvdCRLF = true;
                }
            }
        } catch (System.Exception) {
        }

        return hasRcvd;
    }
开发者ID:yasokada,项目名称:unity-150920-rs232cEcho,代码行数:25,代码来源:echoServerCS.cs


示例20: ExampleThreadFunction

        public static void ExampleThreadFunction()
        {

            // bit rate change acording your GPS
            SerialPort serialPort = new SerialPort("COM3", 4800);
            serialPort.Open();

            //here we create file in SD card main folder
            string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
            FileStream FileHandle = new FileStream(rootDirectory + @"\gps.txt", FileMode.Create);


            while (true)
            {

                int bytesToRead = serialPort.BytesToRead;
                if (bytesToRead > 0)
                {

                    // all struff from GPS streams in to file
                    byte[] buffer = new byte[bytesToRead];
                    serialPort.Read(buffer, 0, buffer.Length);
                    Debug.Print(new String(System.Text.Encoding.UTF8.GetChars(buffer)) + "\n");
                    FileHandle.Write(buffer, 0, buffer.Length);
                    Thread.Sleep(500);
                }
                // Cleaning 
                Debug.GC(true);
                Debug.EnableGCMessages(false);

            }

        }
开发者ID:BdGL3,项目名称:CXPortal,代码行数:33,代码来源:FileIO.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# SerializableDictionary类代码示例发布时间:2022-05-24
下一篇:
C# Serial类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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