Visitors

Saturday, July 15, 2017

Servo Motor Control by Flex Sensor



In this tutorial we are going to develop a circuit using FLEX sensor, Arduino Uno and a Servo motor. This project is a servo control system where the servo shaft position is determined by the flex or bent or deviation of the FLEX sensor.


Lets first talk a bit about servo motors. Servo Motors are used where there is a need for accurate shaft movement or position. These are not proposed for high speed applications. These are proposed for low speed, medium torque and accurate position application. These motors are used in robotic arm machines, flight controls and control systems. Servo motors are used in embedded systems like vending machines etc.

Servo motors are available at different shapes and sizes. A servo motor will have mainly there wires, one is for positive voltage another is for ground and last one is for position setting. The RED wire is connected to power, Black wire is connected to ground and YELLOW wire is connected to signal.

A servo motor is a combination of DC motor, position control system, gears. The position of the shaft of the DC motor is adjusted by the control electronics in the servo, based on the duty ratio of the PWM signal the SIGNAL pin.

Simply speaking the control electronics adjust shaft position by controlling DC motor. This data regarding position of shaft is sent through the SIGNAL pin. The position data to the control should be sent in the form of PWM signal through the Signal pin of servo motor.

The frequency of PWM (Pulse Width Modulated) signal can vary based on type of servo motor. The important thing here is the DUTY RATIO of the PWM signal. Based on this DUTY RATION the control electronics adjust the shaft. For the shaft to be moved to 9o clock the TURN ON RATION must be 1/18.ie. 1 milli second of ‘ON time’ and 17 milli second of ‘OFF time’ in a 18 ms signal



For the shaft to be moved to 12o clock the ON time of signal must be 1.5ms and OFF time should be 16.5ms. This ratio is decoded by control system in servo and it adjusts the position based on it.

This PWM in here is generated by using ARDUINO UNO. So for now we know that, we can control the servo motor shaft by varying the duty ratio of PWM signal generated by Arduino Uno. The UNO has a special function which enables us to provide the position of SERVO without troubling the PWM signal. However it is important to know the PWM duty ration - servo position relation. We will talk more about it in description.

Now let’s talk about FLEX SENSOR. To interface a FLEX sensor to ARDUINO UNO,  we are going use 8 bit ADC (Analog to Digital Conversion) feature to do the job. A FLEX sensor is a transducer which changes its resistance when its shape is changed.  A FLEX sensor is of 2.2 inches long or of finger length. It is shown in figure.




Flex sensor is a transducer which changes its resistance when the linear surface is bent. Hence the name flex sensor. Simply speaking the sensor terminal resistance increases when it’s bent. 

This change in resistance can do no good unless we can read them. The controller at hand can only read the chances in voltage and nothing less, for this we are going to use voltage divider circuit, with that we can derive the resistance change as voltage change.

Voltage divider is a resistive circuit and is shown in figure. In this resistive network we have one constant resistance and other variable resistance. As shown in figure, R1 here is a constant resistance and R2 is FLEX sensor which acts as a resistance.

The midpoint of branch is taken to measurement. With R2 change, we have change at Vout. So with this we have a voltage which changes with weight.


Now important thing to note here is, the input taken by the controller for ADC conversion is as low as 50µAmp. This loading effect of resistance based voltage divider is important as the current drawn from Vout of voltage divider increases the error percentage increases, for now we need not worry about loading effect.

FLEX SENSOR when bent its resistance changes. With this transducer connected to a voltage divider circuit, we will have a changing voltage with FLEX on transducer. This variable voltage is FED to one of ADC channels, we will have a digital value relating to FLEX.

We will match this digital value to servo position, with this we will have servo control by flex.


Components :


Hardware: Arduino Uno, Power supply (5v), 1000 uF capacitor, 100nF capacitor (3 pieces), 100KΩ resistor, SERVO MOTOR (SG 90), 220Ω resistor, FLEX sensor.

Software: Atmel studio 6.2 or Aurdino nightly.



Circuit Diagram and Explanation :




