python和c#函数的结果差异

2024-06-06 15:12:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用C#/Mono和Python来玩覆盆子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。在

^{pr2}$

Tags: 函数infalsetrueoutputgpioifbit
1条回答
网友
1楼 · 发布于 2024-06-06 15:12:39

在Python实现的最后,您将转移一点解析:

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

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

^{pr2}$

右移一位等于除以二。因此,C版本返回的值应该是原来的两倍。在

相关问题 更多 >