sub retV4 ()
{
my $in = $_[0];
my @ipv6 = split (“:”, $in);

$v6part1 = hex ($ipv6[6]);
$v6part2 = hex($ipv6[7]);

$ip41=scalar($v6part1>>8);
$ip42=scalar($v6part1&0xff);
$ip43=scalar($v6part2>>8);
$ip44=scalar($v6part2&0xff);

$out = $ip41 . “.” . $ip42 . “.” . $ip43 . “.” . $ip44;
return $out;
}

Function takes an IPv6 address such as: 0:0:0:0:0:0:c713:97e4 and will convert it to IPv4: 199.19.151.228.

The last part of the IPv6 address can be converted. The basic idea is as follows.
1. Take c713
2. Convert c to base 10 (12*16) = 192
3. add 7 – 192 + 7 = 199
4. Take 1 and convert to base 10 – 1 * 16 = 16
5. Add 3 – 16 + 3 = 19

The result is that c713 is equal to 199.19.

Two arduino systems are connected using XBee radios. One arduino system controls a button, the second controls a yellow LED. The system with the button is the controller, the system with the LED is the slave. Pressing the button on the controller, will send a message to using the XBee radio. Once this message is received by the slave, it is processed. If it matches the expected input the yellow LED will light.

Arduino controller

Arduino slave

Controller source code:

/*
* doorbell button
* 1/11/2013
*/
int BUTTON=2;
int but_state=0;
int LED=11;

void setup()
{
pinMode (BUTTON, INPUT);
pinMode (LED,OUTPUT);
Serial.begin (9600);
}

void loop()
{

if ((digitalRead(BUTTON) == HIGH) && (but_state ==0))
{
but_state=1;
delayMicroseconds (250);
Serial.print (‘D’);
delay (100);
}
else {
delayMicroseconds (200);
but_state=0;
}

if (Serial.available() > 0) {
if (Serial.read() == ‘K’) {
digitalWrite (LED,HIGH);
}
}

if (digitalRead(BUTTON) == LOW) {
digitalWrite (LED,LOW);
}

}

 

Slave source code:

/*
* doorbell – bell
* using Piezo
*/

int LED=5;
int speakerpin=5;

void setup()
{
pinMode (LED,OUTPUT);

Serial.begin (9600);
}

void loop()
{
if (Serial.available() > 0) {
if (Serial.read() == ‘D’) {
Serial.print (‘K’);
digitalWrite (LED,HIGH);
delay (1000);
digitalWrite (LED,LOW);
}
}

}

Internet Clock

Posted: August 26, 2012 in Arduino, Software development

This experiment uses the an Ethernet shield, real-time clock and LCD modules. The Arduino will get the current time from NTP on an hourly basis. The NTP return value is translated to Unix (POSIX) time. This value is adjusted to for the time-zone  and used to set the real-time clock. Unfortunately, the time zone offset is hard-coded. Eventually, this value can also be obtained from the Internet. The LCD will display the time and date, every second. The hardware includes a DS1307 clock module, which is connected to analog ports 4 and 5. The Ethernet shield uses DHCP to obtain an IP address. It will send an NTP UDP request whenever the current hour is not equal to the previous hour. Finally, the clock output is sent to both the serial interface and the LCD. The clock and Internet functions form the basis for many types of automation.  The Ethernet shield and the LCD can conflict. It was necessary to move the LCD connections, until they no longer caused a conflict with the Ethernet.

Components:


/*
* Internet Clock using NTP and LCD display module
* William Beckett (c) 2012
* RightAResearch.com
*
*/

#include <LiquidCrystal.h>
#include <Time.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUDP.h>

// Connections:
// changed based on Ethernet conflicts
// rs (LCD pin 4) to Arduino pin 9
// rw (LCD pin 5) to Arduino pin 8
// enable (LCD pin 6) to Arduino pin 7
// LCD pin 15 to Arduino pin 6
// LCD pins d4, d5, d6, d7 to Arduino pins 5, 4, 3, 2
LiquidCrystal lcd(9, 8, 7, 5, 4, 3, 2);

int backLight = 6;    // pin 6 will control the backlight

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  // MAC address to use

unsigned int localPort = 8888;      // local port to listen for UDP packets

IPAddress timeServer(192, 43, 244, 18); // time.nist.gov NTP server
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48
// bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; // buffer to hold incoming/outgoing packets

const  long timeZoneOffset = -14400L;
boolean pm=false;

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

