2012-10-31 48 views
0

我正在用C#/ Mono和Python玩Raspberry Pi。我目前正在将一些代码从Python转换为C#,并且这些值会不同。python和c#函数结果之间的区别

当调整一个电位计并重复采样这些函数时,我得到0-1023的Python,0-2047的C#。

究竟有什么区别?我对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 - 在你的Python执行结束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

你说得对移出分辨率的一位:

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

的相同的代码不存在于您的C#实现中:

return adcout; 

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

+0

Doh!惊人的第二双眼睛会做什么。谢谢! –

相关问题