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