int lasthour=0;
int currenthour=-1;

void setup()
{
pinMode(backLight, OUTPUT);
digitalWrite(backLight,HIGH); // turn backlight on. Replace ‘HIGH’ with ‘LOW’ to turn it off.
lcd.begin(16,4);              // columns, rows.
lcd.clear();                  // start with a blank screen
lcd.setCursor(0,0);           // set cursor to column 0, row 0 (the first row)
lcd.print(“RightAResearch.com”);
lcd.setCursor(0,1);           // set cursor to column 0, row 1
lcd.print(” “);

// if you have a 4 row LCD, uncomment these lines to write to the bottom rows
// and change the lcd.begin() statement above.
lcd.setCursor(0,2);         // set cursor to column 0, row 2
lcd.print(” “);
lcd.setCursor(0,3);         // set cursor to column 0, row 3
lcd.print(” “);

Serial.begin(9600);
setSyncProvider(RTC.get);   // the function to get the time from the RTC

if (Ethernet.begin(mac) == 0) {
Serial.println(“Failed to configure Ethernet using DHCP”);
}

}

void loop()
{

if (lasthour != currenthour)
getSetTime();             // get NTP time

digitalClockDisplay();
currenthour=hour();
delay(1000);
}

void getSetTime()
{
lcd.setCursor (0,1);
lcd.print (“Getting NTP Time”);
Udp.begin(localPort);
time_t t = getUNIXTime();

if(t >0)
{
RTC.set(t);   // set the RTC and the system time to the received value
setTime(t);
}

lcd.setCursor (0,1);
lcd.print (“Set NTP Time      “);
lasthour=hour();
currenthour=hour();

}

void digitalClockDisplay(){
// digital clock display of the time

int h=hour();
if (h> 12) {
h -= 12;
pm=true;
}
else if (h ==12) {
if (!pm)
pm=true;
else
pm=false;
}
lcd.setCursor (0,1);
lcd.print (”                “);
Serial.print(h);
printDigits(minute());
printDigits(second());
Serial.print(” “);
Serial.print(day());
Serial.print(” “);
Serial.print(month());
Serial.print(” “);
Serial.print(year());
Serial.println();
lcd.setCursor (3,2);
lcdPrintDigits (h);
lcd.print (“:”);
lcdPrintDigits (minute());
lcd.print (“:”);
lcdPrintDigits (second());
if (pm)
lcd.print (” pm”);
else
lcd.print (” am”);
lcd.setCursor (0,3);
lcd.print (dayShortStr (weekday()));
lcd.print (” “);
lcd.print (monthShortStr(month()));
lcd.print (” “);
lcd.print (day());
lcd.print (“, “);
lcd.print (year());
}

void printDigits(int digits){
// utility function for digital clock display: prints
// preceding colon and leading 0
Serial.print(“:”);
if(digits < 10)
Serial.print(‘0’);
Serial.print(digits);
}

void lcdPrintDigits(int digits){
// utility function for digital clock display: prints
// preceding colon and leading 0

if(digits < 10)
lcd.print(‘0’);

lcd.print(digits);
}

unsigned long getUNIXTime()
{

unsigned long epoch=0;
sendNTPpacket(timeServer); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
if ( Udp.parsePacket() ) {
Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer

//the timestamp starts at byte 40, convert four bytes into a long integer
unsigned long hi = word(packetBuffer[40], packetBuffer[41]);
unsigned long low = word(packetBuffer[42], packetBuffer[43]);
unsigned long secsSince1900 = hi << 16 | low;  // this is NTP time
// (seconds since Jan 1 1900)

Serial.print(“Seconds since Jan 1 1900 = ” );
Serial.println(secsSince1900);

Serial.print(“Unix time = “);
// Unix time starts on Jan 1 1970
const unsigned long seventyYears = 2208988800UL;
epoch = secsSince1900 – seventyYears + timeZoneOffset;  // subtract 70 years
Serial.println(epoch);                               // print Unix time

// print the hour, minute and second:
// UTC is the time at Greenwich Meridian (GMT)
Serial.print(“The UTC time is “);
// print the hour (86400 equals secs per day)
Serial.print((epoch  % 86400L) / 3600);
Serial.print(‘:’);
if ( ((epoch % 3600) / 60) < 10 ) {
// Add leading zero for the first 10 minutes of each hour
Serial.print(‘0’);
}
// print the minute (3600 equals secs per minute)
Serial.print((epoch  % 3600) / 60);
Serial.print(‘:’);
if ( (epoch % 60) < 10 ) {
// Add leading zero for the first 10 seconds of each minute
Serial.print(‘0’);
}
Serial.println(epoch %60); // print the second
}

return epoch;
}

// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(IPAddress& address)
{

memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0

// Initialize values needed to form NTP request
packetBuffer[0] = B11100011;   // LI, Version, Mode
packetBuffer[1] = 0;     // Stratum
packetBuffer[2] = 6;     // Max Interval between messages in seconds
packetBuffer[3] = 0xEC;  // Clock Precision
// bytes 4 – 11 are for Root Delay and Dispersion and were set to 0 by memset
packetBuffer[12]  = 49;  // four byte reference ID identifying
packetBuffer[13]  = 0x4E;
packetBuffer[14]  = 49;
packetBuffer[15]  = 52;

// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer,NTP_PACKET_SIZE);
Udp.endPacket();
}

 

Arduino Relay

Posted: August 12, 2012 in Arduino, Software development

 

Simple project to incorporate a relay. The relay allows us to switch on and off devices which require more current than can be supplied by the Arduino. This simple project demonstrates the basics of using the relay. The demo has a satisfying click as the relay is switched on and off. The RED LED is on when the relay is on. The YELLOW LED is on when the relay is off.

Source code:

int ledpin=2;

void setup()
{
pinMode (ledpin, OUTPUT);
Serial.begin (9600);
}

void loop()
{

Serial.println (“Switching on – RED LED”);
digitalWrite (ledpin, HIGH);
delay (1000);
Serial.println (“Switching off – YELLOW LED”);
digitalWrite (ledpin, LOW);
delay (1000);

}

This experiment utilizes two buttons, two LEDs, a photo sensor and an LCD display. The buttons control whether the LEDs are on or off. The light sensor controls the intensity of the LEDs. The LCD display will show the current value of the LED, based on the input from the light sensor. The LCD will also display the status of the two LEDs.  The 4 line, 20 character LCD display requires some assembly, in addition to using 7 connections to the Arduino. The goal of the experiment is to utilize the LCD with both real-time streaming data and with event driven data. The photo sensor provides the real-time stream, while each button provides an event.

LCD Datasheet

Source code:

#include

int yellowled =9; // yellow led
int redled =10; // red led
int inpin=8; // input button 0
int inpin2=7; // input button 1
int potpin =0; // light sensor

int lcdb=13; // LCD backlight
// debounce variables
int lastButtonState[2];
int lastDebounceTime[2];
int debounceDelay=150;
int buttonState[2];

// LCD
const int numRows =4;
const int numCols =16;

// Connect to LCD pins
LiquidCrystal lcd (12, 11, 5, 4, 3, 2);

int count=0;
int index=0;
boolean printed=false; // print the prompt
const int MaxChars=5; // input buffer max
char strValue[MaxChars+1]; // input buffer

boolean redstate=false; //off
boolean yelstate=false; //off

int potval=0;
int percent=0;

void setup ()
{

// setup LCD
lcd.begin (numCols, numRows);
lcd.setCursor (0,0);
lcd.print (“RightAResearch.com “);

pinMode (lcdb, OUTPUT);
digitalWrite (lcdb, HIGH); // turn on LCD backlight
pinMode (yellowled, OUTPUT);
pinMode (redled, OUTPUT);
pinMode (inpin, INPUT);
pinMode (inpin2, INPUT);
Serial.begin (9600);
}

void loop()
{

getPercent(); // get input from light sensor
testStateButton(); // testing the buttons

}

void getPercent()
{
static int last;
static int plast;

potval = analogRead (potpin);
delayMicroseconds (100);
percent = map (potval, 0, 1023,0, 255); // mapping the light sensor to the LED
delayMicroseconds (50);

if ((potval != last) && (plast != percent)) { // did the sesnsor change?
last = potval;
plast = percent;
Serial.print (“Pot in raw value: “);
Serial.print (potval);
Serial.print (” LED value: “);
Serial.println (percent);
lcd.setCursor (0,1);

lcd.print (“LED value: “);
lcd.setCursor (11,1);
lcd.print (” “);
lcd.setCursor (11,1);
lcd.print (percent);
changeLed();
}

}

