Sunday, January 8, 2012

DS1307 RTC with LED

A DSR1307RTC IC is a pretty cheap and accurate Real Time Clock that only needs a few components to work.

The 3 volt battery is necessary for time keeping when the 5V power supply is off. A CR battery will be sufficient to keep time for many many years.

The PWM pin is not really necessary, but it can be used to output a pulse of e.g. 1Hz that can be used to drive a LED that will be pulsing 1x per second. For this one must write a 0x10 (10 in HEX format, 16 in digital format, 00010000 in binary format) to register 07 (HEX).
//-----------
/*
 reading and writing to the Maxim DS1307 real time clock IC
 based on code by Maurice Ribble
 17-4-2008 - http://www.glacialwanderer.com/hobbyrobotics
 ---------------------------------------
 CONTROL REGISTER
 The DS1307 control register is used to control
 the operation of the SQW/OUT pin.

 BIT 7  BIT 6  BIT 5  BIT 4  BIT 3  BIT 2  BIT 1  BIT 0
 OUT     0      0     SQWE     0     0     RS1    RS0

 Bit 4: Square-Wave Enable (SQWE): This bit, when set to logic 1,
       enables the oscillator output. 
 ---------------------------------------
 Pin 5 (SDA) naar analoog4
 Pin 6 (SCL) naar analoog5
 */

#include "Wire.h"   // available in the Arduino files
#define DS1307_I2C_ADDRESS 0x68

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return ( (val/10*16) + (val%10) );
}

// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return ( (val/16*10) + (val%16) );
}

// 1) Sets the date and time on the ds1307
// 2) Starts the clock
// 3) Sets hour mode to 24 hour clock

// Assumes you're passing in valid numbers

void setDateDs1307(byte second,        // 0-59
byte minute,        // 0-59
byte hour,          // 1-23
byte dayOfWeek,     // 1-7
byte dayOfMonth,    // 1-28/29/30/31
byte month,         // 1-12
byte year)          // 0-99
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0);
  Wire.send(decToBcd(second));    // 0 to bit 7 starts the clock
  Wire.send(decToBcd(minute));
  Wire.send(decToBcd(hour));     
  Wire.send(decToBcd(dayOfWeek));
  Wire.send(decToBcd(dayOfMonth));
  Wire.send(decToBcd(month));
  Wire.send(decToBcd(year)); 
  Wire.endTransmission();
}

// Gets the date and time from the ds1307
void getDateDs1307(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
  // Reset the register pointer
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0);
  Wire.endTransmission();

  Wire.requestFrom(DS1307_I2C_ADDRESS, 7);

  // A few of these need masks because certain bits are control bits
  *second     = bcdToDec(Wire.receive() & 0x7f);
  *minute     = bcdToDec(Wire.receive());
  *hour       = bcdToDec(Wire.receive() & 0x3f);  // Need to change this if 12 hour am/pm
  *dayOfWeek  = bcdToDec(Wire.receive());
  *dayOfMonth = bcdToDec(Wire.receive());
  *month      = bcdToDec(Wire.receive());
  *year       = bcdToDec(Wire.receive());
}


// sqw is set here
void sqw1() // set to 1Hz
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0x07); // move pointer to SQW address
  Wire.send(0x10); //  sends 0x10 (hex) 00010000 (binary)
  Wire.endTransmission();
}
//-------------------



void setup()
{
  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  Wire.begin();
  Serial.begin(9600);

  // Change these values to what you want to set your clock to.
  // You probably only want to set your clock once and then remove
  // the setDateDs1307 call.

  second = 0;
  minute = 52;
  hour = 9;
  dayOfWeek = 7;
  dayOfMonth = 7;
  month = 1;
  year = 12;
// uncomment instruction below to set the time
// setDateDs1307(second, minute, hour, dayOfWeek, dayOfMonth, month, year);

//----------------------------
sqw1();  //switch on 1Hz SQW 
//-----------------------------
}

