昨天做了一个C#写的串口测试程序  现在把代码贴上来

Comm.cs

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ComTest
{
    class Comm
    {
        //事件委托
        public delegate void ComRecevied(byte[] byteBuffer);
        //public ComRecevied comRecevied;
        public event ComRecevied EventComReceived;

        private SerialPort serialPort;
        //配置                串口号             波特率     校验位         数据位     停止位
        public void InitCOM(string _PortName,string _baudRate,string _checkBit,string _dataBits,string _stopBit)
        {
            if (serialPort != null && serialPort.IsOpen)
            {
                serialPort.Close();
            }
            serialPort = new SerialPort(_PortName,int.Parse(_baudRate),(Parity)Enum.Parse(typeof(Parity),_checkBit),int.Parse(_dataBits), (StopBits)Enum.Parse(typeof(StopBits), _stopBit));
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.ReceivedBytesThreshold = 1;//设置事件发生前内部输入缓冲区的字节数为1
            serialPort.RtsEnable = true;
        }
        //数据接收
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //byte[] readBuffer = new byte[serialPort.ReadBufferSize];//获取输入缓冲区的大小
            byte[] readBuffer = new byte[serialPort.BytesToRead];//获取接收缓冲区中数据的字节数
            //Console.WriteLine(serialPort.BytesToRead);

            //            要读取的字节数组      起始位置    总个数
            serialPort.Read(readBuffer, 0, readBuffer.Length);
            /*//----------Y-----------
            string str = Encoding.Default.GetString(readBuffer);
            string str1 = str.Substring(str.IndexOf("X")+1,3);
            string str2 = str.Substring(str.IndexOf("Y") + 1, 3);*/
            /*Console.WriteLine(str);
            Console.WriteLine(str1);
            Console.WriteLine(str2);*/
            //MessageBox.Show(str);
            EventComReceived(readBuffer);
        }
        //打开串口
        public bool OpenPort()
        {
            //写成异常处理的形式以免打不开串口导致程序崩溃
            try
            {
                serialPort.Open();
            }
            catch { }

            if (serialPort.IsOpen)
            {
                return true;
            }
            else
            {
                MessageBox.Show("串口打开失败");
                return false;
            }
        }
        //向串口发送数据
        public void SendCommand(string _str1,string _str2)
        {
            int a=int.Parse(_str1);
            int b = int.Parse(_str2);
            string str1 = "";
            if (a <= 9)
            {
                str1 = "00" + a;
            }
            else if (a <= 99&&a>9)
            {
                str1 = "0" + a;
            }
            else
            {
                str1 = a+"";
            }
            string str2 = "";
            if (b <= 9)
            {
                str2 = "00" + b;
            }
            else if (b <= 99 && b > 9)
            {
                str2 = "0" + b;
            }
            else
            {
                str2 = b + "";
            }
            string CommandString = "X"+str1+"Y"+str2;
            byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
            serialPort.Write(WriteBuffer, 0, WriteBuffer.Length);
            //Console.WriteLine(WriteBuffer.Length);
        }
    }
}

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ComTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Comm comm = new Comm();
        public MainWindow()
        {
            InitializeComponent();
            //xTxt.MaxLength = 3;
            comm.EventComReceived += Comm_EventComReceived;
        }
        //接收后触发委托事件
        private void Comm_EventComReceived(byte[] byteBuffer)
        {

            Dispatcher.BeginInvoke(new Action(delegate
            {
                try
                {
                    string str = Encoding.Default.GetString(byteBuffer);

                    string str1 = str.Substring(str.IndexOf("X") + 1, 3);
                    string str2 = str.Substring(str.IndexOf("Y") + 1, 3);
                    labelX.Content = "收到X:" + str1;
                    labelY.Content = "收到Y:" + str2;
                }
                catch { MessageBox.Show("请再打开一个窗口来测试"); }
                
            }));
        }

        //设置
        private void setBtn_Click(object sender, RoutedEventArgs e)
        {
            comm.InitCOM(PortNameTxt.Text,baudRateTxt.Text,checkBitTxt.Text,dataBitsTxt.Text,stopBitTxt.Text);
            comm.OpenPort();
        }
        //发送
        private void sendBtn_Click(object sender, RoutedEventArgs e)
        {
            if (comm.OpenPort())
            {
                comm.SendCommand(xTxt.Text,yTxt.Text);
            }
        }
        

        private void xTxt_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (int.Parse(xTxt.Text) > 180)
            {
                xTxt.Text = "180";
            }
            else if (int.Parse(xTxt.Text) < 0)
            {
                xTxt.Text = "0";
            }

        }

        private void xTxt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9]+");

            e.Handled = re.IsMatch(e.Text);
        }

        private void yTxt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9]+");

            e.Handled = re.IsMatch(e.Text);

        }

        private void yTxt_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (int.Parse(yTxt.Text) > 180)
            {
                yTxt.Text = "180";
            }
            else if (int.Parse(yTxt.Text) < 0)
            {
                yTxt.Text = "0";
            }
        }
    }
}