// changing the intensity of the LED based on the sesor data
void changeLed()
{
if (redstate) {
analogWrite (redled, percent);
Serial.print (“Changing RED LED to “);
Serial.println (percent);

}

if (yelstate){
analogWrite (yellowled, percent);
Serial.print (“Changing YELLOW LED to “);
Serial.println (percent);
}

}

void testStateButton ()
{

if (debounce(inpin,0) == LOW) { /// controlling red
Serial.print (“red button1 pressed – “);
Serial.println (redstate);

delayMicroseconds (250);
if (redstate) {
fadeOut(redled);
lcd.setCursor (0,2);
lcd.print (“RED is OFF”);
redstate =false;
}
else {
fadeIn(redled);
redstate =true;
lcd.setCursor (0,2);
lcd.print (“RED is ON “);
changeLed();
}
}
else if (debounce(inpin2,1) == LOW) { // controlling yello
Serial.print (“yellow button2 pressed – “);
Serial.println (yelstate);
delayMicroseconds (250);
if (yelstate) {
fadeOut (yellowled);
lcd.setCursor (0,3);
lcd.print (“YELLOW is OFF”);
yelstate=false;
}
else {
fadeIn (yellowled);
yelstate=true;
lcd.setCursor (0,3);
lcd.print (“YELLOW is ON “);
changeLed();
}
}

}

int reading[2];

int debounce(int buttonPin, int button) {
// read the state of the switch into a local variable:
reading[button] = digitalRead(buttonPin);

// If the switch changed, due to noise or pressing:
if (reading[button] != lastButtonState[button]) {
// reset the debouncing timer
lastDebounceTime[button] = millis();
}

if ((millis() – lastDebounceTime[button]) > debounceDelay) {
// whatever the reading is at, it’s been there for longer
// than the debounce delay, so take it as the actual current state:
buttonState[button] = reading[button];
}

// set the LED using the state of the button:
digitalWrite(buttonPin, buttonState[button]);

// save the reading. Next time through the loop,
// it’ll be the lastButtonState:
lastButtonState[button] = reading[button];
return lastButtonState[button];
}

void fadeIn (int led)
{

//delayMicroseconds (250);
digitalWrite (led, HIGH);
}

void fadeOut (int led)
{

//delayMicroseconds (250);
digitalWrite (led, LOW);
}

This experiment uses the same code as the two button potentiometer, however, the potentiometer is replaced with a photo resistor. The photo resistor has a high value when the environment is dark and a low value when the environment is bright. The LEDs will be used to display the output of the photo resistor. As the environment is brighter the LEDs will dim. When the environment darkens the LEDs will shine brighter.

int yellowled =9;
int redled =10;
int inpin=2;
int inpin2=3;
int potpin =0;

int count=0;
int index=0;
boolean printed=false; // print the prompt
const int MaxChars=5; // input buffer max
char strValue[MaxChars+1]; // input buffer

boolean redstate=false; //off
boolean yelstate=false; //off

int potval=0;
int percent=0;

void setup ()
{

pinMode (yellowled, OUTPUT);
pinMode (redled, OUTPUT);
pinMode (inpin, INPUT);
pinMode (inpin2, INPUT);
Serial.begin (9600);
}

void loop()
{
// potval = analogRead (potpin);
// percent = map (potval, 0, 1023,0, 100);
getPercent();
testStateButton();

}

void getPercent()
{
static int last;
static int plast;

potval = analogRead (potpin);
delayMicroseconds (100);
percent = map (potval, 0, 1023,0, 255);
delayMicroseconds (50);

if ((potval != last) && (plast != percent)) {
last = potval;
plast = percent;
Serial.print (“Pot in raw value: “);
Serial.print (potval);
Serial.print (” LED mapped value: “);
Serial.println (percent);
changeLed();
}

}

void changeLed()
{
if (redstate) {
analogWrite (redled, percent);
Serial.print (“Changing RED LED to “);
Serial.println (percent);
}

if (yelstate){
analogWrite (yellowled, percent);
Serial.print (“Changing YELLOW LED to “);
Serial.println (percent);
}

}

void testStateButton ()
{

if (digitalRead(inpin) == LOW) { /// controlling red
Serial.print (“red button1 pressed – “);
Serial.println (redstate);

delayMicroseconds (250);
if (redstate) {
// digitalWrite (redled, LOW);
fadeOut(redled);
redstate =false;
}
else {
//digitalWrite (redled, HIGH);

fadeIn(redled);
redstate =true;
changeLed();
}
}
else if (digitalRead(inpin2) == LOW) { // controlling yello
Serial.print (“yellow button2 pressed – “);
Serial.println (yelstate);
delayMicroseconds (250);
if (yelstate) {
//digitalWrite (yellowled, LOW);
fadeOut (yellowled);
yelstate=false;
}
else {
//digitalWrite (yellowled, HIGH);

fadeIn (yellowled);
yelstate=true;
changeLed();
}
}

}

