2013/05/03

LCD Displaying Date, Time From DS1307 And Temperature From LM35

Date and time is useful for many applications. Most visitors to my blog search for rtc stuff. The following sketch show a simple application using a LCD shield, a RTC Sensor shield and a LM35 temperature sensor to display date, time and enviromnental temperature. To use the sketch, you need to download the RTClib library.

There is a new version using Time.h library and showing weekday.

Output:


Sketch:

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
// 2010-02-04 <jcw@equi4.com> http://opensource.org/licenses/mit-license.php
// $Id: ds1307.pde 4773 2010-02-04 14:09:18Z jcw $
// Added LCD display and LM35 temperature function by Befun Hung 2011-10-13
// Take out displayDateTime procedure from loop() by Befun Hung 2013-05-03
// The sketch works on Arduino IDE 0022

#include <Wire.h>
#include <RTClib.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

RTC_DS1307 RTC;
// change potPin value to 0, 1, 2 for A0, A1, A2 respectly
int potPin = 3;
float temperature = 0;

void setup () {
    Serial.begin(9600);
    Wire.begin();
    RTC.begin();
    lcd.begin(16, 2);
    lcd.print("*cheaphousetek*");
    delay(5000);
    lcd.clear();
    
    // following line sets the RTC to the date & time this sketch was compiled
    // RTC.adjust(DateTime(__DATE__, __TIME__));
}

void loop() {
  displayDateTime();
}

void printTenths(long value) {
  // prints a value of 123 as 12.3
  Serial.print(value / 10);
  Serial.print('.');
  Serial.print(value % 10);
  Serial.println();
  lcd.setCursor(10, 1);
  lcd.print(value / 10);
  lcd.setCursor(12, 1);
  lcd.print('.');
  lcd.setCursor(13, 1);
  lcd.print(value % 10);
}

void displayDateTime() {
    DateTime now = RTC.now();
    int span = 10;
    long aRead = 0;
    unsigned long tmp;
      
    tmp = now.year();
    Serial.print(now.year(), DEC);
    lcd.setCursor(0, 0);
    lcd.print(tmp);
    Serial.print('/');
    lcd.setCursor(4, 0);
    lcd.print("-");
    
    tmp = now.month();
    if (now.month() < 10) {
      Serial.print('0');
      Serial.print(now.month(), DEC);
      lcd.setCursor(5, 0);
      lcd.print('0');
      lcd.setCursor(6, 0);
      lcd.print(tmp);
    }
    else {
      Serial.print(now.month(), DEC);
      lcd.setCursor(5, 0);
      lcd.print(tmp);
    }
    Serial.print('/');
    lcd.setCursor(7, 0);
    lcd.print('-');
    
    tmp = now.day();
    if (now.day() < 10) {
      Serial.print('0');
      Serial.print(now.day());
      lcd.setCursor(8, 0);
      lcd.print('0');
      lcd.setCursor(9, 0);
      lcd.print(tmp);
    }
    else {
      Serial.print(now.day(), DEC);
      lcd.setCursor(8, 0);
      lcd.print(tmp);
    }
    Serial.print(' ');
    
    tmp = now.hour();
    if (now.hour() < 10) {
      Serial.print('0');
      Serial.print(now.hour(), DEC);
      lcd.setCursor(0, 1);
      lcd.print('0');
      lcd.setCursor(1, 1);
      lcd.print(tmp);
    }
    else {
      Serial.print(now.hour(), DEC);
      lcd.setCursor(0, 1);
      lcd.print(tmp);
    }
    Serial.print(':');
    lcd.setCursor(2, 1);
    lcd.print(':');
    
    tmp = now.minute();
    if (now.minute() < 10) {
      Serial.print('0');
      Serial.print(now.minute(), DEC);
      lcd.setCursor(3, 1);
      lcd.print('0');
      lcd.setCursor(4, 1);
      lcd.print(tmp);
    }
    else {
      Serial.print(now.minute(), DEC);
      lcd.setCursor(3, 1);
      lcd.print(tmp);
    }
    Serial.print(':');
    lcd.setCursor(5, 1);
    lcd.print(':');
    
    tmp = now.second();
    if (now.second() < 10) {
      Serial.print('0');
      Serial.print(now.second(), DEC);
      lcd.setCursor(6, 1);
      lcd.print('0');
      lcd.setCursor(7, 1);
      lcd.print(tmp);
    }
    else {
      Serial.print(now.second(), DEC);
      lcd.setCursor(6, 1);
      lcd.print(tmp);
    }
    Serial.print (' ');
    lcd.setCursor(8, 1);
    lcd.print(' ');
    // Serial.println();
    
    for (int i=0;i<span;i++) {
      aRead = aRead + analogRead(potPin);
      // Serial.print(aRead);
      // Serial.print(' ');
    }
    // aRead = aRead / span;
    temperature = (aRead / span * 500.0 / 1024.0);
    // Serial.print(aRead);
    // Serial.print(' ');
    // Serial.print(temperature);
    // Serial.print(' ');
    printTenths(long (temperature * 10));
    lcd.setCursor(14, 1);
    lcd.print(char(223));
    lcd.setCursor(15, 1);
    lcd.print('C');
        
    delay(200);
    
    // Serial.print(" since 2000 = ");
    // Serial.print(now.get());
    // Serial.print("s = ");
    // Serial.print(now.get() / 86400L);
    // Serial.println("d");
    
    // calculate a date which is 7 days and 30 seconds into the future
    // DateTime future (now.get() + 7 * 86400L + 30);
    
    // Serial.print(" now + 7d + 30s: ");
    // Serial.print(future.year(), DEC);
    // Serial.print('/');
    // Serial.print(future.month(), DEC);
    // Serial.print('/');
    // Serial.print(future.day(), DEC);
    // Serial.print(' ');
    // Serial.print(future.hour(), DEC);
    // Serial.print(':');
    // Serial.print(future.minute(), DEC);
    // Serial.print(':');
    // Serial.print(future.second(), DEC);
    // Serial.println();
    
    // Serial.println();
    // delay(3000);
}

