×

GRAB CODE: PRESS CMD-C

instil

math science

tutoring

FAVORITES

OPTIONS

CLASS OPTIONS

ARDUINO

BLANK BLANK

Arduino Basics to Get You Started

The Arduino Uno Microcontroller Board

To start, there are just a few things you should know,
this image was created with Fritzing
  1. 5V is the main power pin
  2. There are 3 ground GND pins
  3. There are 14 DIGITAL pins, 0 - 13
  4. Pins with tilde ~ have PWM (Pulse-Width Modulation)... you can turn the power up and down from 0 - 100%
  5. Pin #13 is connected to the yellow LED L onboard
  6. There are 6 analog pins A0 - A5

Directionality of LED & Resistor

One Way or Another

Does the direction of LEDs or resistors matter? Try wiring this up, then reverse the direction of the resistor, and then reverse the direction of the LED. See what happens... Solution

Caution: Always use a resistor (or equivalent) with an LED, otherwise the LED could blow.
The direction of the resistor doesn't matter. Only the direction of the LED matters because it is a diode (Light Emitting Diode). The longer lead/pin is the positive side.

If you're interested, learn more about diodes:
this image was created with Fritzing
Materials:
  • 220 Ω resistor
  • Red LED, 250 mcd
  • Jumper wire

Resistors Modify LEDs

Vary Resistances to See the Effect on Brightness

Connect 4 different resistors to the same type of LEDs and see what happens to brightness.
this image was created with Fritzing
Materials:
  • 220 Ω resistor
  • 1 kΩ resistor
  • 10 kΩ resistor
  • 110 kΩ resistor
  • 4 × Red LED, 250 mcd
  • Jumper wire

Input + Output + LED + Start Code

Digital Inputs and Outputs

The pushbuttons are inputs, and the LEDs are outputs. While the top pushbutton button1 is pressed, LOW, the LEDs will change states. The red LED will turn off and the white LED will turn on. While the bottom pushbuttom button2 is pressed, LOW, the LEDs will always be turned off, even when both buttons are pressed.

Caution: use resistors with pushbuttons to limit the current flowing from the microcontroller pins.
this image was created with Fritzing
Materials:
  • 2 × 300 Ω resistor
  • 2 × 1 kΩ resistor
  • 2 × Pushbutton switch
  • Red LED
  • White LED
  • Jumper wire
Copy and paste the code into your Arduino sketch. Try hacking around with it.
				// Initialize the pin variables as integers
int ledPin1 = 12;
int ledPin2 = 11;
int button1 = 10;
int button2 = 9;

// Define the input and output pins
void setup() {
  pinMode(button1, INPUT_PULLUP);  
  pinMode(button2, INPUT_PULLUP);  
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

// The logic. 
// digitalRead: LOW is pressed, HIGH is unpressed
// digitalWrite: LOW is off, HIGH is on full
void loop() {
  if (digitalRead(button1) == HIGH 
  		&& digitalRead(button2) != LOW) {
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
  }
  if (digitalRead(button1) == LOW 
  		&& digitalRead(button2) != LOW) {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, LOW);
  }
  if (digitalRead(button2) == LOW) {
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
  }
}
			

RGB LED + Input + Serial Input/Output

RGB Colors

Use a pushbutton input to generate random RGB colors with different combinations from 0 - 255, of red, green, and blue. Sometimes the pushbutton needs to be pressed and held.
this image was created with Fritzing
Materials:
  • 3 × 300 Ω resistor
  • 1 × 1 kΩ resistor
  • Pushbutton switch
  • RGB LED
  • Jumper wire
				int redPin = 10;
int greenPin = 9;
int bluePin = 8;
int button = 7;
int randomNum1;
int randomNum2;
int randomNum3;
int inputNum;

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(button, INPUT_PULLUP);  
  Serial.begin(9600); // enable serial monitor
}

void loop() { 
  if (digitalRead(button) == LOW) {
  	// Generate the random number 
  	// from 0 to 255, for each color
    randomNum1 = random(0, 255); // (min, max)
    randomNum2 = random(0, 255);
    randomNum3 = random(0, 255);
    color(randomNum1, randomNum2, randomNum3);
    delay(150);
  } else {
  	// serial monitor input, integer
  	inputNum = Serial.parseInt();
  	if ( inputNum > 0 && inputNum <=255) {
  		color(inputNum, inputNum, inputNum);
  	}
  }
}

