아두이노 우노 스케치 예제: 디지털 입력 풀업

이번 예제 코드는 상시 열림(NO)인 푸시 버튼 스위치를 오픈 상태에서 하이로 바이어스하기 위해 내부 풀업 저항을 사용하는 방법을 보여주기 위함이며 스위치를 누르면 로우로 읽혀 질 것입니다. 풀업 또는 풀다운 저항을 사용하면 플로팅 신호의 발생을 방지할 수 있습니다. 스위치가 “플로팅” 상태이면 스위치의 전위는 0V와 5V 사이에서 자유롭게 이동할 수 있게 됩니다. 회로 내의 노이즈는 스위치의 신호를 잘못된 입력으로 읽을 수 있을 만큼 요동치도록 만들 수 있을 뿐만 아니라 입력을 실질적으로는 사용할 수 없을 정도로 (전위가)오락가락할 수 있습니다. 이런 문제가 발생하지 않도록 하기 위해서는 로우로 끌어 내리기(pull down) 위해 저항을 접지에 연결하거나 하이로 끌어 올리기(pull up) 위해 +5V(하이 신호 레벨)에 연결하는 방식으로 스위치를 하이 또는 로우에 바이어스해야만 합니다.

예제 코드 시작

void setup() {
	//Start the serial connection
	Serial.begin(9600);

	// set pin 2 as an input and use internal pullup resistor
	pinMode(2, INPUT_PULLUP);

	// set pin 13 as an output
	pinMode(13, OUTPUT);
}

void loop() {
	//set up a variable to hold value of the pushbutton
	int sensorVal = digitalRead(2);

	//print the value of the variable to the serial monitor
	Serial.println(sensorVal);

	// check the variable to see if the button is pressed. Remember if HIGH the button has not been pressed, LOW when it is being pressed
	if (sensorVal == HIGH) { 
		digitalWrite(13, LOW); // Turn LED off
	} else {
		digitalWrite(13, HIGH); //turn LED on
	}
}

초기 코드의 배선도

확장 코드

여기에 (LED)불빛을 조금 더 추가해 보겠습니다. 핀 11과 12에 두 개의 LED와 저항을 연결할 것입니다. 그런 다음, 버튼을 누를 때마다 3개의 LED가 켜졌다 꺼질 수 있게 만들 것입니다. 버튼을 누르고 있는 동안 LED 점등은 계속 순환될 것입니다.

void setup() {
	//start serial connection
	Serial.begin(9600);

	//configure pin2 as an input and enable the internal pull-up resistor
	pinMode(2, INPUT_PULLUP);

	// Set pins 11, 12, and 13 to ouputs
	pinMode(13, OUTPUT);
	pinMode(12, OUTPUT);
	pinMode(11, OUTPUT);
}

void loop() {
	int sensorVal = digitalRead(2); //read the pushbutton value into a variable

	Serial.print(sensorVal); //print out the value of the pushbutton on the Serial moniter

	if (sensorVal == HIGH) { // Remember that the buttons logic is inverted. When it is high it is not pressed.

		digitalWrite(13, LOW); // Being button is not pressed turn off all LED's

		digitalWrite(12, LOW);

		digitalWrite(11, LOW);

	} else { // This is when the pushbutton is pressed

		digitalWrite(13, HIGH); // turn on the LED attached to pin 13

		delay(200); // pause for 200 milliseconds before moving on

		digitalWrite(13, LOW); //turn off the LED attached to pin 13

		digitalWrite(12, HIGH); // turn on the LED attached to pin 12

		delay(200); // delay again

		digitalWrite(12, LOW); //turn off pin 12

		digitalWrite(11, HIGH); // turn on pin 11

		delay(200); // delay again

		digitalWrite(11, LOW); //turn off pin 11

		digitalWrite(12, HIGH); // turn on pin 12

		delay(200); // delay again

		digitalWrite(12, LOW); //turn off pin 12

		digitalWrite(13, HIGH); // turn on pin 13

		delay(200); // delay if the button is still held

	}
}

LED 불빛의 움직임을 더 빠르게 또는 더 느리게 하고 싶다면 delay 수치를 변경하시면 됩니다. 각 delay를 1000으로 설정하면 LED 변경 간에 1초 지연이 발생한다는 점을 명심하시기 바랍니다.

확장 코드의 배선도

자재 명세서

장바구니 링크: Digi-Key 장바구니



영문 원본: Arduino Uno Example Sketch: Digital Input Pullup