pComp labs: digital and analog IO

Posted on
intro to pcomp itpnyu

Learning digital and analogue IO with Arduino.

via GIPHY

Basic Digital IO

For my button test, I decided to try using the internal pullup resistor available on the board, rather than wiring a pull down resistor.

The pullup can be used like the below example, but note that using the pullup (instead of pulldown) effectively inverts the signal.

void setup() {
  // put your setup code here, to run once:
  pinMode(2, INPUT);           // set pin to input
  digitalWrite(2, HIGH);       // turn on pullup resistor
}

void loop() {
   // read the switch input:
   if (digitalRead(2) == HIGH) {
     // if the switch is open:
     digitalWrite(13, HIGH);    // turn on the LED
   }
   else {
     // if the switch is closed:
     digitalWrite(13, LOW);     // turn off the LED
   }
 }

I also tried using a button library I found on Github that differentiated between taps and long presses on a button.

Basic Analogue IO

I decided to try using an accelerometer I had and ended up having to transform the signal to get a decent mapping between shaking and lighting up the LED.

I was surprised C let me get away with an open if statement without an else clause.

int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
float accel = 0.00;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin, OUTPUT);
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  accel = (float) abs(sensorValue - 619);
  accel = sqrt(accel);
  if (accel > 5) {
      digitalWrite(ledPin, HIGH);
      delay(accel);
      digitalWrite(ledPin, LOW);
  }
}