// Construct the color combination of:
// red, green, and blue
void color(int red, int green, int blue) {
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);  
  
  // Show the color combination in the Serial Monitor
  Serial.print("\nThe RGB color is: ");
  Serial.print("(");Serial.print(red);Serial.print(", ");
  Serial.print(green);Serial.print(", ");
  Serial.print(blue);Serial.print(")");
}

			

Analog Potentiometer and LED Array

Trim Pot Controls LED Bar Graph Array

This is a fairly simple program to control an array of 8 LEDs with the analog input from a trim potentiometer. As you turn the potentiometer up (open) the LEDs light up like a bar graph. Try it...

Caution: use a resistor with a potentiometer to limit the current flowing to the microcontroller pin.
this image was created with Fritzing
Materials:
  • 8 × 300 Ω resistor
  • 1 × 10 kΩ resistor
  • 4 × White LEDs
  • 4 × Red LEDs
  • 1 kΩ (or 10 kΩ, or any) trim potentiometer
  • Jumper wire
				// the pin that the potentiometer is attached to
const int analogPin = A5;
// the number of LEDs in the bar graph
const int ledCount = 8;

// an array of pin numbers to which LEDs are attached
int ledPins[] = { 
  5, 6, 7, 8, 9, 10, 11, 12
};

void setup() {
  // loop over the pin array and set them all to output:
  for (int thisLed = 0; thisLed < ledCount; thisLed++) {
    pinMode(ledPins[thisLed], OUTPUT); 
  }
}

void loop() {
  // read the potentiometer:
  int sensorReading = analogRead(analogPin);
  // map the result to a range
  // from 0 to the number of LEDs:
  int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

  // loop over the LED array:
  for (int thisLed = 0; thisLed < ledCount; thisLed++) {
    // if the array element's index is less than ledLevel,
    // turn the pin for this element on:
    if (thisLed < ledLevel) {
      digitalWrite(ledPins[thisLed], HIGH);
    } 
    // turn off all pins higher than the ledLevel:
    else {
      digitalWrite(ledPins[thisLed], LOW); 
    }
  }
}
			

Light Sensor (LDR) + LED Auto Dimmer

Dim an LED according to the brightness around the light sensor

The LED will auto-dim according to the light level in your room or environment. The photoresisitor detects the relative light levels and changes its resistance. The analog pin on the Arduino detects this analog input, with analogRead(), in a range from 0 - 1023. The LED is controlled by pulse wave modulation (PWM) on pin ~11 with the analogWrite() command.

You will have to calibrate your values first because you will probably have a different combination than me of: light levels, photocell, and resistor. Calibrate your setup by replacing Serial.println(calValue); with Serial.println(lightSensorLevel);. Then set calibrateLowest and calibrateHigest to the lowest and highest readings that you get in your Serial Monitor in your Arduino IDE.
this image was created with Fritzing
Materials:
  • Photoresistor (LDR), 5mm, GL5626
  • 5 kΩ resistor
  • 220 Ω resistor
  • Blue Ultra-Bright LED
  • Jumper wire
				int liSenLev; // light sensor level
int calVal; // calibrated value
int ledValue;
int liSenPin = A0; // analog
int ledPin = 11; // ~PWM

// Calibration depends on your 3 things: 
// light levels, photocell, resistor.
// set from "liSenLev" reading... the darkest
// it usually gets in the room you're in
int calibrateLow = 25;

// set from "liSenLev" reading... the brightest
// it usually gets in the room you're in
int calibrateHigh = 575;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(liSenPin, INPUT);
  Serial.begin(9600); //enable serial monitor
}

void loop() {
	// analog reading: 0 - 1023
  liSenLev = analogRead(liSenPin);
  
  // map liSenLev (0 - 1023) using reversed, 
  // calibrated range (calibrateHigh to calibrateLow),
  // to 0 - 255 LED brightness
  calVal = map(liSenLev, calibrateHigh, calibrateLow, 0, 255);
  
  // failsafe, if sensed value goes above
  // your defined calibrated range
  if (calVal > 255) {
    calVal = 255;
  } else if (calVal < 0) {
    calVal = 0;
  }
  
  analogWrite(ledPin, calVal);
  // determine your calibrated range using "liSenLev"
  Serial.println("liSenLev: " + String(liSenLev) + 
  				",  calVal: " + String(calVal));
  delay(100);
}
			

