Arduino Servo Motor Tutorial

A servomotor is a rotary actuator or linear actuator that allows for precise control of angular or linear position, velocity and acceleration.
Servomotors are used in applications such as robotics, CNC machinery or automated manufacturing.
This tutorial will show you how to use the principals of a servo motor with your Arduino board.
This code moves the shaft of a RC servo motor back and forth across 180 degrees.
This example makes use of the Arduino servo library.

1 Arduino Board
1 Servo Motor
Hookup wires

1.Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin of your Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow, orange or white and should be connected to pin 7 on the board.
2. Input following code into your Arduino Sketch and compile.
3. Plug USB A/B Cable into your laptop and connect it to your Arduino.
4. Press the upload program to run the code. Notice how the Servo motor will move 0 to 180 degrees clockwise, pause, then move 180 degrees in the reverse direction.


// This code will move the servo back and forth from 0-180 degrees.

Servo servoobj; // create servo object to control a servo

int var = 0; // variable to store the servo position

void setup() {
servoobj.attach(7); // attaches the servo on pin to the servo object

void loop() {
for (var = 0; var <= 180; var += 1) { // goes from 0 degrees to 180 degrees // in steps of 1 degree servoobj.write(var); // tell servo to go to position in variable ‘var’ delay(15); // waits 15ms for the servo to reach the position } for (var = 180; var >= 0; var -= 1) { // goes from 180 degrees to 0 degrees
servoobj.write(var); // tell servo to go to position in variable ‘var’
delay(15); // waits 15ms for the servo to reach the position

Arduino Tutorial: Dog Door Buzzer

This Arduino tutorial will use a photoresistor and a piezo buzzer to create a buzzer for your dog door to know when your best friend comes and goes. A photoresistor is a light-controlled variable resistor whose resistance  decreases with exposure to light. As your dog passes through the door, the photoresistor’s resistance will decrease and cause thepiezo buzzer to sound.



1 Arduino Board

1 Breadboard

1 Photoresistor

1 Piezo Buzzer

1 10K ohm resistor

1  6” USB A/B cable

Hookup Wires



  1. Start off by placing your photoresistor on the breadboard. Connect a wire from the 5V source to the photoresistor. Place a 10k Ω resistor on the other pin of the photoresistor. Connect a wire from the resistor to the A0 pin and a wire from the other leg of the resistor to the ground of your Arudino board.
  2. Connect a wire from digital pin 7 to the piezo buzzer on the breadboard. Be sure to ground the Piezo Buzzer.
  1. Open the Arduino software and create a new sketch; then upload the code below into the sketch:

int rcvpin=A0;

int buzzpin=7;


void setup()




















void loop()




int ldrval=analogRead(rcvpin);














void buzz(unsigned char time)














4.Connect a USB A/B cable from your computer to the Arduino. Click “Upload” in the Arduino program to run your sketch.


5.To test your code, cover the photoresistor to buzz the piezo buzzer.

Learning with Arduino: How to use a Thermistor

A thermistor is a type of resistor whose resistance is dependent on temperature.
Thermistors are of two opposite fundamental types:
With Negative Temperature Coefficient, NTC, resistance decreases with temperature to protect against inrush overvoltage conditions.
With Positive Temperature Coefficient, PTC, resistance increases with temperature to protect against overcurrent conditions.
The purpose of this tutorial is to understand how to use a thermistor to create a reminder to turn on either your AC or your heat based on the temperature in your house.
Note: The temperature setting in this tutorial corresponds to a specific voltage that comes out of the Analog to Digital Convertor (ADC) Reading:
Analog to Digital Converter (ADC) reading = (Voltage at Pin / 5V) * 1023
Extra Tip: To select a ADC reading based on the temperature setting of your choice, use the Steinhart-Hart equation to convert the ADC voltage readings to a setpoint temperature.

Arduino Board
1 6” USB A/B cable
3 220 ohm resistor
2 LEDs
Hookup Wires

1. Place your thermistor on the breadboard. Connect a wire from the 5V source to the thermistor. Place a 220 Ω resistor on the other pin of the thermistor. Connect a wire from the resistor to the A0 pin. Connect a wire from the other leg of the resistor to the ground of your arudino board.
2. Connect a wire from digital pin 9 to your breadboard and then place a 220ohm resistor and a blue LED on the breadboard. Be sure to ground the LED.
3. Connect a wire from digital pin 8 to your breadboard. Next,, place a 220ohm resistor and a red LED on the breadboard. Be sure to ground the LED.


4. Open the Arduino software and create a new sketch. Upload the code (seen below) into the sketch.

// LEDS will indicate when the heat needs to be turned on and when the AC needs to be turned on.

//400=60 degrees farenheit
//525=80 degrees farenheit

int tempPin = 0;
int temp; // the analog reading from the sensor divider
int ACSensor = 9; // connect Blue LED to pin 9
int HEATSensor = 8; // connect Red LED to pin 8
int HEATon= 400;
int ACon= 525;
void setup(void) {

void loop(void) {
temp = analogRead(tempPin);

Serial.print(“Temp = “);
Serial.println(temp); // reading the values

if (temp <= HEATon){ digitalWrite (ACSensor, LOW); digitalWrite (HEATSensor, HIGH); } else if (temp >= ACon){
digitalWrite (ACSensor, HIGH);
digitalWrite (HEATSensor, LOW);
digitalWrite (ACSensor, LOW);
digitalWrite (HEATSensor, LOW);

5. Connect a USB A/B cable from your computer to the Arduino. Click “Upload” in the Arduino program to run your sketch.
6. Finally, to test your code,  set both the AC and heat temperature setting to the current temperature setting in your house to light the LEDs.

Record Data on a SD Card


One of the most important things in engineering (really in life) is data logging and the ability to go back and look at whats going on. Typically you would need the Arduino connected to the computer so that you can record, copy, and then paste the code into excel.  As a result, you typically can’t go very far from your computer. So is there another way to record data but not be confined to a computer? The answer is yes, and it’s pretty easy to do also.  All you need is an SD card and a method for the SD card and the Arduino to communicate (SD card Module).

There are libraries that easily handle the reading and writing to an SD card.  For this tutorial, we are only going to be looking at writing to the SD card.

I’m going to show you how to wire the SD card module along with a DHT11 temperature and barometric pressure sensor.  You will then record data from the DHT11 onto the Arduino SD card module



1X Arduino Compatible Board

1X Male – Male jumper cables

1X DHT11 module

1XSD card Module

dht11 and SD



#include <DHT.h>
#include <SPI.h>
#include <SD.h>

int DHTPIN = 2;
const int chipSelect = 4;
unsigned long Secs=0;
#define DHTTYPE DHT11   // DHT 11


void setup() {
  // Open serial communications and wait for port to open:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only


  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
  Serial.println("card initialized.");

void loop() {
  // make a string for assembling the data to log:
  String dataString = "";
  int h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  int t = dht.readTemperature(true); //true : fahrenheit   false:celsius
  unsigned long Secs=millis();

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile ="temp.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    // print to the serial port too:
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");

Microphone Sensor

Microphone Sensor

Hey guys, for this tutorial i’m going to show you how to set up a microphone sensor.  The microphone sensor is just like any other sensor in the fact that it takes some sort of external stimuli and turns it into something that the computer can read.  For the microphone sensor this external stimuli is sound.  Basically, rather than a button this sensor will allow you to control something using a clap, a door slamming, or even a dog bark.


There are 2 ways to set up this microphone sensor, one is by using the analog sensor and the other is the digital.  For the sake of this tutorial we are going to use the analog signal. Besides the analog pin, the microphone sensor only needs to be connected to power and ground.  

For a visual I also set up a LED to pin 13 so that we can see if we are effectively using the microphone sensor.  Connecting this LED is optional but I always prefer to have some sort of visual outside of the serial monitor.

Once you get the setup together you can move onto the code section and we can get this working!


Take a look over the code briefly and see how many of the functions you recognize.

As you can see this is a very basic code that reads an analog signal then and checks to see if it reaches a threshold.  If it does then it adds 1 to ‘lightState’.  We then check ‘lightState’ to see if it is divisible by 2.  This means that if the threshold was reached 5 times and we divide 5 by 2, we will have a remainder of 1: this will turn the light on.  On the other hand, if you clap one more time and the lightState is 6, the remainder will be 0 and the light will turn off.  

Once you have your system set up and coded, check out the challenge and see if you can figure it out!


For this tutorial i used a modulus function that checks if a number is divisible by 2, but you could also do something similar with a boolean function.  Can you figure this out?


1X Arduino Compatible Board

1X Female – Male Jumper Cables


1X sound module


This sound module requires a connection to 5v, ground, and either the analog out or the digital out.  For sake of this tutorial we will only be going over the analog signal.  Once you have it wired up as show below take a step into the code following the diagram


arduino sketch



We will be utilizing very basic functions such as digitalWrite and analogRead


#define input A0 //defining the analog pin 
#define light 13 //defining digital pin for LED

int lightState=0;//used for on and off

void setup() {
  pinMode(input,INPUT); //defines the analog pin as an input
  pinMode(light,OUTPUT);//defines digital pin as an output

void loop() {
if (analogRead(input)>275){ //checks to see if light reached a threshold
    lightState++; //increments light integer
    digitalWrite(light,lightState%2);//if devisable by 2 light off if not light on
  Serial.println(lightState%2);//print to screen for trouble shooting

Joy Stick

Joy Stick Sensor

Ever wonder how the joystick sensor in a controller works? Well, essentially it’s 2 variable resistors (potentiometers) with springs that keep them centered.  This means that we can set them up as voltage dividers and read there positions via an analog input with the Arduino.

This is a very simple tutorial on how to hook up a joystick for the Arduino
1X Arduino Compatible Board
1X Female – Male Jumper Cables
1X Joystick

The Joystick is what I like to call a “compound device” because it has multiple signals on a single device. It can read a X positions (up/down) Y position (side to side) and a button. The position sensors are potentiometer are set up the exact same way. The button is slightly trickier but can easily be handled using an internal pull up resister



We will be ultilizing very basic functions such as digitalWrite, digitalRead, and analogRead



//Defines the 3 device inputs button, Y Axis, X Axis
# define button 8
# define posX A0
# define posY A1

void setup() {
  pinMode(button,INPUT);  //button will read as an input
  digitalWrite(button,HIGH); //ultilizes the arduino internal
                             //pull up resister
  pinMode(posX,INPUT);  //X axis as an input
  pinMode(posY,INPUT);  //Y axis as an input
  Serial.begin(9600);   //set up serial Com


void loop() {
  int ibutton = digitalRead(button);//stores button state
  int iposX = analogRead(posX);//stores X position
  int iposY = analogRead(posY);//stores Y position

  Serial.print("button is ");
  if(ibutton){ //check to see if button is high or low prints appropriately

  Serial.print("X posisition is ");
  Serial.println(iposX);  //prints X position
  Serial.print("Y posisition is ");
  Serial.println(iposY);  //prints Y position

  delay(500);//delay so that the results are readable

Photocells and Photoresistors

Today were going to go over detecting light using and photoresistor and how we can use this information to control something (for this example: LEDS)


The basic idea here is that we can wire the photoresistor in some way so that it creates a voltage divider.  We can then read resultant voltage with our development board.


1X Arduino Compatible Board

1X Jumper Wire Set

2X 220Ω Resistors


1X 10kΩ Resistor

1x Photoresistor



PWM LED: long leg digital- pin 9; short leg 220Ω resistor then to ground

On/off LED: long leg digital- pin 2; short leg 220Ω resistor then to ground


And finally you want to 1 end of the photoresistor to one leg of the 10kΩ resistor.  Now the other leg of the photoresistor connects to power, the other leg of the resistor connects to ground, and the center leg where they are tied together connects to A5.



We will be ultilizing very basic functions such as analog read, analog write (PWM), and digital write.



/*Simple program to show how to use a photo resistor to detect light
 * intesity.  This information can then be used to control an object.
 * In This case 2 LEDS.  1) as an on/off and 2) as a PWM dimming LED

int photoInput = A0; //declares pin as an analog pin 
float photoValue;    //variable used to store analog value 
float photoVoltage;  //analog signal converted into a voltage 
int pwmLED = 6;      //declares digital pin for PWM LED
int onOffLED = 2;    //declares digital pin for on off LED
float lightLimit = 2.5; //threshold to turn on/off LED

void setup() {

void loop() {
  Serial.print("DAC: ");
  Serial.print("     Voltage: ");





Keypad Tutorial


let’s talk about keypads, and most importantly matrix keypads.  These are extremely easy to set up and you only need a pin for each row and each column.  So if you have a 4×4 keypad (shown below) you need 4+4 totaling 8 pins.  8 pins for 16 buttons?  Seems like a good deal to me!

For this one I’m going to show you how to set up the key pad and code so that when the end user has to put in a ‘password’ .  If the password is right: a green light comes one.  If the password is wrong: a red light blinks 4 times.

Now these LEDs can be pretty much anything.  You could use this as the basic code to open and close a door, turn on a light, or even turn off an alarm


1X Arduino Compatible Board

1X 4×4 Key Pad

1X Male – Male jumper cables


2X 220Ω Resistors




#include <Keypad.h>

#define greenLED 11
#define redLED 10

const byte ROWS = 4; 
const byte COLS = 4; 
char keys[ROWS][COLS] = {

String passWord ="1234"; //manually define password
String passInput;

byte rowPins[ROWS] = {2,3,4,5}; //connect to row pinouts 
byte colPins[COLS] = {6,7,8,9}; //connect to column pinouts

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){

void loop(){
  char key = keypad.getKey();//gets the character pressed

  if (key != NO_KEY){
    if (key=='#'){//checks to see if "enter" is pressed
      if(passInput==passWord){ //is the password entered the same as the one defined?
        Serial.println("congratulations you have unlocked the safe");//yes
        Serial.println("Sorry... Wrong Password!");

        for (int i=0;i<4;i++){ //blink light 4 times
       passInput="";//clear password string
    }else{//if "enter" is not pressed add the key char to the nd of the string

Serial Communications and RGB LEDs

As we all know ;), LEDs are Light Emitting Diodes. When a voltage is applied to the anode (+ terminal) and ground is connected to the cathode (- terminal), electrons are able to recombine and emit light. RGB LEDs follow the same idea but they have the ability to emit Red, Green, Blue, or a combination of colors.
By the end of this example we are going to be able to connect an RGB LED that has a common cathode, use the serial monitor to communicate with the LED, and control the RGB LED with PWM.
There are two types of RGB LEDs: common Cathode, and Common Diode

Common Cathode:
has a common ground pin and light is emitted by supplying a voltage to the other pins. This is the configuration that is being used in this example

Common Anode:
has a common supply voltage and light is emitted when the other pins are connected to ground. Pretty simple?

Now, the goal is to control the brightness of each one of these lights using analogWrite (on a ~pin) and PWM (Pulse Width Modulation). PWM switches the voltage from HIGH to LOW with different amounts of on and off time. The result is an average voltage. For example: at 50% Duty Cycle the voltage will read 2.5Vs, at 75% the voltage will read 3.75Vs.


1 UNO Board

1 Breadboard

1 680 Ω Resistor

2 1k Ω Resistor

1  6” USB A/B cable


Jumper Cable



duino set up


  1. Connect the common pin (the longest lead) to ground (Common Cathode) or 5v(Common Anode)
  2. The Red pin, which is the single pin next to the common lead, gets connected to digital pin 11 through a 680Ω resistor
  3. Now, connect the blue lead to pin 10 and the green lead to pin 9. Both should have a 1kΩ resistor between them and their pins



/*This program controls a RGB LED through the Serial monitor.  The input is the the form 
 * 255,255,255 [R,G,B}; where the 255 erpresents any number from 0-255 seperated by a non 
 * digit character.

int LED9 = 11;//RED PWM pin
int LED10 = 10;//green PWM pin
int LED11 = 9;//BLUE  PWM pin

int colors[] = {0,0,0}; //starts with all of the LED off
int colorID=0; //will be used to define the locations is 'colors[colorID] 0 to 2

String inputString = "";         //a string to hold incoming data
int inChar;                      //stores each byte of incoming data

void setup() {

void loop() {

while (Serial.available() >0) { //checks for an available byte waiting on its internal storage
    inChar =;     //saves the information as a character 
    if (isDigit(inChar)){      //if the saved character is a digit DO THHIS......
      inputString+=(char)inChar;//adds character to the end of a string
    }else if(inChar=='\n' || colorID==2){      //checks to see if there is a line end or too many color calls
      colors[colorID]=inputString.toInt();    //converts string to an int and saves to color
      while(colorID<2){  //this loop turns off all colors not defined the the serial
      colorID=0;   //resets colorID
      Serial.println(inputString); //serial terminal for trouble shooting
      inputString="";//resets string
    }else{ //runs if colors have not been defined or a charcter besides a number was sent

    /* writes the PWM value for each color*/ 

LCD Counter with Pull Down Resistor and Debounce

This tutorial will go over the basic functions of a button and a LCD screen. By the end of the tutorial you will be able to properly wire both components and use them for your own projects.
1X Arduino Compatible Board
1X Jumper Wire Set
1X 220Ω Resistors
1X 10kΩ Resistor
1X button
1X potentiometer

Let’s go over 2 of the most important items for that can be used for the Arduino platform. The button and the LCD screen.

This is a very simple item, but in practice can be a little tricky to get working properly. The 2 common things you need to be aware of are floating pins and button bouncing.

A floating pin will give you random spikes which can cause a false reading. This is caused because the digital IO pins are very sensitive to interference or capacitance. To get rid of this you will need to use a pull down (or pull up) resistor to pull it to a known state.

Button bouncing occurs when you press the button, but the controller sees it as 2,3, or even more presses. This is caused because the contacts bounce off each other very briefly before they settle to fully closed position. We’ll fix this problem in the arduino code. Because the bounces last only a few milliseconds, we can use we can add a time check to make sure that the button has changed state for a certain amount of time.

LCD Display
These are super easy to set up and all you really need is a bunch of jumper wires, a 220Ω resistor, a 10Ω potentiameter and, the liquidcrystal library from the arduino IDE. From there just follow the code and diagram and then you should be up and running!


We will be ultilizing very basic functions such as analog read, analog write (PWM), and digital write.

#include <LiquidCrystal.h> //pulls code from the LCD library and makes life easy

LiquidCrystal lcd(9, 8,7, 6, 5, 4); //defines (RS,enable,D4,D5,D6,D7) pins
#define button 2 //defines digital pin 2 as an IO
bool buttonState=false;//button starts off low
int count =0;//variable that will be incremented starting from 0
unsigned long timeStamp=0; //saves current time when a button has been pressed.  
                           //defined as a positive long number

void setup()
  pinMode(button,INPUT);  //decalares button as an input
  lcd.begin(16,2);        //defines the size of the LCD display
  lcd.setCursor(0,0);     //sets where the LCD will start writing 0,0 is top left

void loop() {
  if (digitalRead(button)==HIGH){ //loop to see if button is pressed
    if(buttonState==false&& millis()-timeStamp>200){ /*makes sure the the button isn't being held down and that 
      200ms has passed since last press.  this stops the button from bouncing.  Try making it a low value and you 
      will the number jump a few times each time you press the button*/
      count++;  //increments count
      buttonState=true;//saves that button is pressed
      timeStamp=millis();    //saves time that button is pressed
    }}    else{
      buttonState=false;    //saves that the button is not pressed
  lcd.setCursor(0,0);      //starts curser at 0,0
  lcd.print(count);        //prints the counter to the LCD