Vernier Software and Technology
Vernier Software & Technology
Arduino and Vernier Sensors

Triggering a Buzzer with a Button Press

The Vernier Arduino Interface Shield includes a general purpose button connected to digital line 12 on the Arduino. You can use this button to control an action in your project. Before this button will work, however, you need to add this line to the setup portion of your sketch:

pinMode(12,INPUT_PULLUP);

You read the status of the button with this line of code:

int button = digitalRead(12);

The value of button will be LOW when the button is pressed and HIGH when it is not pressed.

The sample sketch, VernierLibTutorialDCUButtonPress, will turn on a buzzer connected to DCU line D1 when the general purpose button on the Vernier Arduino Interface Shield is pressed. The sketch assumes the buzzer is connected to lines D1 and GND on the DCU, and the DCU is plugged into the Digital 2 port on the Vernier Arduino Interface Shield. Note that this sketch will not work with a Digital Protoboard Adapter unless you wire a button to digital line D12 as there is no general purpose button on the adapter.

/* VernierLibTutorialDCUButtonPress (v2017)
 * This sketch turns on a DC electrical device connected to DCU 
 * line D1 when the general purpose button on the Vernier 
 * Arduino Interface Shield is pressed.
 * 
 * Plug the DCU into the Digital 2 port on the Vernier Arduino 
 * Interface Shield.
 */

#include "VernierLib.h" //include Vernier functions in this sketch
VernierLib Vernier; //create an instance of the VernierLib library

int button; //create a global variable for button state (LOW=button pressed, HIGH=button not pressed)
 
void setup() {
  pinMode(12,INPUT_PULLUP); //setup digital line 12 for button state
}

void loop() {
  button=digitalRead(12); //get button state
  if(button=LOW) //check if button pressed down
  {
    Vernier.DCU(1); //turn on DCU line D1
  }
  else //check if button not pressed
  {
    Vernier.DCU(0); //turn off all DCU lines
  }
  delay(500); //wait half second
}


Contents

Introduction

Vernier Engineering Contest

Vernier recognizes instructors for creative uses of Vernier sensors to introduce engineering concepts and/or practices. Vernier Engineering Award »

Go to top