2013/04/26

HC-05 Bluetooth Module AT Mode Using FTDI USB To TTL Converter and Arduino Serial Monitor


The easiest way to configure the HC-05 Bluetooth Module using AT command, is by using a USB to TTL converter.

The HC-05 Bluetooth Module (with factory default baud rate 9600, 8, N, 1 and is set as slave) used:



The USB to TTL Converter used:



Only 4 pins on the HC-05 Bluetooth Module are used with connections to FTDI USB to TTL Converter.

HC-05.VCC - FTDI.VCC
HC-05.GND - FTDI.GND
HC-05.RX - FTDI.RXI
HC-05.TX - FTDI.TXO

To enter the AT mode, follow the procedure listed.

Step 1: Plug the FTDI USB To TTL Converter (with connections to HC-05 Bluetooth Module listed above)  to the USB Socket on Computer. The led on the HC-05 Bluetooth Module will flash quickly at about 2Hz.

Step 2: Short the HC-05.VCC and HC-05.KEY pins for a short time (touch and seprate) to set
the HC-05 in AT Mode. The led flash as quickly as ever.

Step 3: Open Arduino IDE Serial Monitor. Set baud rate to 9600 and select "Both NL & CR".

Step 4: Type AT, press "Enter" on keyboard or click "Send" icon on Serial Monitor. The "OK" response should be displayed.


2013/03/31

Freeduino/Arduino Ultrasonic Ranger HC-SR04 with LCD Shield

HC-SR04 is inexpensive and practical, use Arduino with LCD Keypad Shield, you can make a standalone rangefinder device ranging 2cm to 400cm.

Connections:

VCC--5V
GND--GND
Trig--D2
Echo--D3

Output:



Code:


/* HC-SR04 Sensor

   This sketch reads a device ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.
   
   The circuit:
      * +V connection of thj device attached to +5V
      * GND connection of the device attached to ground
      * SIG connection of the device attached to digital pin 7
   
   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Jun 2009
   by Tom Igoe
   Added on Mar. 31, 2013 by Befun Hung to fit pins of cheaphousetek LCD Keypad Shield

   This example code is in the public domain.

*/