void fadeIn (int led)
{
//int max = 255 * (percent/100);

for (int i=0; i0; i–) {
analogWrite (led, i);
delay(10);
}
digitalWrite (led, LOW);
}

void flashBoth ()
{
int blinkRate =2;
for (int i=0; i<blinkRate; i++) {
blink (200,redled);
blink (200,yellowled);
}
}

// function to turn on and off an LED for a specific time

void blink (int rate, int pin)
{

digitalWrite (pin, HIGH);
delay (rate);
digitalWrite (pin, LOW);

}

void microBlink (int rate, int pin)
{

digitalWrite (pin, HIGH);
// delay (rate);
delayMicroseconds (rate);
digitalWrite (pin, LOW);

}

Took the project with two buttons and two LEDs, and added a potentiometer. This device is also called a variable resistor. It provides variable resistance which results in variable voltage levels ranging from 0 to 5 volts. The voltage can be measured via an analog port on the Arduino. The result is a number between 0 and 1024, which represents the amount of voltage flowing to the analog port. The Arduino development environment supports a map function, which will map the 0 to 1024 value into another relevant value. In this case, we are mapping to the value of the LED, which is between 0 and 255. The output of the map is applied to the LED, if it is lit. The serial output displays the value of the potentiometer and the LED value. Here is an example:

Pot in raw value: 300 LED mapped value: 74

If either or both LEDs are lit, they will be dimmed or brightened to the value of the potentiometer.

Source code:

int yellowled =9;
int redled =10;
int inpin=2;
int inpin2=3;
int potpin =0;

int count=0;
int index=0;
boolean printed=false; // print the prompt
const int MaxChars=5; // input buffer max
char strValue[MaxChars+1]; // input buffer

boolean redstate=false; //off
boolean yelstate=false; //off

int potval=0;
int percent=0;

void setup ()
{

pinMode (yellowled, OUTPUT);
pinMode (redled, OUTPUT);
pinMode (inpin, INPUT);
pinMode (inpin2, INPUT);
Serial.begin (9600);
}

void loop()
{
// potval = analogRead (potpin);
// percent = map (potval, 0, 1023,0, 100);
getPercent();
testStateButton();

}

void getPercent()
{
static int last;
static int plast;

potval = analogRead (potpin);
delayMicroseconds (100);
percent = map (potval, 0, 1023,0, 255);
delayMicroseconds (50);

if ((potval != last) && (plast != percent)) {
last = potval;
plast = percent;
Serial.print (“Pot in raw value: “);
Serial.print (potval);
Serial.print (” LED mapped value: “);
Serial.println (percent);
changeLed();
}

}

void changeLed()
{
if (redstate) {
analogWrite (redled, percent);
Serial.print (“Changing RED LED to “);
Serial.println (percent);
}

if (yelstate){
analogWrite (yellowled, percent);
Serial.print (“Changing YELLOW LED to “);
Serial.println (percent);
}

}

void testStateButton ()
{

if (digitalRead(inpin) == LOW) { /// controlling red
Serial.print (“red button1 pressed – “);
Serial.println (redstate);

delayMicroseconds (250);
if (redstate) {
// digitalWrite (redled, LOW);
fadeOut(redled);
redstate =false;
}
else {
//digitalWrite (redled, HIGH);

fadeIn(redled);
redstate =true;
changeLed();
}
}
else if (digitalRead(inpin2) == LOW) { // controlling yello
Serial.print (“yellow button2 pressed – “);
Serial.println (yelstate);
delayMicroseconds (250);
if (yelstate) {
//digitalWrite (yellowled, LOW);
fadeOut (yellowled);
yelstate=false;
}
else {
//digitalWrite (yellowled, HIGH);

fadeIn (yellowled);
yelstate=true;
changeLed();
}
}

}

void fadeIn (int led)
{
//int max = 255 * (percent/100);

for (int i=0; i0; i–) {
analogWrite (led, i);
delay(10);
}
digitalWrite (led, LOW);
}

