Thursday, 23 June 2016

Beat detection and a Dancing Robot Arm

This project is my personal favourite. For one , I learned something about music and the science used to process it. And also , through this project I was able to revisit and apply a lot of concepts that I had learned during the last semester but thought were useless. I listened to Queen's 'We Will Rock You' , a hundred times or so while working on this project. So much so that I can no longer tolerate it.
That aside , this project used a lot of components that I will each visit separately in this tutorial.

Feeding Audio into the Arduino

1.Sound is an analog signal that is stored and processed digitally in computers. We use an Arduino's  inbuilt ADC ( analog to digital converter) to read an audio signal. The ADC is built for a 0-5V range of values, that is , it can convert analog signals in this range into a corresponding digital value between 0 and 1023.
Music output from an MP3 or smart phones,however, will be in milli-volts. This raises the issue of not being able to use the entire resolution of the ADC. Thus , the input signal will have to be amplified. You can use an operational amplifier IC or use a simple transistor to do this. The circuit is very simple , you will just need a couple of capacitors and resistors. I however was too lazy to do this. I managed by maxing the volume from my laptop but that is not the proper solution.

2. An audio signal can have both positive and negative values of voltage.However , your tiny micro-controller's ADC is made for only positive value. You will have to make an offset circuit for that. What this offsetting circuit does is that it shifts the entire signal such that the bias value become the origin. For example if you provide a bias of 2.5 V , the signal value will oscillate about this value.

Here is how it is made :



The 22uF capacitor with the 10K resistor make a High Pass Filter. A high pass filter allows frequencies only above a certain value to pass.  This cutoff frequency is given by f=1/2*pi*R*C.
For this arrangement we see the value 0.7 Hz. Thus , the DC component is removed from the incoming signal.
The two 10K resistors make a voltage divider, creating a bias of 2.5V. This is connected to a 1K pull up resistor and a coupling capacitor , to reduce noise. This also makes a low pass filter.

3. This is fed into the ADC. At analog pin 0 or whichever you might choose.

Sampling and Processing
 
1.  We need to sample this input signal. Sampling mean recording amplitudes at regular intervals. This is how analog signals are read by computers. The issue is the analogRead() function only allows sampling a 8Khz which is very poor for Audio. Typical sampling rates for audio is 40Khz. However all hope is not lost. There is a way to change the ADC sampling rate by setting values for the four MUX that control the ADC.
Check this another blog post to understand how it is done :
http://yaab-arduino.blogspot.in/2015/02/fast-sampling-from-analog-input.html

2. That done , now we need to compute the FFT (Fast Fourier Transform) on the signal. What this does is that it converts the signal from time domain to frequency domain. What this means is that you can get amplitudes of different frequency ranges in your sound signal. Typical Bass frequency ranges from 50-200Hz. It is this that we are interested in. All drum kicks , snares and rhythm information is contained here. There are various optimizations of the FFT available for the arduino. The one I used is developed by Open Music Labs and can be downloaded from the link below :
http://wiki.openmusiclabs.com/wiki/ArduinoFFT
You will have to read a bit from their website to get a better grasp of using this library.


3.Now with the FFT done , we look for peaks/ increase in amplitudes in the lower frequency ranges. that is when a beat happens.Once we have that , rest is easy. Control Lights or Motors.

These might be useful :

http://dpeckett.com/beat-detection-on-the-arduino

http://www.arduinoos.com/2010/10/fast-fourier-transform-fft/

Finally here is the Video of my project in action :




The code :


#define LIN_OUT8 1 // use the Lin_OUT8 output function
#define FFT_N 16
#include <Servo.h>
#include <FFT.h> // include the library
int led=13;
Servo servo;
Servo servo1;// create servo object to control a servo
int j=1,l=1; //for changing direction
int sel=1; //variable to select one of the two servos
int pos =0;
int pos1=0;// variable to store the servo position
int k=0;
int flag=1;
int sum=0;
int sam=60;
void setup() {
  Serial.begin(115200); // use the serial port
  TIMSK0 = 0; // turn off timer0 for lower jitter
  ADCSRA = 0xe5; // set the adc to free running mode
  ADMUX = 0x40; // use adc0
  DIDR0 = 0x01;
  pinMode(led, OUTPUT);  // turn off the digital input for adc0
  servo.attach(6);
  servo1.attach(10);
 
}