#include <LiquidCrystal.h>               // include LiquidCrystal library
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);     // modified to fit cheaphousetek LcdKeypad Shield

// this constant won't change.  It's the pin number
// of the sensor's input and output:
const int triggerPin = 2;
const int echoPin = 3;

void setup() {
  // initialize serial communication. We are going to watch our progress in the monitor
  Serial.begin(9600);
  lcd.begin(16, 2);
  // lcd.clear();
  lcd.print("testing...");
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The device is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(triggerPin, OUTPUT);
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(triggerPin, LOW);

  // The echo pin is used to read the signal from the device: a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(inches);
  lcd.print("in, ");
  lcd.print(cm);
  lcd.print("cm");

  delay(1000);
}

long microsecondsToInches(long microseconds)
{
  // ***  THIS NEEDS TO BE CHECKED FOR THE HC-SR04  ***
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // ***  THIS NEEDS TO BE CHECKED FOR THE HC-SR04  ***
  return microseconds / 29 / 2;
}

2013/01/31

Freeduino/Arduino LCD IR Decoder

Output:

Code:

/*

 * LCDIRDecoder.pde: Freeduino/Arduino + cheaphousetek LCDKeypad Shield + IR Reveiver Breakout 
 * Ken Shirriff's IRremote.h page 
 * Original from Cooper Maa 
 * Modified on Jan. 31, 2013 by Befun Hung to fit pins of cheaphousetek LCD Keypad Shield
 */

#include <LiquidCrystal.h>               // include LiquidCrystal library
#include <IRremote.h>                    // include IRRemote library

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);     // modified to fit cheaphousetek LcdKeypad Shield

const int irReceiverPin = 2;             // IR Breakout Output Pin: Digital 2

IRrecv irrecv(irReceiverPin);            // define IRrecv object to receive IR singal
decode_results results;                  // decoded result is stored to variable rusult of struct decode_results

void setup() {
  lcd.begin(16, 2);                      // set numbers of rows and columns of LCD 
  lcd.print("IR Decoder");               // print "IR Decoder" message on LCD

  irrecv.blink13(true);                  // blinking pin 13 lcd on receiving IR singal
  irrecv.enableIRIn();                   // start IR decode    
}

// display IR protocol
void showIRProtocol(decode_results *results) 
{
  // judge IR protocol
  switch(results->decode_type) {
   case NEC:
     lcd.print("NEC");
     break;
   case SONY:
     lcd.print("SONY");
     break;
   case RC5:
     lcd.print("RC5");
     break;
   case RC6:
     lcd.print("RC6");
     break;
   default:
     lcd.print("Unknown");  
  }  

  // print IR code on LCD
  lcd.print(" ");
  lcd.print(results->value, HEX);        // IR code
  lcd.print(" (");
  lcd.print(results->bits);              // bytes of IR code    
  lcd.print(")");
}

void loop() {
  // set cursor to column 0, line 1
  // Note: line 1 is the second row,line 0 is the first row
  lcd.setCursor(0, 1);

  if (irrecv.decode(&results)) {         // successful decode, receiving a set of IR singal
    showIRProtocol(&results);            // display IR protocol
    irrecv.resume();                     // continue to receive the next IR singal        
  }    
}

2012/12/21

Rikomagic MK802IIIs Now Available at Taipei, Taiwan


The new MK802 IIIs is still a tiny computer with a USB port on one end, an HDMI adapter on the other, and a Rockchip RK3066 dual core process in the middle.

But the new model adds two new features: Bluetooth support, an ESD circuit for better stability, and support for software apps that let you actually turn off the little computer without unplugging it.



The MK802IIIs with 8 Gb memory now is available at 4F, Guanghua Digital Plaza, Taipei, Taiwan.

Update: Also avalable at Jianguo 2nd Rd.,Kaohsiung City, Taiwan since Dec. 29, 2012

2012/11/16

Freeduino/Arduino Web Controlled (Configured) Automatic Switches

