Basic Digital Sensing

Digital sensing refers to the binary states of high/low voltage that a digital input pin can detect.

On the mote, LOW = 0V, HIGH = 3.3V. When we read the state from the pin, we assign a HIGH/LOW, TRUE/FALSE, 1/0 binary state to a variable – these terms are equivalent and interchangeable in the Arduino IDE, although HIGH/LOW makes the most sense electrically.

In this recipe, we are using a basic tilt switch as a demonstration of the digital switch. If you use any basic digital sensor, pushbutton switch, or even bare wire, that connects pin 13 to Ground, you should get the same result.

The key command here is:

  digitalRead(x)

which returns a HIGH/LOW result.

x is the digital pin number. If you refer to the Programmer board, the pins available to us on the mote are 0, 2, 12, 13, 14, 15, 16. Use pins 12-16 (excluding 15) where possible. Pin 0 is involved in firmware upgrade/reset and so might interfere with your code (refer to this GPIO Overview for more information).

The crucial aspect in this recipe is to use a pull-up resistor for the digital line you are sensing. Not doing this will cause that line to fluctuate from physical movement of the wire, EMI, or heck, the entropy of the universe (which perhaps could be an interesting phenomenon to sense).

One could add a physical resistor connected to 3.3V and the digital pin to ‘pull it up’ to 3.3V, with the sensor acting as a grounding agent when it is activated.

Alternatively, we can substitute this physical resistor with an internal one, using the following line:

  pinMode(13, INPUT_PULLUP);

Libraries Used


Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const int SENSEPIN = 13;
boolean senseState = LOW;

// code in this setup function runs just once, when mote is powered up or reset
void setup() {
    Serial.begin(9600);         // Open a connection via the Serial port / USB cable – useful for debugging
    pinMode(SENSEPIN, INPUT_PULLUP);
}

// code in this loop function runs forever, until you cut power!
void loop() {
    senseState = digitalRead(SENSEPIN);
    Serial.println(senseState);
    delay(500);
}