欢迎光临散文网 会员登陆 & 注册

模拟温湿度的代码

2023-05-21 10:28 作者:被栓住的Q  | 我要投稿


简介

        本人使用的操作系统是:Windows11。本次项目使用到的软件有:编写代码——Visual Studio 2022、发送数据——UartAssist.exe(串口调试助手)、创建虚拟串口——vspdconfig.exe(虚拟串口驱动)。

界面代码

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="温湿度采集" Height="215" Width="448" ResizeMode="CanMinimize" WindowStartupLocation="CenterScreen">
    <Grid HorizontalAlignment="Center" Width="446" Height="170" VerticalAlignment="Top">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="0*"/>
            <ColumnDefinition Width="0*"/>
            <ColumnDefinition Width="0*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="5*"/>
            <RowDefinition Height="389"/>
            <RowDefinition Height="3*"/>
        </Grid.RowDefinitions>
        <GroupBox Header="串口设置" Height="NaN" Margin="10,10,0,312" Width="415" FontFamily="MiSans" FontSize="16" HorizontalAlignment="Left" Grid.RowSpan="2">
            <Grid Margin="12,0,0,0" HorizontalAlignment="Left" Width="393" Height="41">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="23*"/>
                    <ColumnDefinition Width="142*"/>
                    <ColumnDefinition Width="228*"/>
                </Grid.ColumnDefinitions>
                <Label Content="选择串口:" HorizontalAlignment="Left" Margin="10,0,0,10" Grid.ColumnSpan="2"/>
                <ComboBox x:Name="ComboBoxPortNames" HorizontalAlignment="Left" Margin="82,0,0,10" VerticalAlignment="Bottom" Width="120" Grid.Column="1" Grid.ColumnSpan="2"/>
                <Button x:Name="ButtonPortOpenClose" Content="打开" Margin="94,4,59,9" RenderTransformOrigin="-0.628,0.085" Grid.Column="2" Click="ButtonPortOpenClose_Click" Width="75"/>
            </Grid>
        </GroupBox>
        <GroupBox Header="温湿度" Margin="10,77,0,228" FontSize="16" FontFamily="MiSans" HorizontalAlignment="Left" Width="415" Grid.Row="1">
            <Grid Height="46" Margin="0,0,-12,0">
                <Label Content="温度:" Margin="0,9,347,6" RenderTransformOrigin="-0.583,-0.212" HorizontalAlignment="Right" Width="58"/>
                <TextBox x:Name="TextBoxTemp" HorizontalAlignment="Left" Margin="73,10,0,13" TextWrapping="Wrap" Text="—℃—" Width="120" FontSize="16" FontFamily="MiSans" TextAlignment="Center" IsReadOnly="True"/>
                <Label Content="湿度:" HorizontalAlignment="Left" Margin="198,9,0,6" RenderTransformOrigin="-0.583,-0.212"/>
                <TextBox x:Name="TextBoxHum" Margin="261,9,24,14" TextWrapping="Wrap" Text="—%—" FontSize="16" FontFamily="MiSans" TextAlignment="Center" IsReadOnly="True"/>
            </Grid>
        </GroupBox>
    </Grid>
</Window>

运行代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.IO.Ports;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        SerialPort serialPort = new SerialPort();
        byte[] byteReceived;

        public MainWindow()
        {
            InitializeComponent();
            ComboBoxPortNames.ItemsSource = SerialPort.GetPortNames();
            serialPort.DataReceived += SerialPort_DataReceived;
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int intRead = 0;
            intRead = serialPort.BytesToRead;
            if (intRead > 0)
            {
                byteReceived = new byte[intRead];
                serialPort.Read(byteReceived, 0, intRead);
                Console.WriteLine();
                foreach (byte b in byteReceived)
                {
                    Console.WriteLine(b.ToString("X2" + " "));
                }
                Console.WriteLine();
            }
            double wendu = ByteToValue(byteReceived[18], byteReceived[19], 60.0, -10.0);
            double shidu = ByteToValue(byteReceived[20], byteReceived[21], 100.0, 0.0);
            Console.WriteLine("温度:"+wendu.ToString("f0")+"℃");
            Console.WriteLine("湿度:" + shidu.ToString("f0") + "%");
            this.Dispatcher.BeginInvoke(
                new Action(
                    delegate
                    {
                        TextBoxTemp.Text =wendu.ToString("f0") + "℃";
                        TextBoxHum.Text = shidu.ToString("f0") + "%";
                    }
               )
            );
        }

        private double ByteToValue(byte value1,byte value2,double max,double min)
        {
            int intAnalog = value1|(value2 << 8);
            return(intAnalog * 3300.0 / 1023.0 / 150.0 - 4.0) * (max - min) / 16.0 + min;
         }

        private void ButtonPortOpenClose_Click(object sender, RoutedEventArgs e)
        {
            if (ComboBoxPortNames.Text=="")
            {
                MessageBox.Show("请选择一个串口!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            if(serialPort.IsOpen)
            {
                serialPort.Close();
                TextBoxTemp.Text = "—℃—";
                TextBoxHum.Text = "—%—";
                ButtonPortOpenClose.Content = "打开";
                ComboBoxPortNames.IsEnabled = true;
            }
            else
            {
                serialPort.PortName = ComboBoxPortNames.Text;
                try 
                { 
                    serialPort.Open(); 
                }
                catch(Exception)
                {
                    MessageBox.Show("打开端口异常!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                ButtonPortOpenClose.Content = serialPort.IsOpen ? "关闭" : "打开";
                ComboBoxPortNames.IsEnabled= serialPort.IsOpen ? false : true ;
            }
        }
    }
}

运行效果



模拟温湿度的代码的评论 (共 条)

分享到微博请遵守国家法律