void loop() {
  while(1) { // reduces jitter
    cli();  // UDRE interrupt slows this way down on arduino1.0
    for (int i = 0 ; i < 32 ; i += 2) { // save 256 samples
      while(!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fft_input[i] = k; // put real data into even bins
      fft_input[i+1] = 0; // set odd bins to 0
    }
    fft_window(); // window the data for better frequency response
    fft_reorder(); // reorder the data before doing the fft
    fft_run(); // process the data in the fft
    fft_mag_lin8(); // take the output of the fft
    sei();
   
    //for(int i=0;i<7;i++) // print FFT results
    //{
      //Serial.print(fft_lin_out8[i]);
      //Serial.print("   ");
    //}
    //Serial.println();
    k++;
    sum=sum+fft_lin_out8[0];
    servo.write(pos); // tell servo to go to position in variable 'pos'
    servo1.write(pos1);
    if(k==sam)
    {
       k=0;
       sum=sum/sam;
       Serial.println(sum);
     
       if (sum>10)
       {
                   
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
    
         sel=-sel;
      
         if(flag==1) //  Dance sequencce
         { if(sel==1)
           {
                pos=pos+ (j*60);
                j=(-j);
             }
        
                 pos1=pos1+(l*40);
                 l=-l;
            
          }
        flag=0;
      
        }
        else
        {
          digitalWrite(led, LOW);
          flag=1;
        }
       sum=0;
    }
  

  }
}

Sunday, 19 June 2016

Raspberry Pi powered Smart Dustbin

Recently , with a team of students from Delhi University , DTU and IP , I was involved in building a raspberry pi based smart dustbin. This post has been long overdue.  We had built our first prototype in the month March. Since then, I have not been able to find time to update my blog.

This smart dustbin is an initiative to incentivize proper recycling practices.We, in India are at a break-point of a looming waste management crisis. This project is our small attempt to address the cause of Solid Waste Management.
  
When you put some waste object into this dustbin , it tries to determine what that object is. This is done through image processing algorithms. The machine has been programmed to accept only cans and PET bottles. If the object you put in was either of these , the machine will accept it and confirm with a detected message on the screen. This message is followed by a USSD code that can be used to recharge your phone or get a discount coupon on you mobile phone. We partnered with Favcy to handle our reward system. Favcy helps  brands gamify social market engagements and provide real world rewards against those engagements.


Here is a video of the prototype (it is a little slow , but we made it quick and awesome finally) :





The machine ready to be tested at metro station , malls and other public places.



We tested the machine at a few locations ,  to gauge the response of users.





                                                                   Check out:

                                                           http://weconvert.org/

Currently , we are in the process of building a second prototype, using the feedback we collected during the trial runs of the first machine.

Thursday, 31 December 2015

The Story Of An Arduino

The Arduino is a 8 bit micro-controller board. This means , that it can send and recieve data in 8 bits only. It runs on an IC made by a company called Atmel. You will see it inscribed on top of the IC.
Arduino UNO usually runs on Atmel 168. This link will take to the datasheet of the IC:

www.atmel.com/devices/atmega168.aspx

These ICs employ the AVR architecture which was conceived by two students at the Norwegian Institute of Technology. This architecture ( meaning the layout of circuit components on the IC) , took the micro-controller industry by storm.

Current AVRs offer a wide range of capabilities. These include :
1. Integrated SRAM , EEPROM and Flash memories. This negates the requirement of connecting external memory elements. (The bootloader program , and the one you upload are stored here)
2. Analog to Digital and Digital to Analog converters.
3. USB support and endless other functionalities.
Read more :https://en.wikipedia.org/wiki/Atmel_AVR

The Arduino itself was conceived by Massimo Banzi. The creators of Arduino named it after a bar where they met often.

An interesting interview of Massimo Banzi : 

https://twit.tv/shows/triangulation/episodes/110


If you have ever wondered what the silvery thing below the IC is - it is the clock signal generator. Basically a quartz crystal that oscillates at the frequency of 16MHz. Some circuits are clocked, which means their operation is dependent on a clock signal. The circuit operates only during half the clock cycle. This is helpful for many bit operations.

 The small thing next to the USB connector is the FTDI chip ,  which is the USB to serial adapter. You probably installed an FTDI driver when you powered up the arduino with your computer for the first time. Now you know why.

There are two L.E.Ds on board with the tx and rx marking. tx(transferx) and rx(receivex) light up whenever data is transferred or received by the board respectively. You see them light up when you upload a program to the Arduino using your computer. These two (tx and rx) are available through pins 0 and 1 on the arduino. You will use these when use Xbee radio chips with the arduino.

The ICSP pins are used to program the arduino with a external programmer , if you decide not to use the user friendly IDE built for us.

The reset button needless to say, makes the arduino start from square one.
The Arduino gives you 13 input/ output digital pins. Of these 6 are PMW (pulse width modulation) enabled. There are three ground pins and 6 analog input pins.
There are many variations of the Arduino:

https://www.arduino.cc/en/Main/Boards

The Arduino hardware specifications are openly available, which means you do not need to buy the board. If you have the heart , you can build it from scratch.
Time now to put your creative hats on and make something wonderful. See you around :)

