Synchronize Christmas Lights for Music using Raspberry Pi

Be the house in the neighborhood that puts on the light show! Blink your decorative lights to the beat of music and play it on the radio.

So it all started a few years back, when I discovered YouTube video of people that had put up Christmas lights, and had them blinking in sequence to music.  It sure lit a fire within me to figure out how it was done.  So after some research, I found that there are many ways to get this accomplished. So I decided to choose option is least expensive and at the same time I get to learn the ins and outs of the implementation.  I always believe knowledge gained is waste if not shared. So in this blog I will explain how I accomplished this project.

About the Project 
Synchronize lights to ANY music using Raspberry pi.
Components used

    1. Raspberry Pi 3.
    2. USB WiFi Adapter.
    3. 8 Channel Relay Module
    4. FM Transmitter
    5. Jumper Wires (Female to Female, 1 Pin to 1 Pin).
    6. Power Strip.
    7. Duplex outlets.
    8. 3 Gang outlet box.
    9. Wire nut wire connectors.
    10. 14 gauge wire.
    11. wire stripper.

STEP 1 : Setting up Raspberry pi.

1. Download Raspberry Pi Raspian

2. Convert the image so that you can burn it onto your micro SD card. I like to use Etcher.

3. Enable SSH by doing the following

cd /Volumes/boot
touch ssh

This will enable the SSH to connect remotely.

STEP 2 : Installing LightshowPi on Raspberry Pi

  1. Update the Pi software.
    sudo apt-get update
    sudo apt-get upgrade
  2. Download LightSHowPi
  3. # Install git (if you don't already have it)
    sudo apt-get install git-core
    # Clone the repository to /home/pi/lightshowpi
    cd ~
    git clone https://togiles@bitbucket.org/togiles/lightshowpi.git
    # Grab the stable branch
    cd lightshowpi
    git fetch && git checkout stable
    

Install LightShow Pi
Install the LightShow Pi by navigating to the home directory of your code.

cd /home/pi/lightshowpisudo 
./install.sh

Make sure to restart to Pi after the install. The install might take while make sure to get a cup of coffee for your self.
sudo reboot

STEP 3 : Connect relay to Raspberry Pi
It’s time to get some connection completed b/w Pi and 8 channel relay. Make sure to shutdown the Pi before performing the connection. Please follow the diagram shown below in making the connection b/w Pi and Relay.

lightpi_bRrvXtrhEv

Now comes the moment of truth. Testing the connection b/w Pi and Relay. Turn on the Pi and SSH into Pi. Navigate to folder LightshowPi and execute the below commands.

cd lightshowpi
sudo python py/hardware_controller.py --state=flash

The above command should make the Relay Led flash for a second. Now that we have confirmed all the Leds are flashing , its time to test an mp3 file. LightShowPi already comes with few sample mp3 files to test. SO execute the below command to test the music file.

sudo python py/synchronized_lights.py --file=/home/pi/lightshowpi/music/sample/ovenrake_deck-the-halls.mp3

You should now hear music and also see the led’s on relay flash according to music.

STEP 4 : Connecting Relay to Duplex Outlet.
plug

The duplex  have a hot side and are neutral bridged. Make sure to  cut the bridge of hot side so that we can use it independently to plug 8 separate christmas lights. The hot side of the duplex has golder screws whereas neutral side has silver screws.
Please follow the connection show below for connecting duplex to relay.
relay-receptacles

You can use a Four Gang Device Box to pack receptacles in it and use a receptacle wall plate to cover it. You have eight receptacles so you can plug in up to eight 110v lights to the Pi. Just keep in mind that these SSD relays can’t handle too much load so, don’t plug a heavy load into the receptacle.

Now you can either put lights on your Christmas tree or decorate your house with those lights.

STEP 5 : FINAL SHOW DOWN

In this step let’s create a play list and automate the light show for a particular duration using the cron job.
1. Creating a playlist.
a. Create a folder under music directory located under LightShowPi. Example myMusic
 > mkdir myMusic