LCD + Flex Sensor + OUTPUT LED

Flex Sensor Analog Input with LED/LCD Outputs

Use a flex/bend sensor to detect a certain threshold level of bending. Then activate something, represented with an LED here, and print the readings on the screen. The LCD shows the maximum and minimum readings beside the current analog reading, so you can understand the magnitudes of the readings and adjust the threshold. In this setup the readings normalize at around 288, but it will be different for you depending on your resistor and flex sensor. [If the LCD is not displaying, try turning the contrast potentiometer all the way in either direction]
this image was created with Fritzing
Materials:
  • 2.2" Flex Sensor (SEN-10264)
  • LCD Display, 16 × 2
  • LED
  • 10 kΩ resistor
  • 220 Ω resistor
  • 100 Ω resistor
  • 10 kΩ Trim Potentiometer
  • Jumper wire
				#include <LiquidCrystal.h>
// initialize the library with numbers of interface pins
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

int flexPin = A0;
int loadPin = 6;
int storeMax = 0; // initial
int storeMin = 1000; // initial
int threshold = 250; // adjust, as necessary
String storeMaxS;
String storeMinS;
String lcdView;

void setup() {
  pinMode(flexPin, INPUT);
  pinMode(loadPin, OUTPUT);
  lcd.begin(16, 2);// set LCD's number of columns and rows
  lcd.clear(); // clear existing text on screen
}

void loop() {
  int flexVal = analogRead(flexPin);
  if (flexVal > storeMax) {
    storeMax = flexVal;
    storeMaxS = String(storeMax);
  }
  if (flexVal < storeMin) {
    storeMin = flexVal;
    storeMinS = String(storeMin);
  }
  lcd.clear();
  
  // turn something (LED) on based on threshold
  if (flexVal < threshold) {
    digitalWrite(loadPin, HIGH);
    lcdView = "   ***ACTIVE***";
  } else {
    digitalWrite(loadPin, LOW);
    lcdView = "";
  }
  
  // display in the form: MIN < CURRENT VALUE < MAX
  lcd.print(storeMinS + " < " + String(flexVal) + 
  	" < " + storeMaxS + lcdView);
  
  delay(200); // more human-friendly
}
			

LCD + BUTTON INPUT

Display Your Button Inputs on LCD

This is a simple example where you can see the screen detecting the buttons as you press them. Using the provided LCD display, wire this setup and start pushing buttons. You will see that you can connect inputs to make stuff display on screen. After trying this for fun, since you already have the LCD setup, try adding new components and change the code to do what you want. [If the LCD is not displaying, try turning the contrast potentiometer all the way in either direction]
this image was created with Fritzing
Materials:
  • 4 × Pushbutton switch
  • 4 × 1 kΩ resistors
  • 100 Ω resistor
  • 10 kΩ Trim Potentiometer
  • Jumper wire
  • LCD Display, 16 × 2
				#include <LiquidCrystal.h>
// initialize library with numbers of interface pins
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

int up = 5;
int right = 4;
int left = 3;
int down = 2;
String stringy;

void setup() {
  pinMode(up, INPUT_PULLUP);  
  pinMode(right, INPUT_PULLUP);  
  pinMode(left, INPUT_PULLUP);  
  pinMode(down, INPUT_PULLUP);  
  lcd.begin(16, 2); // set LCD's number of columns and rows
  lcd.clear(); // clear existing text on screen
  lcd.print("PRESS BUTTONS"); // startup message
}

void loop() {
  if (digitalRead(up) == LOW) {
    writeLCD("up");
  } else if (digitalRead(right) == LOW) {
    writeLCD("right");
  } else if (digitalRead(left) == LOW) {
    writeLCD("left");
  } else if (digitalRead(down) == LOW) {
    writeLCD("down");
  }
}

void writeLCD(String stringy) {
  lcd.clear();
  lcd.print(stringy); // print string to LCD
  delay(10); // good practice to delay after commands to LCD
}
			

Variables + LCD + Buttons + LEDs

Increment and Decrement Variables to Control LED Brightness with PWM

