2016-03-12 53 views
1

我試圖編碼一個簡單的PWM伺服控制,它使用Arduino Mega 2560上的引腳11,這個伺服應該順時針旋轉或逆時針旋轉。取決於按下並按住兩個按鈕中的一個(L和R)。我似乎遇到的問題是,即使當'if'語句不正確時,我設置爲更改OCR1A(i)的變量也正在增加。這些按鈕的工作原理與我使用Serial.println(PINA)進行測試一樣。我真的不確定我哪裏出了問題。我將不勝感激任何幫助。我的OCR1A即使在'if'條件沒有被滿足時也在改變

void setup() { 
    // put your setup code here, to run once: 
    TCCR1A |= (1<<COM1A1)|(1<<WGM11)|(1<<WGM10); 
    TCCR1B = 0B00001100; // set mode 7 and prescale to 256 
    DDRB |= (1<<PB5); // data direction register for PORTB(pwm output pin 11) 
    DDRA = (1<<2)|(1<<3); // Last 2 digits of PORTA are inputs 
    Serial.begin(9600); //initialize the serial 
} 

void loop() { 
    int i = 63; 
    // This value controls the duty cycle, duty(%) = OCR1A/255*100 
    // 63 is just a random start position 
    OCR1A = i; 
    int swL; 
    int swR; 
    swL = PINA & 0b00000001; 
    swR = PINA & 0b00000010; 
    while(i<160) { 
    if (swR != 0b00000001) { 
     i++; // increments OCR1A when button R is pressed 
     Serial.println(PINA); // For testing button is pressed 
     Serial.println(OCR1A); // debugging use 
     Serial.println(i); // debugging use 
     delay(100); 
    } 
    if(swL != 0b00000010) { 
     i--; // negative increments when button L is pressed 
     Serial.println(PINA); 
     Serial.println(OCR1A); 
     Serial.println(i); 
     delay(100); 
    } 
    } 
} 
+1

你用0b10屏蔽'swR',然後與0b01比較。所以'if'永遠是真的。 – user3386109

回答

0

好像PINA & 0b00000001提供了一定的參考價值swL。現在我無法找到的PINA初始值,但我認爲它是具有二進制值等其他變量,當兩個值進行位與他們提供了一個不同的值swL

我想這就是爲什麼if條件 if (swL != 0b00000001)評估爲TRUE然後它進入if語句的原因。

其他變量swR也是如此,所以它也進入if statement

我可能是錯的,但看看行:

swL = PINA & 0b00000001; swR = PINA & 0b00000010;

0

謝謝,原來我只需要一組額外的眼睛。我的swR和swL交換了。其他一些變化現在可以按預期工作。謝謝你們。

相關問題