Connecting a Freetronics Twenty Ten to a HanRun Ethernet Adapter

Connecting a Freetronics Twenty Ten to a HanRun Ethernet Adapter (ENC28J60 Ethernet LAN+Network Module)

hanrun2

hanrun1

What hardware you will need

  • 1x Freetronics TwentyTen
  • 1x HanRun HR911105A 12/18 Ethernet Board (eBay)
  • Misc Solder-less breadboard cables (Male/Female)

Router Configuration

I prefer to assign static IP’s to any of my test devices (Arduino or Raspberry Pi). This way I know what the IP is in case I need to connect to it. If you want to use your arduino in a Dynamic IP network then you may not have much luck with this guide as I am configuring the arduino to use an static ip that I have reserved in my router.

    Arduino Static

The HanRun Ethernet adapter does not have a mac address built in so I made one up ( 00:12:34:43:21:00 ), you can generate mac addresses here http://www.miniwebtool.com/mac-address-generator/.

Software Configuration

  • Arduino.cc IDE (Set the ‘Board’ to ‘Arduino Nano w/ ATMmegda 328’ and the virtual serial port for your USB cable)
  • Download ‘Ethercard’ from https://github.com/jcw/ethercard (add it as a library into arduino.cc IDE)

The Wiring

HanRun Side | Arduino Side

    GND = Power Ground
    SCK = Pin 13
    SO = Pin 12
    VCC = Power 3V3
    CS = Pin 8
    SI = Pin 11

photo 2

    The Code
    Now this is my code solution for returning a date from a website (php script). Yu can change the IP, Gateway, Server Name, IP and Path to your server if need be.

    // This demo does web requests to a fixed IP address, using a fixed gateway.
    // 2010-11-27 http://opensource.org/licenses/mit-license.php
    // 2013-11-23 Modified by Simon Fearby

    #include
    #include

    #define SLEEP_TIME_AFTER_SETUP 10000 // How often do we poll the server

    //static long timersetup; // Used to remember the last millisecond for the last call (during setup)
    static long timerloop; // Used to remember the last millisecond for the last call (after setup)

    static byte mymac[] = { 0x00, 0x12, 0x34, 0x43, 0x21, 0x00 }; // ethernet interface mac address
    static byte myip[] = { 192,168,1,201 }; // ethernet interface ip address
    static byte gwip[] = { 192,168,1,1 }; // gateway ip address
    static byte hisip[] = { 175,107,162,121 }; // remote website ip address and port

    char website[] PROGMEM = "fearby.com"; // remote website name

    byte Ethernet::buffer[1000]; // a very small tcp/ip buffer is enough here

    void setup () {
    Serial.begin(57600);
    while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
    }
    Serial.println("Ready");
    if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println( "Error Failed to access Ethernet controller");

    ether.staticSetup(myip, gwip); // Our router has a Static IP already setup for us so dont ask for a IP via DHCP
    ether.copyIp(ether.hisip, hisip); // Is it the IP we expect?

    ether.printIp("My Gateway: ", ether.myip); // Output the routers IP (Gateway)
    ether.printIp("My IP: ", ether.gwip); // Output the Arduino's IP)
    ether.printIp("Remote Server: ", ether.hisip); // Output the IP of the remote server.

    while (ether.clientWaitingGw()) // Check to see if the gateway is up before moving on.
    ether.packetLoop(ether.packetReceive());

    Serial.println("Gateway found"); // Congrats, Move on

    Serial.println("Waiting 10 seconds before polling data."); // Congrats, Move on

    }

    static void my_result_cb (byte status, word off, word len) { // called when the client request is complete
    Serial.print("<<< reply "); // We got a reply from the web server Serial.print(millis() - timerloop); // Time Stuff Serial.println(" ms"); // Print the time diff between the call and data received Serial.println((const char*) Ethernet::buffer + off); // Ok print the contents of the webpage } void loop () { ether.packetLoop(ether.packetReceive()); // Process Incoming Packets if (millis() > timerloop + SLEEP_TIME_AFTER_SETUP) { // Do we need to sleep? We dont want to load a website 10,000 a second.
    timerloop = millis(); // Remember the last time we loaded the webpage
    Serial.println("\n>>> Webpage Request Sent.."); // Lets get a Webpage
    ether.browseUrl(PSTR("/temp/printdate.php"), "?", website, my_result_cb); // Query Google
    }
    }

    Result from the Arduino

    hanrun3

    Where to now

    Remember that this code running on a small circuit board that runs < 20Mhz 8bit processor that can be powered by AA batteries.

    You can point to your own scripts and save/read database values or trigger other Arduinos or external processes.

    The next step is to have this device read from any external sensors or control the physical world around us with expansion cards.

Why Can’t Programmers.. Program?

A great forum thread from 2007 asks Why Can’t Programmers.. Program? The discussion reports that 199 out of 200 applicants for every programming job can’t write code at all. I repeat: they can’t write any code whatsoever.