The voltage across sensor is not completely linear; it will be a noisy one. To filter out the noise, capacitors are placed across each resistor in the divider circuit as shown in figure. 
Here we are going to take the voltage provided by the divider (voltage which represents weight linearly) and feed it into one of ADC Channels of Arduino UNO. We are going to use A0 for this. After the ADC initialization, we will have digital value representing the bent on sensor. We will take this value and match it with servo position.

For this to happened we need to establish few instructions in program and we will talk about them in detail below.
ARDUINO has six ADC channels, as show in figure. In those any one or all of them can be used as inputs for analog voltage. The UNO ADC is of 10 bit resolution (so the integer values from (0-(2^10) 1023)).This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. So for every (5/1024= 4.9mV) per unit.
Here we are going to use A0 of UNO.
We need to know a few things.

  1. analogRead(pin);
  2. analogReference();
  3. analogReadResolution(bits);


First of all the UNO ADC channels has a default reference value of 5V. This means we can give a maximum input voltage of 5V for ADC conversion at any input channel. Since some sensors provide voltages from 0-2.5V, with a 5V reference we get lesser accuracy, so we have a instruction that enables us to change this reference value.  So for changing the reference value we have (“analogReference();”) For now we leave it as.

As default we get the maximum board ADC resolution which is 10bits, this resolution can be changed by using instruction (“analogReadResolution(bits);”). This resolution change can come in handy for some cases. For now we leave it as.

Now if the above conditions are set to default, the we can read value from ADC of channel ‘0’ by directly calling function “analogRead(pin);”, here “pin” represents pin where we connected analog signal, in this case it would be “A0”.

The value from ADC can be taken into an integer as “int SENSORVALUE = analogRead(A0); ”, by this instruction the value after ADC gets stored in the integer “SENSORVALUE”.

Now let’s talk about the SERVO, the UNO has a feature which enables us to control the servo position by just giving the degree value.  Say if we want the servo to be at 30, we can directly represent the value in the program. The SERVO header file takes care of all the duty ratio calculations internally.

#include <Servo.h>
Servo servo;
servo.attach(3);
servo.write(degrees);

First statement represents the header file for controlling the SERVO MOTOR.
Second statement is naming the servo; we leave it as servo itself.
Third statement states where the servo signal pin is connected; this must be a PWM pin. Here we are using PIN3.
Fourth statement gives commands for positioning servo motor and is in degrees. If it is given 30, the servo motor rotates 30 degrees.
Now the sg90 can move from 0-180 degrees, we have ADC result 0-1024
So ADC is approximately six times the SERVO POSITION. So by divided the ADC result by 6 we will get the approximate SERVO hand position.

With this we will have servo position value fed to servo motor, which is in proportion to flex or bent. When this flex sensor mounted on glove, we can control servo position by movement of hand.

Code: 

#include <Servo.h>
// header for controller servo
Servo servo; //keeping name of servo SERVO itself
int sensorvalue =0;
void setup()
{
            pinMode(A0,INPUT);// voltage divider value input
            pinMode(3,OUTPUT);// PWM output to servo
            servo.attach(3);// telling where signal pin of servo attached(must be a PWM pin)
}
void loop()
{
            sensorvalue = analogRead(A0); //read analog value from sensor
            servo.write((sensorvalue-250)/2); //to avoid initial positioning of servo we need to neutralize the default voltage provided by voltage divider( setting servo position based on ADC result)
}





Friday, July 14, 2017

The great gadget ripoff: Why we can't fix our own electronics


Traditionally, when a car breaks down, the solution has been to fix it. 
Repair manuals, knowledgeable mechanics and auto parts stores make car repairs common, quick and relatively inexpensive. 
Even with modern computer-equipped vehicles, regular people have plenty they can do: change oil, change tires and many more advanced upgrades.




