This week we took our circuits to the next level via the power of Microcontrollers. More specifically, I used our given Arduino Nanos to create more sophisticated and versatile circuits. I’ve used Arduinos a little in the past, but it was years ago, so jumping back into the software was both daunting and exciting.

In Lab 1, we learned how to set up the Arduino IDE and upload code to our microcontrollers to control LEDs. Unlike a circuit powered by a simple power source, we aren’t limited to a binary ON switch = ON load anymore. Instead, I built a circuit that had one LED that went on/off according to the switch state, and one LED that went opposite of the switch state. I also converted a potentiometer’s analog input into an analog output: the luminosity of the LED.

IMG_9646.MOV

IMG_9647.MOV

In Lab 2 we learned more about types of analog inputs, including these force sensing resistors that can dim LEDs depending on how hard they’re pressed. It was really neat to see how tangible sensors like theses FSRs and the potentiometer can be read in by the Nano and instantly channeled into our load, the LED.

FullSizeRender.MOV

Binary Button Clicker

IMG_9654.MOV

Based off Lab 3’s button counter code, I wrote a relatively simple script to create this LED display that shows in binary how many times you’ve clicked the button, from 0-7 (and loops back to 0 afterwards). The Red LEDs represent a bit being either 0 (off) or 1 (on).

int lastButtonState = LOW;   // state of the button last time you checked
int buttonPresses = 0;

int buttonPin = 9;
int led0Pin = 18;
int led1Pin = 15;
int led2Pin = 14; 

void setup() {
  Serial.begin(9600);
  pinMode(9, INPUT);
  pinMode(led0Pin, OUTPUT);
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
}

void loop() {
  int buttonState = digitalRead(9);
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      buttonPresses = (buttonPresses + 1) % 8;
      Serial.print(buttonPresses);
			lastButtonState = buttonState;
			
			  if (buttonPresses & (1 << 0)){
			    digitalWrite(led0Pin, HIGH);
			  }
			  else{
			    digitalWrite(led0Pin, LOW);
			  }
			  if (buttonPresses & (1 << 1)){
			    digitalWrite(led1Pin, HIGH);
			  }
			  else{
			    digitalWrite(led1Pin, LOW);
			  }
			  if (buttonPresses & (1 << 2)){
			    digitalWrite(led2Pin, HIGH);
			  }
			  else{
			    digitalWrite(led2Pin, LOW);
			  }
		}
  }
}

This code could definitely be shortened using a for loop, but since I only had three bits to account for I thought this implementation was easier for readability and debugging. But this project could easily be extrapolated to include more bits, and I’d modify the code to be something like this:

// we'd store our LED output numbers in an array, ledArray
for (int i = 0; i < NUM_BITS; i++){
	if (buttonPresses & (1 << NUM_BITS)){
    digitalWrite(ledArray[NUM_BITS], HIGH);
  }
  else {
	  digitalWrite(ledArray[NUM_BITS], LOW);
  }
}