Now try controlling outputs (LEDs) with inputs (pushbuttons) with an LCD display to show the current state. Switch between LEDs with the left and right buttons, and increase and decrease the brightness of each LED with the up and down buttons. Wire it up, grab the code, and check it out for yourself. [If the LCD is not displaying, try turning the contrast potentiometer all the way in either direction]
this image was created with Fritzing
Materials:
  • Red LED
  • Blue or White LED
  • 10 kΩ Trim Potentiometer
  • 100 Ω resistor
  • 2 × 220 Ω resistors
  • 4 × 1 kΩ resistors
  • 4 × Pushbutton switch
  • Jumper wire
  • LCD Display, 16 × 2
 
				#include <LiquidCrystal.h>

// initialize library with numbers of interface pins
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

int rightLED = 6; // ~PWM, right side
int leftLED = 5; // ~PWM, left side
int up = A0;
int right = A1;
int left = A2;
int down = A3;
int rightPower = 50;
int leftPower = 50;
int currentFlagLED = 0;

void setup() {
  pinMode(rightLED, OUTPUT);  
  pinMode(leftLED, OUTPUT);  
  pinMode(up, INPUT_PULLUP);  
  pinMode(right, INPUT_PULLUP);  
  pinMode(left, INPUT_PULLUP);  
  pinMode(down, INPUT_PULLUP);  
  lcd.begin(16, 2); // set LCD's number of columns & rows
  lcd.clear();
  lcd.print("PRESS BUTTONS");
  setLED(""); // start with LEDs on
}

/* 
=======
Control
=======
*/
void loop() {
  if (digitalRead(up) == LOW) {
    setLED("up");
  } else if (digitalRead(right) == LOW) {
    blinkie(rightLED, rightPower);
    currentFlagLED = 2;
  } else if (digitalRead(left) == LOW) {
    blinkie(leftLED, leftPower);
    currentFlagLED = 1;
  } else if (digitalRead(down) == LOW) {
    setLED("down");
  }
  delay(40);// prevent from jumping too fast, skipping
}

/* 
================
Helper Functions
================
*/
void displayPower(int leftPower, int rightPower) {
  lcd.clear();
  lcd.setCursor(0, 0);
  String concatString1 = "LEFT LED: " 
                      + String(leftPower) 
                      + "%";
  lcd.print(concatString1); // print string to LCD   
  lcd.setCursor(0, 1);                 
  String concatString2 = "RIGHT LED: " 
                      + String(rightPower) 
                      + "%";
  lcd.print(concatString2); // print string to LCD                      
  delay(10);
}

void setPower(int led, int powerLevel) {
  int val = (float) (powerLevel*255)/100;
  analogWrite(led, val);
}

void setLED(String forWhat) {
  if (currentFlagLED == 0) 
  // when just turn on
  {
    blinkie(rightLED, rightPower);
    blinkie(leftLED, leftPower);
  } 
  else if (currentFlagLED == 1 && forWhat == "up") 
  // left, UP
  {
    if (leftPower < 100) { ++leftPower; }
  } 
  else if (currentFlagLED == 1 && forWhat == "down") 
  // left, DOWN
  {
    if (leftPower > 0) { --leftPower; }
  } 
  else if (currentFlagLED == 2 && forWhat == "up") 
  // right, UP
  {
    if (rightPower < 100) { ++rightPower; }
  } 
  else if (currentFlagLED == 2 && forWhat == "down") 
  // right, DOWN
  {
    if (rightPower > 0) { --rightPower; }
  }
  setPower(leftLED, leftPower);
  setPower(rightLED, rightPower);
  displayPower(leftPower, rightPower);
}

void blinkie(int led, int power) {
  digitalWrite(led, LOW);
  delay(200);
  digitalWrite(led, power);
}
			

ALARM: LED + PIEZO BUZZER + FORCE SENSOR

Alarm Detects When Item is Lifted

This force sensor works well with items that are no lighter than a cell phone. It works best when you put a rubber ring or washer with a smaller diameter on top of the round sensor, so that the force is more in the center. After you wire this up, put an object with enough weight on and press the calibration/activation button. The LED should blink periodically to indicate it's the device is armed. Try removing the object to see and hear the alarm sound. I've tried to make the code a straightforward as possible so you can see what's going on and maybe even change some things if you want to see what happens.
this image was created with Fritzing
Materials:
  • 0.5" diameter Force Sensor, FSR (SEN-09375), 0.1 - 10 kg
  • 9mm Piezo buzzer, 3 - 6 V
  • Red Ultra-Bright LED, 20 mA
  • 100 Ω resistor
  • 220 Ω resistor
  • 1 kΩ resistor
  • 33 kΩ resistor
  • Jumper wires
				int ledPin = 12;
