Thursday, December 27, 2012

Mini Wireless Keyboard/Touchpad and Nano USB Wifi Adaptor that works with Raspberry Pi


As part of my Christmas presents I got a couple of bits to go with my Raspberry Pi.
As I sometimes take the Raspberry Pi out and about I wanted a mini wireless keyboard/touchpad to pack in my box of wires.
I heard good things about the Rii 2.4GHz Wireless Mini PC Keyboard Touchpad so added it to my wish list. I plugged in the dongle to the Raspberry Pi, turned on the keyboard and it worked first time. No problems at all.  I read some comments that the range is very short. I'm getting about 3 metres from it as I haven't tested any further.  Very happy. Keys are big enough for me to use comfortably and the main keys are all in the expected places.  It also has a laser pointer built in if needed.
Also, the extra function keys beyond [F8] are at [FN],1,2,3,4 so you do get the full 12 functions keys but only the first 8 are shown.
The one I received was in a plain white box.

I also got the Edimax EW-7811UN Wireless 802.11b/g/n 150Mbps Nano USB Adaptor.
Using Raspbian it worked first time with no additional drivers required.

With the 2 of these plugged in I have a full functioning compact computer with only the power and HDMI coming from it.

So, when I'm logging in remotely using Xming and Putty I can put the Raspberry Pi where ever there is a spare socket and work away.

I also got  the beautiful Pibow Colour Raspberry Pi Case.  and the Adafruit Pi Cobbler Breakout Kit. So, very happy with the presents.





Note: Links are to Amazon UK stores where mine came from.  My wife has learned that the best thing is for me to email her actual links rather than having me expect her to known what I'm looking for.
One year a link went from being a processor to a couple of wires. luckily she checked with me before buying.





Friday, December 21, 2012

Learning Scratch for CodeClub


I've signed up to run a CodeClub at my kids school from  January.
Before I received the official course work I thought it might be a good idea to actually try and make something with Scratch. So, I put together a simplistic shooter.

You can see it and download it from the Scratch Site.
Dragon vs The Ghosts
http://scratch.mit.edu/projects/winkleink/2847788


You can play the game in a browser as well if you don't want to install Scratch.

The game took about 2 to 3 hours to make using the built in graphics and sounds. With most of that time me just figuring out how to use Scratch.  For those who have experienced Scratch before I'd expect a game like this would take less than 30 minutes.

Also, I just saw that Scratch 2.0 is going into public beta on the 28th of January and that the Raspberry Pi Foundation are supporting work to improve Scratch's performance on the Raspberry Pi.
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=77&t=26361

It's looking good for Scratch.

Sunday, November 25, 2012

Great Day at Milton Keynes Raspberry Jam (25th Nov)

Today was the 4th Raspberry Jam at Milton Keynes today and it was another great event.  I brought along my simple Raspberry Pi controlling an Arduino over the network (more later)

Best of all I got to see some brilliant projects.

There was Daniel Bull's BerryIO a fantastic web interface for controlling the GPIO pins on the Raspberry Pi.  Not only is BerryIO functional but the interface is gorgeous. Ideal for an event at the National Museum of Computing with it's switches and lights..  Daniel had a problem with the wifi at the Museum,but luckily after the last visit I had brought along an old wifi router to act as a wifi/Ethernet switch. So, Daniel got to use the network to get the BerryIO working.  It was really interesting to see how it worked and has inspired me to see if I can improve the quality of my own web interface.

There is a great video on raspi.tv showing off BerryIO - go check it out


Next to BerryIO was a project by raspi.tv (I think it was Alex) where he was using a Raspberry Pi to control 2 relays to turn on/off a light and fan.  Light if it got dark and fan if it got hot being expertly  demonstrated by (I assume) his son.
Again, there is a great write up on raspi.tv with a video


