python和c#函数结果的区别

时间:2012-10-31 02:45:50

标签: c# python raspberry-pi

我正在使用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;

    }

1 个答案:

答案 0 :(得分:1)

在Python实现结束时,你正在转移一点分辨率:

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

C#实现中没有相同的代码:

return adcout;

向右移动一位相当于除以2。因此,C#版本返回值的两倍是有道理的。