Arduino Programming For Beginners: The Traffic Light Controller

Compare Cost: Get 8 Free E-Commerce Design Bids
Service:
Location:
Budget:
Deadline:
Compare: Web Design Calculator | Web Design Cost Guidelines

Are you an E-Commerce Web Designer? Add a Free Listing

traffic light controllerLast week, we learnt about the basic structure of an Arduino program and took a closer look at the ‘blink’ example. Hopefully you took the opportunity to experiment with code, adjusting the timings. This time, we’ll be writing something from scratch. In fact, let’s make a traffic light.

Apart from the basic Arduino, you’ll need:

Note: This is the latest in a series of beginner level tutorials for Arduino, the open source electronics prototyping platform. Here’s a list of the previous articles in the series:

You may also want to download and install Fritzing, the tool I used to draw the wiring diagrams for these projects.

Wiring

Here’s a quick schematic I made up in Fritzing. It’s very simple – just the three LEDs wired with resistors to three separate input pins, and all connected to the ground.

traffic light controller

Programming

We’ll start by defining variables so that we can address the lights by name rather than a number. Start a new Arduino project, and begin with these lines:

int red = 13;
int yellow = 12;
int green = 11;

Next, let’s add the setup function, where’ll we define the red, yellow and green LEDs to be output mode. Since we’ve created variables to represent the pin numbers, we can now refer to the pins by names instead.

void setup(){
pinMode(red,OUTPUT);
pinMode(yellow,OUTPUT);
pinMode(green,OUTPUT);
}

That was easy. Now for the difficult part – the actual logic of a traffic light. I’m going to create a separate function for changing the lights, and you’ll see why later.

When you first begin programming, the code itself is very rudimentary – it’s figuring out the minute logic details that presents the biggest problem. The key to being a good programmer is to be able to look at any process, and break it down into its fundamental steps.

void loop(){
changeLights();
delay(15000);
}

void changeLights(){
// green off, yellow for 3 seconds
digitalWrite(green,HIGH);
digitalWrite(yellow,LOW);
delay(3000);

// turn off yellow, then turn red on for 5 seconds
digitalWrite(yellow,LOW);
digitalWrite(red,HIGH);
delay(5000);

// red and yellow on for 2 seconds (red is already on though)
digitalWrite(yellow,HIGH);
delay(2000);

// turn off red and yellow, then turn on green
digitalWrite(yellow,LOW);
digitalWrite(red,LOW);
digitalWrite(green,HIGH);
}

Done! Now, upload and run. You should have a working traffic light that changes every 15 seconds. However, I think it’s a little basic right now, so let’s add in a pushbutton for pedestrians to change the light whenever they like. Refer to the updated circuit diagram below:

traffic light controller

You’ll notice that the switch has a high-impedance 10k resistor attached to it, and may be wondering why. This is called a pull down resistor. It’s a difficult concept to grasp at first, but bear with me.

A switch either lets the current flow, or doesn’t. This seems simple enough, but in a logic circuit, the current should be always flowing in either a high or low state (remember – 0 or 1, high or low). You might assume that a pushbutton switch that isn’t actually being pushed would be defined as being in a low state, but in fact it’s said to be ‘floating’, because no current is being drawn at all.

In this floating state, it’s possible that a false reading will occur as it fluctuates with electrical interference. In other words, a floating switch is giving neither a reliable high, nor low state reading. A pull down resistor keeps a small amount of current flowing when the switch is closed, thereby ensuring an accurate low state reading. In other logic circuits, you may find a pull-up resistor instead – this works on the same principle, but in reverse, making sure that particular logic gate defaults to high.

Now, in the loop part of the code, instead of changing the lights every 15 seconds, we’re going to read the state of the pushbutton switch instead, and only change the lights when it’s activated.

Start by adding some new variables to the start of the app:

int button = 2; // switch is on pin 2
int buttonValue = 0; // switch defaults to 0 or LOW

Now, in the setup function, add a new line to declare the switch as an input. I’ve also added a single line to start the traffic lights in the green stage. Without this initial setting, they would be turned off, until the first time a changeLights() was initiated using a function.