But when a computer or smartphone breaks, it's hard to get it fixed, and much more common to throw the broken device away. 
Even small electronic devices can add up to massive amounts of electronic waste – between 20 million and 50 million metric tons of electronic devices every year, worldwide. 
Some of this waste is recycled, but most – including components involving lead and mercury – goes into landfills.
Bigger equipment can be just as difficult to repair. 
Today's farmers often can't fix the computers running their tractors, because manufacturers claim that farmers don't actually own them. 
Companies argue that specialized software running tractors and other machines is protected by copyright and patent laws, and allowing farmers access to it would harm the companies' intellectual property rights.
Users' right to repair – or to pay others to fix – objects they own is in jeopardy. 
However, in our surveys and examinations of product life cycles, my colleagues and I are finding that supporting people who want to repair and reuse their broken devices can yield benefits – including profits – for electronics manufacturers.
At least eight states – Nebraska, Kansas, Wyoming, Illinois, Massachusetts, Minnesota, New York and Tennessee – are considering laws that would require companies to let customers fix their broken electronics. 
The proposals typically make manufacturers sell parts, publish repair manuals and make available diagnostic tools, such as scanning devices that identify sources of malfunctions. 
In an encouraging move, the U.S. Copyright Office suggested in June that similar rules should apply nationwide. 
And the U.S. Supreme Court recently ruled that companies' patent rights don't prevent people from reselling their electronics privately.
Seen one way, these regulations put manufacturing companies in a tough spot. 
Manufacturers can earn a lot of money from selling authorized parts and service.





Yet to remain competitive, they must constantly innovate and develop new products. 
To keep costs down, they can't keep making and stocking parts for old and outdated devices forever. 
This leads to what's called 'planned obsolescence,' the principle that a company designs its items to have relatively short useful lives, which will end roughly around the time a new version of the product comes out.
However, our research suggests that companies can take a different approach – designing and building products that can be refurbished and repaired for reuse – while building customer loyalty and brand awareness. 




By analyzing surveys of hobbyists and the repair industry, we've also found that there are barriers, such as a lack of repair manuals and spare parts, that impede the growth of the repair industry that can be improved upon.
Even as machines and devices have become less mechanical and more electronic, we have found that customers still expect to be able to repair and continue using electronic products they purchase. 



When manufacturers support that expectation, by offering repair manuals, spare parts and other guidance on how to fix their products, they build customer loyalty.
Specifically, we found that customers are more likely to buy additional products from that manufacturer, and are more likely to recommend that manufacturer's product to friends. 



Wednesday, July 12, 2017

Arduino Solar Tracker using LDR and Servo Motor




In this article we are going to make a Solar Panel Tracker using Arduino, in which we will use two LDRs (Light dependent resistor) to sense the light and a servo motor to automatically rotate the solar panel in the direction of the sun light. Advantage of this project is that Solar panel will always follow the sun light will always face towards the sun to get charge all the time and can provide the supply the maximum power. The prototype is very easy to build. Below you will find the complete description of how it works and how the prototype is made.



Required Components:

  • Servo Motor (sg90)
  • Solar panel
  • Arduino Uno
  • LDR’s X 2 (Light Dependent Resistor)
  • 10K resistors X 2
  • Battery (6 to 12V)



How it Works:

In this project, LDR’s are working as light detectors. Before we go into detail, we will have to understand how the LDR’s work. LDR (Light Dependent Resistor) also known as photo resistor is the light sensitive device. Its resistance decrease when the light falls on it and that’s why it is frequently used in Dark or Light Detector Circuit. Check the various circuits based on LDR here.
The two LDR’s are placed at the two sides of solar panel and the Servo Motor is used to rotate the solar panel. The servo will move the solar panel towards the LDR whose resistance will be low, mean towards the LDR on which light is falling, that way it will keep following the light. And if there is same amount of light falling on both the LDR, then servo will not rotate. The servo will try to move the solar panel in the position where both LDR’s will have the same resistance means where same amount of light will fall on both the resistors and if resistance of one of the LDR will change then it rotates towards lower resistance LDR. Check the Demonstration Video at the end of this Article.


Circuit Diagram and Explanation:




In this Arduino Solar Panel Tracker, Arduino is powered by the 9V battery and all the other parts are powered by the Arduino. Arduino recommended input voltage is from 7 to 12 volts but you can power it within the range of 6 to 20 volts which is the limit. Try to power it within the recommended input voltage. So connect the positive wire of the battery to the Vin of the Arduino and the negative wire of the battery to the ground of the Arduino.
Next connect the servo to the Arduino. Connect the positive wire of the servo to the 5V of Arduino and ground wire to the ground of the Arduino and then connect the signal wire of Servo to the digital pin 9 of Arduino. The servo will help in moving the solar panel.
Now connect the LDRs to the Arduino. Connect one end of the LDR to the one end of the 10k resistor and also connect this end to the A0 of the Arduino and connect the other end of that resistor to the ground and connect the other end of LDR to the 5V. Similarly, connect the one end of second LDR to the one end of other 10k resistor and also connect that end to the A1 of Arduino and connect the other end of that resistor to ground and connect the other end of LDR to 5V of Arduino.