There was also a Raspberry running RISC OS. I was amazed how fast it is and how responsive it is.  Hopefully, somebody way more capable than me will have some fun with it. I'm really looking forward to seeing what's possible.

The final project I took peek at appeared to be a project after my own heart as it was Arduino MIDI interface.  I didn't get a chance to talk the person who brought it along but it looked really cool and maybe if I see it again I'll find out what the knobs and buttons on the little red board do.




In amongst these great projects I set up my Raspberry Pi and Arduino with the Linksys router in a corner.  This time I brought an extension lead which was lucky as I only had 1 socket for 3 plug.
This is a revised version of the Arduino + ENC28J60 project I posted about before but using an ebay purhcaed W5100 based shield so I could use the official library from the Arduino people.  Others may disagree but to me the W5100 board may cost a little more but the time saved unless you know the ENC28J60 board inside out is well worth it. Especially as the generic versions of the W5100 board are not available.
I got mine on ebay.co.uk from EachDesk, so you can search their store for the board.  It was delivered in a few weeks from Hong Kong.  The current list for the W5100 shield costs less than £7.00.
The ENC28J60 boards are on ebay.co.uk for as little as £3.19 so yes, less than half price, but really it's only £4 more expensive for a whole lot of reduced grief.

My project allows you to control as many Arduino as you want over Ethernet/Internet from a web server running on a Raspberry Pi.
On the Raspberry Pi is a LAMP server with an entry in the mySQL database for each Arduino and then for each pin on the Arduinos that you wish to control or read.
The Raspberry Pi presents a simple web interface with switches to switch on and off the pins on the Arduino.  When you click [ON] a GET statement is called from the Raspberry Pi to the Arduino using fopen in PHP.  The Arduino has a web server running on and when it receives the request it interprets the GET command to find out which pin is being actioned and what to do with it.
Then the Pin is either set HIGH or LOW depending on the request.

For today I also set it up to read 2 of the Analogue pins. 1 with a rotary pot on it
and the other with an Light Dependent Resistor (LDR).

Giving the ability to turn on/off 3 LEDs and read the values for the pot and the LDR through the web interface.

After the command is actioned the Arduino then sends back a web page with the status of the Digital Pins and the Analogue Pins.

The Raspberry Pi then interprets this page and compares it to the pins being controlled based on the database entries.  It updates the interface so that only the Pins listed in the database  that are High (On) have the option to be set Low (Off). With the unused pins not presented.  What this means is that the Sketch on the Arduino is generic and the specific pins  controlled is defined by the database and not the Sketch.

My next steps are to add a little bit of security as at present if you know the IP address of the Arduino you can control the pins directly when my goal is that you have to use the web interface.

I also need to update the database scheme and the PHP page to better manage the analogue inputs and also use the PWM lines.  This will mean the Arduino code would have to be modified so the digital pins being used for PWM can be defined but I think this is a small price to pay for the ability to take full advantage of the Arduino's capability.

After the Jam some of us got a private guide to the WITCH - the oldest working computer.  BBC piece and videowikipedia article. It's a 10 bit computer using dekatron based memory, rather than relays or core storage.  This was the first time I'd heard of dekatrons, so that alone was interesting.




This was another wonderful Jam and I'm looking forward to attending more. if you're interested in the Raspberry Pi or just seeing fun projects then definitely find a Jam to go along to or if there isn't one in your area see if you can arrange one.



Tuesday, October 30, 2012

Attended 3rd Milton Keynes Raspberry Jam


The 3rd Milton Keynes Raspberry Jam was on Sunday and I really enjoyed it.
It was held at the National Museum of Computer in Bletchley Park.

There were about 30 people there showing off different Raspberry Pi projects.
I cobbled together a Raspberry Pi running as a web server controlling an Arduino over Ethernet.
The bits weren't even set up when I started to get questions about what it was and how it worked.
It was fun discussion the bits that worked and also some ideas for enhancements.

