分类 C# 下的文章

MWC飞控通讯

前几个星期入手了一款基于MWC飞控的WIFI小四轴,缺点就是只有手机APP。操作起来没有手感。寻思着用Ardiuno+C#做一个实体遥控器。首先是封装MWC通讯格式,下面就是封装的代码。最后结局就是手滑没调好撞废一个硬盘

/// <summary>
/// 获取发送Byte
/// </summary>
/// <param name="command">操作</param>
/// <param name="data">数据</param>
/// <returns></returns>
public byte[] GetFlyByte(int command, int[] data)
{
    byte[] FlyByte = new byte[data.Length + 6];
    // $
    FlyByte[0] = (byte)Convert.ToInt32("24", 16);
    // M
    FlyByte[1] = (byte)Convert.ToInt32("4D", 16);
    // <
    FlyByte[2] = (byte)Convert.ToInt32("3C", 16);
    //数据长度
    FlyByte[3] = (byte)Convert.ToInt32(data.Length.ToString("X"), 16);
    //操作
    FlyByte[4] = (byte)Convert.ToInt32(command.ToString("X"), 16);
    
    byte[] ConvertData = new byte[data.Length];
    //发送数据赋值 与 校验数据赋值
    for (int i = 5, j = 0; i < data.Length + 5; i++, j++ )
    { 
        FlyByte[i] = (byte)data[j];
        ConvertData[j] = (byte)data[j];
    }

    FlyByte[FlyByte.Length-1] = CheckNumber((byte)command, ConvertData);
    return FlyByte;
}

/// <summary>
/// 获取校验码
/// </summary>
/// <param name="command">操作</param>
/// <param name="data">数据</param>
/// <returns>校验码</returns>
private byte CheckNumber(byte command, byte[] data)
{
    byte rdata = 0;

    rdata ^= (byte)(data.Length & 0xFF);
    rdata ^= (byte)(command & 0xFF);

    for (int i = 0; i < data.Length; i++)
        rdata ^= (byte)(data[i] & 0xFF);

    return rdata;
}

flyc.jpg
MWC通讯格式官方文档:http://www.multiwii.com/wiki/index.php?title=Multiwii_Serial_Protocol

C#自定义事件

声明委托

public delegate void ServerHandler(ServerConfig e);

在需要被触发的事件类内绑定委托

public event ServerHandler ServerStop;
public event ServerHandler ServerStart;

触发事件

//防止没有订阅引发异常
if(ServerStart != null) ServerStart(new ServerConfig()); 
if(ServerStop != null)  ServerStop(new ServerConfig());

订阅事件

Server.ServerStart += new ServerHandler(this.Server_Start);
Server.ServerStop += new ServerHandler(this.Server_Stop);

private void Server_Start(ServerConfig e)
{
    MessageBox.Show("服务端进程启动~");
}

private void Server_Stop(ServerConfig e)
{
    MessageBox.Show("服务端进程退出~");
}

记得释放事件 以免发生内存泄漏!

利用Process获取CPU占用率

using (var pro = Process)
{
    //间隔时间(毫秒)
    int interval = 1000;
    //上次记录的CPU时间
    var prevCpuTime = TimeSpan.Zero;
    while (true)
    {
        try
        {
            //当前时间
            var curTime = pro.TotalProcessorTime;
            //多核占用
            //var value = (curTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
            //单核占用
            var value = (curTime - prevCpuTime).TotalMilliseconds / interval * 100;
            prevCpuTime = curTime;
            CPU = value;
        }catch{
            CPU = 0;
        }
        Thread.Sleep(interval);
    }
}