TSR18测速雷达C#对接

目录

效果

协议

项目

代码

下载


效果

协议

项目

代码

using NLog;

using System;

using System.IO.Ports;

using System.Text;

using System.Threading;

using System.Windows.Forms;

namespace 雷达测速测试

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this);

}

private Logger log = NLog.LogManager.GetCurrentClassLogger();

private byte[] buffer = new byte[1024];

private int bufferIndex = 0;

private const int PACKET_SIZE = 12; // 帧头2 + 帧类型2 + B0-B7 8个字节

private const ushort FRAME_HEADER = 0xAAAA;

private const ushort FRAME_TYPE = 0x700C; // 注意:低字节在前,实际是0x0C70

private void Form1_Load(object sender, EventArgs e)

{

// 获取所有串口名称

string[] ports = SerialPort.GetPortNames();

// 清空ComboBox中的现有项(如果需要)

comboBox1.Items.Clear();

// 将所有串口名称添加到ComboBox中

foreach (string port in ports)

{

comboBox1.Items.Add(port);

}

// 可选:默认选中第一个串口(如果有的话)

if (comboBox1.Items.Count > 0)

{

comboBox1.SelectedIndex = 0;

}

}

private void button1_Click(object sender, EventArgs e)

{

if (button1.Text == "打开串口")

{

if (comboBox1.SelectedItem != null)

{

try

{

string selectedPort = comboBox1.SelectedItem.ToString();

// 串口名

serialPort1.PortName = selectedPort;

// 波特率

serialPort1.BaudRate = 115200;

// 数据位

serialPort1.DataBits = 8;

// 停止位

serialPort1.StopBits = System.IO.Ports.StopBits.One;

// 奇偶校验位

serialPort1.Parity = System.IO.Ports.Parity.None;

serialPort1.WriteTimeout = 3000; //串口发送的超时时间

serialPort1.ReadTimeout = 18000;//读取数据的超时时间

serialPort1.ReadBufferSize = 1024 * 1024; //串口接收缓冲区大小

serialPort1.WriteBufferSize = 1024 * 1024; //串口发送缓冲区大小

serialPort1.Open();

button1.Text = "关闭串口";

log.Info("打开成功!");

}

catch (Exception ex)

{

log.Error("打开串口失败:" + ex.Message);

}

}

}

else

{

labelSpeed.Text = "速度: -- km/h";

labelDirection.Text = "目标方向: --";

try

{

serialPort1.Close();

button1.Text = "打开串口";

log.Info("关闭成功!");

}

catch (Exception ex)

{

log.Error("关闭串口失败:" + ex.Message);

}

}

}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)

{

Thread.Sleep(100);//这个延时非常重要

try

{

byte[] m_recvBytes = new byte[14]; //定义缓冲区大小

int result = serialPort1.Read(m_recvBytes, 0, m_recvBytes.Length); //从串口读取数据

if (result <= 0)

return;

string hexString = BitConverter.ToString(m_recvBytes).Replace("-", " ");

//string strResult = Encoding.UTF8.GetString(m_recvBytes, 0, m_recvBytes.Length); //对数据进行转换

log.Info("Data Received:" + hexString);

// 计算速度

double speed = CalculateSpeed(m_recvBytes[9], m_recvBytes[10]);

String direction = Direction(m_recvBytes[4]);

// 更新UI

Invoke(new Action(() => UpdateSpeedDisplay(speed, direction, m_recvBytes)));

}

catch (Exception ex)

{

log.Error("读取数据异常:" + ex.Message);

}

}

private String Direction(byte b0)

{

if (b0 == 0)

{

return "目标方向: 来向";

}

else if (b0 == 1)

{

return "目标方向: 去向";

}

else if (b0 == 2)

{

return "目标方向: 无方向";

}

else

{

return "目标方向: --";

}

}

private double CalculateSpeed(byte b5, byte b6)

{

// velocity = ((B5>>5)*256 + B6)/10*3.6;

int speedValue = ((b5 >> 5) * 256 + b6);

double speed = speedValue / 10.0 * 3.6;

return speed;

}

private void UpdateSpeedDisplay(double speed, string direction, byte[] dataBytes)

{

// 显示速度

labelSpeed.Text = $"速度: {speed:F1} km/h";

labelDirection.Text = direction;

// 记录到日志

StringBuilder info = new StringBuilder();

info.AppendLine($"{DateTime.Now:HH:mm:ss} 检测到目标");

info.AppendLine($" 速度: {speed:F1} km/h");

info.AppendLine($" 原始数据: B5=0x{dataBytes[9]:X2}, B6=0x{dataBytes[10]:X2}");

info.AppendLine($" 计算: ((0x{dataBytes[9]:X2}>>5)*256 + 0x{dataBytes[10]:X2})/10*3.6 = {speed:F1}");

info.AppendLine(new string('-', 40));

log.Info(info.ToString());

}

private void serialPort1_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)

{

//log.Error("ErrorReceived");

}

private void serialPort1_PinChanged(object sender, SerialPinChangedEventArgs e)

{

log.Error("PinChanged");

}

}

}