Code: 

#include <Servo.h>      //including the library of servo motor 
Servo sg90;             //initializing a variable for servo named sg90
int initial_position = 90;   //Declaring the initial position at 90
int LDR1 = A0;          //Pin at which LDR is connected
int LDR2 = A1;          //Pin at which LDR is connected
int error = 5;          //initializing variable for error
int servopin=9;
void setup() 
  sg90.attach(servopin);  // attaches the servo on pin 9
  pinMode(LDR1, INPUT);   //Making the LDR pin as input
  pinMode(LDR2, INPUT);
  sg90.write(initial_position);   //Move servo at 90 degree
  delay(2000);            // giving a delay of 2 seconds
}  
 
void loop() 

  int R1 = analogRead(LDR1); // reading value from LDR 1
  int R2 = analogRead(LDR2); // reading value from LDR 2
  int diff1= abs(R1 - R2);   // Calculating the difference between the LDR's
  int diff2= abs(R2 - R1);
  
  if((diff1 <= error) || (diff2 <= error)) {
    //if the difference is under the error then do nothing
  } else {    
    if(R1 > R2)
    {
      initial_position = --initial_position;  //Move the servo towards 0 degree
    }
    if(R1 < R2) 
    {
      initial_position = ++initial_position; //Move the servo towards 180 degree
    }
  }
  sg90.write(initial_position); // write the position to servo
  delay(100);
}







Sunday, July 9, 2017

Arduino Radar System using Processing Android App and Ultrasonic Sensor





This is an interesting project in which we explore the power of an Arduino and Android to create a Surveillance device which uses Arduino and Ultra Sonic Sensor to broadcast the information to a mobile application (Android) using Bluetooth.


Safety and Security has been our primary concern since ages. Installing a security camera that has night mode with tilt and pan option will burn a big hole on our pockets. Hence let us make an economic device which does almost the same but without any video features.
This device senses objects with the help of Ultrasonic Sensor and hence can work even during night times. Also we are mounting the US (Ultra Sonic) sensor over a servo motor, this servo motor can be either be set to rotate automatically to scan the area or can be rotated manually using our Mobile app, so that we can focus the ultrasonic sensor in our required direction and sense the objects present over there. All the information sensed by the US sensor will be broadcasted to our Smart phone using Bluetooth Module (HC-05). So it will work like a Sonar or a Radar.


Requirements:


Hardware:
  • A +5V power supply ( I am using my Arduino (another) board for power supply) 
  • Arduino Mega (You can use anything from pro mini to Yun)
  • Servo Motor (any rating)
  • Bluetooth Module (HC-05)
  • Ultra Sonic Sensor (HC-SR04)
  • Breadboard (not mandatory)
  • Connecting wires
  • Android mobile
  • Computer for programming


Software:
  1. Arduino Software
  2. Android SDK
  3. Processing Android (To create mobile application)



Arduino Hardware part and Circuit Diagram:


This project involves a lot of components like the Servo Motor, Bluetooth Module, Ultrasonic Sensor etc. Hence if you are an absolute beginner then it would be recommended to start with some basic tutorial which involves these components and then come back here. Check out our various projects on Servo MotorBluetooth Module and Ultrasonic Sensor here.
All components are not powered by the Arduino itself because, the servo motor, Bluetooth module and US sensor altogether draws a lot of current which the Arduino will not be able to source. Hence it is strictly advisable to use any external +5V supply. If you do not have an external +5V supply at your reach, you can share the components between two Arduino boards as I have done. I have connected the Servos power rails to another Arduino board (red colour) and connected the Bluetooth module HC-05 and Ultrasonic sensor HC-SR04 to the Arduino mega. CAUTION: Powering up all these modules using one Arduino board will fry up the Arduino voltage regulator.

