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 byte1024;

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 byte14; //定义缓冲区大小

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_recvBytes9, m_recvBytes10);

String direction = Direction(m_recvBytes4);

// 更新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{dataBytes9:X2}, B6=0x{dataBytes10:X2}");

info.AppendLine($" 计算: ((0x{dataBytes9:X2}>>5)*256 + 0x{dataBytes10: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");
        }

    }
}

下载

下载地址

相关推荐
泛凡(Linyongui)8 小时前
基于 CW32L010 的智能厨卫调温旋钮方案--低成本 EC21 编码旋钮全解析
单片机·嵌入式硬件·c#
暴走约伯10 小时前
【VFX工具链源码拆解 02】告别机械劳动(上):一键统改百个子粒子颜色与批量重命名
3d·unity·c#·材质
信息安全失业大专人员12 小时前
每日了解一个智能体-WorkBuddy
开发语言·ai·c#·智能体
呆呆敲代码的小Y12 小时前
【实战精选面试题】C# 面试题详细解答,按难易程度排序
android·java·游戏·c#·游戏开发·unity面试题·c#面试题
淡海水13 小时前
09-01-内存-Unity资源生命周期全景
unity·c#·游戏引擎·.netcore·gc
椒颜皮皮虾྅16 小时前
让 C# 读懂整张图:DeploySharp 驱动 PaddleOCR v4/v5/v6,打通 OCR 全流程
开发语言·人工智能·深度学习·学习·c#·ocr·cuda
昂好的day16 小时前
C# 同步异步与多线程:Thread / Task / 线程池一次讲透(上篇)
开发语言·windows·c#
吃一碗粉只付一碗钱1 天前
12-给SPA友好的401和403响应
c#·状态模式
caimouse1 天前
MonoDevelop 编译用户应用程序时调用的是哪个编译器
c#
will_net1 天前
apollo 站点部署&C#接入
开发语言·c#·apollo