You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移植Python RFM69库频率相关位操作到C#的问题求助

RFM69 C#移植:频率与频偏属性读写不一致问题

我正在将适用于树莓派的SPI无线电模块库Adafruit_CircuitPython_RFM69移植到C#。目前大部分Python属性已移植并测试通过,但frequency_mhz和frequency_deviation属性的读写存在偏差——设置频率为433MHz后读取到432MHz,设置频偏为250000后读取到249978。这导致我的C#移植版本无法接收无线电数据包,但Python版本工作正常,我怀疑正是这两个属性的问题。

频率相关代码

// works? - not perfectly accurate
rfm.Frequency = 433;
Console.WriteLine("Frequency: {0}", rfm.Frequency); // after setting 'rfm.Frequency = 433' the get method reports '432'

private int GetFrequency()
{
    // FRF register is computed from the frequency following the datasheet.
    // See section 6.2 and FRF register description.
    // Read bytes of FRF register and assemble into a 24-bit unsigned value.
    byte msb = ReadByte(_REG_FRF_MSB);
    byte mid = ReadByte(_REG_FRF_MID);
    byte lsb = ReadByte(_REG_FRF_LSB);
    int frf = ((msb << 16) | (mid << 8) | lsb) & 0xFFFFFF;
    int frequency = (frf * _FSTEP) / 1000000;
    return frequency;
}

private void SetFrequency(int freq)
{
    if (freq < 290 || freq > 1020)
        throw new ArgumentOutOfRangeException(nameof(freq), freq, "frequency must be between range(290, 1020)");

    // Calculate FRF register 24-bit value using section 6.2 of the datasheet.
    int frf = ((freq * 1000000) / _FSTEP) & 0xFFFFFF;

    // Extract byte values and update registers.
    byte msb = (byte)(frf >> 16);
    byte mid = (byte)((frf >> 8) & 0xFF);
    byte lsb = (byte)(frf & 0xFF);

    WriteByte(_REG_FRF_MSB, msb);
    WriteByte(_REG_FRF_MID, mid);
    WriteByte(_REG_FRF_LSB, lsb);
}

频偏相关代码

// works? - not perfectly accurate
rfm.FrequencyDeviation = 250000;
Console.WriteLine("FrequencyDeviation: {0}", rfm.FrequencyDeviation); // after setting 'rfm.FrequencyDeviation = 250000' the get method reports '249978'

private int GetFrequencyDeviation()
{
    byte msb = ReadByte(_REG_FDEV_MSB);
    byte lsb = ReadByte(_REG_FDEV_LSB);
    return _FSTEP * ((msb << 8) | lsb);
}

private void SetFrequencyDeviation(int value)
{
    if (value < 0 || value > _FSTEP * 16383) // fdev is a 14-bit unsigned value
        throw new ArgumentOutOfRangeException(nameof(value), value, $"frequency deviation must be between range(0, {_FSTEP * 16383})");

    // Round up to the next closest integer value with addition of 0.5.

    int fdev = (int)((value / _FSTEP) + 0.5) & 0x3FFF;
    WriteByte(_REG_FDEV_MSB, (byte)(fdev >> 8));
    WriteByte(_REG_FDEV_LSB, (byte)(fdev & 0xFF));
}

我测试了Python版本的这两个属性,读写值完全一致,尝试了多种C#类型转换和取整方法都无效。我认为问题出在C#与Python的类型差异导致的位操作不一致,希望获得相关解决建议或指导。

内容的提问来源于stack exchange,提问作者tottaka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:31:04