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");
        }

    }
}

下载

下载地址

相关推荐
bugcome_com7 小时前
零基础入门C#:一篇搞懂核心知识点
c#
程序员敲代码吗10 小时前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
缺点内向12 小时前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
喵叔哟13 小时前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
2501_9307077813 小时前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
初级代码游戏14 小时前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放
大空大地202615 小时前
流程控制语句--switch多分支语句使用、while循环语句的使用、do...while语句、for循环
c#
kylezhao201916 小时前
C#序列化与反序列化详细讲解与应用
c#
JQLvopkk17 小时前
C# 实践AI :Visual Studio + VSCode 组合方案
人工智能·c#·visual studio
故事不长丨17 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#