Connection diagram for this Arduino Based Sonar Project is given below:




Android Mobile Application for Ultrasonic Radar:


If you do not want to make your own application and instead just want to install the same application used in this tutorial you can follow the steps below.

1. You can directly download the APK file from the below link. This APK file is made for Android version 4.4.2 and above (Kitkat an above). Extract the APK file from the zip file.
2. Transfer the .Apk file from your computer to your mobile phone.
3. Enable installing application from Unknown sources in your android settings.
4. Install the application.



Code: 

 //*Include the required header files**//

#include <Servo.h>
#include <SoftwareSerial.h>
//__End of including headers__//

//**Defining pins for US sensor**//

#define trigPin 4
#define echoPin 5
///__End of defaniton__//

SoftwareSerial Blueboy(10, 11); //Naming our Bluetooth module as Blueboy and defiing the RX and TX pins as 10 and 11

Servo servo;  //Initializing a servo object called servo

//**Global variabel declarations**//

int BluetoothData; 
int posc = 0; 
int flag=10;
//__End of global variable declartion__//


void setup() //Runce only once
{
  servo.attach(9); //Servo is connected to pin 9
  pinMode(trigPin, OUTPUT); //trigpin of US sensor is output
  pinMode(echoPin, INPUT);  //echopin of US sensor is Input
  Serial.begin(38400); //Serial monitor is started at 38400 baud rate for debugging
  Blueboy.begin(9600); //Bluetooth module works at 9600 baudrate
  Blueboy.println("Blueboy is active"); //Conformation from Bluetooth
}

void loop()  //The infinite loop

{

//**Program to start or stop the Survilance devide**//

   if (Blueboy.available())
{
Serial.println("Incoming");   //for debugging
BluetoothData=Blueboy.read(); //read data from bluetooth  
Serial.println(BluetoothData); //for debugging

   if (BluetoothData == 'p') //if the mobile app has sent a 'p'

   {
   flag=0; //play the device in auto mode
   }
   if (BluetoothData == 's') //if the mobile app has sent a 's'
   {
   flag=1; //stop the device and enter manual mode
   } 
Serial.println(flag); //for debugging
}

if (flag==0)

servofun(); //Servo sweeps on own 
if (flag==1)
manualservo(); //Manual sweeping

}

//_End of loop program__//


//**Function for servo to sweep**//

void servofun()
{
  Serial.println("Sweeping"); //for debugging 
  for(posc = 10;posc <= 170;posc++)   // Using 10 to 170 degree is safe than 0 to 180 because some servo might not be operational at extreme angels 
  {                                
    servo.write(posc); // set the position of servo motor
    delay(50);  
  us();    //measure the distance of objects sing the US sensor                
  } 
  
  for(posc = 170;posc >= 10;posc--)   
  {                                
    servo.write(posc);
    delay(50); 
    us();    //measure the distance of objects sing the US sensor             
  } 
  Serial.println ("Scan Complete"); //for debugging
  flag=0;
}
//**End of Servo sweeping function**//


//**Function to control Servo manually**//

void manualservo()
{  
us();

// Get value from user and control the servo

   if (Blueboy.available())
{
BluetoothData=Blueboy.read();
Serial.println(BluetoothData);
  servo.write(BluetoothData);
  Serial.println("Written");
   if (BluetoothData == 'p')
   {
   flag=0;
   }
}
}
//__End of manual control function__//


//**Function to measure the distance**//

void us()
{
 int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1; // Calculates the distance from the sensor
  if (distance<200 && distance >0)
Blueboy.write(distance);       
}
//__End of distance measuring function__//





Thursday, July 6, 2017

IoT Pet Feeder



story :

 This IoT pet feeder is our first IoT project with circuito.io! We are happy to share it with our community to demonstrate how simple it can be to make basic IoT projects with circuito.io. We are also excited to share this project with you because it's based on a product that we worked on in the past called Playdog. You can make the feeder for your pets at home - it's both fun JPand useful.



Hardware components :

1- Arduino Arduino UNO & Genuino UNO

2- PIR Motion Sensor (generic)       

3- Everything ESP ESP8266 ESP-0 
                  
4- Speaker: 0.25W, 8 ohms             