b. Place all the mp3 files you would like in the playlist in the folder myMusic.
c. Navigate to tools folder under lightshiwPi and execute the command
python /home/pi/lightshowpi/tools/playlist_generator.py .This command will ask you for the absolute path of the myMusic folder. Provide the path and press ENTER. This should create a .playlist  file under the myMusic folder.
d. Create an overrides.cfg from defaults.cfg. We will now over ride the overrides.cfg file to enable playlist file.
e. Scroll down to the [lightshow] section, comment the default playlist path and add a new one to reflect our music directory. It should look like this:
playlist_path = $SYNCHRONIZED_LIGHTS_HOME/music/sample/.playlist

Change it to

playlist_path = $SYNCHRONIZED_LIGHTS_HOME/music/myMusic/.playlist.
Thats it. Save it and close the file. Now test if the new playlist is working:
sudo python /home/pi/lightshowpi/py/synchronized_lights.py --playlist=/home/pi/lightshowpi/music/myMusic/.playlist

STEP 6 : FM Transmitter 
If you’re going to have a Christmas light display one of the best parts is having friends, family, and strangers pull up and turn the dial in their cars to hear your display. But if you want your display to be heard then you need to connect a FM transmitter to Audio out of your Raspberry Pi. Please don’t make the mistake of putting up a speaker…you might annoy your neighbors.  Here is the FM transmitter I usedfor my project. Click here

Credit where due: This tutorial is a result of immense work done by many individuals. Many thanks to Lightshowpi team that created this amazingly cool open source project.

Raspberry Pi : Smart Pet Treater

During October of 2015 I  got an opportunity to display my project “Smart Pet Treater” built using Raspberry Pi 2 at Charlotte Makers Faire. Here comes few pictures of the Demo.

Using the Smart Treater , the owner can treat the dog from anywhere just by using the Mobile App. When a Treat button is clicked in the Mobile app, the system does the following

  1. Play a music to attract the Pet near the System.
  2. Dispatch the treat ONLY if pet is near the system. The system uses motion sensor to detect the presence of the Pet.
  3. Take a picture
  4. Email the picture to Owner as a confirmation.

 

blogpic.png

SharePoint 2010 Service Accounts: Part 1

The SharePoint 2010 provides multiple services which are managed by multiple service accounts. Which once you need before the installation of SharePoint depends on what services do you need. This post covers minimum necessary account for basic installation.

Since SharePoint shows close relationship with SQL Server and Active Directory(AD) , AD provides identity and authentication services for SharePoint. In brief , AD stores user accounts and passwords and validates account logons. SQL Server stores almost all the configuration information of SharePoint(SP) farm. So in order to support the administration and services of SQL Server and SP , identities needs to be created in AD and proper permissions must be granted. Here it is important to adhere to the security practices of least privilege.  Following accounts need to be created as Domain accounts before the basic installation of SP:
   

  • SharePoint setup user and administration: SP_Admin
  • SharePoint farm account: SP_Farm
  • SQL Server Administration account: SQL_Admin
  • SQL Server service account: SQL_Service
  • Web Application pool account(s) : SP_WebApp

TODO during creation of above domain accounts in AD:

  • Store accounts in separate organizational unit(OU).
  • Try to follow a good naming convention for each account like starting with SP(for SharePoint) or SQL (for SQL Server).
  • Make sure to follow proper security for accounts like expiration. SP can detect security changes in AD from SharePoint central administration.
  • Provide least privileges to these accounts.

In my next post I will explain the importance of each account for proper function of SharePoint within a farm.

C# Parameter Modifiers Part 2

3. Using ref Modifier

C# ref parameters are useful when you want the method to change the values of various data points declared in callers scope.

So what’s the difference between ref  and out  modifiers ?
Output parameters need not be initialized before passing it to a method. The calling method initializes the value for the parameter. Where as , the reference parameters need to be initialized before sending. This is because, the called method need to get the reference to the parameter and no reference is created unless a variable is initialized.

Coding:

Lets create a static method which takes two strings and interchanges their values.

public static void RefParameterExample(ref string firstName, ref string LastName)
{

string tempString = firstName;

firstName = LastName;

LastName = tempString;


}

The above method interchanges the value assigned by calling method to first name and last name. Lets call the above method with following code.

