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);

}