Once you've selected the components you waLunant, click on Generate and our engines will start working on your circuit and will generate your circuito reply. The reply has three parts:
1. BoM - A list of all the components you'll need for the project, including auxiliary parts such as resistors and capacitors.
2. Step-by-step wiring guide - shows you how to connect all your components to the Arduino board using a breadboard.
3. Code - a sample code for your circuit. This code is not specific for the pet feeder project, but rather it is a sample code that creates an interaction between the different components in your circuit.
To Upload the code, follow these steps:
  • Download the code from the circuito.io reply
  • Extract it to your computer
  • Open with Arduino IDE
  • Upload to your Arduino
4. Once everything is set up, replace the sample code from the circuito reply with the code in this tutorial. Make sure to leave the //Include Libraries and //Pin Definitions at the top of the code, and also keep all the libraries that are on the original code from circuito.io.
4. Connectivity - this section will guide you how to configure the connection of your project to the internet. Since you're not going to use the sample code from circuito, but rather the code provided in this tutorial, if you click "create dashboard" you'll have to configure the dashboard manually.
If you want to use the pre-set dashboard we used, download the attached pet_feeder_dashboard html file and open it in your browser. Then follow the instructions below.
- Click on “Clone" and create a copy of the dashboard for your project.
- Choose a unique ‘thingName’.
You can find your thingname in the firmware.ino.
- Click on the settings icon at the top of the page.

Assembly :


Now that you have the electronics set up, it's time to put the parts together.
We designed a 3d printed casing for the servo, the PIR sensor and the speaker.
The .stl files are attached here. This part isn't mandatory and you can choose to connect it in a different way, it's really up to you, but look how nice and colorful it is.




code :
const int ServoRestPosition   = 20;  //Starting position
const int ServoTargetPosition = 150; //Position when event is detected
unsigned int HoorayLength          = 6;                                                      // amount of notes in melody
unsigned int HoorayMelody[]        = {NOTE_C4, NOTE_E4, NOTE_G4, NOTE_C5, NOTE_G4, NOTE_C5}; // list of notes. List length must match HoorayLength!
unsigned int HoorayNoteDurations[] = {8      , 8      , 8      , 4      , 8      , 4      }; // note durations; 4 = quarter note, 8 = eighth note, etc. List length must match HoorayLength!

unsigned int comeLength          = 3;
unsigned int comeMelody[]        = {NOTE_C5, NOTE_G5, NOTE_C5};
unsigned int comeNoteDurations[] = {8      , 8      , 8};

ESP8266 wifi(WIFI_PIN_RXD,WIFI_PIN_TXD);
Servo servo;
PIR pir(PIR_PIN_SIG);
PiezoSpeaker piezoSpeaker(PIEZOSPEAKER_PIN_SIG);

int pirCounter = 0;
// ====================================================================
// vvvvvvvvvvvvvvvvvvvv ENTER YOUR WI-FI SETTINGS  vvvvvvvvvvvvvvvvvvvv
//
const char *SSID     = "YOURWIFI"; // Enter your Wi-Fi name 
const char *PASSWORD = "YOURPASSWORD" ; // Enter your Wi-Fi password
//
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ====================================================================


// These Dweet tokens have been auto generated for you.
char* const inputToken  = "12b2cbb8-3f8e-11e7-a810-0242ac110028_input";
char* const outputToken = "12b2cbb8-3f8e-11e7-a810-0242ac110028_output";

Dweet dweet( &wifi, inputToken, outputToken);

/* This code sets up the essentials for your circuit to work. It runs first every time your circuit is powered with electricity. */
void setup() {
    // Setup Serial which is useful for debugging
    // Use the Serial Monitor to view printed messages
    Serial.begin(9600);
    Serial.println("start");
    
    if (!wifi.init(SSID, PASSWORD))
    {
        Serial.println(F("Wifi Init failed. Check configuration."));
        while (true) ; // loop eternally
    }
    servo.attach(SERVO_PIN);
    servo.write(ServoRestPosition);
    delay(100);
    servo.detach();
}

