我試圖編碼一個簡單的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);
}
}
}
你用0b10屏蔽'swR',然後與0b01比較。所以'if'永遠是真的。 – user3386109