Peter Onion did a tuition on soldering.  It was great to get some pointers on how to solder properly. Up until now I've stuck with breadboarding most of my projects, but the plan is to start at least moving to strip boards.

The next Milton Keynes Raspberry Jam is on the 25th of November and fingers crossed I'll get back for another entertaining morning.




Wednesday, September 19, 2012

Just received a W5100 Ethershield



Look what just arrived in the post.
Christmas last I got a ENC28J60 Ethernet socket and I've been playing with that a bit thinking that doing Ethernet with Arduino is just plain hard.
A few people recommended I get a W5100 based board so I could use the official Ethernet library.  When I had a look at the difference between the code it was clear the W5100 based boards are so much easier to code for as the library is more robust and easier to use.
So, I bought one on Ebay from China for about £7.50-inc postage so a big difference to the £30 for the official shield.  The ENC28J60 boards are still cheaper at about £5.00 but the difference is so small now that I have a felling the W5100 boards are now a good low cost option.

Now I have to modify my web server controlled Arduino code tonight to work with the shield.  All the fun.

NOTE: Image links to UK Ebay listing I used.  Delivered in about 3 weeks.  Packed in a Jiffy Bag.  

Tuesday, September 18, 2012

Controlling multiple Arduinos from a webserver with the details stored in a mySQL database using ENC28J60 network adaptor


See previous post for original details and code for the Arduino.

Following the last tinkering session I finally got a chance to look at the webserver side.
On my XAMPP install I enabled mySQL
Created a Database - arduinolist
Created 2 tables - alist (list of the Arduinos) and apin (pins used on each Arduino)

Used mySqlAdmin to enter some data to test it

Code to create the Arduino List Table

