0

C#/Mono と Python を使用して Raspberry Pi で遊んでいます。現在、一部のコードを Python から C# に変換していますが、値が異なっています。

ポテンショメータを調整してこれらの関数を繰り返しサンプリングすると、Python では 0 ~ 1023、C# では 0 ~ 2047 になります。

違いの原因は何ですか?私はPythonに非常に慣れていません。

Python では、この関数は 0 から 1023 の間の値を生成します (ポテンショメータを調整する場合)。

def readadc(adcnum, clockpin, mosipin, misopin, cspin):
    if ((adcnum > 7) or (adcnum < 0)):
            return -1
    GPIO.output(cspin, True)

    GPIO.output(clockpin, False)  # start clock low
    GPIO.output(cspin, False)     # bring CS low

    commandout = adcnum
    commandout |= 0x18  # start bit + single-ended bit
    commandout <<= 3    # we only need to send 5 bits here
    for i in range(5):
            if (commandout & 0x80):
                    GPIO.output(mosipin, True)
            else:
                    GPIO.output(mosipin, False)
            commandout <<= 1
            GPIO.output(clockpin, True)
            GPIO.output(clockpin, False)

    adcout = 0
    # read in one empty bit, one null bit and 10 ADC bits
    for i in range(12):
            GPIO.output(clockpin, True)
            GPIO.output(clockpin, False)
            adcout <<= 1
            if (GPIO.input(misopin)):
                    adcout |= 0x1

    GPIO.output(cspin, True)

    adcout >>= 1       # first bit is 'null' so drop it
    return adcout

c#では0~2047を返すようです。

static int returnadc(int adcnum, GPIO.GPIOPins clockpin, GPIO.GPIOPins mosipin,
 GPIO.GPIOPins misopin, GPIO.GPIOPins cspin)
    {
        int commandOut = 0;
        GPIOMem cpPin = new GPIOMem(clockpin, GPIO.DirectionEnum.OUT);
        GPIOMem moPin = new GPIOMem(mosipin, GPIO.DirectionEnum.OUT);
        GPIOMem miPin = new GPIOMem(misopin, GPIO.DirectionEnum.IN);
        GPIOMem cspPin = new GPIOMem(cspin, GPIO.DirectionEnum.OUT);

        cspPin.Write(true);
        cpPin.Write(false);
        cspPin.Write(false);

        commandOut = adcnum;

        commandOut |= 0x18;
        commandOut <<= 3;
        for (int x = 1; x <6 ; x++)
        {
            if ((commandOut & 0x80) > 0)
            {
                moPin.Write(true);
            }
            else
            {
                moPin.Write(false);
            }
            commandOut <<= 1;
            cpPin.Write(true);
            cpPin.Write(false);

        }

        int adcout = 0;
        for (int xx = 1; xx < 13; xx++)
        {
            cpPin.Write(true);
            cpPin.Write(false);
            adcout <<= 1;
            if (miPin.Read())
            {
                adcout |= 0x1;
            }
        }
        cspPin.Write(true);

        return adcout;

    }
4

1 に答える 1

1

Python 実装の最後で、解決策を 1 ビット シフトアウトします。

adcout >>= 1       # first bit is 'null' so drop it
return adcout

C# 実装には同じコードはありません。

return adcout;

1 ビット右にシフトすることは、2 で除算することと同じです。したがって、C# バージョンが 2 倍の値を返すことは理にかなっています。

于 2012-10-31T02:48:44.523 に答える