Sunday, 22 November 2015

A Taste of Home Automation


This tutorial will help you setup an entry/exit detector at your doorstep. I paired it up with a relay to control the lights in my room. So , depending upon the number of people in the room , lights are switched on and off. I will break down the tutorial in two parts :

1.Entry/ Exit Detection
We will use two HC-SR04 sensors. These are capable of emitting and detecting ultrasonic sound waves. Here is how one of these looks :

          


The idea is to use them to send sound pulses continuously. We will measure the time required to detect a pulse that has bounced off some object. Using this time and the known average speed of sound in air , we will calculate the approximate distance of the object from the sensor. Now , if a person enters or exits, this value of distance will change. This change thus becomes an indication of if something has passed through the door.  If we use two sensors kept next to each other , we can also detect if that someone has entered or exited , depending upon which sensor's value changes first.

About the sensor : We see it has four pins. Vcc goes to +5V of Arduino. Trig Pin when high produces a sound pulse. Echo pin is high when the reflected pulse falls on the sensor.

2. Controlling The lights

Now that we know , whenever someone has entered or exited the room, we use this information to control lights. You can use a relay or any other mechanism to switch the light on or off. I used a motor to do it. I agree that it is a very inefficient way but given that nobody at home would be happy with me opening switchboards and pulling wires out of it , I took the other road.
Now , whenever no one is in the room , the motor turn to turn the light switch off.
See my earlier posts to learn how to use motors with the arduino.
This is how my setup looked :


WIRING IT UP
  
                        

Created using Fritzing

THE PROGRAM

#define trigPin1 9 // HC-SR04 pins
#define echoPin1 8
#define trigPin2 11#define echoPin2 10
int in1Pin = 6; // Motor Pins
int in2Pin = 7;

int n=0,l=0,m=0;
// n : No. of people in the room
void setup()
{
 Serial.begin (9600);

 pinMode(trigPin1, OUTPUT);
 pinMode(echoPin1, INPUT);
 pinMode(trigPin2, OUTPUT);
 pinMode(echoPin2, INPUT);
 pinMode(in1Pin, OUTPUT);
 pinMode(in2Pin, OUTPUT);

}

long ping(int trigPin,int echoPin)// returns distance
{
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPin, HIGH);

 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);

 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 return distance;
}

void loop()
{
 
  long x,xx,y,yy; // variable to store distances
  x=ping(trigPin1,echoPin1);
  xx=ping(trigPin1,echoPin1);
  if((x-xx)>20) // Change this to increace/decrease sensitivity
  {Serial.println("Entered ");
   n++;
   delay(1000);
  }
  else
  {
  y=ping(trigPin2,echoPin2);
  yy=ping(trigPin2,echoPin2);
  if((y-yy)>20)
  {Serial.println("Exited  ");
  n--;
  delay(1000);
  }
  }
  Serial.println();
 
  if (n==-1) n=0;
  if (n==1 && l==0)
  {ON();l++;m++;}
  if(n==0 && m!=0)
  {OFF();m=0;l=0;}
  Serial.println("No. of people in room:  " );
  Serial.print(n);
 
}
void ON() // runs motor to turn on switch
{
  digitalWrite(in2Pin, HIGH);
  digitalWrite(in1Pin, LOW);
  delay(300);
  digitalWrite(in2Pin, LOW);
}
void OFF() // runs motor to turn off switch
{
  digitalWrite(in2Pin, LOW);
  digitalWrite(in1Pin, HIGH);
  delay(300);
  digitalWrite(in1Pin, LOW);
}


-----------------------------------------------------------------------------------------------------------------------------