MainWindow.xaml

<Window x:Class="ComTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ComTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox x:Name="PortNameTxt" Margin="59,84,0,0" TextWrapping="Wrap" Text="COM1" HorizontalAlignment="Left" Width="85" Height="23" VerticalAlignment="Top"/>
        <Label x:Name="PortNameLabel" Content="串口号" Margin="75,52,0,0" HorizontalAlignment="Left" Width="46" Height="26" VerticalAlignment="Top"/>
        <Label x:Name="baudRateLabel" Content="波特率" Margin="190,51,0,0" HorizontalAlignment="Left" Width="46" Height="26" VerticalAlignment="Top"/>
        <TextBox x:Name="baudRateTxt" Margin="174,84,0,0" TextWrapping="Wrap" Text="9600" HorizontalAlignment="Left" Width="82" Height="23" VerticalAlignment="Top"/>
        <Button x:Name="setBtn" Content="确定设置" Margin="238,163,0,0" Click="setBtn_Click" HorizontalAlignment="Left" Width="75" Height="22" VerticalAlignment="Top"/>
        <Label x:Name="xLabel_" Content="X轴" Margin="39,202,0,0" HorizontalAlignment="Left" Width="30" Height="26" VerticalAlignment="Top"/>
        <TextBox x:Name="xTxt" Margin="20,234,0,0" TextWrapping="Wrap" Text="123" HorizontalAlignment="Left" Width="69" Height="23" VerticalAlignment="Top" PreviewTextInput="xTxt_PreviewTextInput" TextChanged="xTxt_TextChanged"/>
        <Label x:Name="yLabel" Content="Y轴" Margin="127,203,0,0" HorizontalAlignment="Left" Width="29" Height="26" VerticalAlignment="Top"/>
        <TextBox x:Name="yTxt" Margin="106,235,0,0" TextWrapping="Wrap" Text="321" HorizontalAlignment="Left" Width="69" Height="23" VerticalAlignment="Top" PreviewTextInput="yTxt_PreviewTextInput" TextChanged="yTxt_TextChanged"/>
        <Button x:Name="sendBtn" Content="发送" Margin="59,278,0,0" Click="sendBtn_Click" HorizontalAlignment="Left" Width="75" Height="22" VerticalAlignment="Top"/>
        <Label x:Name="checkBitLabel" Content="校验位" Margin="301,50,0,0" HorizontalAlignment="Left" Width="46" Height="26" VerticalAlignment="Top"/>
        <TextBox x:Name="checkBitTxt" Margin="286,84,0,0" TextWrapping="Wrap" Text="None" HorizontalAlignment="Left" Width="82" Height="23" VerticalAlignment="Top"/>
        <Label x:Name="dataBitsLabel" Content="数据位" Margin="408,51,0,0" HorizontalAlignment="Left" Width="46" Height="26" VerticalAlignment="Top"/>
        <TextBox x:Name="dataBitsTxt" Margin="389,84,0,0" TextWrapping="Wrap" Text="8" HorizontalAlignment="Left" Width="82" Height="23" VerticalAlignment="Top"/>
        <Label x:Name="stopBitLabel" Content="停止位" Margin="98,133,0,0" HorizontalAlignment="Left" Width="46" Height="26" VerticalAlignment="Top"/>
        <TextBox x:Name="stopBitTxt" Margin="78,164,0,0" TextWrapping="Wrap" Text="1" Height="23" VerticalAlignment="Top" HorizontalAlignment="Left" Width="82"/>
        <Label x:Name="labelX" Content="收到X:" HorizontalAlignment="Left" Margin="286,214,0,0" VerticalAlignment="Top" Width="141"/>
        <Label x:Name="labelY" Content="收到Y:" HorizontalAlignment="Left" Margin="286,256,0,0" VerticalAlignment="Top" Width="141"/>
    </Grid>
</Window>

 

没啥想说的,先这样吧,以后有什么代码再接着往上贴

posted on 2017-11-09 15:55  凌落成迷  阅读(321)  评论(0编辑  收藏  举报