void loop()
{
  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

  getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  Serial.print(hour, DEC);// convert the byte variable to a decimal number when being displayed
  Serial.print(":");
  if (minute<10)
  {
      Serial.print("0");
  }
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second<10)
  {
      Serial.print("0");
  }
  Serial.print(second, DEC);
  Serial.print("  ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/");
  Serial.print(year, DEC);
  //Serial.print("  Day of week:");
  switch(dayOfWeek){
  case 1: 
    Serial.println(" Sunday");
    break;
  case 2: 
    Serial.println(" Monday");
    break;
  case 3: 
    Serial.println(" Tuesday");
    break;
  case 4: 
    Serial.println(" Wednesday");
    break;
  case 5: 
    Serial.println(" Thursday");
    break;
  case 6: 
    Serial.println(" Friday");
    break;
  case 7: 
    Serial.println(" Saturday");
    break;
  }
  //  Serial.println(dayOfWeek, DEC);
  delay(1000);
}

/* To access the RAM (65 bytes)
   void WriteRam(int address,byte data){
   Wire.beginTransmission(0x68);    // Select DS1307
   Wire.send(address+8);   // address location starts at 8, 0-6 are date, 7 is control
   Wire.send(data);        // send data
   Wire.endTransmission();
}
  
*/

/*
//12 hours:

void setDateDs1307
….
Wire.send(decToBcd(hour) | _BV(6)); // set bit 6 for 12 hour mode

void getDateDs1307:
….
*hour = bcdToDec(Wire.receive() & 0x1f); // mask output for 12 hour mode
*/
//----------
Below a program that will make the SQW/PWM pin flash at several frequencies (but your eyes won't see it at the higher frequencies)
/*
DS1307 Square-wave machine
 Used to demonstrate the four different square-wave outputs from Maxim DS1307
 See page nine of data sheet for more information
 John Boxall - tronixstuff.wordpress.com
 Register:
 OUT 0 0 SQWE 0 0 RS1 RS2
 */
#include "Wire.h"
#define DS1307_I2C_ADDRESS 0x68 // each I2C object has a unique bus address, the DS1307 is 0x68
void setup()
{
  Wire.begin();
}
void sqw1() // set to 1Hz
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0x07); // move pointer to SQW address
  Wire.send(0x10); //  sends 0x10 (hex) 00010000 (binary)
  Wire.endTransmission();
}
void sqw2() // set to 4.096 kHz
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0x07); // move pointer to SQW address
  Wire.send(0x11); //  sends 0x11 (hex) 00010001 (binary)
  Wire.endTransmission();
}
void sqw3() // set to 8.192 kHz
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0x07); // move pointer to SQW address
  Wire.send(0x12); // sends 0x12 (hex) 00010010 (binary)
  Wire.endTransmission();
}
void sqw4() // set to 32.768 kHz (the crystal frequency)
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0x07); // move pointer to SQW address
  Wire.send(0x13); // sends 0x13 (hex) 00010011 (binary)
  Wire.endTransmission();
}
void sqwOff()
// turns the SQW off
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0x07); // move pointer to SQW address
  Wire.send(0x00); // turns the SQW pin off
  Wire.endTransmission();
}
void loop()
{
  sqw1();
  delay(5000);
  sqw2();
  delay(5000);
  sqw3();
  delay(5000);
  sqw4();
  delay(5000);
  sqwOff();
  delay(5000);
}

Monday, June 20, 2011

Adding a Facebook social bookmark or 'Share' button to your blog

Adding a Facebook social bookmark (or 'Share') button to your blogger/blogspot blog is quite easy. Only involves two steps:
1: localize the place in your templates HTML where it should be
2: add code

ad 1: search in your HTML for  the following code







Ad 2: Once you found that, insert the following code beneat the section above.









This code 'Likes' a specific posting and not your entire blog.
The icon in this example is taken directly from the facebook website. This enables for quick testing of the code. When you have the code working, it is a better idea to download the icon, store it on yr own webspace and change the reference accordingly

Sunday, June 12, 2011

Slave Unit for Digital Camera with Pre-flash

Not specifically a program, but a Slave Unit for a Flash. The essence of this circuit is that it will ignore the preflash that many digital camera's have.

Friday, July 3, 2009

searching and updating a database

search.html is the search form. passes the data to dbsearch.php
dbsearch.php  searches the database and presents the found records. passes the records to view.php for viewing or editinfo.php to edit the record.
dbsearch.php takes the record Id, adds it to a link and passes it thus to the required programs.
For a full explanation of the programs editinfo and update info, check it’s source