复制代码
using NLog;
using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 雷达测速测试
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this);
        }

        private Logger log = NLog.LogManager.GetCurrentClassLogger();

        private byte[] buffer = new byte[1024];
        private int bufferIndex = 0;
        private const int PACKET_SIZE = 12; // 帧头2 + 帧类型2 + B0-B7 8个字节
        private const ushort FRAME_HEADER = 0xAAAA;
        private const ushort FRAME_TYPE = 0x700C; // 注意:低字节在前,实际是0x0C70

        private void Form1_Load(object sender, EventArgs e)
        {
            // 获取所有串口名称
            string[] ports = SerialPort.GetPortNames();

            // 清空ComboBox中的现有项(如果需要)
            comboBox1.Items.Clear();

            // 将所有串口名称添加到ComboBox中
            foreach (string port in ports)
            {
                comboBox1.Items.Add(port);
            }

            // 可选:默认选中第一个串口(如果有的话)
            if (comboBox1.Items.Count > 0)
            {
                comboBox1.SelectedIndex = 0;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "打开串口")
            {

                if (comboBox1.SelectedItem != null)
                {
                    try
                    {
                        string selectedPort = comboBox1.SelectedItem.ToString();
                        // 串口名  
                        serialPort1.PortName = selectedPort;
                        // 波特率  
                        serialPort1.BaudRate = 115200;
                        // 数据位  
                        serialPort1.DataBits = 8;
                        // 停止位  
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                        // 奇偶校验位  
                        serialPort1.Parity = System.IO.Ports.Parity.None;

                        serialPort1.WriteTimeout = 3000; //串口发送的超时时间
                        serialPort1.ReadTimeout = 18000;//读取数据的超时时间

                        serialPort1.ReadBufferSize = 1024 * 1024;    //串口接收缓冲区大小
                        serialPort1.WriteBufferSize = 1024 * 1024;   //串口发送缓冲区大小

                        serialPort1.Open();

                        button1.Text = "关闭串口";

                        log.Info("打开成功!");

                    }
                    catch (Exception ex)
                    {
                        log.Error("打开串口失败:" + ex.Message);
                    }
                }

            }
            else
            {
                labelSpeed.Text = "速度: -- km/h";
                labelDirection.Text = "目标方向: --";

                try
                {
                    serialPort1.Close();

                    button1.Text = "打开串口";
                    log.Info("关闭成功!");

                }
                catch (Exception ex)
                {

                    log.Error("关闭串口失败:" + ex.Message);
                }

            }
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            Thread.Sleep(100);//这个延时非常重要

            try
            {
                byte[] m_recvBytes = new byte[14]; //定义缓冲区大小  
                int result = serialPort1.Read(m_recvBytes, 0, m_recvBytes.Length); //从串口读取数据  
                if (result <= 0)
                    return;

                string hexString = BitConverter.ToString(m_recvBytes).Replace("-", " ");
                //string strResult = Encoding.UTF8.GetString(m_recvBytes, 0, m_recvBytes.Length); //对数据进行转换  
                log.Info("Data Received:" + hexString);

                // 计算速度
                double speed = CalculateSpeed(m_recvBytes[9], m_recvBytes[10]);
                String direction = Direction(m_recvBytes[4]);
                // 更新UI
                Invoke(new Action(() => UpdateSpeedDisplay(speed, direction, m_recvBytes)));

            }
            catch (Exception ex)
            {

                log.Error("读取数据异常:" + ex.Message);
            }

        }

        private String Direction(byte b0)
        {

            if (b0 == 0)
            {
                return "目标方向: 来向";
            }
            else if (b0 == 1)
            {
                return "目标方向: 去向";

            }
            else if (b0 == 2)
            {
                return "目标方向: 无方向";
            }
            else
            {
                return "目标方向: --";
            }
        }

        private double CalculateSpeed(byte b5, byte b6)
        {
            // velocity = ((B5>>5)*256 + B6)/10*3.6;
            int speedValue = ((b5 >> 5) * 256 + b6);
            double speed = speedValue / 10.0 * 3.6;
            return speed;
        }

        private void UpdateSpeedDisplay(double speed, string direction, byte[] dataBytes)
        {
            // 显示速度
            labelSpeed.Text = $"速度: {speed:F1} km/h";
            labelDirection.Text = direction;

            // 记录到日志
            StringBuilder info = new StringBuilder();
            info.AppendLine($"{DateTime.Now:HH:mm:ss} 检测到目标");
            info.AppendLine($"  速度: {speed:F1} km/h");
            info.AppendLine($"  原始数据: B5=0x{dataBytes[9]:X2}, B6=0x{dataBytes[10]:X2}");
            info.AppendLine($"  计算: ((0x{dataBytes[9]:X2}>>5)*256 + 0x{dataBytes[10]:X2})/10*3.6 = {speed:F1}");
            info.AppendLine(new string('-', 40));
            log.Info(info.ToString());
        }

        private void serialPort1_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            //log.Error("ErrorReceived");
        }

        private void serialPort1_PinChanged(object sender, SerialPinChangedEventArgs e)
        {
            log.Error("PinChanged");
        }

    }
}

下载

下载地址

相关推荐
道一231 小时前
C#获取操作系统版本号方法
开发语言·c#
道一231 小时前
C# 判断文件是否存在的方法
开发语言·c#
唐青枫3 小时前
C#.NET 范围与索引(Range、Index)完全解析:语法、用法与最佳实践
c#·.net
矶鹬笛手10 小时前
(2.1) 信息技术及其发展
sql·计算机网络·c#
u***276111 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
笑非不退12 小时前
C# c++ 实现程序开机自启动
开发语言·c++·c#
周杰伦fans15 小时前
[特殊字符] 代理模式超详细讲解 ——.NET
数据库·c#·代理模式
用户83562907805116 小时前
C# 高效生成 Word 表格:复杂表格创建实战指南
后端·c#
屠夫16 小时前
C# LINQ
c#