pinMode(switch,INPUT);
digitalWrite(green,HIGH);

Change the entire loop function to the following instead:

void loop(){
// read the value of the switch
switchValue = digitalRead(button);

// if the switch is HIGH, ie. pushed down - change the lights!
if (buttonValue == HIGH){
changeLights();
delay(15000); // wait for 15 seconds
}
}

That should do it. By waiting inside the “if” statement for 15 seconds, we ensure the traffic lights can’t change for at least that duration. Once 15 seconds is up, the loop restarts. Each restart of the loop, we will read the state of the button again, but if it isn’t pressed then the “if” statement never activates, the lights never change, and it simply restarts again.

That’s it for this time, so I hope you learnt lots and had fun writing from scratch. You got your hands dirty with a few LEDs and resistors, as well as adding a switch with a pull down resistor – hopefully you understood why we need one. Play around with the code, adjust it, and most importantly have fun. If you make any additions or changes, why not let us know about it in the comments?


Source http://www.makeuseof.com/?p=93070
Wed, 07 Dec 2011 19:01:44 GMT
Tags: arduino, coding, Hardware & Gadgets, programming,
Palm Harbor E-Commerce | Johns Creek E-Commerce | Richmond Hill E-Commerce | Auburn Hills E-Commerce | Linthicum E-Commerce | Safety Harbor E-Commerce | Albuquerque E-Commerce | Fort Collins E-Commerce | Chicago E-Commerce | Iowa Park E-Commerce |

arduino


Fritzing – The Ultimate Tool For Sketching Out Electronics Projects [Cross Platform]

Despite sounding like an alcopop, Fritzing is actually an incredible bit of free software you can use to create circuit and component diagrams for use with rapid-prototyping electronics boards such as the fantastic open-source Arduino. As such, it’s open

Getting Started With Your Arduino Starter Kit – Installing Drivers & Setting Up The Board & Port

So, you’ve bought yourself an Arduino starter kit, and possibly some other random cool components - now what? How do you actually get started with programming this Arduino thing? How do you set it up and upload some code? Read on and I'll explain all. I’

First Steps With The Arduino: A Closer Look At The Circuit Board & The Structure Of A Program

Last time I left you having set up your Arduino to work with Mac or Windows, and having uploaded a simple test app that blinked the on-board LED. Today I’m going to explain the code you uploaded, the structure of Arduino software, and a little more about

coding


Time To Try A Slick, New Text Editor Called Tincta [Mac]

While you may already think you've found the text editor love of your life, you could hardly stand by it honourably without giving the competition a go. So, today we'll introduce you to a sleek new player in the Mac text editor game called Tincta. It's

4 Hacker Software Tools Every Budding Coder Should Have

If you’re a computer geek, chances are you like fiddling around with things. You are, in short, a hacker. Although most hackers probably use Linux, there are some that use Windows. Maybe your business requires you to use Windows. This post covers some ess

Make A Product Review Database With WordPress: Custom Post Types, Custom Fields, Featured Images & Widgets!

Last time we showed you how to create a simple events listing using perhaps the most powerful feature of WordPress 3.0 - custom post types. After some requests to develop this further, today we’ll be creating a product review database to tie together ever

Hardware & Gadgets


Can’t Decide Which Smartphone To Choose? Here Is One Good Way To Do It

Choosing a phone used to be easy. Well, easier. No matter what your maker of choice was, the differences weren’t all that big, and Nokia held the winning hand anyway. But those were the good old days. All of that has changed in recent years, and the marke

[Black Friday] 5 Cool Deals In Amazon’s Electronics Dept [At Least 40% Off]

For all you tech-savvy MakeUseOf.com readers, I headed over to Amazon.com to see what Black Friday and Cyber Monday deals the best-selling site was offering in terms of electronics and other gadgetry. Although Amazon is typically known for selling books,


Need E-commerce Design? Check out our member profiles:

Miami
Trendy by Design Profile
Trendy by Design