Monday, 12 October 2015

Making A Line Following Robot

The working of an LFR , is very simple. It has two sensors placed on either side of the line. If the left sensor comes on the black line , the left motor should stop , for it to correct its position . Similarly if the right sensor comes above the black line , the right motor should stop moving.

How is the black line detected
Black and white colours have different optic properties. While black absorbs light of all colours incident on it , white reflects most of these back. So naturally when the sensor is above the white portion , it will receive a higher intensity of light and thus will provide a higher value.
Our task here then is to make a sensor that can convert light intensity , into a voltage reading , which the Arduino can read via its analog input pins.
We will use a photo resistor , which is a device whose resistance to current changes with the incidence of light intensity.

Making the sensor 

The sensor is a basic voltage divider circuit. The photo-resistor is connected in series with a 100 ohm resistor. On end of this combination is connected to +5v and other to ground. The junction is connected to any of the analog pins on the arduino. A resistor is added to this connection to prevent damage to the arduino due to large currents. The junction potential changes when the resistance of the photo resistor changes. This change in potential is measured by the Arduino and is taken advantage of .







Created using Fritzing
Wiring The Motors.

Check my previous post on running motors using the Arduino.
http://crazzycircuits.blogspot.com/2015/07/how-to-run-motor-using-l293d-double-h.html




The Program:

#define M1pin1 9
#define M1pin2 8
#define M2pin1 10
#define M2pin2 11
#define Sensor1 A0
#define Sensor2 A1

int sensor_value1,sensor_value2,diff;

void setup()
{

 Serial.begin (9600);
 pinMode(M1pin1, OUTPUT);
 pinMode(M1pin2, OUTPUT);
 pinMode(M2pin1, OUTPUT);
 pinMode(M2pin2, OUTPUT);

 sensor_value1 = analogRead(Sensor1);
 sensor_value2=analogRead(Sensor2);
 diff= sensor_value2-sensor_value1;  
// We account for this difference to equalise both sensor inputs values for the white portion. This   little trick eliminates the need for calibration.
}

void loop()
{

  sensor_value1 = analogRead(Sensor1)+diff;
  sensor_value2=analogRead(Sensor2);
  if(sensor_value2-sensor_value1>1)  //Sensor values differ when either sensor is on the black   line
     OFF(M2pin1,M2pin2);
  else
     ON(M2pin1,M2pin2);
   
   
 // ______________________
 
  if(sensor_value1-sensor_value2>1)
     OFF(M1pin1,M1pin2);
  else
      ON(M1pin1,M1pin2);
 
 
  //Serial.println(sensor_value1);
  //Serial.println(sensor_value2);
 
}

void ON(int Mpin1,int Mpin2) // runs motor 
{
  digitalWrite(Mpin1, HIGH);
  digitalWrite(Mpin2, LOW);
  
}
void OFF(int Mpin1,int Mpin2) // Stops motor
{
  digitalWrite(Mpin1, LOW);
  digitalWrite(Mpin2, LOW);
}
//End of Program
...................................................................................................................................................................

Sunday, 16 August 2015

Tracker Camera


I will start with : It was a difficult project . Very challenging.
From learning to work with servos, to using the opencv library , to getting my mind around using a raspberry pi , this was one hell of a learning experience.
The camera basically tracks objects based on their unique colour. The camera feeds what it sees into a raspberry pi , which then uses its computing might , to threshold , morph, and the extract features , all in real time. The extracted coordinate of the centroid of the object are then used to position , the servos. This ,trust me, is no easy task. All of this is implemented using the opencv library for image processing. The GPIO library(wiring pi) for raspberry pi helps me interface with the servos.
I spent a lot of time on this project. It has made me fall in love with the raspberry pi.
Post this project , what has mostly changed is my hair pulling threshold ( meaning the failed attempts after which I start to pull my hair). This has definitely increased, for good.
Here , have a look at what came of the madness :


Friday, 24 July 2015

Line follower

I made this over winter. It took me a week to complete this. Making a line follower is pretty simple.
This one has a special something though. I made my own light sensors , unlike those available in the market. It was based on what I had learned in my first semester electrical course class. Also this one need not be calibrated in different light conditions. It does so itself , with a very simple tweak , that just came to me , somehow. It thus does not run on the same piece of program that is flooded over the internet.
I have shared how to make a line follower :
Here is mine , in action.