---search.html-------
<body>     
<link href="style.css" type="text/css" rel="stylesheet" />     
<link rel="stylesheet" type="text/css" href="style.css" /> 
<form action="dbsearch.php" method="get">    
Keywoord uit Acteur of Titel: <input type="text" name="q" />     
<br>    
<input type="submit" />     
</form>     
<body> 
------dbsearch.php----------------
<?php     
    include 'db.php';    // Include the database     
    // Set the page, use one if the get page is not a number or is negative     
    if(!isset($_GET['page']) || !ctype_digit($_GET['page']))     
        $page = 1;     
    else     
        $page = $_GET['page'];     
    // Set the maximum number of results     
    $max = 10;     
    // Set the start location (when viewing the next page)     
    $limit = ($page * $max) - $max;     
    $q = trim(mysql_real_escape_string($_GET['q'])); // Make a safe string     
    // Make a query, (change "code" and "name" to your column names)     
    $query = "SELECT SQL_CALC_FOUND_ROWS *,     
            MATCH(Titel) AGAINST ('$q' IN BOOLEAN mode) AS score1,     
            MATCH(Acteur) AGAINST ('$q' IN BOOLEAN mode) AS score2     
            FROM DVD     
            WHERE  
            MATCH(Titel,Acteur) AGAINST ('$q' IN BOOLEAN mode)     
            ORDER BY score1 DESC, score2 DESC LIMIT $limit, $max";     
    // Perform the query     
    $sql = mysql_query($query); 
    // Find how many results would have been returned if there wasn't a limit     $result_count = mysql_query("SELECT FOUND_ROWS()")or die(mysql_error());     // Get the number     $total = mysql_fetch_array($result_count);     // Search the array for the total     $totalrows = $total[0];     // Calculate the number of pages, if it is a decimal, then there are     // more reusults, but that number is less than our $max (total number of results     // to display on the page)     $pages = ceil($totalrows / $max);     // Display the results...     if(mysql_num_rows($sql) > 0){         echo '<p>Found <b>'.$totalrows.'</b> results for <b>"'.htmlentities($_GET['q']).'"</b></p>';         $i = $limit + 1;         while($row = mysql_fetch_array($sql)){             echo '<p>'.$i.'. <a href="view.php?id='.$row['x'].'">'.$row['Titel'].'</a>';             echo ' <b ><a href="editinfo.php?id='.$row['x'].'">Edit Data</a></b></p>';             $i++;         }     }else{         // No results were found         echo '<h2>No Results Found!</h2>';     }     // Display the page numbers (if there is more than one page)     if($pages > 1){         echo '<div style="padding:10px;">';             for($i = 1;$i<$pages+1;$i++){                 if($i == $page)                     echo '<span class="page" style="padding:10px;">'.$i.'</span>';                 else                     echo '<a style="padding:10px;" href="'.$_SERVER['PHP_SELF'].'?q='.$_GET['q'].'&amp;page='.$i.'">'.$i.'</a>';             }             echo '<span style="clear:both;display:block;font-size:1px;">&nbsp;</span>';         echo '</div>';     } // Sluit de database echo mysql_error(); mysql_close($db); ?>