Inspired by Freeduino/Arduino Web Sensors And Switches on cheaphousetek blog on Oct. 20, 2012, go a step forward, automatically controll the switches by setting the sensors criteria. It comes out the sketch at the bottom of this post.
By setting the lower limits, upper limits and switch on/off using a browser, one can monitor the conditions of all switches  remotely.
To control the web server outside the local area network, the NAT function of IP router should be enabled. To secure your web server, the SSH or VNC connection should be established.

Pins Used

Sensors: A2, A3
Switches: D2, D3, D4, D5, D6, D7, D8, D9

Output


Sketch


// Freeduino/Arduino Web Controlled Automatic Switches version 1.0
// By Befun Hung on Nov. 16 2012
// Modified From Freeduino/Arduino Web Sensors And Switches At cheaphousetek Blog 
// The Sketch Works On Arduino IDE 1.02

#include <Ethernet.h>
#include <SPI.h>
//network NB: Pins 10, 11, 12 and 13 are reserved for Ethernet module. 
#define sensorPinStart 2
#define noOfSensors 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[] = { 255, 255, 255, 0 };
String inString = String(100);
String minValue, maxValue;
int defaultMinValue[] = {55, 56, 57, 58, 59, 60, 61, 62, 63};
int defaultMaxValue[] = {60, 61, 62, 63, 64, 65, 66, 67, 68};
String defaultOnValue[] = {"Low", "Low", "Low", "Low", "Low", "Low", "Low", "Low", "Low"};
String Led;
int led[] = {00, 2, 3, 4 ,5 ,6 ,7 ,8 ,9  }; //pin num 0 in arry is not used
int numofleds = 8; //number of switches
String value[] = {"off","off","off","off","off","off","off","off","off"}; //startup all led are off
EthernetServer server(80);

void setup()
{
  delay(250); 
  Serial.begin(9600);
  Ethernet.begin(mac, ip,gateway,subnet); 
  server.begin();
  //set pin mode
  for (int j = 1; j < (numofleds + 1); j++)
  {
    pinMode(led[j], OUTPUT);
  }
  Serial.println("Serial READY");
  Serial.println("Ethernet READY");
  Serial.println("Server READY");
}