void flashBoth ()
{
int blinkRate =2;
for (int i=0; i<blinkRate; i++) {
blink (200,redled);
blink (200,yellowled);
}
}

// function to turn on and off an LED for a specific time

void blink (int rate, int pin)
{

digitalWrite (pin, HIGH);
delay (rate);
digitalWrite (pin, LOW);

}

void microBlink (int rate, int pin)
{

digitalWrite (pin, HIGH);
// delay (rate);
delayMicroseconds (rate);
digitalWrite (pin, LOW);

}

The project uses a button to control an LED. The button is wired using a pull-up resistor, which sets the voltage on. The button press event is detected when voltage is off. The LEDs are programmed to fade on and off, based on the state of the individual button. The debounce technique attempts to detect when the button is pressed. This is accomplished by waiting 250 milliseconds after a voltage change is found on the button. The serial interface shows when a button press is detected.

 

 

Source code:

int yellowled =9;
int redled =10;
int inpin=2;
int inpin2=3;

int count=0;
int index=0;
boolean printed=false; // print the prompt
const int MaxChars=5; // input buffer max
char strValue[MaxChars+1]; // input buffer

boolean redstate=false; //off
boolean yelstate=false; //off

void setup ()
{

pinMode (yellowled, OUTPUT);
pinMode (redled, OUTPUT);
pinMode (inpin, INPUT);
pinMode (inpin2, INPUT);
Serial.begin (9600);
}

void loop()
{

testStateButton();

}

void testStateButton ()
{

if (digitalRead(inpin) == LOW) { /// controlling red
Serial.print (“red button1 pressed – “);
Serial.println (redstate);

delayMicroseconds (250);
if (redstate) {
// digitalWrite (redled, LOW);
fadeOut(redled);
redstate =false;
}
else {
//digitalWrite (redled, HIGH);

fadeIn(redled);
redstate =true;
}
}
else if (digitalRead(inpin2) == LOW) { // controlling yello
Serial.print (“yellow button2 pressed – “);
Serial.println (yelstate);
delayMicroseconds (250);
if (yelstate) {
//digitalWrite (yellowled, LOW);
fadeOut (yellowled);
yelstate=false;
}
else {
//digitalWrite (yellowled, HIGH);

fadeIn (yellowled);
yelstate=true;
}
}

}

void fadeIn (int led)
{
for (int i=0; i0; i–) {
analogWrite (led, i);
delay(10);
}
digitalWrite (led, LOW);
}

void flashBoth ()
{
int blinkRate =2;
for (int i=0; i<blinkRate; i++) {
blink (200,redled);
blink (200,yellowled);
}
}

// function to turn on and off an LED for a specific time

void blink (int rate, int pin)
{

digitalWrite (pin, HIGH);
delay (rate);
digitalWrite (pin, LOW);

}

void microBlink (int rate, int pin)
{

digitalWrite (pin, HIGH);
// delay (rate);
delayMicroseconds (rate);
digitalWrite (pin, LOW);

}

The project takes the basic LED and adds music via a Piezo element. This device makes a clicking sound each time it is pulsed. Pulsing at the correct frequency will result in a musical note. The software will play Twinkle Twinkle Little Star and blink the LEDs with the music. This project supports the serial interface, so the music is played when the user enters an ‘s’ in the serial interface.

Arduino

Here is the source code:

int speakerpin =9;
int yellowled =11;
int redled =12;
int length =15;
int count=0;
int index=0;
boolean printed=false;      // print the prompt
const int MaxChars=5;       // input buffer max
char strValue[MaxChars+1];  // input buffer

void setup ()
{
pinMode (speakerpin,OUTPUT);
pinMode (yellowled, OUTPUT);
pinMode (redled, OUTPUT);
Serial.begin (9600);
}

void loop()
{
if( Serial.available()) {
char ch = Serial.read();
if( index < MaxChars && isDigit( ch) )
{
strValue[index++] = ch; // add the ASCII character to the string;
}
else { // here when buffer full or on the first non digit

if (ch == ‘s’)  {    //
Serial.println (“Play song”);
count=0;
playSong();
}
else
Serial.println (“Invalid option”);

printed=false;      // ensures the Wait prompt is displayed
index = 0;
}
}

// printing out waiting for input
if (!printed) {
Serial.println (“Waiting for input:”);
printed=true;
}

}

void playSong()
{
char notes[] = “ccggaagffeeddc “;
int beats[] = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1};
int tempo =300;