-------view.php-------------------------
<?     
$id = trim(mysql_real_escape_string($_GET['id'])); // Make a safe string     
//echo $id;     
include 'db.php';    // Include the database     
$query=("SELECT * FROM DVD WHERE x=$id ORDER BY Titel ASC ")  or die (mysql_error());     
//echo $query;     
$result=mysql_query($query);     
//echo $result;     
$row = mysql_fetch_array($result);     
$x= $row[0];     
$titel= $row[1];     
$acteur = $row[2];     
$taal= $row[3];     
$jaar= $row[4];     
$imdb = $row[5];     
$summary=$row[6];     
$foto=$row[7];     
?> 
<div class="example1">    
<?php     
echo '<b>';     
echo $titel;     
echo '</b><br /><em>';     
echo $acteur;     
echo '</em><br />';     
echo $taal;     
echo '<br />';     
echo $jaar;     
echo '<br />';     
echo "<a href='{$row['IMDB']}'>$titel at imdb</a>";     
echo '<br />';     
echo $summary;     
echo '<br />';     
echo "<img src='{$row['Foto']}' >"; 
// Sluit de database    
echo mysql_error();     
mysql_close($db); 
?>    
</div> 
-------------- editinfo.php---------
This file is a slight alteration from the file found Here
<?php    
$id = trim(mysql_real_escape_string($_GET['id'])); // Make a safe string     
//replace usernaem,password, and yourdb with the information for your database     
mysql_connect("localhost","zz","zz") or die("Error: ".mysqlerror());     
mysql_select_db("DVD"); 
//replace TestTable with the name of your table    
//also in a real app you would get the id dynamically     
$sql = "select * from `DVD` where x = $id";     
$query = mysql_query($sql); 
while ($row = mysql_fetch_array($query)){ 
    $id = $row['x'];    
    $titel = $row['Titel'];     
    $acteur = $row['Acteur'];  
    $taal = $row['Taal'];     
    $jaar = $row['Jaar'];     
    $imdb = $row['IMDB'];  
    $summary =  $row['Summary'];     
    $foto = $row['Foto']; 
    //we will echo these into the proper fields 
}    
mysql_free_result($query);     
?> 
<html>    
<head>     
<title>Edit DVD Info</title>     
</head> 
<body> 
<form action="updateinfo.php" method="post"> 
id:<br/>    
<input type="text" value="<?php echo $id;?>" name="x" disabled />     
<input type="hidden" value="<?php echo $id;?>" name="x"  />     
<br/> 
-------------updateinfo.php-----------
see here for full description
Titel:<br/>     
<input type="text" value="<?php echo $titel;?>" name="Titel" size=60/> 
<br/> 
Acteur:<br/>    
<input type="text" value="<?php echo $acteur;?>" name="Acteur" size=60/> 
<br/> 
Taal:<br/>    
<input type="text" value="<?php echo $taal;?>" name="Taal"/> 
<br/> 
Jaar:<br/>    
<input type="text" value="<?php echo $jaar;?>" name="Jaar" size=10/> 
<br/> 
IMDB:<br/>    
<input type="text" value="<?php echo $imdb;?>" name="IMDB" size=38/> 
<br/>    
Summary:<br/>     

<TEXTAREA NAME="Summary"  ROWS=6 COLS=45>     
<?php echo $summary;?>     
</TEXTAREA>     
<br/> 
Foto locatie:<br/>    
<input type="text" value="<?php echo $foto;?>" name="Foto" size=59/> 
</br> 
<input type="submit" value="submit changes"/> 
</form>    
</body>     
</html>

Sunday, June 7, 2009

Rename file if exists in PHP

function rename_if_exists($dir, $filename) {
    $ext = strrchr($filename, '.');
    $prefix = substr($filename, 0, -strlen($ext));
    $i = 0;
    while(file_exists($dir . $filename)) { // If file exists, add a number to it.
        $filename = $prefix . ++$i . $ext;
    }

    return $filename;
}

Download youtube video’s with PHP

<?
//example string for the function
get_youtube_download_link("http://www.youtube.com/watch?v=8yOa-7fHNwo&feature=rec-HM-r2");

function str_between($string, $start, $end){ $string = " ".$string;
$ini = strpos($string,$start); if ($ini == 0) return ""; $ini +=
strlen($start); $len = strpos($string,$end,$ini) - $ini; return
substr($string,$ini,$len); }
function get_youtube_download_link($url){
if( $url !== "")
{
$youtube_link = $url;
//$url = get_post_meta($post->ID, 'url', true);
if ( file_get_contents($youtube_link) !== "")
{
$youtube_page = file_get_contents($youtube_link);
$v_id = str_between($youtube_page, "&video_id=", "&");
$t_id = str_between($youtube_page, "&t=", "&");
$flv_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id";
$hq_flv_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=6";
$mp4_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=18";
$threegp_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=17";
echo "\t\tDownload (right-click &gt; save as)&#58;\n\t\t";
echo "<a href=\"$flv_link\">FLV</a>\n\t\t";
echo "<a href=\"$hq_flv_link\">HQ FLV (if available)</a>\n\t\t";
echo "<a href=\"$mp4_link\">MP4</a>\n\t\t";
echo "<a href=\"$threegp_link\">3GP</a><br><br>\n";
}
}
}
?>

Show the last x number of posts on Wordpress in PHP

This code shows the last x-number of posts (15 in this example) in your wordpress blog. Make sure you put in the proper directory in the ‘require()’  string. This code can be on a completely seperate page, fully outside of wordpress

<?php
// Include Wordpress
define('WP_USE_THEMES', false);
require('./wordpress/wp-blog-header.php');
query_posts('showposts=15');
?>

<ul>
<?php while (have_posts()): the_post(); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>