int buzzPin = 11;
int forSenPin = A5;
int buttonPin = 2;
int flag; // unarmed = 0, armed = 1
int force;
int range = 10; // (%) whole number only, adjust sensitivity
int rangeAccept;
int rangeAcceptHigh;
int rangeAcceptLow;
// non-blocking blink [credit: Mellis & Stoffregen]
unsigned long previousMillis = 0;
int ledState = LOW;
int interval = 3000;
int intervalFast = 100;

void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(buzzPin, OUTPUT);
  pinMode(forSenPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);  
  Serial.begin(9600); // enable serial monitor
}

void loop(){
  force = analogRead(forSenPin);
  outputs();
  if (digitalRead(buttonPin) == LOW) {
    calibrate(); // press button to calibrate & activate alarm
  }  
  delay(20); // reduce rate affects readings and buzzer
}

void calibrate() {
  if(force == 0) { // if calibrated with nothing on first
    flag = 0; // disarm
    // failsafe: undo buzzer and led
    digitalWrite(ledPin, LOW);
    tone(buzzPin, 0, 100);
  } else if (force > 0) {
    flag = 1;
  }
  // calibrate to ± __% of force
  // cast the float with (int)
  rangeAccept = (int) (force/100*range);
  rangeAcceptHigh = force + rangeAccept;
  rangeAcceptLow = force - rangeAccept;
  delay(500); // just one reading while button pressed
}

void outputs() {
	// max: 4294967295 ms = 1193 hr = 49 days
  unsigned long currentMillis = millis();
  
  // Blink to show when detected and protected
  if (force > rangeAcceptLow && 
  	force < rangeAcceptHigh && flag == 1) {
      if (currentMillis - previousMillis > interval) {
      // save the last time you blinked the LED 
      previousMillis = currentMillis;   
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {
        ledState = HIGH;
        interval = intervalFast; // blip LED on
      } else {
        ledState = LOW;
        interval = 3000; // reset to low rest state
      }
      // set the LED with the ledState of the variable:
      digitalWrite(ledPin, ledState);
    }
  }
  
  // Blink very fast and sound buzzer for alarm...
  if (force < rangeAcceptLow && flag == 1 || 
  	force > rangeAcceptHigh && flag == 1) {
    if (currentMillis - previousMillis > intervalFast) {
      // save the last time you blinked the LED 
      previousMillis = currentMillis;   
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      // set the LED with the ledState of the variable:
      digitalWrite(ledPin, ledState);
      // sound the buzzer alarm: tone(pin, frequency, duration)
      // 50, 1100, 0r 1605 sound pretty alarm-y
      tone(buzzPin, 1100, 100);
    }
  }
}

			

LOCKED: Solenoids & Serial Monitor Input

LOCKED: Piezo (Clapper) & Lock & LCD

LOCKED: PSP-style 2-axis Joystick

LOCKED: Motors & PWM

LOCKED: Motion Sensor (PIR) + Outputs

LOCKED: Infrared (IR) Message Remote

LOCKED: Humidity & Temperature + LCD

LOCKED: NFC/RFID & Lock & LCD & Data

LOCKED: Fingerprinting & Locks

LOCKED: Coin Acceptor (Vending Machine)

WISHLIST: Proximity Sensor (Applications)

WISHLIST: 3-Axis Accelerometer

WISHLIST: Stepper Motor (Applications)

WISHLIST: GPS (Applications)

WISHLIST: Magstripe Card Reader

WISHLIST: Wireless Inductive Charging

WISHLIST: WiFi (Applications)

WISHLIST: Camera with NTSC Video + WiFi

WISHLIST: Solar

WISHLIST: GSM Text Message + Sensor

WISHLIST: Twitter Tweets + WiFi

PRESS START
★ WORK FOR IT & LEVEL UP
×

CLASS PAGE SETTINGS

Streamlined Question View

Show Videos
Show Solutions
Show Level Badges
Sound

Level of Difficulty

1 2 3 4 5 6 7 8 9 10 11
×

KEYBOARD SHORTCUTS

  • class settings
  • keyboard shortcuts
  • drawing tools
  • table of contents
  • fullscreen
  • close
  • previous question
  • next question
2 15 ×
Google