for (int i=0; i<length; i++) {
if (notes[i] == ‘ ‘) {
delay(beats[i] * tempo);
}
else {
playNote (notes[i], beats[i] * tempo);
}

delay (tempo/2);
}
flashBoth();
}

void playTone (int tone, int duration, int color)
{
for (long i=0; i<duration*1000L; i+= tone*2) {
digitalWrite (speakerpin, HIGH);
//  delayMicroseconds (tone)
microBlink (tone,color);
digitalWrite (speakerpin, LOW);
microBlink (tone,color);
//delayMicroseconds (tone);
}
}

void playNote (char note, int duration) {
char names[] = {‘c’,’d’,’e’,’f’,’g’,’a’,’b’,’c’};
int tones[] = {1915,1700,1519,1432,1275,1136,1014,956};

for (int i=0; i<8; i++) {
if (names[i] == note) {
count++;
if ((count%2) == 0)
playTone (tones[i], duration, yellowled);
else
playTone (tones[i], duration, redled);
}
}

}

void flashBoth ()
{
int blinkRate =2;
for (int i=0; i<blinkRate; i++) {
blink (200,redled);
blink (200,yellowled);
}
}

// function to turn on and off an LED for a specific time

void blink (int rate, int pin)
{

digitalWrite (pin, HIGH);
delay (rate);
digitalWrite (pin, LOW);

}

void microBlink (int rate, int pin)
{

digitalWrite (pin, HIGH);
//  delay (rate);
delayMicroseconds (rate);
digitalWrite (pin, LOW);

}

Here is a simple Java class to test binary operations on integers. The class shows first creates a character array as a method to set bits on and off. The character array is then converted to an integer. Then the code reproduces the same results using the bit shift operator.

Here is the output:

Using character array:

All on: 255
pin[0] on: 128 : 10000000
pin[1] on: 64 : 01000000
pin[2] on: 32 : 00100000
pin[3] on: 16 : 00010000
pin[4] on: 8 : 00001000
pin[5] on: 4 : 00000100
pin[6] on: 2 : 00000010
pin[7] on: 1 : 00000001
pin[0] on: 192 : 11000000
pin[1] on: 96 : 01100000
pin[2] on: 48 : 00110000
pin[3] on: 24 : 00011000
pin[4] on: 12 : 00001100
pin[5] on: 6 : 00000110
pin[6] on: 3 : 00000011

Using integer:
bit: i 0 : 1
bit: i 1 : 2
bit: i 2 : 4
bit: i 3 : 8
bit: i 4 : 16
bit: i 5 : 32
bit: i 6 : 64
bit: i 7 : 128
bit: i 0 : 3
bit: i 1 : 6
bit: i 2 : 12
bit: i 3 : 24
bit: i 4 : 48
bit: i 5 : 96
bit: i 6 : 192

The first part of the output shows the character array approach. The second part shows the results from shifting bits on an integer. The results show that the state of the bits is the same using either the character array method or the bit shift method.

 

public class BinaryOps {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int x=0;
//String pins = “00000000”;
char pins[] = {‘0′,’0′,’0′,’0′,’0′,’0′,’0′,’0′};

x = Integer.parseInt(“11111111”,2);
System.out.println (“All on: ” + x);

for (int i=0; i<8; i++ ) {
pins[i] =’1′;
if (i>0) {
pins[i-1] =’0’;
}
String s = String.valueOf(pins);
x = Integer.parseInt(s,2);
System.out.println (“pin[” + i + “] on: ” + x + ” : ” + s);
}
char pins2[] = {‘0′,’0′,’0′,’0′,’0′,’0′,’0′,’0′};

for (int i=0, ii=1; ii<8; i++,ii++ ) {
pins2[i] =’1′;
pins2[ii]=’1′;

if (i>0) {
pins2[i-1] =’0′;
//pins2[ii-1] =’0’;
}

String s = String.valueOf(pins2);
x = Integer.parseInt(s,2);
System.out.println (“pin[” + i + “] on: ” + x + ” : ” + s);
}
short bit=0;

for (short i=0; i<8; i++ ) {
bit = (short) (1 << i);
System.out.println (“bit: i ” + i + ” : “+ bit);
}

for (short i=0,ii=1; ii<8; i++ ,ii++) {
bit = (short) (1 << i);
bit += (short) (1 <<ii);
System.out.println (“bit: i ” + i + ” : “+ bit);
}
}

}