USB hőmérő példaprogram

A Fizipedia wikiből
CSharpSerialtest.png

A Form tartalma:

  • SerialPort serial1;
  • ListBox comList;
  • TextBox dataBox;
  • RichTextBox infoBox;
  • Button initButton;
  • Button readButton;
  • Button infoButton;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;   //hozzaadni
 
namespace SerialTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
          //rendelkezesre allo portok listazasa
            string[] ports=SerialPort.GetPortNames();
          //az eredmeny egy stringekbol allo tomb
            foreach (string port in ports)
            {
                comList.Items.Add(port);
            }
 
        }
        private void initButton_Click(object sender, EventArgs e)
        {
          //ha mar nyitva van a port, akkor bezarjuk
            if (serial1.IsOpen)
            {
                serial1.Close();
            }
            //init COM port
            serial1.PortName = comList.SelectedItem.ToString(); //a listabol kivalasztott nev
            serial1.DataBits = 8;                               //es a meresleiras szerinti beallitasok
            serial1.StopBits = StopBits.One;
            serial1.Parity = Parity.None;
            serial1.BaudRate = 38400;
            //COM port megnyitasa
            serial1.Open();          
        }
        //gombnyomasra homerseklet olvasasa
        private void readButton_Click(object sender, EventArgs e)
        {
            serial1.WriteLine("R");     //write char 'R' to device
            dataBox.Text = serial1.ReadLine().Trim(); //read single line
        }
        //gombnyomasra info olvasasa 
        private void infoButton_Click(object sender, EventArgs e)
        {
           serial1.WriteLine("I");     //write char 'I' to device
           infoBox.Clear();
           for (int i = 0; i < 3; i++)      //Read 3 lines
           {
               infoBox.AppendText(Serial1.ReadLine());
           }
 
        }
        //A Form bezarasakor port lezarasa
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            serial1.Close();        //Release COM port
        }
 
    }
}