/* This code is the main logic of your circuit. It defines the interaction between the components you selected. After setup, it runs over and over again, in an eternal loop. */
void loop() {

    bool pirVal = pir.read();
    
    //SET DWEETS
    dweet.setDweet("pir", pirVal );
    dweet.setDweet("pirCounter",  pirCounter);
    
    
    dweet.sendDweetKeys();
    
    
    if (pirVal)
    {
        pirCounter++;
        // The servo will rotate to target position and back to resting position with an interval of 500 milliseconds (0.5 seconds) 
        servo.attach(SERVO_PIN);         // 1. attach the servo to correct pin to control it.
        servo.write(ServoTargetPosition);  // 2. turns servo to target position. Modify target position by modifying the 'ServoTargetPosition' definition above.
        delay(500);                              // 3. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
        servo.write(ServoRestPosition);    // 4. turns servo back to rest position. Modify initial position by modifying the 'ServoRestPosition' definition above.
        delay(500);                              // 5. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
        servo.detach();                    // 6. release the servo to conserve power. When detached the servo will NOT hold it's position under stress.
        
        // The Piezo Speaker light will play a beep for half a second, wait for another 500ms(half a second) and then play a tune
        piezoSpeaker.tone(400);                                                    // 1. plays a 400Hz beep. Change the value in the brackets (400) for a higher or lower beep.
        delay(500);                                                               // 2. keeps playing it for 500ms
        piezoSpeaker.off();                                                        // 3. stops the beep
        delay(500);                                                               // 4. waits 500ms                   
        piezoSpeaker.playMelody(HoorayLength, HoorayMelody, HoorayNoteDurations);  // 5. plays the Hurray melody. to play a different melody, modify HoorayLength, HoorayMelody and HoorayNoteDuration above.                    
        delay(500);                                                               // 4. waits 500ms
    }
    
    
    //GET DWEETS  
    dweet.receiveDweetEvents();
    
    
    if(strcmp(dweet.getValue() , "servo") == 0)
    {
        Serial.println(F("servo was pressed!"));
        // The servo will rotate to target position and back to resting position with an interval of 500 milliseconds (0.5 seconds) 
        servo.attach(SERVO_PIN);         // 1. attach the servo to correct pin to control it.
        servo.write(ServoTargetPosition);  // 2. turns servo to target position. Modify target position by modifying the 'ServoTargetPosition' definition above.
        delay(500);                              // 3. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
        servo.write(ServoRestPosition);    // 4. turns servo back to rest position. Modify initial position by modifying the 'ServoRestPosition' definition above.
        delay(500);                              // 5. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
        servo.detach();                    // 6. release the servo to conserve power. When detached the servo will NOT hold it's position under stress.
    }
    else if(strcmp(dweet.getValue() , "piezoSpeaker") == 0)
    {
        Serial.println(F("piezoSpeaker was pressed!"));
        // The Piezo Speaker light will play a beep for half a second, wait for another 500ms(half a second) and then play a tune
        piezoSpeaker.tone(400);                                                    // 1. plays a 400Hz beep. Change the value in the brackets (400) for a higher or lower beep.
        delay(500);                                                               // 2. keeps playing it for 500ms
        piezoSpeaker.off();                                                        // 3. stops the beep
        delay(500);                                                               // 4. waits 500ms                   
        piezoSpeaker.playMelody(HoorayLength, HoorayMelody, HoorayNoteDurations);  // 5. plays the Hurray melody. to play a different melody, modify HoorayLength, HoorayMelody and HoorayNoteDuration above.                    
        delay(500);                                                               // 4. waits 500ms
    }
    else if(strcmp(dweet.getValue() , "playGame") == 0)
    {
        Serial.println(F("Playing Game!"));
        while (!pir.read())
        {
          piezoSpeaker.playMelody(comeLength, comeMelody, comeNoteDurations);
          delay(500);
        }
        
        servo.attach(SERVO_PIN);
        servo.write(ServoTargetPosition);
        delay(1000);
        servo.write(ServoRestPosition);
        delay(1000);
        servo.detach();
        
        piezoSpeaker.playMelody(HoorayLength, HoorayMelody, HoorayNoteDurations);  // 5. plays the Hurray melody. to play a different melody, modify HoorayLength, HoorayMelody and HoorayNoteDuration above.                    
        
        delay(100);
    }
}