public static void TestRefParameterModifier()
{

Console.WriteLine("------ Using ref Modifiers-------");

string firstName, LastName;

firstName = "Bill";

LastName = "Gates";

Console.WriteLine("Before Call");

Console.WriteLine(" First Name is {0} and Last Name is {1}", firstName, LastName);

// Lets call the RefParameterExample which interchanges the first name and last name

CodeSample.RefParameterExample(ref firstName, ref LastName);

Console.WriteLine("After Call");

Console.WriteLine(" First Name is {0} and Last Name is {1}", firstName, LastName);

Console.ReadKey();


}

Output:

image

4. Using params Modifier

With the use of params keyword, you can make a method accept a variable number of parameters(of same type) as a single logical parameter. Also, the arguments marked with params keyboard can accept comma deliminated values or strongly types array.

Coding

Suppose you want to define a method which can find average of numbers  that are passed though a calling method. Here is the sample code for the method using the params modifier.

public static double  paramsParamterExample(params double[] values)
{

double total = 0;

if (values.Length == 0)

return total;


for(int i =0; i < values.Length ; i++)

{

total += values[i];

}

return total / values.Length;


}

The above method can be called with following code:

public static void TestParamsParamterModifier()
{

Console.WriteLine("------ Using params Modifiers-------");

Console.WriteLine("------ Testing with comma deliminated values-------");

// CodeSample.paramsParamterExample(2.3, 3.4, 55.6) would give error if the method was defined with params keywaord

Console.WriteLine(" Average of 2.3,3.4,55.6 is {0}", CodeSample.paramsParamterExample(2.3, 3.4, 55.6));

Console.WriteLine("------ Testing with strongly types array of double-------");

double[] thisArray = { 3.4, 5.4, 1.2, 6.6 };

Console.WriteLine("Average is {0}", CodeSample.paramsParamterExample(thisArray));

Console.ReadKey();


}

 

Here comes the output for above code:

Coding

image

This concludes the discussion on C# modifiers. Having the knowledge of C# modifiers greatly helps in using proper techniques while passing the data.

C# Parameter Modifiers Part 1

 
Keywords are used to control how the parameters are passed to the method in C#. These can be categorized into “out”,”ref” and “params”. Parameters can also be skipped with modifiers. Following section will explain more about each of the modifier type used in C#.

1. Using no Modifiers

When a parameter is not marked with any modifiers, the called method receives the copy of the original data. This is also the default type of passing a parameter to methods.

Coding:

Lets create a static function which takes in 2 numbers  and returns the multiplication of 2 numbers.

class CodeSample
{

public static int Multiply(int x, int y)
{

int answer = x * y;

// following changes will not be seen on main function

x = 12;
y = 56;

// end of comment

return answer;


}
}

 
Since the numerical data falls under value types, the caller of the method will be unaware if the values are changed within the called method. Lets call the above function from main method with following code.

public static void TestNoModifier()
{

Console.WriteLine("------ Using No Modifiers-------");

int x = 10;
int y = 34;

Console.WriteLine(" Before call : X = {0}, Y= {1}", x, y);

Console.WriteLine(" Multiplied Value = {0}", CodeSample.Multiply(x, y));

Console.WriteLine(" After call : X = {0}, Y= {1}", x, y);

Console.ReadKey();

}

 

Output
image

As expected the values of X and Y remain the same before and after the call.

2. Using out Modifiers

Methods that receive the parameters with out  keyword defined in the parameter are obligated to assign an appropriate value before exiting the method. Failure to do so will result in compiler error.

Coding:

Lets modify the Multiply  method above to take parameters with out  keyword.

public static void MultiplyForOutModifier(int x, int y, out int ans)

{

ans = x * y;

}

Note that method does not have any return type. The result of multiplication is assigned to variable ans  which is defined using out  modifier. The local variables x and y need not be reassigned with value since they are not defined with out  modifier.

Lets call the above method from main program.
In the below code the variable ans  is sent by prefixing it with out  modifier.

public static void TestOutModifier()
{

Console.WriteLine("------ Using Out Modifiers-------");

int x = 10;
int y = 45;

int ans;

CodeSample.MultiplyForOutModifier(x, y, out ans);

Console.WriteLine(" 10 * 45 = {0}", ans);

Console.ReadKey();


}

Output
image

The C# out  modifier also helps in returning multiple return values to the calling function. Here is the sample code for the same;