CREATE TABLE IF NOT EXISTS `alist` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Arduino` varchar(17) NOT NULL,
  `Active` int(11) NOT NULL,
  `aname` varchar(200) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Code to insert the entry for the Arduino


INSERT INTO `alist` (`ID`, `Arduino`, `Active`, `aname`) VALUES
(1, '192.168.1.205', 1, '1st Arduino'),
(2, '192.158.1.205', 1, '2nd Arduino');

Code to create the table for the pins used per Arduino

CREATE TABLE IF NOT EXISTS `apin` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `pinName` varchar(200) NOT NULL,
  `alistID` int(11) NOT NULL,
  `pin` int(11) NOT NULL,
  `active` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;


Code to enter the details for the 2 pins I am using

INSERT INTO `apin` (`ID`, `pinName`, `alistID`, `pin`, `active`) VALUES
(1, 'Pin 2', 1, 2, 1),
(2, 'Pin 4', 1, 4, 1)

(3, 'Pin 4 on Arduino 2', 2, 4, 1);

From above this structure means you can add as many Arduinos as you spare IP addresses
It also means you can add as many pins as there are available on your Arduino

Once I added all the data I now had he data in place for the Arduino and the pins I have LEDs on.

Then it was a matter of doing the PHP code.  This is when I discovered my PHP is very rusty. So, it took a while to get this sorted.

In the end I got there and now the PHP code on the server will list all the Arduinos and then the pins on each Arduino.  As I only have 1 Arduino/ENC28J60 I  added a 2nd entry for the same Arduino with a different name and added one of the pins again.and gave it a different name.

Since the code references the Arduino by it's ID record in the database rather than the IP address this was a successful test of whether the code would support multiple Arduinos with multiple pins on each.


If you are interested then below is the revised PHP code for the real webserver.
This is real nasty ugly code so there will be a lot of places where it can be improved which is my next task.

<!--
Winlkeink
September 2012
For feedback, comments and questions go to winkleink.blogspot.com

This code works with the Ethercard_LED_ONOFF_PHPCall code for Arduino to control Pins on Arduinos
using a web server as the interface.
The web page is served from a database where you list your Arduinos and the pins used.
With the options and when you click the button it does an fopen in the background
to the Arduino with the relevant command.
By doing this the IP address of the Arduino is not displayed on the webpage and also the
commands to control the Arduino is not shown publicly.
When compared to using the Arduino as the web server itself and using a GET REQUEST.

By doing it this way you have more control over the Arduino and the web interface.
This version is VERY rough with horrible colours.

NOTE:
As always my code is rough and is designed to get things done rather than beign perfect or pretty.
Use as you wish and let me know your thoughts.

-->

<!-- Start of the HTML -->
<html>
<head>
<title>Click to Turn on or OFF the LED in the background</title>
</head>
<body bgcolor="#FF9933">
<?php

// START CONNECT TO DATABASE

$database = "ArduinoList";
$username = "root";
$password = "";

IF ($LinkID = mysql_connect('localhost', $username, $password))
{
//print ('mySQL Connected<BR>');
}
else
{
//print ("mySQL NOT Connected<BR>");
//echo mysql_error();
//echo "<P>";
}

//Select the Database
IF (mysql_select_db($database))
{
#print ('Selected Database<BR>');
}
else
{
# print ("Failed to Select Database<BR>");
# echo mysql_error();
echo "<P>";
}

// END CONNECT TO DATABASE

//
// Start check for button presses
//

// Get the list of Arduinos
$querya = "SELECT ID, Arduino, aname FROM alist WHERE Active=1 ORDER BY ID DESC";
        IF ($resulta = mysql_query($querya))
        {
        # The Query was successful
        $column_counta = mysql_num_rows($resulta);
       
        // echo "column_counta is $column_counta";
            IF ($column_counta != 0 )
            {
                for ($column_numa = 0;
                $column_numa < $column_counta;
                $column_numa++)
                    {
                    $result_arra = mysql_fetch_array($resulta);
                    $AID  = $result_arra['ID'];
                    $Arduino = $result_arra['Arduino'];
?>
<?php
// Check if this Arduino is the one where a button was pressed.  If it is use it
if (isset($_POST["AID"]) == $AID)
{
?>       
<?php
//
// If Arduino is the correct one then check the pins to see which one was selected
//

                    // Get a list of all the pins being used on this Arduino
                    $queryb = "SELECT ID, alistID, pin FROM apin WHERE alistID=$AID AND Active=1 ORDER BY pin DESC";
                        IF ($resultb = mysql_query($queryb))
                        {
                        # The Query was successful
                        $column_countb = mysql_num_rows($resultb);
                            IF ($column_countb != 0 )
                            {
                                for ($column_numb = 0;
                                $column_numb < $column_countb;
                                $column_numb++)
                                    {
                                    $result_arrb = mysql_fetch_array($resultb);
                                    $pinID  = $result_arrb['ID'];
                                    $pin  = $result_arrb['pin'];
?>

<?php
// Check if a PIN has been actioned
if (isset($_POST["LED".$pin]) == "ON")
{
    if ($_POST["LED".$pin] == "ON")
    {
    // Set ON by calling the Arduino using fopen
    $h = @fopen("http://192.168.1.205/?LED".$pin."=ON", "rb");
    }
    else if ($_POST["LED".$pin] == "OFF")
    {
    // Set OFF by calling the Arduino using fopen
    $h = @fopen("http://192.168.1.205/?LED".$pin."=OFF", "rb");
    }
}
?>

<?php



                                }
                            }
                        }
?>

<?php

// END Check if an Arduino is Selected
}
?>


<?php

                   
                }
            }
        }
?>

<?php
?>

<!-- LED2 FORM -->
<!-- <table> -->
<?php

// Get the list of Arduinos
$querya = "SELECT ID, Arduino, aname FROM alist WHERE Active=1 ORDER BY ID DESC";
        IF ($resulta = mysql_query($querya))
        {
        # The Query was successful
        $column_counta = mysql_num_rows($resulta);
       
        // echo "column_counta is $column_counta";
            IF ($column_counta != 0 )
            {
                for ($column_numa = 0;
                $column_numa < $column_counta;
                $column_numa++)
                    {
                    $result_arra = mysql_fetch_array($resulta);
                    $AID  = $result_arra['ID'];
                    $Arduino = $result_arra['Arduino'];
                    $aname = $result_arra['aname'];
?>

<table>
<tr><td colspan="2"><b>
<?php echo "$aname";?>
 </b></td></tr>
       
<?php       
                    $queryb = "SELECT ID, pinName, alistID, pin FROM apin WHERE alistID=$AID AND Active=1 ORDER BY ID DESC";
                        IF ($resultb = mysql_query($queryb))
                        {
                        # The Query was successful
                        $column_countb = mysql_num_rows($resultb);
                            IF ($column_countb != 0 )
                            {
                                for ($column_numb = 0;
                                $column_numb < $column_countb;
                                $column_numb++)
                                    {
                                    $result_arrb = mysql_fetch_array($resultb);
                                    $pinID  = $result_arrb['ID'];
                                    $pinName  = $result_arrb['pinName'];
                                    $pin  = $result_arrb['pin'];
?>
<tr><td colspan="2"><font size="4" color="yellow">Turn on and off <?php echo $pinName;?><!!!!/font></H4></td></tr>
<tr><td>   
<form action="led2_sql.php" method="post">
<input type="hidden" name="AID" value="<?php echo$AID;?>">
<input type="hidden" name="LED<?php echo $pin;?>" value="ON">
<input type="submit" name="submit" value="ON!!">
</form>
</td><td>
<form action="led2_sql.php" method="post">
<input type="hidden" name="AID" value="<?php echo$AID;?>">
<input type="hidden" name="LED<?php echo $pin;?>" value="OFF">
<input type="submit" name="submit" value="OFF!!">
</form>
</td></tr>

<?php



                                }
                            }
                        }
?>
</table>
<?php

                   
                }
            }
        }
?>
</body>
</html>

Saturday, August 25, 2012

Arduino, Ethernet, Ethercard, XAMPP web server, PHP web page controlling 2 LEDs

[UPDATE 17 Sept 2012 - I have modified the XAMPP webserver code  get the details for the Arduino(s) from a database.  See the updated version here

I tinkered a while back with using a web server to control and Arduino over a serial connection and then I got an ENC28J60.  A really cheap Ethernet socket that can work with the Arduino. It uses the Ethercard community provided library.

My goal was to find a way to turn on and off LEDs which can later become Servos once I've done the hard coding from a web server that then connects to the Arduino over Ethernet.

Using this method the web server and the Arduino don't have to be near each other and even more importantly they don't need to be physically connected.

After a bit of research and trial and error I have something working.
This example presents a simple PHP based web page on the web server with the options to turn on or off 2 LEDs. (sorry for the gaudy colours in the video I thought it would be good to match the LED colours with the menus.

When you click a button on the web page it calls itself with a POST variable set.
The PHP page then interprets this and does an fopen() to the Arduino to do the requested action.

By doing an fopen() the actual connection to the Arduino is not shown on the web page.

The fun with this is that it could be expanded to control more pins easily and also control more than 1 Arduino.



PHP Code on the Server


<!--
Winlkeink
August 2012
For feedback, comments and questions go to winkleink.blogspot.com

This code works with the Ethercard_LED_ONOFF_PHPCall code for Arduino to control Pin2 and Pin4 on
the Arduino using a web server as the interface.
The web page is served with the options and when you click the button it does an fopen in the background
to the Arduino with the relevant command.
By doing this the IP address of the Arduino is not needed and also the commands to control the Arduino is not 
shown publicly when compared to using the Arduino as the web server itself and using a GET REQUEST.

By doing it this way you have more control over the Arduino and the web interface.

NOTE:
As always my code is rough and is designed to get things done rather than beign perfect or pretty.
Use as you wish and let me know your thoughts.

-->

<!-- Start of the HTML -->
<html>
<head>
<title>Click to Turn on or OFF the LED in the background</title>
</head>
<body bgcolor="#FF9933">
<?php

// Check of LED2 is set.  If it is use it
if (isset($_POST["LED2"]))
{
$LED2= $_POST["LED2"];
//echo "<b>$LED2</b>";
}
else
{
$LED2 ="";
}
if ($LED2 == "ON")
{
// Set led2 ON by calling the Arduino using fopen
//ini_set("allow_url_fopen On", true);
$h = @fopen("http://192.168.1.5/?LED2=ON", "rb");
}
else if ($LED2 == "OFF")
{
// Set led2 OFF by calling the Arduino using fopen
//ini_set("allow_url_fopen On", true);
$h= @fopen("http://192.168.1.5/?LED2=OFF", "rb");
}

// Check of LED4 is set.  If it is use it
if (isset($_POST["LED4"]))
{
$LED4= $_POST["LED4"];
//echo "<b>LED4 is $LED4</b>";
}
else
{
$LED4 ="";
}
if ($LED4 == "ON")
{
// Set led4 ON by calling the Arduino using fopen
//ini_set("allow_url_fopen On", true);
$h = @fopen("http://192.168.1.5/?LED4=ON", "rb");
}
else if ($LED4 == "OFF")
{
// Set led4 OFF by calling the Arduino using fopen
//ini_set("allow_url_fopen On", true);
$h= @fopen("http://192.168.1.5/?LED4=OFF", "rb");
}

?>
<!-- LED2 FORM -->
<table>
<tr><td colspan="2"><font size="4" color="yellow">Turn on and off the LED2</font></H4></td></tr>
<tr><td>
<form action="led2.php" method="post">
<input type="hidden" name="LED2" value="ON">
<input type="submit" name="submit" value="ON">
</form>
</td><td>
<form action="led2.php" method="post">
<input type="hidden" name="LED2" value="OFF">
<input type="submit" name="submit" value="OFF">
</form>
</td></tr>
</table>

<table>
<tr><td colspan="2"><font size="4" color="green">Turn on and off the LED4</font></td></tr>
<tr><td>
<form action="led2.php" method="post">
<input type="hidden" name="LED4" value="ON">
<input type="submit" name="submit" value="ON">
</form>
</td><td>
<form action="led2.php" method="post">
<input type="hidden" name="LED4" value="OFF">
<input type="submit" name="submit" value="OFF">
</form>
</td></tr>
</table>


</body>
</html>

Arduino code

/*
Winlkeink
August 2012
For feedback, comments and questions go to winkleink.blogspot.com

Script to allow the controling on the Arduino over Ethernet using an ENC28J60 Ethernet socket and the Ethercard library
Assigning Static IP for the Arduino so I can know exactly which Arduino I am controlling
For this example the request is either http://192.168.1.5/?LED2=ON or http://192.168.1.5/?LED2=OFF
These can be called directly but then the Arduino would have to be the web server and present back the web page
with the option to turn the LED off or ON

For this example I am controlling the Arduino from a webserver on my PC (XAMP) using a PHP script.

*/
// I took took inspiration from the following 2 examples

// The BackSoon example provided with the EtherCard library
// Present a "Will be back soon web page", as stand-in webserver.
// 2011-01-30 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

// Example from the Internet
// https://github.com/lucadentella/enc28j60_tutorial/blob/master/_5_BasicServer/_5_BasicServer.ino
#include <EtherCard.h>

// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
// ethernet interface ip address
static byte myip[] = { 192,168,1,5 };
// gateway ip address
static byte gwip[] = { 192,168,1,1 };

byte Ethernet::buffer[500]; // tcp/ip send and receive buffer

// Using a Variable for the Pin, but it is not necessary 
const int ledPin2 = 2;
const int ledPin4 = 4;


// Some stuff for responding to the request
char* on = "ON";
char* off = "OFF";
char* statusLabel;
char* buttonLabel;

// Small web page to return so the request is completed
char page[] PROGMEM =
"HTTP/1.0 503 Service Unavailable\r\n"
"Content-Type: text/html\r\n"
"Retry-After: 600\r\n"
"\r\n"
"<html>"
  "<head><title>"
    "Arduino 192.168.1.5"
  "</title></head>"
  "<body>"
    "<h3>Arduino 192.168.1.5</h3>"
  "</body>"
"</html>"
;

void setup(){
// Set Pin2 to be an Output
  pinMode(ledPin2, OUTPUT);
// Set Pin4 to be an Output
  pinMode(ledPin4, OUTPUT);

// Scary complex intializing of the EtherCard - I don't understand this stuff (yet0  
  ether.begin(sizeof Ethernet::buffer, mymac);
// Set IP using Static
  ether.staticSetup(myip, gwip);
}

void loop(){
  
  word len = ether.packetReceive();
  word pos = ether.packetLoop(len);

// IF LED2=ON turn it ON
  if(strstr((char *)Ethernet::buffer + pos, "GET /?LED2=ON") != 0) {
      Serial.println("Received ON command");
      digitalWrite(ledPin2, HIGH);
    }

// IF LED2=OFF turn it OFF  
    if(strstr((char *)Ethernet::buffer + pos, "GET /?LED2=OFF") != 0) {
      Serial.println("Received OFF command");
      digitalWrite(ledPin2, LOW);
    }

// IF LED4=ON turn it ON
  if(strstr((char *)Ethernet::buffer + pos, "GET /?LED4=ON") != 0) {
      Serial.println("Received ON command");
      digitalWrite(ledPin4, HIGH);
    }

// IF LED4=OFF turn it OFF  
    if(strstr((char *)Ethernet::buffer + pos, "GET /?LED4=OFF") != 0) {
      Serial.println("Received OFF command");
      digitalWrite(ledPin4, LOW);
    }

//Return a page so the request is completed.

    memcpy_P(ether.tcpOffset(), page, sizeof page);
    ether.httpServerReply(sizeof page - 1);
  
}

If you want more details on using the ENC28J60 check out my previous post on it.  It gives details on wiring and various libraries for it.







Tuesday, May 15, 2012

Arduino - HC-SR04 ultrasonic distance sensor

Last Christmas as part of my stocking fillers I got an HC-SR04 ultrasonic distance sensor.
Like most of my electronic bits it's a cheap generic device from ebay.  It's a small sensor that is suppose to do the same thing as the Ping sensor but for less money.


I finally unwrapped it and found a library for Arduino IDE 1.0 at HERE.  There is even some sample code to read the HC-SR04 and display the results on an LCD display.


Wiring is really simple
VCC - 5V
GND - GND

Trig - Trigger Pin you define in the code
Echo - Echo Pin defined in the code

Since I don't have an LCD display (yet) I modified the code to use the Serial Monitor as the output.
Code Below:

    #include "Ultrasonic.h"

      int TriggerP = 13; // Trigger Pin for Sensor
      int EchoP = 12; // Echo Pin for Sensor
     
      Ultrasonic ultrasonic(TriggerP,EchoP);   
   
       void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
      Serial.print("Distance: ");
      Serial.print(ultrasonic.Ranging(CM)); // Get Range in Centimetres
      Serial.println(" Cm.");
      delay(1000);
      Serial.println("..."); // Next lines.
    }

This worked great up to about 16cm.  But beyond that it started to give me some random numbers greater than 4000, so I'd expect not very robust.

I continued my search and found the following code that doesn't use any library, and this code even does the Serial Monitor as the output so no modification needed.


/*
 HC-SR04 Ping distance sensor]
 VCC to arduino 5v GND to arduino GND
 Echo to Arduino pin 13 Trig to Arduino pin 12
 More info at: http://goo.gl/kJ8Gl
 */

#define trigPin 12
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

This code performed better, working out to about 24cm.  
While doing my research on using the HC-SR04 I did find a post (somewhere...) stating that when powering from USB the 5V line can be a little bit off so this might be part of my problem.

But, using either method I have a sensor that is good up to 15cm which could be good enough for a small autonimous robot as if I'm within 15 cms I will need to look around for another direction.

NOTE: If you are using a version of the Arduino IDE before 1.0 then at the following LINK you can get the relevant library.  It looks like it's the same as the 1.0 library and has similar performance.

The hunt is on to see if there is a way of getting a reading beyond 24cm that is reliable.

Loving the tinkering.


UPDATE:
I combined some of the code from the Library with the direct code and now it reliably(ish) without detailed testing will work to 70cm.

The modified code is below.


/*
 HC-SR04 Ping distance sensor]
 VCC to arduino 5v GND to arduino GND
 Echo to Arduino pin 13 Trig to Arduino pin 12
 More info at: http://goo.gl/kJ8Gl
 */

#define trigPin 13
#define echoPin 12

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line

  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

Once again, I love this Tinkering.


Tuesday, May 1, 2012

Arduino & TVout Game Columns

After the little bits of coding and small videos that I have posted already I now have a working version of the classic game Columns working on an Arduino using the TVOut Lobrary to drive a composite video display.

I need to do a little cleaning up of the code, but if you want a copy just ask.  Happy to share.

Here's the usual video showing it working.


As promised now that I've tidied up the cdoe a bit here it is.

Update: 6 May 2012: Link to Code
http://dl.dropbox.com/u/9935575/Code/Ardunio_TVOut_Columns.zip


Update 8 May 2012 - Added Breadboard Layout using Fritzing

Thursday, April 26, 2012

Arduino TVOut 3 Blocks Falling


Still working with the Arduino and the TVOut library.
Now I have 3 block falling instead of 1.
Starting to look more like the basics of a game.  A bit more coding to do and maybe some buttons to enable the player to actually control something.







Thursday, April 19, 2012

Prime Numbers

I was watching the video below and I spotted that the Benchmark BM9 is getting Prime Numbers. 

 

This reminded me of a program I wrote in 1986 (20 I'm old years ago) to work out Primes on an Apple ][ in school.
So, I just had to fire up a BASIC interpreter (BASIC-256) to see if I could recreate it again.
Below is the code I did today with loads of REM comments to explain what I did.

REM Printing the Prime numbers up to 10,000 (maxcheck)
REM Winkleink - 2012
REM Just print the 1st 3 Primes
print 1
print 2
print 3
REM x is what we are checking set x to the next biggest odd number
x=5
REM number up to which we will check for primes
maxcheck = 10000
while x < maxcheck
REM Start the checking with 3 as 1 isn't valid and we are only checking odd number
i = 3
REM Set indicator if prime to 1 (means prime)
isprime =1
REM We only have to check odd numbers up to the Square Root of X as any number that will divide into X evenly will be made up of a number below SQR(x) and 1 above SQR(x)
while i <= int(sqr(x))
REM Check not Prime by seeing if there is a remainder if there is no remainder set isprime to 0
if x/i = int(x/i) then isprime=0
REM If not prime then set i to be above the while loop
if isprime = 0 then i= int(sqr(x))
REM Increment i by 2 as only need to divide by odd
i = i +2
endwhile
REM If isprime is still 1 then it is a prime number
if isprime=1 then print x
REM Increment x by 2,again even numbers won't be prime
x = x +2
endwhile

It was great fun to do and really brought back memories of sitting in the computer room in school watching as it slowly printed out the results.  A bit faster today.

And here is a video of it working.


 
As always.  Code is rough and just done for fun.  If you know a better way to calculate primes let me know in the comments.