void loop()
{
  EthernetClient client = server.available();  
  if (client)
  {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    while (client.connected()) 
    {     
      if (client.available()) 
      {      
        char c = client.read();
        // if we've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so we can send a reply
        if (inString.length() < 35) 
        {
          inString.concat(c);
        } 
        if (c == '\n' && current_line_is_blank) 
        {                    
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<html>");
          client.println("<meta http-equiv=\"refresh\" content=\"5\">");
          client.println("<body><form method=get>");
          client.println("<center><p><h1>Freeduino/Arduino Web Controlled Automatic Switches</h1></p><hr></center>"); 
          client.println("<h2>");
          // Sensor Reading and Setting -----------------------------------------------------------------------------
          client.println("Sensor Reading And Setting:<br>");
          for (int analogChannel = sensorPinStart ; analogChannel < sensorPinStart+noOfSensors ; analogChannel++)
          {
            minValue = String("Low") + analogChannel;
            // fixValue = String("Fix") + analogChannel;
            maxValue = String("High") + analogChannel;
            Led = String("RelayOn") + analogChannel;
            int sensorReading = analogRead(analogChannel);
            
            if (inString.indexOf(minValue+"=Dn") > 0) defaultMinValue[analogChannel] -= 1;
            if (inString.indexOf(minValue+"=Up") > 0) defaultMinValue[analogChannel] += 1;
            if (inString.indexOf(maxValue+"=Dn") > 0) defaultMaxValue[analogChannel] -= 1;
            if (inString.indexOf(maxValue+"=Up") > 0) defaultMaxValue[analogChannel] += 1; 
            if (inString.indexOf(Led+"=High") > 0)    defaultOnValue[analogChannel] = "Low";
            if (inString.indexOf(Led+"=Low") > 0)     defaultOnValue[analogChannel] = "High";
            client.print("Input A");
            client.print(analogChannel);
            client.print(":");
            client.print(sensorReading);
            client.print("  Low");
            // client.print(analogChannel);
            client.print(":");
            client.print(defaultMinValue[analogChannel]);
            client.print("<input type=submit name="+minValue+" value=Dn><input type=submit name="+minValue+" value=Fix><input type=submit name="+minValue+" value=Up>");
            client.print("  High");
            // client.print(analogChannel);
            client.print(":");
            client.print(defaultMaxValue[analogChannel]);
            client.print("<input type=submit name="+maxValue+" value=Dn><input type=submit name="+maxValue+" value=Fix><input type=submit name="+maxValue+" value=Up>");
            client.print("  On");
            // client.print(analogChannel);
            client.print(":");
            client.print("<input type=submit name="+Led+" value="+defaultOnValue[analogChannel]+">");
            client.println("<br>");
          }
          // Switch Monitoring -------------------------------------------------------------------------------------------
          client.println("<p></p>Switches Status:<br>"); 
          for (int i=1; i < (noOfSensors+1) ; i++)
          { 
            Led = String("Switch") + i;
            int sensorReading = analogRead(sensorPinStart+i-1);
            if ((sensorReading > defaultMaxValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "High")) {
              digitalWrite(led[i], HIGH);
              value[i] = "on";
            }
            if ((sensorReading < defaultMinValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "High")) {
              digitalWrite(led[i], LOW);
              value[i] = "off";
            }
            if ((sensorReading < defaultMinValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "Low")) {
              digitalWrite(led[i], HIGH);
              value[i] = "on";
            }
            if ((sensorReading > defaultMaxValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "Low")) {
              digitalWrite(led[i], LOW);
              value[i] = "off";
            }
            client.println(Led+"  <input type=submit name="+Led+" value="+value[i]+">"+"<br>");
          }
          client.println("</form><hr></h2>");
          client.println("<center>The web page will automatically refresh every 5 seconds.</center>");
          client.println("</html></body>");
          break;
        }
        if (c == '\n') 
        {
          // we're starting a new line
          current_line_is_blank = true;
        } 
        else if (c != '\r') 
        {
          // we've gotten a character on the current line
          current_line_is_blank = false;
        }
      }  // End of if (client.available)
    }  // End of while (client.connected())
    // give the web browser time to receive the data
    delay(1);
    inString = "";
    client.stop();
  } //End of if (client)
}

2012/11/14

GlobalSat EM-411 GPS Module Test Sketch Using Arduino 0022

Once buying an GPS module, the first idea is to check whether the module works as expect. To check the module using Arduino, first connecting the module and Arduino Uno/Duemilanove, then using the following sketch running on Arduino IDE 0022 (should also run on 0023 but not tested). The sketch should work for other GPS module, because GPS module usually need only VCC, GND to run and additional TX and RX to transmit/recive data.
As soon as checked the connections and powering the Arduino Uno/Duemilanove , one can monitor the NMEA sentenc output using Arduino serial monitor or any terminal emulator such as Putty. For me, I use SSCOM to test GPS and bluetooth modules on Windows XP.

Pin Used And Connection

Arduino - GPS Module
5V - Pin2(VIN)
GND - Pin1(GND) and Pin5(GND)
D2(SoftwareSerial RX) - Pin3(TX)
D3(SoftwareSerial TX) - Pin4(RX)

Output


Sketch 

// Test Code for GlobalSat EM-411 GPS Modules 
// Arduino 0022 Has Built-in SoftwareSerial.h Library
// Download the Library is not Needed
// The sketch works on Arduino IDE 0022

#include <SoftwareSerial.h>
SoftwareSerial GPS = SoftwareSerial(2, 3);

void setup()  
{
  Serial.begin(9600);
  Serial.println("GlobatSat EM-411 GPS Module NMEA Sentence Test!");

  // EM-411 factory default baud rate is 4800, the module used has been changed the baud rate
  GPS.begin(9600);
}

void loop()  // whatever read from GPS, sent to Arduino serial monitor or terminal emulator
{
  Serial.print(GPS.read(), BYTE);
}