public static void ReturnMultipleValues(out int a, out string name, out bool val)
{

a = 12;

name = "Marsh";

val = false;

}

The above method can be called by following code.

public static void TestMultipleOutModifier()
{

Console.WriteLine("------ Using Out Modifiers-------");

int b;

string thisString;

bool isStrue;

CodeSample.ReturnMultipleValues(out b, out thisString, out isStrue);

Console.WriteLine(" B value = {0}", b);

Console.WriteLine(" thisStrin = {0}", thisString);

Console.WriteLine(" isStrue = {0}", isStrue);

Console.ReadKey();

}

Output
image

Always remember that method that defines the output parameters must  assign the parameter to a valid value. Following method will result in compiler error since  variable a  is unassigned.

public static void MethodWithError(out int a)
{

Console.WriteLine(" This will result in Error");
}

In part 2 of C# modifier I will explain ref  and params  modifiers.

Stack Exchange API Photo stats using iPhone SDK

The project I am working on required me to pull the statistical data from stack exchange API. I needed to pull the data for photography category of stack exchange website. Here comes a code to pull statistical data using iphone sdk.

In order for this code to work you need to have added the TouchJson frame work to your iphone project.

To learn more about the usage of photo API please visit api.photo.stachexchange.com/1.1/usage. The following code returns an NSMutableArray with required statistical data.

+(NSMutableArray *)getStatsData {

NSString *searchString = @”http://api.photo.stackexchange.com/1.1/stats&#8221;;

// Execute search by performing an HTTP GET to the REST web service which returns JSON

NSString *jsonString = [self jsonFromURLString:searchString];

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];

// Parse JSON results with TouchJSON. It converts it into a dictionary.

CJSONDeserializer *jsonDeserializer = [CJSONDeserializerdeserializer];

NSError *error = nil;

NSDictionary *resultsDictionary = [jsonDeserializer deserializeAsDictionary:jsonData error:&error];

[self handleError:error];

NSArray *tagArray = [resultsDictionary objectForKey:@”statistics”];

NSMutableArray *tagReturnArray = [[[NSMutableArray alloc] init] autorelease];

for (NSDictionary *tagDictionary in tagArray) {

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”total_questions”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”total_unanswered”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”total_accepted”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”total_answers”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”total_comments”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”total_votes”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”total_users”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”questions_per_minute”]]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”answers_per_minute”] ]];

[tagReturnArray addObject:[NSString stringWithFormat:@”%@”,[tagDictionary objectForKey:@”views_per_day”] ]];

}

return tagReturnArray ;

}

Customize UITableView in iPhone

UITableView row can be easily customized by modifying the delegate function of UITableDelegate. Listed below are some modification which can be done to get an impressive tableRow.

 

1. To add image to a UITableView.

 

-(void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell

forRowAtIndexPath: (NSIndexPath*)indexPath {

 

UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”tablecell.jpg”]];

[cell setBackgroundView:myImageView];

}

 

here “tablecell.jpg” is the image which gives the background image for table Row.

 

2. To Change the height of the Table Row

 

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

return 100.0f;

}

 

3. To determine number of sections in the Table

 

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

 

return count;  // Count is the number of sections you want for the table.

}

 

4. Determine the number of rows for the Table.

 

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

 

return [photoTitle count]; // Here photoTitle is NSArray.

}

 

5. Perform something when a row is selected. The below code is taken from one of my project. You can modify the code as per your requirement.

 

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

ViewSinglePhotoViewController *viewcontroller = [[ViewSinglePhotoViewController alloc] initWithNibName:@”ViewSinglePhotoViewController” bundle:nil];

NSString *passString = [LargImgUrl objectAtIndex:[indexPath row]];

NSURL *url = [NSURL URLWithString:passString];

viewcontroller.myURL = url;

viewcontroller.titleName = [photoTitle objectAtIndex:[indexPath row]];

[self.navigationController pushViewController:viewcontroller animated:YES];

[viewcontroller release];

}

 

6. Content for a row. Configuring the cell for each row.

 

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 

static NSString *CellIdentifier = @”Cell”;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

 

if (cell == nil) {

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

 

//configure cell here

}

return cell;

 

}

 

I explained above some of the important delegate function of UITableViewDelegate which are frequently used. For more information on other delegate function you can check Apple documentation.