A surprisingly large fraction of applicants, even those with masters’ degrees and PhDs in computer science, fail during interviews when asked to carry out basic programming tasks. For example, I’ve personally interviewed graduates who can’t answer “Write a loop that counts from 1 to 10” or “What’s the number after F in hexadecimal?” Less trivially, I’ve interviewed many candidates who can’t use recursion to solve a real problem. These are basic skills; anyone who lacks them probably hasn’t done much programming.

Speaking on behalf of software engineers who have to interview prospective new hires, I can safely say that we’re tired of talking to candidates who can’t program their way out of a paper bag. If you can successfully write a loop that goes from 1 to 10 in every language on your resume, can do simple arithmetic without a calculator, and can use recursion to solve a real problem, you’re already ahead of the pack!

Between Reginald, Dan, and Imran, I’m starting to get a little worried. I’m more than willing to cut freshly minted software developers slack at the beginning of their career. Everybody has to start somewhere. But I am disturbed and appalled that any so-called programmer would apply for a job without being able to write the simplest of programs. That’s a slap in the face to anyone who writes software for a living.

One comment sums up newbie programmers.

    Isn’t the code for that ..

    int main() { ExitPaperBag(); return 0; }

    I’m not sure … copied it from somewhere 😛

Another comment listed a true programmers skill:

    In my first month at my new job I had to learn VB and C++ from scratch, two months later I was moved on to a project in C# using ASP.Net which I’d never used before. I’ve seen similar tests to the fizzbang questions, and they are useful.

Your Challenge:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Choose your own language,

Ok, how did you go?

Here is my code.. I used Lua as I have been doing a bit of that recently.

for i = 1,100 do
	sTmp = ""
	if (i % 3 == 0) then
		sTmp = "Fizz"
	end
	if (i % 5 == 0) then
		if (sTmp == "Fizz") then
			sTmp = "FizzBuzz"
		else
			sTmp = "Buzz"
		end
	end
	if (sTmp == "") then
		sTmp = tostring(i)
	end
	print(sTmp)
end

Installing Visual Basic 2010 Express

Most of my demos are going to use Visual Basic 2010 Express (a free development studio from Microsoft). This download is about 600MB.

Visual Studio Express 2012 requires Windows XP, Vista or Windows 7 with 2GB minimum of memory with 3GB hard drive space and a 1.6Ghz processor or more.

How to download and Installing Visual Studio Express 2010.

    1. http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-basic-express
    2. Click Install now (save vb_web.exe)
    3. Run vb_web.exe
    4. Click next
    5. Select I have read and accept the licence.
    6. Click Install

    7. Click Exit when Done
    8. http://go.microsoft.com/fwlink/?LinkId=209902
    9. Download VS10sp1-KB983509.exe
    10. Click Next to install Visual Studio Service Pack 1

    11. Click next then click I have read and accept the licence terms then click next (this will download about 500MB).

    12. You should now have Visual Studio Express Installed.

    13. Check your Windows for software updates.

Future posts will show you how to develop programs in Visual Studio Express (Visual Basic) 2010. If you are a Mac user I will get into Apple’s Objective C with XCode but for now you can install Visual Studio in a Virtual Machine on OSX.

If you are keen read some of these guides.

Programming Logic and Basic Programming terms

Programming logic is a quick description of the flow of your program.
A very simple program logic may be

    START MAIN
    CHECK ITEM_PRICE
    CHECK BANK_BALANCE
    IF ITEM_PRICE < BANK_BALANCE THEN
      BUY_ITEM

    END IF
    END MAIN

Before we write the program above we need to identify what is data and what is language associated with the programming language.

Data would be BANK_BALANCE (that is a number) and ITEM_PRICE is a number too.

“IF” and “END IF” are commands available in this program. When dealing with data you can assign the data to a variable name, for example your bank balance (a number) can be saved in the variable MyBankBalance and your credit card balance can be saved in a variable called MyCreditCardBalance.

There are different types of variables used in Visual Studio 2010 – Visual Basic.

    Bits: 0 or 1 (True or False)
    Byte: -128 to 127
    String: any text you can think of.
    Number variables:
    Short: -32,768 through 32,767.
    Long: -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
    Decimal: -79,228,162,514,264,337,593,543,950,335 through 79,228,162,514,264,337,593,543,950,335

There are other types but you can read about them here: http://msdn.microsoft.com/en-us/library/ae55hdtk.aspxIf you have to choose one type of variable choose a string as it can hold almost anything.

