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

    }
}

下载

下载地址

相关推荐
FL16238631298 小时前
[C#][winform]segment-anything分割万物部署onnx模型一键抠图演示
开发语言·c#
love530love10 小时前
OpenClaw 手机直连配置全流程
人工智能·windows·python·智能手机·c#·agent·openclaw
bcbobo21cn11 小时前
C# byte类型和byte数组的使用
开发语言·c#·字节数组·byte类型
月巴月巴白勺合鸟月半13 小时前
一次PDF文件的处理(一)
pdf·c#
大鹏说大话15 小时前
Java 锁膨胀机制深度解析:从偏向锁到重量级锁的进化之路
开发语言·c#
武藤一雄17 小时前
WPF处理耗时操作的7种方法
microsoft·c#·.net·wpf
武藤一雄17 小时前
C#常见面试题100问 (第一弹)
windows·microsoft·面试·c#·.net·.netcore
l1t19 小时前
DeepSeek总结的用 C# 构建 DuckDB 插件说明
前端·数据库·c#·插件·duckdb
iReachers20 小时前
恒盾C#混淆加密大师 1.4.5 最新2026版本发布 (附CSDN下载地址)
c#·c#混淆·c#加密·wpf加密·winform加密
历程里程碑21 小时前
43. TCP -2实现英文查中文功能
java·linux·开发语言·c++·udp·c#·排序算法