Trendy by Design is a full-service creative design company specializing in unique graphic & web design for women and small businesses. Visit us today at http://www.trendybydesign.com today!

Miami, Florida US
Fredericksburg
Greater Works Business Services Profile
Greater Works Business Services

We are a web development company offering affordable web design solutions for individuals, businesses, and nonprofit organizations.

Fredericksburg, Virginia US
Austell
Studio Chic Design Profile
Studio Chic Design

Studio Chic Designs offers affordable boutique graphic design for small businesses. Logo design, blog design, website design,and more. Visit studiochicdesign.com to view packages, rates and reviews.

Austell, Georgia US
Mt Pocono
RachelWoods.com - Ecommerce Specialist Profile
RachelWoods.com - Ecommerce Specialist

(800)605-5146 - Web Design & E-Commerce Specialist. Get your instant quote now! We work with any budget because looking professional doesn't have to be expensive!

Mt Pocono, Pennsylvania US
New York
SiteStore123.com Profile
SiteStore123.com

A solution for event promotion, grand opening pages for retailers, eBay listings. We promote your business via the web!

New York, New York US
North Babylon
Mental Pixel Profile
Mental Pixel

Mental Pixel Web Design and Development. Full Service Website Design and Marketing starting at $525, Located in Long Island, NY.

North Babylon, New York US
Fort Lauderdale
14 East Profile
14 East

14 East offers a wide range of Internet solutions including advanced web design & development, E-commerce, database programming, search engine optimization and credit card processing.

Fort Lauderdale, Florida US
Kolkata
Credence BPO Pvt Ltd Profile
Credence BPO Pvt Ltd

We are a ISO 9001:2008 certified company and STPI registered. Our Services are: Web designing, Web Development, Content & Article Writing, SEO, SEM, SMM

Kolkata, West Bengal IN



Get Free Logo Design Quotes






Cool Tech Deals Of The Week – Edimax BR-6258n 150Mbps 802.11N Wireless Nano Router or Bridge $24.99 & More!

Newegg has the Edimax BR 6258n 150Mbps 802 11N Wireless N Router for a low 24 99 and 0 99 Shipping



Minecraft Available Soon On Many Android 2.3+ Devices [News]

Minecraft Pocket Edition for Android is about to be re released with support for a wider range of



The 3 Steps To Setting Up Your Android Tablet’s Touchscreen Keyboard

Over a year after the initial launch of the iPad we are finally seeing some decent tablet alternati



Hot Tech Deals – Zotac ZT-40604-10L NVIDIA Geforce GT 430 1GB HDCP PCI-E Video Card for $19.99 & More

Newegg has the Zotac ZT 40604 10L NVIDIA Geforce GT 430 1GB HDCP PCI E Video Card for 19 99 reduce



44 Colorful and Awesome Vectors for Your Inspiration

Drawing vector art requires skills and patience In today 8217 s article we 8217 ve handpicked som



5 Best Websites With Fun Activities For Toddlers

If you re looking online for fun activities for toddlers you ve probably realised that there s a lo



Is TightVNC Really More Tight Than Other VNC Clients?

When it comes to remotely connecting to a desktop PC or a server most people quickly opt for instal




Design Leads

Article Tags
E-commerce Design Articles
Web Apps & Internet (369)
News (290)
Web Apps (129)
Inspiration (128)
Music (119)
iPhone / iPad / iPod (114)
cool web apps (108)
Mobile Tips (100)
Google Android (100)
Announcements (99)
deals (88)
Games & Gaming Tips (84)
Tech Deals (82)
Opinion & Polls (76)
Cool Software Apps (76)
Browser Tips & Tricks (66)
iOS (66)
Social Media (65)
iPhone Apps (59)
Photography (58)
Freebies (58)
geeky fun (58)
iphone (55)
Google (53)
troubleshoot (53)
android (52)
Photoshop (52)
Graphics (51)
facebook (50)
How-To Articles (50)

Friends:
E-Commerce Website Pricing
Web Design Quote
Website Design
Graphic Designers


E-commerce Design Valid HTML 4.0 Transitional Valid CSS!