With numbers try and use the variable with the smallest maximum to save using too much memory (e.g. If you were creating a variable to hold ones age use a Byte, if you were creating a variable to hold a bank balance use a Decimal over an integer mostly because Decimals allow decimal points where Integers round off anything after a decimal point.

Now what we have our programming logic decided our programming variables how can we optimize my program. Let’s say we want to check our primary bank balance then our secondary bank balance if the primary bank balance does not have enough money. If we duplicated the code that checks the bank balance that would work but the code would get twice as big. What we need to do is move the code that checks the bank balance into a FUNCTION called “CHECK_BANK_BALANCE” and pass in the name of the bank account to check. No we can check 1, 2 or 2000 bank balances without duplicating code.

The new code might look like

    START MAIN
    CHECK ITEM_PRICE
    IF ITEM_PRICE < CHECK_BANK_BALANCE(BANK_ACCOUNT_NUMBER) THEN
      BUY_ITEM

    END IF
    END MAIN

    FUNCTION CHECK_BANK_BALANCE(BANK_ACCOUNT_NUMBER)

      RETURN BANK_BALANCE

    END FUNCTION

The code above is not perfect, we do not have a breakdown of the check price function but pseudo code allows you to flesh out the structure of your program before you start coding.

Another alternative to using a function may be to use a “Sub” (Subroutine), A subroutine is like a function but it does not return any data. You could use a sub routine to deduct an amount from a bank balance and not return the bank balance when done.

CONCLUSION:

  • Pseudo code allows you to flesh out your program. If you have an idea just write our the pseudo code, review and optimise it. When you are happy with the flow, choose a suitable software language and start turning the pseudo code into real code.
  • Variables are used to hold data.
  • There are variables for text, numbers etc.
  • Use FUNCTIONS instead of duplicating code.

Programming 101

Before you can learn how to program you need to understand what a computer is, a computer at its simplest form is a really fast calculator that can only do one thing at a time. Technically it can do more than one thing at a time but we will come to that discussion at a later date.

In the 1940’s computers and electronics were very basic, there was no internet, no mobile phones or iPods. The world was at war and the Allies and NAZI’s were busy designing computers to assist with encrypting war messages or to accurately predict artillery accuracy. One of the first programmable computers (ENIAC) was developed by the US during WW2 to help calculate artillery firing tables. The ENIAC was able to perform calculations in hours that previously took days. The ENIAC was 100% electronic, the NAZI’s were designing a mix of electronic and mechanical computers (but lucky for us the allies blew it up).

Moving forward to the 1960’s NASA was planning on sending humans to the moon, they needed a way to make computers on the Apollo spacecraft more reliable. NASA contractors files patent US3517171 http://www.google.com/patents/US3517171 for a “Self testing and repairing computer”. This patent allowed computers to interrupt a running program and start doing something else more important. Without the benefit of this invention most computers would still be boring calculators running batches of calculations.

So you may be asking when do we stop learning about history and start programming?

    Ok in the next 5 minutes we will create a program to create a new thread, initialize the TCP stack, create a socket to send an ICMP packet to ping a server after returning the context to the current thread, but when the ICMP reply returns we will invoke the current thread via a delegate and update the UI.

Just kidding, we will not be doing that for some time to come. We will do some fun stuff before that.

Going back to our quick history lesson, The WW2 allies and NASA had to learn how to write software, we have to master the same concepts before we can program. We need to understand what processor is and what memory is.

A processor is a silicon chip that performs calculations really fast, it is the heart of your computer/iPad/Laptop. Processors are quite powerful these days but they still have to read our calculations from memory and write the results back to memory. Memory is basically a huge empty storage area for data. When you turn on your computer its memory is completely empty until your operating system or software writes data to the memory. Software can read and write anything to memory (images, videos, this blog post or games).

Processors speed are measured in Mhz and Memory is measured in Megabytes. I am using a processor with 4 processors running at 3,400,000,000 Mhz, on any good second I could calculate 3 billion calculations a second.

Most x86 compatible (Intel or AMD) processors use commands like ADD, DIV, SUB, MUL, OR, AND CALL, to calculator or evaluate data. Instructions like Divide are truncated to “DIV” and Multiply is shortened to “MUL”. Lucky we do not call these commands directly, we have fancy programming development environments to do all the hard work for us. See the full instruction set here http://en.wikipedia.org/wiki/X86_instruction_listings

Conclusion

  • A computer is a calculator, we have to tell it what to do.
  • A processor can only read from memory, calculate and write the result back to memory.

New Programming Blog Category

I have decided to add a blog category for programming, yes computer programming. Programming is a very creative and fun thing to do. You could program a website, program a bath file to manage your files or program a software program to read you the outside temperature.

Far too many school students are leaving school having studied programming but could not explain 5 computer variable types. That would be like asking a keen cook to name 5 cooking ingredients that you could use in a sweet and savoury dish.

Over the next few months please join me on a journey for basic programming.

Topics:

  • Programming basics.
  • Different types of programming.
    • Windows Software Programming.
    • Webpage programming.
    • Database programming.
    • iPhone/iPad and Android Programming.

I will hope to demonstrate programming using as much free software as possible. Worst case you may require a personal website but that is a cheap as $5 a month (via a host like http://www.jumba.com.au/hosting/personal).

Show me the programming posts.